From 60dc83a14d795e6edd2d8cce4e52186176c5f6ed Mon Sep 17 00:00:00 2001 From: zhongjianfei Date: Sat, 11 Sep 2021 22:51:39 +0800 Subject: [PATCH] zhongjianfei@huawei.com Signed-off-by: zhongjianfei Change-Id: Ib48cb6aca6cf1476ba2d5cf242d883d3b2712e19 --- frameworks/kits/ability/native/BUILD.gn | 44 +- .../kits/ability/native/include/ability.h | 547 +- .../ability/native/include/ability_impl.h | 75 +- .../ability/native/include/ability_keyevent.h | 50 + .../include/ability_post_event_timeout.h | 56 + .../ability/native/include/ability_thread.h | 53 + .../native/include/ability_touchevent.h | 50 + .../ability/native/include/ability_window.h | 2 +- .../native/include/data_ability_helper.h | 81 + .../native/include/data_ability_impl.h | 26 + .../native/include/data_ability_operation.h | 14 +- .../ability/native/include/data_uri_utils.h | 6 +- .../native/include/form_js_event_handler.h | 62 + .../native/include/form_provider_client.h | 160 + .../kits/ability/native/src/ability.cpp | 1261 ++++- .../ability/native/src/ability_context.cpp | 97 +- .../kits/ability/native/src/ability_impl.cpp | 217 +- .../ability/native/src/ability_keyevent.cpp | 82 + .../native/src/ability_post_event_timeout.cpp | 90 + .../ability/native/src/ability_process.cpp | 72 +- .../ability/native/src/ability_thread.cpp | 276 +- .../ability/native/src/ability_touchevent.cpp | 68 + .../ability/native/src/ability_window.cpp | 26 +- .../native/src/data_ability_helper.cpp | 752 ++- .../ability/native/src/data_ability_impl.cpp | 45 + .../native/src/data_ability_operation.cpp | 2 +- .../src/data_ability_operation_builder.cpp | 1 + .../native/src/data_ability_result.cpp | 3 + .../ability/native/src/data_uri_utils.cpp | 17 +- .../native/src/form_js_event_handler.cpp | 140 + .../native/src/form_provider_client.cpp | 475 ++ .../ability/native/src/page_ability_impl.cpp | 28 +- .../native/src/service_ability_impl.cpp | 6 +- frameworks/kits/ability/native/test/BUILD.gn | 133 +- .../test/mock/include/bundle_mgr_interface.h | 8 +- .../include/mock_ability_manager_client.h | 22 + ...manager_client_for_data_ability_observer.h | 118 + .../include/mock_ability_manager_service.h | 19 + .../mock_ability_scheduler_for_observer.h | 62 + ...read_for_ability_on_configuration_update.h | 57 + .../test/mock/include/mock_bundle_manager.cpp | 2 + .../test/mock/include/mock_bundle_manager.h | 28 + .../mock/include/mock_bundle_manager_form.cpp | 172 + .../mock/include/mock_bundle_manager_form.h | 527 ++ .../test/mock/include/mock_form_mgr_service.h | 236 + .../include/mock_form_supply_callback.cpp | 60 + .../mock/include/mock_form_supply_callback.h | 56 + .../mock_resourceManager_interface1.cpp | 15 +- ...ad_for_ability_on_configuration_update.cpp | 130 + .../unittest/data_ability_helper_test.cpp | 941 ++-- .../test/unittest/data_uri_utils_test.cpp | 42 +- .../test/unittest/form_ability_test.cpp | 1260 +++++ .../test/unittest/form_host_client_test.cpp | 157 + .../unittest/form_provider_client_test.cpp | 512 ++ .../native/test/unittest/pac_map_test.cpp | 152 +- .../base/cpp/src/ohos/aafwk/base/base.cpp | 6 + .../ohos/aafwk/base/pac_map_node_array.cpp | 688 --- .../src/ohos/aafwk/base/pac_map_node_base.cpp | 586 --- .../aafwk/base/pac_map_node_user_object.cpp | 195 - .../ohos/aafwk/base/user_object_wrapper.cpp | 131 + .../cpp/src/ohos/aafwk/content/pac_map.cpp | 1326 ++++- .../cpp/src/ohos/aafwk/content/want.cpp | 62 +- frameworks/kits/content/cpp/test/BUILD.gn | 6 +- .../common/want_params_wrapper_test.cpp | 2 +- .../cpp/test/unittest/common/want_test.cpp | 116 +- frameworks/kits/test/BUILD.gn | 50 + .../mock/AMS/mock_ability_manager_service.h | 17 + .../AMS/mock_serviceability_manager_service.h | 16 + .../test/mock/DemoAbility/mock_ability_test.h | 109 + .../mock_ability_hancle_for_data_observer.h} | 27 +- .../mock_ability_manager_client.h | 81 + .../mock_ability_thread_for_data_observer.h | 72 + .../cpp/abilitytest/ability_test.cpp | 659 --- .../data_ability_helper_module_test.cpp | 653 +++ frameworks/kits/tools/BUILD.gn | 23 + .../kits/tools/simulateEntryAbility/BUILD.gn | 64 + .../tools/simulateEntryAbility/config.json | 49 + .../include/simulate_entry_ability_fir.h | 31 + .../include/simulate_entry_ability_sed.h | 31 + .../src/simulate_entry_ability_fir.cpp | 47 + .../src/simulate_entry_ability_sed.cpp | 47 + .../tools/simulateFeatureAbility/BUILD.gn | 63 + .../tools/simulateFeatureAbility/config.json | 49 + .../include/simulate_feature_ability_fir.h | 31 + .../include/simulate_feature_ability_sed.h | 31 + .../src/simulate_feature_ability_fir.cpp | 47 + .../src/simulate_feature_ability_sed.cpp | 47 + .../verifyAbility/verifyActAbility/BUILD.gn | 76 + .../verifyActAbility/config.json | 141 + .../include/verify_act_data_first_ability.h | 44 + .../include/verify_act_eighth_ability.h | 38 + .../include/verify_act_fifth_ability.h | 72 + .../include/verify_act_first_ability.h | 86 + .../include/verify_act_fourth_ability.h | 47 + .../include/verify_act_ninth_ability.h | 53 + .../include/verify_act_second_ability.h | 40 + .../include/verify_act_seventh_ability.h | 37 + .../include/verify_act_sixth_ability.h | 32 + .../include/verify_act_tenth_ability.h | 38 + .../include/verify_act_third_ability.h | 43 + .../include/verify_service_first_ability.h | 37 + .../src/verify_act_data_first_ability.cpp | 63 + .../src/verify_act_eighth_ability.cpp | 44 + .../src/verify_act_fifth_ability.cpp | 74 + .../src/verify_act_first_ability.cpp | 75 + .../src/verify_act_fourth_ability.cpp | 48 + .../src/verify_act_ninth_ability.cpp | 48 + .../src/verify_act_second_ability.cpp | 45 + .../src/verify_act_seventh_ability.cpp | 44 + .../src/verify_act_sixth_ability.cpp | 42 + .../src/verify_act_tenth_ability.cpp | 44 + .../src/verify_act_third_ability.cpp | 48 + .../src/verify_service_first_ability.cpp | 63 + .../verifyAbility/verifyIOAbility/BUILD.gn | 70 + .../verifyAbility/verifyIOAbility/config.json | 121 + .../include/verify_io_eighth_ability.h | 32 + .../include/verify_io_fifth_ability.h | 32 + .../include/verify_io_first_ability.h | 32 + .../include/verify_io_fourth_ability.h | 41 + .../include/verify_io_ninth_ability.h | 32 + .../include/verify_io_second_ability.h | 32 + .../include/verify_io_seventh_ability.h | 38 + .../include/verify_io_sixth_ability.h | 32 + .../include/verify_io_tenth_ability.h | 32 + .../include/verify_io_third_ability.h | 43 + .../src/verify_io_eighth_ability.cpp | 42 + .../src/verify_io_fifth_ability.cpp | 42 + .../src/verify_io_first_ability.cpp | 44 + .../src/verify_io_fourth_ability.cpp | 99 +- .../src/verify_io_ninth_ability.cpp | 42 + .../src/verify_io_second_ability.cpp | 43 + .../src/verify_io_seventh_ability.cpp | 42 + .../src/verify_io_sixth_ability.cpp | 49 + .../src/verify_io_tenth_ability.cpp | 42 + .../src/verify_io_third_ability.cpp | 57 + interfaces/innerkits/ability_manager/BUILD.gn | 6 + .../ability_manager_headers.gni | 5 + .../include/aafwk_dummy_configuration.h | 73 + .../include/ability_manager_client.h | 75 +- .../include/ability_manager_errors.h | 67 + .../include/ability_manager_interface.h | 117 +- .../include/ability_scheduler_interface.h | 63 +- .../include/ability_start_setting.h | 109 + .../include/ability_window_configuration.h | 48 + .../include/lifecycle_state_info.h | 2 + .../ability_manager/include/mission_option.h | 57 + .../ability_manager/include/stack_setting.h | 50 + interfaces/innerkits/base/BUILD.gn | 12 +- .../include/ohos/aafwk/base/base_interfaces.h | 30 +- .../include/ohos/aafwk/base/pac_map_node.h | 122 - .../ohos/aafwk/base/pac_map_node_array.h | 264 - .../ohos/aafwk/base/pac_map_node_base.h | 263 - ..._node_user_object.h => user_object_base.h} | 160 +- .../ohos/aafwk/base/user_object_wrapper.h | 55 + interfaces/innerkits/want/BUILD.gn | 2 + .../want/include/ohos/aafwk/content/pac_map.h | 170 +- .../want/include/ohos/aafwk/content/want.h | 1 + ...d.ts => @ohos.ability.featureAbility.d.ts} | 101 +- ....ts => @ohos.ability.particleAbility.d.ts} | 157 +- .../kits/js/@ohos.ability.wantConstant.d.ts | 341 ++ .../kits/js/@ohos.ability.wantconstant.d.ts | 263 - .../kits/js/@ohos.app.abilityManager.d.ts | 90 + .../kits/js/@ohos.app.abilitymanager.d.ts | 228 - interfaces/kits/js/@ohos.bundle.d.ts | 580 +-- .../abilityResult.d.ts} | 31 +- .../kits/js/ability/connectOptions.d.ts | 32 + ...ameter.d.ts => startAbilityParameter.d.ts} | 9 +- interfaces/kits/js/ability/want.d.ts | 74 +- ...ssioninfo.d.ts => abilityMissionInfo.d.ts} | 84 +- interfaces/kits/js/app/activeProcessInfo.d.ts | 53 + interfaces/kits/js/app/context.d.ts | 98 + .../{abilityinfo.d.ts => abilityInfo.d.ts} | 116 +- ...licationinfo.d.ts => applicationInfo.d.ts} | 83 +- .../{bundleinfo.d.ts => bundleInfo.d.ts} | 151 +- ...dleinstaller.d.ts => bundleInstaller.d.ts} | 170 +- interfaces/kits/js/bundle/customizeData.d.ts | 19 + .../{elementname.d.ts => elementName.d.ts} | 0 .../{moduleinfo.d.ts => moduleInfo.d.ts} | 0 ...moduleinfo.d.ts => moduleUsageRecord.d.ts} | 35 +- interfaces/kits/js/bundle/shortcutInfo.d.ts | 31 + interfaces/kits/napi/BUILD.gn | 2 + .../abilityManager/napi_ability_manager.cpp | 189 +- .../abilityManager/napi_ability_manager.h | 10 + .../aafwk/abilityManager/native_module.cpp | 4 + .../kits/napi/aafwk/dataUriUtils/BUILD.gn | 3 +- .../dataUriUtils/napi_data_uri_utils.cpp | 45 +- .../aafwk/featureAbility/feature_ability.cpp | 3436 ++----------- .../aafwk/featureAbility/feature_ability.h | 675 +-- .../aafwk/featureAbility/napi_context.cpp | 355 +- .../napi/aafwk/featureAbility/napi_context.h | 3 +- .../napi_data_ability_helper.cpp | 2021 +++++++- .../featureAbility/napi_data_ability_helper.h | 135 + .../kits/napi/aafwk/formAbility/BUILD.gn | 47 + .../aafwk/formAbility/napi_form_ability.cpp | 3327 ++++++++++++ .../aafwk/formAbility/napi_form_ability.h | 244 + .../napi/aafwk/formAbility/native_module.cpp | 114 + .../napi/aafwk/inner/napi_common/BUILD.gn | 1 + .../napi_common}/feature_ability_common.h | 128 +- .../inner/napi_common/napi_common_ability.cpp | 4551 +++++++++++++++++ .../inner/napi_common/napi_common_ability.h | 233 + .../inner/napi_common/napi_common_data.h | 4 + .../inner/napi_common/napi_common_error.h | 11 +- .../inner/napi_common/napi_common_util.cpp | 44 +- .../inner/napi_common/napi_common_util.h | 2 + .../inner/napi_common/napi_common_want.cpp | 21 +- .../inner/napi_common/napi_common_want.h | 2 + .../kits/napi/aafwk/particleAbility/BUILD.gn | 57 + .../aafwk/particleAbility/native_module.cpp | 55 + .../particleAbility/particle_ability.cpp | 264 + .../aafwk/particleAbility/particle_ability.h | 36 + .../napi/aafwk/wantConstant/want_constant.cpp | 82 +- .../napi/aafwk/wantConstant/want_constant.h | 1 + ohos.build | 3 +- services/abilitymgr/abilitymgr.gni | 7 + services/abilitymgr/include/ability_config.h | 87 +- .../include/ability_connect_manager.h | 2 + .../include/ability_manager_proxy.h | 82 +- .../include/ability_manager_service.h | 122 +- .../abilitymgr/include/ability_manager_stub.h | 11 + services/abilitymgr/include/ability_record.h | 118 +- .../include/ability_scheduler_proxy.h | 44 + .../include/ability_scheduler_stub.h | 5 + .../include/ability_stack_manager.h | 160 +- services/abilitymgr/include/ability_util.h | 140 +- services/abilitymgr/include/app_scheduler.h | 27 + .../abilitymgr/include/configuration_holder.h | 61 + .../include/data_ability_caller_recipient.h | 41 + .../abilitymgr/include/data_ability_manager.h | 5 +- .../abilitymgr/include/data_ability_record.h | 13 +- .../include/kernal_system_app_manager.h | 6 + services/abilitymgr/include/lifecycle_deal.h | 3 + services/abilitymgr/include/mission_record.h | 34 +- services/abilitymgr/include/mission_stack.h | 14 +- .../abilitymgr/include/pending_want_key.h | 10 +- .../abilitymgr/include/pending_want_manager.h | 14 +- services/abilitymgr/include/power_storage.h | 9 +- .../include/resume_mission_container.h | 43 + .../src/aafwk_dummy_configuration.cpp | 95 + .../src/ability_connect_callback_stub.cpp | 21 +- .../src/ability_connect_manager.cpp | 155 +- .../abilitymgr/src/ability_event_handler.cpp | 14 +- .../abilitymgr/src/ability_manager_client.cpp | 371 +- .../abilitymgr/src/ability_manager_proxy.cpp | 443 +- .../src/ability_manager_service.cpp | 554 +- .../abilitymgr/src/ability_manager_stub.cpp | 222 +- services/abilitymgr/src/ability_record.cpp | 316 +- .../src/ability_scheduler_proxy.cpp | 160 + .../abilitymgr/src/ability_scheduler_stub.cpp | 81 +- .../abilitymgr/src/ability_stack_manager.cpp | 2459 ++++++--- .../abilitymgr/src/ability_start_setting.cpp | 180 + services/abilitymgr/src/app_scheduler.cpp | 31 +- .../abilitymgr/src/configuration_holder.cpp | 89 + services/abilitymgr/src/connection_record.cpp | 4 +- .../src/data_ability_caller_recipient.cpp | 40 + .../abilitymgr/src/data_ability_manager.cpp | 49 +- .../abilitymgr/src/data_ability_record.cpp | 194 +- .../src/kernal_system_app_manager.cpp | 52 +- services/abilitymgr/src/lifecycle_deal.cpp | 38 +- .../abilitymgr/src/lifecycle_state_info.cpp | 12 +- services/abilitymgr/src/mission_option.cpp | 94 + services/abilitymgr/src/mission_record.cpp | 120 +- services/abilitymgr/src/mission_stack.cpp | 35 + .../src/pending_want_common_event.cpp | 2 +- services/abilitymgr/src/pending_want_key.cpp | 20 +- .../abilitymgr/src/pending_want_manager.cpp | 33 +- .../abilitymgr/src/pending_want_record.cpp | 20 +- services/abilitymgr/src/power_storage.cpp | 26 +- .../src/resume_mission_container.cpp | 70 + services/abilitymgr/src/sa_mgr_client.cpp | 2 +- services/abilitymgr/src/stack_setting.cpp | 55 + services/abilitymgr/test/BUILD.gn | 13 + .../test/mock/appmgr_test_service/BUILD.gn | 24 +- .../test/mock/include/mock_app_mgr_client.h | 1 - .../mock/include/mock_configuration_holder.h | 52 + .../abilitymgr/test/mock/libs/aakit/BUILD.gn | 19 +- .../libs/aakit/include/ability_scheduler.h | 8 + .../mock/libs/aakit/src/ability_scheduler.cpp | 20 + .../ability_scheduler_mock.h | 15 + .../test/mock/libs/appexecfwk_core/BUILD.gn | 28 +- .../include/appmgr/app_mgr_client.h | 256 +- .../include/appmgr/app_mgr_interface.h | 160 + .../include/appmgr/app_process_data.h | 60 + .../include/appmgr/app_state_callback_host.h | 43 +- .../include/appmgr/iapp_state_callback.h | 97 +- .../bundlemgr/bundle_installer_interface.h | 70 + .../include/bundlemgr/bundle_mgr_interface.h | 380 +- .../bundle_status_callback_interface.h | 66 + .../include/bundlemgr/mock_bundle_manager.h | 111 +- ...n_permission_changed_callback_interface.h} | 88 +- .../bundlemgr/status_receiver_interface.h | 102 + .../src/appmgr/app_mgr_client.cpp | 117 + .../src/appmgr/app_state_callback_host.cpp | 59 + .../src/appmgr/app_state_callback_proxy.cpp | 40 + .../src/appmgr/mock_app_manager.cpp | 229 +- .../src/bundlemgr/mock_bundle_manager.cpp | 44 +- .../BUILD.gn | 3 +- .../ability_connect_manage_test/BUILD.gn | 1 - .../ability_connect_manage_test.cpp | 3 +- .../phone/ability_manager_proxy_test/BUILD.gn | 4 +- .../ability_manager_stub_mock.h | 51 + .../ability_manager_service_test/BUILD.gn | 1 + .../ability_manager_service_test.cpp | 9 +- .../ability_manager_stub_impl_mock.h | 51 + .../phone/ability_manager_test/BUILD.gn | 7 +- .../ability_manager_stub_mock.h | 14 +- .../ability_record_test.cpp | 32 + .../ability_scheduler_proxy_test/BUILD.gn | 3 +- .../ability_schedule_stub_mock.h | 20 + .../phone/ability_stack_manager_test/BUILD.gn | 1 + .../ability_stack_manager_test.cpp | 1065 +++- .../mock_ability_scheduler.cpp | 21 + .../phone/abilityms_appms_test/BUILD.gn | 1 + .../abilityms_appms_test.cpp | 8 +- .../app_scheduler_test/app_scheduler_test.cpp | 1 + .../app_state_call_back_mock.h | 4 +- .../phone/configuration_holder_test/BUILD.gn | 65 + .../configuration_holder_test.cpp | 123 + .../connection_record_test.cpp | 1 + .../phone/data_ability_manager_test/BUILD.gn | 5 +- .../data_ability_manager_test.cpp | 23 +- .../data_ability_record_test.cpp | 63 +- .../test/unittest/phone/info_test/BUILD.gn | 3 +- .../unittest/phone/info_test/info_test.cpp | 12 +- .../kernal_system_app_manager_test.cpp | 25 + .../lifecycle_deal_test.cpp | 1 + .../mission_record_test.cpp | 80 + .../mission_stack_test/mission_stack_test.cpp | 55 + .../pending_want_manager_test.cpp | 50 +- .../resume_mission_container_test/BUILD.gn | 59 + .../resume_mission_container_test.cpp | 169 + .../terminate_ability_test.cpp | 3 + .../unittest/phone/wants_info_test/BUILD.gn | 1 + .../unittest/phone/window_info_test/BUILD.gn | 8 +- services/test/BUILD.gn | 6 +- .../mock/include/mock_ability_manager_proxy.h | 2 +- .../mock/include/mock_ability_mgr_service.h | 13 + .../mock/include/mock_ability_scheduler.h | 15 + .../include/mock_ability_scheduler_stub.h | 5 + .../test/mock/include/mock_app_mgr_client.h | 21 +- services/test/mock/include/mock_bundle_mgr.h | 30 +- .../test/mock/src/mock_app_mgr_client.cpp | 44 + services/test/mock/src/mock_bundle_mgr.cpp | 10 +- .../ability_mgr_service_test/BUILD.gn | 9 +- .../ability_mgr_module_test.cpp | 197 +- .../moduletest/ability_record_test/BUILD.gn | 5 + .../ability_record_module_test.cpp | 49 +- .../moduletest/ability_stack_test/BUILD.gn | 8 +- .../ability_stack_module_test.cpp | 2663 +++++++++- .../test/moduletest/dump_module_test/BUILD.gn | 3 +- .../dump_module_test/dump_module_test.cpp | 12 +- .../moduletest/ipc_ability_mgr_test/BUILD.gn | 3 +- .../ipc_ability_mgr_module_test.cpp | 2 +- .../ipc_ability_scheduler_test/BUILD.gn | 3 + .../panding_want_manager_test/BUILD.gn | 4 + .../panding_want_manager_test.cpp | 1 + tools/BUILD.gn | 0 tools/aa/BUILD.gn | 1 + tools/test/mock/mock_ability_manager_stub.h | 13 + tools/test/systemtest/aa/BUILD.gn | 7 + 359 files changed, 40270 insertions(+), 12137 deletions(-) mode change 100644 => 100755 frameworks/kits/ability/native/include/ability.h mode change 100755 => 100644 frameworks/kits/ability/native/include/ability_impl.h create mode 100644 frameworks/kits/ability/native/include/ability_keyevent.h create mode 100644 frameworks/kits/ability/native/include/ability_post_event_timeout.h create mode 100644 frameworks/kits/ability/native/include/ability_touchevent.h create mode 100755 frameworks/kits/ability/native/include/form_js_event_handler.h create mode 100755 frameworks/kits/ability/native/include/form_provider_client.h mode change 100644 => 100755 frameworks/kits/ability/native/src/ability.cpp mode change 100755 => 100644 frameworks/kits/ability/native/src/ability_impl.cpp create mode 100644 frameworks/kits/ability/native/src/ability_keyevent.cpp create mode 100644 frameworks/kits/ability/native/src/ability_post_event_timeout.cpp mode change 100755 => 100644 frameworks/kits/ability/native/src/ability_thread.cpp create mode 100644 frameworks/kits/ability/native/src/ability_touchevent.cpp create mode 100644 frameworks/kits/ability/native/src/form_js_event_handler.cpp create mode 100755 frameworks/kits/ability/native/src/form_provider_client.cpp create mode 100644 frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_for_data_ability_observer.h create mode 100644 frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h create mode 100644 frameworks/kits/ability/native/test/mock/include/mock_ability_thread_for_ability_on_configuration_update.h create mode 100644 frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.cpp create mode 100644 frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h create mode 100755 frameworks/kits/ability/native/test/mock/include/mock_form_mgr_service.h create mode 100644 frameworks/kits/ability/native/test/mock/include/mock_form_supply_callback.cpp create mode 100644 frameworks/kits/ability/native/test/mock/include/mock_form_supply_callback.h create mode 100644 frameworks/kits/ability/native/test/unittest/ability_thread_for_ability_on_configuration_update.cpp create mode 100755 frameworks/kits/ability/native/test/unittest/form_ability_test.cpp create mode 100644 frameworks/kits/ability/native/test/unittest/form_host_client_test.cpp create mode 100644 frameworks/kits/ability/native/test/unittest/form_provider_client_test.cpp mode change 100644 => 100755 frameworks/kits/base/cpp/src/ohos/aafwk/base/base.cpp delete mode 100755 frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_array.cpp delete mode 100755 frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_base.cpp delete mode 100755 frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_user_object.cpp create mode 100755 frameworks/kits/base/cpp/src/ohos/aafwk/base/user_object_wrapper.cpp create mode 100644 frameworks/kits/test/mock/DemoAbility/mock_ability_test.h rename frameworks/kits/{base/cpp/src/ohos/aafwk/base/pac_map_node.cpp => test/mock/DemoObServer/mock_ability_hancle_for_data_observer.h} (64%) create mode 100644 frameworks/kits/test/mock/DemoObServer/mock_ability_manager_client.h create mode 100644 frameworks/kits/test/mock/DemoObServer/mock_ability_thread_for_data_observer.h create mode 100644 frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_helper_module_test.cpp create mode 100644 frameworks/kits/tools/BUILD.gn create mode 100644 frameworks/kits/tools/simulateEntryAbility/BUILD.gn create mode 100644 frameworks/kits/tools/simulateEntryAbility/config.json create mode 100644 frameworks/kits/tools/simulateEntryAbility/include/simulate_entry_ability_fir.h create mode 100644 frameworks/kits/tools/simulateEntryAbility/include/simulate_entry_ability_sed.h create mode 100644 frameworks/kits/tools/simulateEntryAbility/src/simulate_entry_ability_fir.cpp create mode 100644 frameworks/kits/tools/simulateEntryAbility/src/simulate_entry_ability_sed.cpp create mode 100644 frameworks/kits/tools/simulateFeatureAbility/BUILD.gn create mode 100644 frameworks/kits/tools/simulateFeatureAbility/config.json create mode 100644 frameworks/kits/tools/simulateFeatureAbility/include/simulate_feature_ability_fir.h create mode 100644 frameworks/kits/tools/simulateFeatureAbility/include/simulate_feature_ability_sed.h create mode 100644 frameworks/kits/tools/simulateFeatureAbility/src/simulate_feature_ability_fir.cpp create mode 100644 frameworks/kits/tools/simulateFeatureAbility/src/simulate_feature_ability_sed.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/BUILD.gn create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/config.json create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_data_first_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_eighth_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_fifth_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_first_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_fourth_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_ninth_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_second_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_seventh_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_sixth_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_tenth_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_third_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_service_first_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_data_first_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_eighth_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_fifth_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_first_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_fourth_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_ninth_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_second_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_seventh_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_sixth_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_tenth_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_third_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_service_first_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/BUILD.gn create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/config.json create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_eighth_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_fifth_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_first_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_fourth_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_ninth_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_second_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_seventh_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_sixth_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_tenth_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_third_ability.h create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_eighth_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_fifth_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_first_ability.cpp rename interfaces/kits/js/ability/abilityresult.d.ts => frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_fourth_ability.cpp (45%) create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_ninth_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_second_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_seventh_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_sixth_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_tenth_ability.cpp create mode 100644 frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_third_ability.cpp mode change 100644 => 100755 interfaces/innerkits/ability_manager/BUILD.gn create mode 100644 interfaces/innerkits/ability_manager/include/aafwk_dummy_configuration.h create mode 100644 interfaces/innerkits/ability_manager/include/ability_start_setting.h create mode 100644 interfaces/innerkits/ability_manager/include/ability_window_configuration.h create mode 100644 interfaces/innerkits/ability_manager/include/mission_option.h create mode 100644 interfaces/innerkits/ability_manager/include/stack_setting.h mode change 100644 => 100755 interfaces/innerkits/base/BUILD.gn mode change 100644 => 100755 interfaces/innerkits/base/include/ohos/aafwk/base/base_interfaces.h delete mode 100644 interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node.h delete mode 100644 interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node_array.h delete mode 100755 interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node_base.h rename interfaces/innerkits/base/include/ohos/aafwk/base/{pac_map_node_user_object.h => user_object_base.h} (36%) create mode 100755 interfaces/innerkits/base/include/ohos/aafwk/base/user_object_wrapper.h mode change 100644 => 100755 interfaces/innerkits/want/include/ohos/aafwk/content/pac_map.h rename interfaces/kits/js/{@ohos.ability.featureability.d.ts => @ohos.ability.featureAbility.d.ts} (48%) rename interfaces/kits/js/{app/runningprocessinfo.d.ts => @ohos.ability.particleAbility.d.ts} (32%) mode change 100755 => 100644 create mode 100644 interfaces/kits/js/@ohos.ability.wantConstant.d.ts delete mode 100644 interfaces/kits/js/@ohos.ability.wantconstant.d.ts create mode 100644 interfaces/kits/js/@ohos.app.abilityManager.d.ts delete mode 100644 interfaces/kits/js/@ohos.app.abilitymanager.d.ts rename interfaces/kits/js/{app/processinfo.d.ts => ability/abilityResult.d.ts} (60%) create mode 100644 interfaces/kits/js/ability/connectOptions.d.ts rename interfaces/kits/js/ability/{startabilityparameter.d.ts => startAbilityParameter.d.ts} (81%) rename interfaces/kits/js/app/{abilitymissioninfo.d.ts => abilityMissionInfo.d.ts} (34%) create mode 100644 interfaces/kits/js/app/activeProcessInfo.d.ts create mode 100755 interfaces/kits/js/app/context.d.ts rename interfaces/kits/js/bundle/{abilityinfo.d.ts => abilityInfo.d.ts} (92%) rename interfaces/kits/js/bundle/{applicationinfo.d.ts => applicationInfo.d.ts} (90%) rename interfaces/kits/js/bundle/{bundleinfo.d.ts => bundleInfo.d.ts} (84%) rename interfaces/kits/js/bundle/{bundleinstaller.d.ts => bundleInstaller.d.ts} (94%) create mode 100644 interfaces/kits/js/bundle/customizeData.d.ts rename interfaces/kits/js/bundle/{elementname.d.ts => elementName.d.ts} (100%) rename interfaces/kits/js/bundle/{moduleinfo.d.ts => moduleInfo.d.ts} (100%) rename interfaces/kits/js/bundle/{hapmoduleinfo.d.ts => moduleUsageRecord.d.ts} (52%) create mode 100644 interfaces/kits/js/bundle/shortcutInfo.d.ts mode change 100755 => 100644 interfaces/kits/napi/BUILD.gn mode change 100644 => 100755 interfaces/kits/napi/aafwk/featureAbility/feature_ability.h create mode 100644 interfaces/kits/napi/aafwk/formAbility/BUILD.gn create mode 100644 interfaces/kits/napi/aafwk/formAbility/napi_form_ability.cpp create mode 100755 interfaces/kits/napi/aafwk/formAbility/napi_form_ability.h create mode 100755 interfaces/kits/napi/aafwk/formAbility/native_module.cpp rename interfaces/kits/napi/aafwk/{featureAbility => inner/napi_common}/feature_ability_common.h (62%) mode change 100755 => 100644 create mode 100755 interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp create mode 100755 interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h create mode 100755 interfaces/kits/napi/aafwk/particleAbility/BUILD.gn create mode 100755 interfaces/kits/napi/aafwk/particleAbility/native_module.cpp create mode 100755 interfaces/kits/napi/aafwk/particleAbility/particle_ability.cpp create mode 100755 interfaces/kits/napi/aafwk/particleAbility/particle_ability.h create mode 100644 services/abilitymgr/include/configuration_holder.h create mode 100644 services/abilitymgr/include/data_ability_caller_recipient.h create mode 100644 services/abilitymgr/include/resume_mission_container.h create mode 100644 services/abilitymgr/src/aafwk_dummy_configuration.cpp create mode 100644 services/abilitymgr/src/ability_start_setting.cpp create mode 100644 services/abilitymgr/src/configuration_holder.cpp create mode 100644 services/abilitymgr/src/data_ability_caller_recipient.cpp create mode 100644 services/abilitymgr/src/mission_option.cpp create mode 100644 services/abilitymgr/src/resume_mission_container.cpp create mode 100644 services/abilitymgr/src/stack_setting.cpp mode change 100644 => 100755 services/abilitymgr/test/mock/appmgr_test_service/BUILD.gn create mode 100644 services/abilitymgr/test/mock/include/mock_configuration_holder.h mode change 100644 => 100755 services/abilitymgr/test/mock/libs/aakit/BUILD.gn create mode 100644 services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_interface.h create mode 100644 services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_process_data.h create mode 100644 services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_installer_interface.h create mode 100644 services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_status_callback_interface.h rename services/abilitymgr/test/mock/libs/appexecfwk_core/include/{appmgr/app_mgr_constants.h => bundlemgr/on_permission_changed_callback_interface.h} (48%) create mode 100644 services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/status_receiver_interface.h create mode 100644 services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp create mode 100644 services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_state_callback_host.cpp create mode 100644 services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp create mode 100644 services/abilitymgr/test/unittest/phone/configuration_holder_test/BUILD.gn create mode 100644 services/abilitymgr/test/unittest/phone/configuration_holder_test/configuration_holder_test.cpp create mode 100644 services/abilitymgr/test/unittest/phone/resume_mission_container_test/BUILD.gn create mode 100644 services/abilitymgr/test/unittest/phone/resume_mission_container_test/resume_mission_container_test.cpp mode change 100644 => 100755 services/test/BUILD.gn create mode 100644 services/test/mock/src/mock_app_mgr_client.cpp mode change 100644 => 100755 services/test/moduletest/ability_mgr_service_test/BUILD.gn mode change 100644 => 100755 services/test/moduletest/ability_record_test/BUILD.gn mode change 100644 => 100755 services/test/moduletest/ability_stack_test/BUILD.gn mode change 100644 => 100755 services/test/moduletest/ipc_ability_mgr_test/BUILD.gn mode change 100644 => 100755 services/test/moduletest/ipc_ability_scheduler_test/BUILD.gn mode change 100644 => 100755 services/test/moduletest/panding_want_manager_test/BUILD.gn mode change 100644 => 100755 tools/BUILD.gn mode change 100644 => 100755 tools/aa/BUILD.gn mode change 100644 => 100755 tools/test/systemtest/aa/BUILD.gn diff --git a/frameworks/kits/ability/native/BUILD.gn b/frameworks/kits/ability/native/BUILD.gn index 63007ba61fd..453d91e6c26 100755 --- a/frameworks/kits/ability/native/BUILD.gn +++ b/frameworks/kits/ability/native/BUILD.gn @@ -29,14 +29,18 @@ config("ability_config") { "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/appexecfwk/standard/common/log/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr", "//foundation/appexecfwk/standard/kits/appkit/native/app/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//base/global/resmgr_standard/interfaces/innerkits/include", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility", "//foundation/ace/napi/interfaces/kits", "//third_party/node/src", - "//foundation/multimodalinput/input/interfaces/native/innerkits/event/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - + "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/kits", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/dispatcher", "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/task", "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/threading", @@ -62,12 +66,17 @@ config("ability_public_config") { "${SUBSYSTEM_DIR}/include", "//third_party/libuv/include", "//foundation/aafwk/standard/interfaces/innerkits/base/include/ohos/aafwk/base", - "//foundation/multimodalinput/input/interfaces/native/innerkits/event/include", + "//base/global/resmgr_standard/interfaces/innerkits/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/kits", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include", ] } ohos_shared_library("abilitykit_native") { + cflags = [ + #"-DMMI_COMPILE" + ] + sources = [ "${SUBSYSTEM_APPEXEXFWK_DIR}/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp", "${SUBSYSTEM_DIR}/src/ability.cpp", @@ -75,12 +84,15 @@ ohos_shared_library("abilitykit_native") { "${SUBSYSTEM_DIR}/src/ability_handler.cpp", "${SUBSYSTEM_DIR}/src/ability_impl.cpp", "${SUBSYSTEM_DIR}/src/ability_impl_factory.cpp", + "${SUBSYSTEM_DIR}/src/ability_keyevent.cpp", "${SUBSYSTEM_DIR}/src/ability_lifecycle.cpp", "${SUBSYSTEM_DIR}/src/ability_lifecycle_executor.cpp", "${SUBSYSTEM_DIR}/src/ability_loader.cpp", "${SUBSYSTEM_DIR}/src/ability_local_record.cpp", + "${SUBSYSTEM_DIR}/src/ability_post_event_timeout.cpp", "${SUBSYSTEM_DIR}/src/ability_process.cpp", "${SUBSYSTEM_DIR}/src/ability_thread.cpp", + "${SUBSYSTEM_DIR}/src/ability_touchevent.cpp", "${SUBSYSTEM_DIR}/src/ability_window.cpp", "${SUBSYSTEM_DIR}/src/data_ability_helper.cpp", "${SUBSYSTEM_DIR}/src/data_ability_impl.cpp", @@ -89,16 +101,21 @@ ohos_shared_library("abilitykit_native") { "${SUBSYSTEM_DIR}/src/data_ability_result.cpp", "${SUBSYSTEM_DIR}/src/data_uri_utils.cpp", "${SUBSYSTEM_DIR}/src/dummy_data_ability_predicates.cpp", + "${SUBSYSTEM_DIR}/src/dummy_result_set.cpp", "${SUBSYSTEM_DIR}/src/dummy_values_bucket.cpp", + "${SUBSYSTEM_DIR}/src/form_js_event_handler.cpp", + "${SUBSYSTEM_DIR}/src/form_provider_client.cpp", "${SUBSYSTEM_DIR}/src/mission_information.cpp", "${SUBSYSTEM_DIR}/src/page_ability_impl.cpp", "${SUBSYSTEM_DIR}/src/service_ability_impl.cpp", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp", - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ability_start_setting.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/ability_start_setting.cpp", + + # "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp", + # "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp", + # "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp", + # "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp", + # "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp", + # "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp", "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp", "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_deal.cpp", @@ -110,21 +127,26 @@ ohos_shared_library("abilitykit_native") { deps = [ "${INNERKITS_PATH}/base:base", "${INNERKITS_PATH}/want:want", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", - "//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/appexecfwk/standard/interfaces/innerkits/fmskit:fmskit_native", "//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/interfaces/native/innerkits/event:mmi_event", "//utils/native/base:utils", ] external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + + #"multimodalinput_base:libmmi-util", + #"multimodalinput_base:libmmi-client", + #"multimodalinput_base:mmi_event", ] public_deps = [ diff --git a/frameworks/kits/ability/native/include/ability.h b/frameworks/kits/ability/native/include/ability.h old mode 100644 new mode 100755 index 53f92b7ed41..6622c9e1deb --- a/frameworks/kits/ability/native/include/ability.h +++ b/frameworks/kits/ability/native/include/ability.h @@ -24,10 +24,8 @@ #include #include "context.h" #include "want.h" -#include "key_event.h" #include "dummy_component_container.h" #include "pac_map.h" -#include "touch_event.h" #include "dummy_notification_request.h" #include "dummy_data_ability_predicates.h" #include "dummy_values_bucket.h" @@ -35,14 +33,32 @@ #include "dummy_continuation_state.h" #include "dummy_ability_package.h" #include "dummy_configuration.h" +#include "aafwk_dummy_configuration.h" #include "ability_window.h" #include "ability_lifecycle_interface.h" #include "ability_lifecycle_executor.h" +#include "ability_continuation_interface.h" + +#include "form_callback_interface.h" +#include "form_constants.h" +#include "form_death_callback.h" +#include "form_provider_info.h" +#include "form_info.h" + +#ifndef MMI_COMPILE +#include "key_event.h" +#include "touch_event.h" +#endif using Uri = OHOS::Uri; namespace OHOS { +#ifdef MMI_COMPILE +class KeyEvent; +class TouchEvent; +#endif namespace AppExecFwk { +class AbilityPostEventTimeout; class OHOSApplication; class AbilityHandler; class AbilityWindow; @@ -50,6 +66,8 @@ class ILifeCycle; class Ability : public IAbilityEvent, public ILifeCycle, public AbilityContext, + public FormCallbackInterface, + public IAbilityContinuation, public std::enable_shared_from_this { public: Ability() = default; @@ -537,7 +555,7 @@ public: * @param resultData Indicates the data returned after the ability is destroyed. You can define the data returned. * This parameter can be null. */ - virtual void SetResult(int resultCode, /*const AAFwk::Want& resultData*/ const Want &resultData) final; + virtual void SetResult(int resultCode, const Want &resultData) final; /** * @brief Sets the type of audio whose volume will be adjusted by the volume button. @@ -600,7 +618,7 @@ public: * * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. */ - virtual const std::shared_ptr NormalizeUri(const Uri &uri); + virtual Uri NormalizeUri(const Uri &uri); /** * @brief Deletes one or more data records. This method should be implemented by a Data ability. @@ -725,7 +743,7 @@ public: * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found * in the current environment. */ - virtual std::shared_ptr DenormalizeUri(const Uri &uri); + virtual Uri DenormalizeUri(const Uri &uri); /** * @brief Reloads data in the database. @@ -837,22 +855,533 @@ public: */ void TerminateAndRemoveMission() override; + /** + * @brief Create a PostEvent timeout task. The default delay is 5000ms + * + * @return Return a smart pointer to a timeout object + */ + std::shared_ptr CreatePostEventTimeouter(std::string taskstr); + + /** + * Releases an obtained form by its ID. + * + *

After this method is called, the form won't be available for use by the application, but the Form Manager + * Service still keeps the cache information about the form, so that the application can quickly obtain it based on + * the {@code formId}.

+ *

Permission: {@link ohos.security.SystemPermission#REQUIRE_FORM}

+ * + * @param formId Indicates the form ID. + * @return Returns {@code true} if the form is successfully released; returns {@code false} otherwise. + * + *
    + *
  • The passed {@code formId} is invalid. Its value must be larger than 0.
  • + *
  • The specified form has not been added by the application.
  • + *
  • An error occurred when connecting to the Form Manager Service.
  • + *
  • The application is not granted with the {@link ohos.security.SystemPermission#REQUIRE_FORM} permission.
  • + *
  • The form has been obtained by another application and cannot be released by the current application.
  • + *
  • The form is being restored.
  • + *
+ */ + bool ReleaseForm(const int64_t formId); + + /** + * @brief Releases an obtained form by its ID. + * + *

After this method is called, the form won't be available for use by the application, if isReleaseCache is + * false, this method is same as {@link #releaseForm(int)}, otherwise the Form Manager Service still store this + * form in the cache.

+ *

Permission: {@link ohos.security.SystemPermission#REQUIRE_FORM}

+ * + * @param formId Indicates the form ID. + * @param isReleaseCache Indicates whether to clear cache in service. + * @return Returns {@code true} if the form is successfully released; returns {@code false} otherwise. + * + *
    + *
  • The passed {@code formId} is invalid. Its value must be larger than 0.
  • + *
  • The specified form has not been added by the application.
  • + *
  • An error occurred when connecting to the Form Manager Service.
  • + *
  • The application is not granted with the {@link ohos.security.SystemPermission#REQUIRE_FORM} permission.
  • + *
  • The form has been obtained by another application and cannot be released by the current application.
  • + *
  • The form is being restored.
  • + *
+ */ + bool ReleaseForm(const int64_t formId, const bool isReleaseCache); + + /** + * @brief Deletes an obtained form by its ID. + * + *

After this method is called, the form won't be available for use by the application and the Form Manager + * Service no longer keeps the cache information about the form.

+ *

Permission: {@link ohos.security.SystemPermission#REQUIRE_FORM}

+ * + * @param formId Indicates the form ID. + * @return Returns {@code true} if the form is successfully deleted; returns {@code false} otherwise. + * + *
    + *
  • The passed {@code formId} is invalid. Its value must be larger than 0.
  • + *
  • The specified form has not been added by the application.
  • + *
  • An error occurred when connecting to the Form Manager Service.
  • + *
  • The application is not granted with the {@link ohos.security.SystemPermission#REQUIRE_FORM} permission.
  • + *
  • The form has been obtained by another application and cannot be deleted by the current application.
  • + *
  • The form is being restored.
  • + *
+ */ + bool DeleteForm(const int64_t formId); + + /** + * @brief The form callback. + */ + class FormCallback { + public: + static const int32_t OHOS_FORM_ACQUIRE_SUCCESS = 0; + static const int32_t OHOS_FORM_UPDATE_SUCCESS = 0; + static const int32_t OHOS_FORM_PREVIEW_FAILURE = 1; + static const int32_t OHOS_FORM_RESTORE_FAILURE = 2; + + /** + * @brief Called to notify the application that the {@code FormJsInfo} instance has been obtained after + * the application called the asynchronous method {@link Ability#acquireForm(Want, FormCallback)}. + * The application must present the form information on a specific page in this callback. + * + * @param result Specifies whether the asynchronous form acquisition process is successful. + * {@link FormCallback#OHOS_FORM_ACQUIRE_SUCCESS} indicates that the form + * is successfully obtained, and other values indicate that the process fails. + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ + virtual void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const = 0; + + /** + * @brief Called to notify the application that the {@code FormJsInfo} instance has been obtained after + * the application called the asynchronous method {@link Ability#acquireForm(Want, FormCallback)}. + * The application must present the form information on a specific page in this callback. + * + * @param result Specifies whether the asynchronous form acquisition process is successful. + * {@link FormCallback#OHOS_FORM_UPDATE_SUCCESS} indicates that the form is + * successfully obtained, and other values indicate that the process fails. + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ + virtual void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const = 0; + + /** + * @brief Called to notify the application that the {@code Form} provider has been uninstalled and the + * corresponding + * {@code Form} instance is no longer available. + * + * @param formId Indicates the ID of the {@code Form} instance provided by the uninstalled form provider. + */ + virtual void OnFormUninstall(const int64_t formId) const = 0; + }; + + /** + * @brief Obtains a specified form that matches the application bundle name, module name, form name, and + * other related information specified in the passed {@code Want}. + * + *

This method is asynchronous. After the {@link FormJsInfo} instance is obtained. + * + * @param formId Indicates the form ID. + * @param want Indicates the detailed information about the form to be obtained, including the bundle name, + * module name, ability name, form name, form id, tempForm flag, form dimension, and form customize data. + * @param callback Indicates the callback to be invoked whenever the {@link FormJsInfo} instance is obtained. + * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise. + */ + bool AcquireForm(const int64_t formId, const Want &want, const std::shared_ptr callback); + + /** + * @brief Updates the content of a specified JS form. + * + *

This method is called by a form provider to update JS form data as needed. + * + * @param formId Indicates the form ID. + * @param formProviderData The data used to update the JS form displayed on the client. + * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise. + */ + bool UpdateForm(const int64_t formId, const FormProviderData &formProviderData); + + /** + * @brief Cast temp form with formId. + * + * @param formId Indicates the form's ID. + * + * @return Returns {@code true} if the form is successfully casted; returns {@code false} otherwise. + */ + bool CastTempForm(const int64_t formId); + + /** + * @brief Sends a notification to the form framework to make the specified forms visible. + * + *

After this method is successfully called, {@link Ability#OnVisibilityChanged(std::map)} + * will be called to notify the form provider of the form visibility change event.

+ * + * @param formIds Indicates the IDs of the forms to be made visible. + * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise. + */ + bool NotifyVisibleForms(const std::vector &formIds); + + /** + * @brief Sends a notification to the form framework to make the specified forms invisible. + * + *

After this method is successfully called, {@link Ability#OnVisibilityChanged(std::map)} + * will be called to notify the form provider of the form visibility change event.

+ * + * @param formIds Indicates the IDs of the forms to be made invisible. + * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise. + */ + bool NotifyInvisibleForms(const std::vector &formIds); + + /** + * @brief Set form next refresh time. + * + *

This method is called by a form provider to set refresh time. + * + * @param formId Indicates the ID of the form to set refresh time. + * @param nextTime Indicates the next time gap now in seconds, can not be litter than 300 seconds. + * @return Returns {@code true} if seting succeed; returns {@code false} otherwise. + */ + + bool SetFormNextRefreshTime(const int64_t formId, const int64_t nextTime); + + /** + * @brief Update form. + * + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ + void ProcessFormUpdate(const FormJsInfo &formJsInfo) override; + + /** + * @brief Uninstall form. + * + * @param formId Indicates the ID of the form to uninstall. + */ + void ProcessFormUninstall(const int64_t formId) override; + + /** + * @brief Called to reacquire form and update the form host after the death callback is received. + * + */ + void OnDeathReceived() override; + + /** + * @brief Called to return a FormProviderInfo object. + * + *

You must override this method if your ability will serve as a form provider to provide a form for clients. + * The default implementation returns nullptr.

+ * + * @param want Indicates the detailed information for creating a FormProviderInfo. + * The Want object must include the form ID, form name of the form, + * which can be obtained from Ability#PARAM_FORM_IDENTITY_KEY, + * Ability#PARAM_FORM_NAME_KEY, and Ability#PARAM_FORM_DIMENSION_KEY, + * respectively. Such form information must be managed as persistent data for further form + * acquisition, update, and deletion. + * + * @return Returns the created FormProviderInfo object. + */ + virtual FormProviderInfo OnCreate(const Want &want); + + /** + * @brief Called to notify the form provider that a specified form has been deleted. Override this method if + * you want your application, as the form provider, to be notified of form deletion. + * + * @param formId Indicates the ID of the deleted form. + * @return None. + */ + virtual void OnDelete(const int64_t formId); + + /** + * @brief Called when the form provider is notified that a temporary form is successfully converted to + * a normal form. + * + * @param formId Indicates the ID of the form. + * @return None. + */ + virtual void OnCastTemptoNormal(const int64_t formId); + + /** + * @brief Called to notify the form provider to update a specified form. + * + * @param formId Indicates the ID of the form to update. + * @return none. + */ + virtual void OnUpdate(const int64_t formId); + + /** + * @brief Called when the form provider receives form events from the fms. + * + * @param formEventsMap Indicates the form events occurred. The key in the Map object indicates the form ID, + * and the value indicates the event type, which can be either FORM_VISIBLE + * or FORM_INVISIBLE. FORM_VISIBLE means that the form becomes visible, + * and FORM_INVISIBLE means that the form becomes invisible. + * @return none. + */ + virtual void OnVisibilityChanged(const std::map &formEventsMap); + /** + * @brief Called to notify the form provider to update a specified form. + * + * @param formId Indicates the ID of the form to update. + * @param message Form event message. + */ + virtual void OnTriggerEvent(const int64_t formId, const std::string &message); + /** + * @brief Requests for form data update. + * + * This method must be called when the application has detected that a system setting item (such as the language, + * resolution, or screen orientation) being listened for has changed. Upon receiving the update request, the form + * provider automatically updates the form data (if there is any update) through the form framework, with the update + * process being unperceivable by the application. + * + * @param formId Indicates the ID of the form to update. + * @return Returns true if the update request is successfully initiated, returns false otherwise. + */ + bool RequestForm(const int64_t formId); + + /** + * @brief Requests for form data update, by passing a set of parameters (using Want) to the form provider. + * + * This method must be called when the application has detected that a system setting item (such as the language, + * resolution, or screen orientation) being listened for has changed. Upon receiving the update request, the form + * provider automatically updates the form data (if there is any update) through the form framework, with the update + * process being unperceivable by the application. + * + * @param formId Indicates the ID of the form to update. + * @param want Indicates a set of parameters to be transparently passed to the form provider. + * @return Returns true if the update request is successfully initiated, returns false otherwise. + */ + bool RequestForm(const int64_t formId, const Want &want); + /** + * @brief Enable form update. + * + * @param formIds formIds of hostclient. + */ + bool EnableUpdateForm(const std::vector &formIds); + + /** + * @brief Disable form update. + * + * @param formIds formIds of hostclient. + */ + bool DisableUpdateForm(const std::vector &formIds); + + /** + * @brief Check form manager service ready. + * + * @return Returns true if form manager service ready; returns false otherwise. + */ + bool CheckFMSReady(); + + /** + * @brief Get All FormsInfo. + * + * @param formInfos Returns the forms' information of all forms provided. + * @return Returns true if the request is successfully initiated; returns false otherwise. + */ + bool GetAllFormsInfo(std::vector &formInfos); + + /** + * @brief Get forms info by application name. + * + * @param bundleName Application name. + * @param formInfos Returns the forms' information of the specify application name. + * @return Returns true if the request is successfully initiated; returns false otherwise. + */ + bool GetFormsInfoByApp(std::string &bundleName, std::vector &formInfos); + + /** + * @brief Get forms info by application name and module name. + * + * @param bundleName Application name. + * @param moduleName Module name of hap. + * @param formInfos Returns the forms' information of the specify application name and module name. + * @return Returns true if the request is successfully initiated; returns false otherwise. + */ + bool GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, std::vector &formInfos); + + /** + * @brief Acquire a bundle manager, if it not existed, + * @return returns the bundle manager ipc object, or nullptr for failed. + */ + sptr GetBundleMgr(); + + /** + * @brief check permission of bundle, if it not existed. + * @return returns the permission is vaild, or false for failed. + */ + bool CheckPermission(); + + /** + * @brief Add the bundle manager instance for debug. + * @param bundleManager the bundle manager ipc object. + */ + void SetBundleManager(const sptr &bundleManager); + + /** + * @brief Migrates this ability to another device on the same distributed network. If there are multiple candidate + * devices, a pop-up will be displayed for users to choose the desired one. The ability to migrate and its ability + * slices must implement the IAbilityContinuation interface. + * + */ + virtual void ContinueAbility() final; + + /** + * @brief Migrates this ability to the given device on the same distributed network. The ability to migrate and its + * ability slices must implement the IAbilityContinuation interface. + * + * @param deviceId Indicates the ID of the target device where this ability will be migrated to. If this parameter + * is null, this method has the same effect as continueAbility(). + * + */ + virtual void ContinueAbility(const std::string &deviceId) final; + + /** + * @brief Callback function to ask the user whether to start the migration . + * + * @return If the user allows migration, it returns true; otherwise, it returns false. + */ + virtual bool OnStartContinuation() override; + + /** + * @brief Save user data of local Ability generated at runtime. + * + * @param saveData Indicates the user data to be saved. + * @return If the data is saved successfully, it returns true; otherwise, it returns false. + */ + virtual bool OnSaveData(WantParams &saveData) override; + + /** + * @brief After creating the Ability on the remote device, + * immediately restore the user data saved during the migration of the Ability on the remote device. + * @param restoreData Indicates the user data to be restored. + * @return If the data is restored successfully, it returns true; otherwise, it returns false . + */ + virtual bool OnRestoreData(WantParams &restoreData) override; + + /** + * @brief This function can be used to implement the processing logic after the migration is completed. + * + * @param result Migration result code. 0 means the migration was successful, -1 means the migration failed. + * @return None. + */ + virtual void OnCompleteContinuation(int result) override; + + /** + * @brief Used to notify the local Ability that the remote Ability has been destroyed. + * + * @return None. + */ + virtual void OnRemoteTerminated() override; + +protected: + /** + * @brief Acquire a form provider remote object. + * @return Returns form provider remote object. + */ + sptr GetFormRemoteObject(); + private: std::shared_ptr abilityInfo_ = nullptr; - std::shared_ptr context_; - std::shared_ptr handler_; + std::shared_ptr context_ = nullptr; + std::shared_ptr handler_ = nullptr; std::shared_ptr lifecycle_ = nullptr; std::shared_ptr abilityLifecycleExecutor_ = nullptr; - std::shared_ptr application_; + std::shared_ptr application_ = nullptr; std::vector types_; std::shared_ptr abilityWindow_ = nullptr; - std::shared_ptr setWant_; + std::shared_ptr setWant_ = nullptr; bool bWindowFocus_ = false; static const std::string SYSTEM_UI; static const std::string STATUS_BAR; static const std::string NAVIGATION_BAR; + + sptr providerRemoteObject_ = nullptr; + std::vector lostedByReconnectTempForms_; + std::map> appCallbacks_; + std::map userReqParams_; + sptr iBundleMgr_; + + static const int32_t OHOS_FORM_ACQUIRE_FORM = 0; + static const int32_t OHOS_FORM_UPDATE_FORM = 1; + + static const int32_t DELETE_FORM = 3; + static const int32_t ENABLE_FORM_UPDATE = 5; + static const int32_t DISABLE_FORM_UPDATE = 6; + static const int32_t RELEASE_FORM = 8; + static const int32_t RELEASE_CACHED_FORM = 9; + static const int64_t MIN_NEXT_TIME = 5; + +private: + /** + * @brief Delete or release form with formId. + * + * @param formId Indicates the form's ID. + * @param deleteType Indicates the type of delete or release. + * @return Returns {@code true} if the form is successfully deleted; returns {@code false} otherwise. + */ + bool DeleteForm(const int64_t formId, const int32_t deleteType); + + /** + * @brief Clean form resource with formId. + * + * @param formId Indicates the form's ID. + */ + void CleanFormResource(const int64_t formId); + + /** + * @brief Handle acquire result of the obtained form instance. + * + * @param want Indicates the detailed information about the form to be obtained, including the bundle name, + * module name, ability name, form name, form id, tempForm flag, form dimension, and form customize data. + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + * @param callback Indicates the callback to be invoked whenever the {@link FormJsInfo} instance is obtained. + */ + void HandleAcquireResult( + const Want &want, const FormJsInfo &formJsInfo, const std::shared_ptr callback); + + /** + * @brief Handle acquire message of the obtained form instance. + * + * @param msgCode Indicates the code of message type. + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ + void HandleFormMessage(const int32_t msgCode, const FormJsInfo &formJsInfo); + + /** + * @brief Notify the forms visibility change event. + * + * @param formIds Indicates the IDs of the forms to be made visible or invisible. + * @param eventType Indicates the form events occurred. FORM_VISIBLE means that the form becomes visible, + * and FORM_INVISIBLE means that the form becomes invisible. + * @return none. + */ + bool NotifyWhetherVisibleForms(const std::vector &formIds, int32_t eventType); + + /** + * @brief Check the param of want. + * + * @param formId Indicates the form's ID. + * @param want Indicates the detailed information about the form to be obtained, including the bundle name, + * module name, ability name, form name, form id, tempForm flag, form dimension, and form customize data. + * @return Returns {@code true} if the check result is ok; returns {@code false} ng. + */ + bool CheckWantValid(const int64_t formId, const Want &want); + + /** + * @brief Handle enable/disable form update. + * + * @param formIds Indicates the IDs of the forms to be made visible. + * @param updateType Update type. + * @return Returns true if the result is ok; returns false otherwise. + */ + bool LifecycleUpdate(std::vector formIds, int32_t updateType); + + /** + * @brief Reacquire a specified form when the death callback is received. + * + * @param formId Indicates the form ID. + * @param want Indicates the detailed information about the form to be obtained. + * @return Returns true if the request is successfully initiated; returns false otherwise. + */ + bool ReAcquireForm(const int64_t formId, const Want &want); }; + } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_H diff --git a/frameworks/kits/ability/native/include/ability_impl.h b/frameworks/kits/ability/native/include/ability_impl.h old mode 100755 new mode 100644 index 23347bd9702..357929720e1 --- a/frameworks/kits/ability/native/include/ability_impl.h +++ b/frameworks/kits/ability/native/include/ability_impl.h @@ -25,13 +25,20 @@ #include "ability_handler.h" #include "ability_manager_client.h" #include "ability_manager_interface.h" -#include "touch_event.h" -#include "key_event.h" #include "dummy_component_container.h" #include "dummy_values_bucket.h" #include "dummy_data_ability_predicates.h" #include "dummy_result_set.h" + +#ifdef MMI_COMPILE +#include "key_events.h" +#include "touch_events.h" +#include "ability_keyevent.h" +#include "ability_touchevent.h" +#else #include "key_event.h" +#include "touch_event.h" +#endif namespace OHOS { namespace AppExecFwk { @@ -284,6 +291,45 @@ public: */ void SetCallingContext(const std::string &deviceId, const std::string &bundleName, const std::string &abilityName); + /** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the + * context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to + * any method that is called on the Data ability must require normalization verification and denormalization. The + * default implementation of this method returns null, indicating that this Data ability does not support URI + * normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ + virtual Uri NormalizeUri(const Uri &uri); + + /** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed + * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found + * in the current environment. + */ + virtual Uri DenormalizeUri(const Uri &uri); + + /** + * @brief ScheduleUpdateConfiguration, scheduling update configuration. + */ + void ScheduleUpdateConfiguration(const AAFwk::DummyConfiguration &config); + + /** + * @brief Create a PostEvent timeout task. The default delay is 5000ms + * + * @return Return a smart pointer to a timeout object + */ + std::shared_ptr CreatePostEventTimeouter(std::string taskstr); + protected: /** * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application @@ -341,6 +387,13 @@ protected: */ void SetLifeCycleStateInfo(const AAFwk::LifeCycleStateInfo &info); + /** + * @brief Check if it needs to restore the data to the ability. + * + * @return Return true if success, otherwise return false. + */ + bool CheckAndRestore(); + int lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL; sptr token_; std::shared_ptr ability_; @@ -358,6 +411,24 @@ private: std::shared_ptr abilityLifecycleCallbacks_; std::shared_ptr applactionImpl_; std::shared_ptr contextDeal_; + +private: + /** + * @brief Multimodal Events Register. + */ + void MMIRegister(); + + /** + * @brief Multimodal Events UnRegister. + */ + void MMIUnRegister(); + +#ifdef MMI_COMPILE + sptr abilityKeyEventHandle_ = nullptr; + sptr abilityTouchEventHandle_ = nullptr; +#endif + bool hasSaveData_ = false; + PacMap restoreData_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/include/ability_keyevent.h b/frameworks/kits/ability/native/include/ability_keyevent.h new file mode 100644 index 00000000000..537da345259 --- /dev/null +++ b/frameworks/kits/ability/native/include/ability_keyevent.h @@ -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. + */ + +#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_KEYEVENT_HANDLE_H +#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_KEYEVENT_HANDLE_H + +#include + +#ifdef MMI_COMPILE +#include "multimodal_events_handler.h" +#include "key_events_handler.h" +#endif + +namespace OHOS { +namespace AppExecFwk { +class AbilityImpl; +class AbilityKeyEventHandle +#ifdef MMI_COMPILE + : public MMI::KeyEventHandler +#endif +{ +public: + AbilityKeyEventHandle(const std::shared_ptr &ability); + ~AbilityKeyEventHandle(); + +#ifdef MMI_COMPILE + /** + * @brief Called back when on key. + */ + virtual bool OnKey(const KeyEvent& keyEvent) override; +#endif + +private: + std::shared_ptr abilityImpl_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_KEYEVENT_HANDLE_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/ability_post_event_timeout.h b/frameworks/kits/ability/native/include/ability_post_event_timeout.h new file mode 100644 index 00000000000..772cd92e2e0 --- /dev/null +++ b/frameworks/kits/ability/native/include/ability_post_event_timeout.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 FOUNDATION_APPEXECFWK_OHOS_ABILITY_POST_EVENT_TIMEOUT_H +#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_POST_EVENT_TIMEOUT_H + +#include +#include +#include +#include + +namespace OHOS { +namespace AppExecFwk { + +class AbilityHandler; +class AbilityPostEventTimeout : public std::enable_shared_from_this { +private: + // default delaytime is 5000ms + static const int64_t defalutDelayTime; + +public: + // AbilityPostEventTimeout(std::string str, std::shared_ptr &eventHandler); + AbilityPostEventTimeout(std::string str, std::shared_ptr &eventHandler); + ~AbilityPostEventTimeout(); + + void TimingBegin(int64_t delaytime = defalutDelayTime); + void TimeEnd(); + +protected: + void TimeOutProc(); + +private: + std::string task_; + // std::shared_ptr handler_; + std::shared_ptr handler_; + std::mutex mtx_; + bool taskExec_; + + static std::atomic allocationId_; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_POST_EVENT_TIMEOUT_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/ability_thread.h b/frameworks/kits/ability/native/include/ability_thread.h index 8499c9442d4..73d02685d16 100644 --- a/frameworks/kits/ability/native/include/ability_thread.h +++ b/frameworks/kits/ability/native/include/ability_thread.h @@ -35,6 +35,7 @@ namespace OHOS { namespace AppExecFwk { using AbilitySchedulerStub = OHOS::AAFwk::AbilitySchedulerStub; using LifeCycleStateInfo = OHOS::AAFwk::LifeCycleStateInfo; +using DummyConfiguration = OHOS::AAFwk::DummyConfiguration; class AbilityImpl; class Ability; class AbilityHandler; @@ -129,6 +130,11 @@ public: */ void ScheduleRestoreAbilityState(const PacMap &state); + /** + * @brief ScheduleUpdateConfiguration, scheduling update configuration. + */ + void ScheduleUpdateConfiguration(const DummyConfiguration &config); + /** * @brief Send the result code and data to be returned by this Page ability to the caller. * When a Page ability is destroyed, the caller overrides the AbilitySlice#onAbilityResult(int, int, Want) method to @@ -255,6 +261,48 @@ public: */ int BatchInsert(const Uri &uri, const std::vector &values); + /** + * @brief notify multi window mode changed. + * + * @param winModeKey Indicates ability Window display mode. + * @param flag Indicates this ability has been enter this mode. + */ + void NotifyMultiWinModeChanged(int32_t winModeKey, bool flag); + + /** + * @brief notify this ability is top active ability. + * + * @param flag true: Indicates this ability is top active ability + */ + void NotifyTopActiveAbilityChanged(bool flag); + + /** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the + * context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to + * any method that is called on the Data ability must require normalization verification and denormalization. The + * default implementation of this method returns null, indicating that this Data ability does not support URI + * normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ + Uri NormalizeUri(const Uri &uri); + + /** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed + * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found + * in the current environment. + */ + Uri DenormalizeUri(const Uri &uri); + private: /** * @description: Create the abilityname. @@ -323,6 +371,11 @@ private: */ void HandleRestoreAbilityState(const PacMap &state); + /* + * @brief Handle the scheduling update configuration. + */ + void HandleUpdateConfiguration(const DummyConfiguration &config); + std::shared_ptr abilityImpl_ = nullptr; sptr token_; std::shared_ptr currentAbility_ = nullptr; diff --git a/frameworks/kits/ability/native/include/ability_touchevent.h b/frameworks/kits/ability/native/include/ability_touchevent.h new file mode 100644 index 00000000000..722e1e0c514 --- /dev/null +++ b/frameworks/kits/ability/native/include/ability_touchevent.h @@ -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. + */ + +#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_TOUCHEVENT_HANDLE_H +#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_TOUCHEVENT_HANDLE_H + +#include + +#ifdef MMI_COMPILE +#include "multimodal_events_handler.h" +#include "touch_events_handler.h" +#endif + +namespace OHOS { +namespace AppExecFwk { +class AbilityImpl; +class AbilityTouchEventHandle +#ifdef MMI_COMPILE + : public MMI::TouchEventHandler +#endif +{ +public: + AbilityTouchEventHandle(std::shared_ptr ability); + virtual ~AbilityTouchEventHandle(); + +#ifdef MMI_COMPILE + /** + * @brief Called back when on touch. + */ + virtual bool OnTouch(const TouchEvent& touchEvent) override; +#endif + +private: + std::shared_ptr abilityImpl_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_TOUCHEVENT_HANDLE_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/ability_window.h b/frameworks/kits/ability/native/include/ability_window.h index 57c79fd8cff..5dca2ae1971 100644 --- a/frameworks/kits/ability/native/include/ability_window.h +++ b/frameworks/kits/ability/native/include/ability_window.h @@ -115,4 +115,4 @@ private: }; } // namespace AppExecFwk } // namespace OHOS -#endif // OHOS_ABILITY_WINDOW_H +#endif // OHOS_ABILITY_WINDOW_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/data_ability_helper.h b/frameworks/kits/ability/native/include/data_ability_helper.h index b359f55b8e9..dbd2a1c9496 100644 --- a/frameworks/kits/ability/native/include/data_ability_helper.h +++ b/frameworks/kits/ability/native/include/data_ability_helper.h @@ -16,11 +16,17 @@ #ifndef FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_HELPER_H #define FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_HELPER_H +#include +#include +#include + #include "context.h" #include "dummy_values_bucket.h" #include "dummy_data_ability_predicates.h" #include "dummy_result_set.h" #include "uri.h" +#include +#include using Uri = OHOS::Uri; @@ -67,6 +73,28 @@ public: static std::shared_ptr Creator( const std::shared_ptr &context, const std::shared_ptr &uri, const bool tryBind); + /** + * @brief Creates a DataAbilityHelper instance without specifying the Uri based. + * + * @param token Indicates the System token. + * + * @return Returns the created DataAbilityHelper instance where Uri is not specified. + */ + static std::shared_ptr Creator(const sptr &token); + + /** + * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship + * between the ability using the Data template (Data ability for short) and the associated client process in + * a DataAbilityHelper instance. + * + * @param token Indicates the System token. + * @param uri Indicates the database table or disk file to operate. + * + * @return Returns the created DataAbilityHelper instance. + */ + static std::shared_ptr Creator( + const sptr &token, const std::shared_ptr &uri); + /** * @brief Releases the client resource of the Data ability. * You should call this method to releases client resource after the data operations are complete. @@ -186,17 +214,70 @@ public: */ int BatchInsert(Uri &uri, const std::vector &values); + /** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the + * context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to + * any method that is called on the Data ability must require normalization verification and denormalization. The + * default implementation of this method returns null, indicating that this Data ability does not support URI + * normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ + Uri NormalizeUri(Uri &uri); + + /** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed + * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found + * in the current environment. + */ + Uri DenormalizeUri(Uri &uri); + private: DataAbilityHelper(const std::shared_ptr &context, const std::shared_ptr &uri, const sptr &dataAbilityProxy, bool tryBind = false); DataAbilityHelper(const std::shared_ptr &context); + DataAbilityHelper(const sptr &token, const std::shared_ptr &uri, + const sptr &dataAbilityProxy); + DataAbilityHelper(const sptr &token); + + void AddDataAbilityDeathRecipient(const sptr &token); + void OnSchedulerDied(const wptr &remote); + + bool CheckUriParam(const Uri &uri); + bool CheckOhosUri(const Uri &uri); sptr token_; std::weak_ptr context_; std::shared_ptr uri_ = nullptr; bool tryBind_ = false; + bool isSystemCaller_ = false; sptr dataAbilityProxy_ = nullptr; + sptr callerDeathRecipient_ = nullptr; // caller binderDied Recipient }; + +class DataAbilityDeathRecipient : public IRemoteObject::DeathRecipient { +public: + using RemoteDiedHandler = std::function &)>; + + explicit DataAbilityDeathRecipient(RemoteDiedHandler handler); + + virtual ~DataAbilityDeathRecipient(); + + virtual void OnRemoteDied(const wptr &remote); + +private: + RemoteDiedHandler handler_; +}; + } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_HELPER_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/data_ability_impl.h b/frameworks/kits/ability/native/include/data_ability_impl.h index 5c78a5d5a4e..32c4405a7e2 100644 --- a/frameworks/kits/ability/native/include/data_ability_impl.h +++ b/frameworks/kits/ability/native/include/data_ability_impl.h @@ -154,6 +154,32 @@ public: * @return Returns the number of data records inserted. */ int BatchInsert(const Uri &uri, const std::vector &values); + + /** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the + * context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to any + * method that is called on the Data ability must require normalization verification and denormalization. The default + * implementation of this method returns null, indicating that this Data ability does not support URI normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ + Uri NormalizeUri(const Uri &uri); + + /** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed to + * this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found in the + * current environment. + */ + Uri DenormalizeUri(const Uri &uri); }; } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/include/data_ability_operation.h b/frameworks/kits/ability/native/include/data_ability_operation.h index 9e40ee02328..70e4f98ee3f 100644 --- a/frameworks/kits/ability/native/include/data_ability_operation.h +++ b/frameworks/kits/ability/native/include/data_ability_operation.h @@ -152,13 +152,13 @@ private: // object exist in parcel static constexpr int VALUE_OBJECT = 1; static constexpr int REFERENCE_THRESHOLD = 3 * 1024 * 1024; - int type_; - int expectedCount_; - bool interrupted_; - std::shared_ptr uri_; - std::shared_ptr valuesBucket_; - std::shared_ptr dataAbilityPredicates_; - std::shared_ptr valuesBucketReferences_; + int type_ = -1; + int expectedCount_ = 0; + bool interrupted_ = false; + std::shared_ptr uri_ = nullptr; + std::shared_ptr valuesBucket_ = nullptr; + std::shared_ptr dataAbilityPredicates_ = nullptr; + std::shared_ptr valuesBucketReferences_ = nullptr; std::map dataAbilityPredicatesBackReferences_; }; } // namespace AppExecFwk diff --git a/frameworks/kits/ability/native/include/data_uri_utils.h b/frameworks/kits/ability/native/include/data_uri_utils.h index df5669ba7e5..d6123e95831 100644 --- a/frameworks/kits/ability/native/include/data_uri_utils.h +++ b/frameworks/kits/ability/native/include/data_uri_utils.h @@ -44,14 +44,14 @@ public: * @param id * @return Uri( scheme://authority/path1/path2/path3/updateIDNumber....) */ - static Uri AttachId(const Uri &dataUri, long id); + static Uri AttachId(const Uri &dataUri, long long id); /** * @brief Obtains the ID attached to the end of the path component of the given URI. * @param dataUri based on RFC 2396( Uniform Resource Identifier ). * @return long ID */ - static long GetId(const Uri &dataUri); + static long long GetId(const Uri &dataUri); /** * @brief Deletes the ID from the end of the path component of the given URI. @@ -66,7 +66,7 @@ public: * @param id indiates Update attached to the end of the path component of the given URI * @return Uri return is the URI after path is updated */ - static Uri UpdateId(const Uri &dataUri, long id); + static Uri UpdateId(const Uri &dataUri, long long id); /** * @brief Does the end path of the path component of the given URI have an ID attached to it? diff --git a/frameworks/kits/ability/native/include/form_js_event_handler.h b/frameworks/kits/ability/native/include/form_js_event_handler.h new file mode 100755 index 00000000000..8c70f8dc1ec --- /dev/null +++ b/frameworks/kits/ability/native/include/form_js_event_handler.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_OHOS_FORM_JS_EVENT_HANDLER_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_JS_EVENT_HANDLER_H + +#include +#include "ability.h" +#include "event_handler.h" + +namespace OHOS { +namespace AppExecFwk { +class FormJsEventHandler : public EventHandler { +public: + FormJsEventHandler(const std::shared_ptr &runner, + const std::shared_ptr& ability, const FormJsInfo& formJsInfo); + ~FormJsEventHandler() = default; + + /** + * Process the event. Developers should override this method. + * + * @param event The event should be processed. + */ + void ProcessEvent(const InnerEvent::Pointer &event) override; + + enum { + FORM_ROUTE_EVENT = 100, + FORM_MESSAGE_EVENT, + }; +private: + /** + * @brief Process js router event. + * @param want Indicates the event to be processed. + */ + void ProcessRouterEvent(Want &want); + + /** + * @brief Process js message event. + * @param want Indicates the event to be processed. + */ + void ProcessMessageEvent(const Want &want); + bool IsSystemApp() const; + +private: + FormJsInfo formJsInfo_; + std::shared_ptr ability_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_JS_EVENT_HANDLER_H diff --git a/frameworks/kits/ability/native/include/form_provider_client.h b/frameworks/kits/ability/native/include/form_provider_client.h new file mode 100755 index 00000000000..b9b0426cb3a --- /dev/null +++ b/frameworks/kits/ability/native/include/form_provider_client.h @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_CLIENT_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_CLIENT_H + +#include +#include +#include +#include "ability.h" +#include "form_constants.h" +#include "form_provider_info.h" +#include "form_provider_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormProviderStub + * The service of the form provider. + */ +class FormProviderClient : public FormProviderStub { +public: + FormProviderClient() = default; + virtual ~FormProviderClient() = default; + + /** + * @brief Acquire to give back an ProviderFormInfo. This is sync API. + * @param formId The Id of the form. + * @param want Indicates the {@link Want} structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int AcquireProviderFormInfo( + const int64_t formId, + const Want &want, + const sptr &callerToken) override; + + /** + * @brief Notify provider when the form was deleted. + * + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormDelete( + const int64_t formId, + const Want &want, + const sptr &callerToken) override; + + /** + * @brief Notify provider when the form was deleted. + * + * @param formIds The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormsDelete( + const std::vector &formIds, + const Want &want, + const sptr &callerToken) override; + + /** + * @brief Notify provider when the form need update. + * + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormUpdate( + const int64_t formId, + const Want &want, + const sptr &callerToken) override; + + /** + * @brief Event notify when change the form visible. + * + * @param formIds The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int EventNotify(const std::vector &formIds, const int32_t formVisibleType, const Want &want, + const sptr &callerToken) override; + + /** + * @brief Notify provider when the temp form was cast to normal form. + * + * @param formId The Id of the form to update. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormCastTempForm( + const int64_t formId, + const Want &want, + const sptr &callerToken) override; + /** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int FireFormEvent( + const int64_t formId, + const std::string &message, + const Want &want, + const sptr &callerToken) override; + /** + * @brief Set the owner ability of the form provider client. + * + * @param ability The owner ability of the form provider client. + * @return none. + */ + void SetOwner(const std::shared_ptr ability); + + /** + * @brief Clear the owner ability of the form provider client. + * + * @param ability The owner ability of the form provider client. + * @return none. + */ + void ClearOwner(const std::shared_ptr ability); + +private: + Want BuildNewWant(const Want &want); + std::shared_ptr GetOwner(); + bool CheckIsSystemApp() const; + int HandleAcquire( + const FormProviderInfo &formProviderInfo, + const Want &newWant, + const sptr &callerToken); + int HandleDisconnect(const Want &want, const sptr &callerToken); + +private: + DISALLOW_COPY_AND_MOVE(FormProviderClient); + mutable std::mutex abilityMutex_; + std::weak_ptr owner_; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_CLIENT_H diff --git a/frameworks/kits/ability/native/src/ability.cpp b/frameworks/kits/ability/native/src/ability.cpp old mode 100644 new mode 100755 index ba9977f6e94..9c0b3ce3afd --- a/frameworks/kits/ability/native/src/ability.cpp +++ b/frameworks/kits/ability/native/src/ability.cpp @@ -13,15 +13,32 @@ * limitations under the License. */ +#include + #include "ability.h" #include "ability_loader.h" #include "app_log_wrapper.h" #include "display_type.h" +#include "form_provider_client.h" +#include "if_system_ability_manager.h" #include "iservice_registry.h" #include "system_ability_definition.h" #include "task_handler_client.h" #include "ohos_application.h" +#include "ability_post_event_timeout.h" + +#ifdef MMI_COMPILE +#include "key_events.h" +#include "touch_events.h" +#else +#include "key_event.h" +#include "touch_event.h" +#endif +#include "form_host_client.h" +#include "form_mgr.h" +#include "ipc_skeleton.h" + namespace OHOS { namespace AppExecFwk { REGISTER_AA(Ability) @@ -29,10 +46,15 @@ const std::string Ability::SYSTEM_UI("com.ohos.systemui"); const std::string Ability::STATUS_BAR("com.ohos.systemui.statusbar.MainAbility"); const std::string Ability::NAVIGATION_BAR("com.ohos.systemui.navigationbar.MainAbility"); +static std::mutex formLock; + +constexpr int64_t SEC_TO_MILLISEC = 1000; +constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; + void Ability::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) { - APP_LOGI("Ability::Init called."); + APP_LOGI("%{public}s begin.", __func__); abilityInfo_ = abilityInfo; handler_ = handler; @@ -41,13 +63,17 @@ void Ability::Init(const std::shared_ptr &abilityInfo, const std::s // page ability only. if (abilityInfo_->type == AbilityType::PAGE) { abilityWindow_ = std::make_shared(); + if (abilityWindow_ != nullptr) { + APP_LOGI("%{public}s begin abilityWindow_->Init", __func__); abilityWindow_->Init(handler_, shared_from_this()); + APP_LOGI("%{public}s end abilityWindow_->Init", __func__); } } lifecycle_ = std::make_shared(); abilityLifecycleExecutor_ = std::make_shared(); application_ = application; + APP_LOGI("%{public}s end.", __func__); } /** @@ -67,7 +93,7 @@ std::shared_ptr Ability::GetResourceManager() */ void Ability::OnStart(const Want &want) { - APP_LOGI("Ability::OnStart called."); + APP_LOGI("%{public}s begin.", __func__); if (abilityInfo_ == nullptr) { APP_LOGE("Ability::OnStart falied abilityInfo_ is nullptr."); return; @@ -75,6 +101,7 @@ void Ability::OnStart(const Want &want) if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { sptr config = WindowOption::Get(); + OHOS::WindowType winType = OHOS::WindowType::WINDOW_TYPE_NORMAL; if (abilityInfo_->bundleName == SYSTEM_UI) { if (abilityInfo_->name == STATUS_BAR) { @@ -98,7 +125,9 @@ void Ability::OnStart(const Want &want) SetUIContent(config); if (abilityWindow_ != nullptr) { + APP_LOGI("%{public}s begin abilityWindow_->OnPostAbilityStart.", __func__); abilityWindow_->OnPostAbilityStart(); + APP_LOGI("%{public}s end abilityWindow_->OnPostAbilityStart.", __func__); } } // should called in ace ability onStart methord. @@ -115,6 +144,7 @@ void Ability::OnStart(const Want &want) return; } lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_START, want); + APP_LOGI("%{public}s end.", __func__); } /** @@ -125,10 +155,12 @@ void Ability::OnStart(const Want &want) */ void Ability::OnStop() { - APP_LOGI("Ability::OnStop called"); + APP_LOGI("%{public}s begin.", __func__); if (abilityWindow_ != nullptr && abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { + APP_LOGI("%{public}s begin abilityWindow_->OnPostAbilityStop.", __func__); abilityWindow_->OnPostAbilityStop(); + APP_LOGI("%{public}s end abilityWindow_->OnPostAbilityStop.", __func__); } if (abilityLifecycleExecutor_ == nullptr) { APP_LOGE("Ability::OnStop error. abilityLifecycleExecutor_ == nullptr."); @@ -141,6 +173,7 @@ void Ability::OnStop() return; } lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_STOP); + APP_LOGI("%{public}s end.", __func__); } /** @@ -153,10 +186,12 @@ void Ability::OnStop() */ void Ability::OnActive() { - APP_LOGI("Ability::OnActive called"); + APP_LOGI("%{public}s begin.", __func__); if (abilityWindow_ != nullptr) { + APP_LOGI("%{public}s begin abilityWindow_->OnPostAbilityActive.", __func__); abilityWindow_->OnPostAbilityActive(); + APP_LOGI("%{public}s end abilityWindow_->OnPostAbilityActive.", __func__); } bWindowFocus_ = true; if (abilityLifecycleExecutor_ == nullptr) { @@ -170,6 +205,7 @@ void Ability::OnActive() return; } lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + APP_LOGI("%{public}s end.", __func__); } /** @@ -180,10 +216,12 @@ void Ability::OnActive() */ void Ability::OnInactive() { - APP_LOGI("Ability::OnInactive called"); + APP_LOGI("%{public}s begin.", __func__); if (abilityWindow_ != nullptr && abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { + APP_LOGI("%{public}s begin abilityWindow_->OnPostAbilityInactive.", __func__); abilityWindow_->OnPostAbilityInactive(); + APP_LOGI("%{public}s end abilityWindow_->OnPostAbilityInactive.", __func__); } bWindowFocus_ = false; if (abilityLifecycleExecutor_ == nullptr) { @@ -197,6 +235,7 @@ void Ability::OnInactive() return; } lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_INACTIVE); + APP_LOGI("%{public}s end.", __func__); } /** @@ -208,10 +247,12 @@ void Ability::OnInactive() */ void Ability::OnForeground(const Want &want) { - APP_LOGI("Ability::OnForeground called"); + APP_LOGI("%{public}s begin.", __func__); if (abilityWindow_ != nullptr) { + APP_LOGI("%{public}s begin abilityWindow_->OnPostAbilityForeground.", __func__); abilityWindow_->OnPostAbilityForeground(); + APP_LOGI("%{public}s end abilityWindow_->OnPostAbilityForeground.", __func__); } if (abilityLifecycleExecutor_ == nullptr) { @@ -225,6 +266,7 @@ void Ability::OnForeground(const Want &want) return; } lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_FOREGROUND, want); + APP_LOGI("%{public}s end.", __func__); } /** @@ -236,10 +278,12 @@ void Ability::OnForeground(const Want &want) */ void Ability::OnBackground() { - APP_LOGI("Ability::OnBackground called"); + APP_LOGI("%{public}s begin.", __func__); if (abilityWindow_ != nullptr && abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { + APP_LOGI("%{public}s begin abilityWindow_->OnPostAbilityBackground.", __func__); abilityWindow_->OnPostAbilityBackground(); + APP_LOGI("%{public}s end abilityWindow_->OnPostAbilityBackground.", __func__); } if (abilityLifecycleExecutor_ == nullptr) { @@ -253,6 +297,7 @@ void Ability::OnBackground() return; } lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND); + APP_LOGI("%{public}s end.", __func__); } /** @@ -265,6 +310,7 @@ void Ability::OnBackground() */ sptr Ability::OnConnect(const Want &want) { + APP_LOGI("%{public}s begin.", __func__); if (abilityLifecycleExecutor_ == nullptr) { APP_LOGE("Ability::OnConnect error. abilityLifecycleExecutor_ == nullptr."); return nullptr; @@ -276,7 +322,7 @@ sptr Ability::OnConnect(const Want &want) return nullptr; } lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); - + APP_LOGI("%{public}s end.", __func__); return nullptr; } @@ -297,6 +343,7 @@ void Ability::OnDisconnect(const Want &want) */ void Ability::StartAbilityForResult(const Want &want, int requestCode) { + APP_LOGI("%{public}s begin.", __func__); if (abilityInfo_ == nullptr) { APP_LOGE("Ability::StartAbilityForResult abilityInfo_ == nullptr"); return; @@ -305,6 +352,7 @@ void Ability::StartAbilityForResult(const Want &want, int requestCode) if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { AbilityContext::StartAbility(want, requestCode); } + APP_LOGI("%{public}s end.", __func__); } /** @@ -320,6 +368,7 @@ void Ability::StartAbilityForResult(const Want &want, int requestCode) */ void Ability::StartAbilityForResult(const Want &want, int requestCode, AbilityStartSetting abilityStartSetting) { + APP_LOGI("%{public}s begin.", __func__); if (abilityInfo_ == nullptr) { APP_LOGE("Ability::StartAbilityForResult abilityInfo_ == nullptr"); return; @@ -328,6 +377,7 @@ void Ability::StartAbilityForResult(const Want &want, int requestCode, AbilitySt if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { AbilityContext::StartAbility(want, requestCode, abilityStartSetting); } + APP_LOGI("%{public}s end.", __func__); } /** @@ -342,6 +392,7 @@ void Ability::StartAbilityForResult(const Want &want, int requestCode, AbilitySt */ void Ability::StartAbility(const Want &want, AbilityStartSetting abilityStartSetting) { + APP_LOGI("%{public}s beign.", __func__); if (abilityInfo_ == nullptr) { APP_LOGE("Ability::StartAbility abilityInfo_ == nullptr"); return; @@ -350,6 +401,7 @@ void Ability::StartAbility(const Want &want, AbilityStartSetting abilityStartSet if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE || abilityInfo_->type == AppExecFwk::AbilityType::SERVICE) { AbilityContext::StartAbility(want, -1, abilityStartSetting); } + APP_LOGI("%{public}s end.", __func__); } /** @@ -367,6 +419,7 @@ void Ability::StartAbility(const Want &want, AbilityStartSetting abilityStartSet bool Ability::OnKeyDown(int keyCode, const KeyEvent &keyEvent) { APP_LOGI("Ability::OnKeyDown called"); + APP_LOGI("Ability::OnKeyDown keyCode: %{public}d.", keyCode); return false; } @@ -385,6 +438,19 @@ bool Ability::OnKeyDown(int keyCode, const KeyEvent &keyEvent) bool Ability::OnKeyUp(int keyCode, const KeyEvent &keyEvent) { APP_LOGI("Ability::OnKeyUp called"); + APP_LOGI("Ability::OnKeyUp keyCode: %{public}d.", keyCode); + switch (keyCode) { +#ifdef MMI_COMPILE + case OHOS::KeyEventEnum::KEY_BACK: +#else + case KeyEvent::CODE_BACK: +#endif + APP_LOGI("Ability::OnKey Back key pressed."); + OnBackPressed(); + return true; + default: + break; + } return false; } @@ -399,6 +465,9 @@ bool Ability::OnKeyUp(int keyCode, const KeyEvent &keyEvent) bool Ability::OnTouchEvent(const TouchEvent &touchEvent) { APP_LOGI("Ability::OnTouchEvent called"); + APP_LOGI("Ability::OnTouchEvent action: %{public}d phase: %{public}d", + const_cast(touchEvent).GetAction(), + const_cast(touchEvent).GetPhase()); return false; } @@ -448,13 +517,14 @@ void Ability::SetUIContent(int layoutRes, std::shared_ptr &context, int */ void Ability::SetUIContent(const sptr &config) { - if (abilityInfo_ == nullptr) { + if (abilityWindow_ == nullptr) { APP_LOGE("Ability::SetUIContent abilityWindow_ is nullptr"); return; } - APP_LOGI("Ability::SetUIContent called"); + APP_LOGI("%{public}s beign abilityWindow_->SetWindowConfig.", __func__); abilityWindow_->SetWindowConfig(config); + APP_LOGI("%{public}s end abilityWindow_->SetWindowConfig.", __func__); } /** @@ -464,7 +534,12 @@ void Ability::SetUIContent(const sptr &config) */ const sptr &Ability::GetWindow() { - return abilityWindow_->GetWindow(); + if (abilityWindow_ != nullptr) { + return abilityWindow_->GetWindow(); + } else { + APP_LOGI("%{public}s abilityWindow_ is nullptr.", __func__); + return nullptr; + } } /** @@ -616,13 +691,13 @@ int Ability::Update(const Uri &uri, const ValuesBucket &value, const DataAbility */ std::shared_ptr Ability::GetApplication() { - APP_LOGI("Ability::GetApplication called"); + APP_LOGI("%{public}s begin.", __func__); if (application_ == nullptr) { APP_LOGE("Ability::GetApplication error. application_ == nullptr."); return nullptr; } - + APP_LOGI("%{public}s end.", __func__); return application_; } @@ -676,7 +751,7 @@ void Ability::OnAbilityResult(int requestCode, int resultCode, const Want &want) */ void Ability::OnBackPressed() { - APP_LOGI("Ability::OnBackPressed called"); + APP_LOGI("%{public}s begin.", __func__); if (abilityInfo_ == nullptr) { APP_LOGE("Ability::OnBackPressed abilityInfo_ is nullptr"); return; @@ -686,6 +761,7 @@ void Ability::OnBackPressed() APP_LOGI("Ability::OnBackPressed the ability is not Launcher"); TerminateAbility(); } + APP_LOGI("%{public}s end.", __func__); } /** @@ -769,6 +845,7 @@ std::shared_ptr Ability::GetWant() */ void Ability::SetResult(int resultCode, const Want &resultData) { + APP_LOGI("%{public}s begin.", __func__); if (abilityInfo_ == nullptr) { APP_LOGE("Ability::SetResult abilityInfo_ == nullptr"); return; @@ -778,6 +855,7 @@ void Ability::SetResult(int resultCode, const Want &resultData) AbilityContext::resultWant_ = resultData; AbilityContext::resultCode_ = resultCode; } + APP_LOGI("%{public}s end.", __func__); } /** @@ -803,6 +881,7 @@ void Ability::SetVolumeTypeAdjustedByKey(int volumeType) */ void Ability::OnCommand(const AAFwk::Want &want, bool restart, int startId) { + APP_LOGI("%{public}s begin restart=%{public}s,startId=%{public}d.", __func__, restart ? "true" : "false", startId); if (abilityLifecycleExecutor_ == nullptr) { APP_LOGE("Ability::OnCommand error. abilityLifecycleExecutor_ == nullptr."); return; @@ -814,6 +893,7 @@ void Ability::OnCommand(const AAFwk::Want &want, bool restart, int startId) return; } lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE); + APP_LOGI("%{public}s end.", __func__); } /** @@ -906,9 +986,9 @@ void Ability::CancelBackgroundRunning() * * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. */ -const std::shared_ptr Ability::NormalizeUri(const Uri &uri) +Uri Ability::NormalizeUri(const Uri &uri) { - return nullptr; + return uri; } /** @@ -997,12 +1077,14 @@ bool Ability::Reload(const Uri &uri, const PacMap &extras) */ int Ability::BatchInsert(const Uri &uri, const std::vector &values) { + APP_LOGI("%{public}s begin.", __func__); int amount = 0; for (auto it = values.begin(); it != values.end(); it++) { if (Insert(uri, *it) >= 0) { amount++; } } + APP_LOGI("%{public}s end, amount=%{public}d", __func__, amount); return amount; } @@ -1079,9 +1161,9 @@ std::shared_ptr Ability::GetAbilityPackage() * this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found in the * current environment. */ -std::shared_ptr Ability::DenormalizeUri(const Uri &uri) +Uri Ability::DenormalizeUri(const Uri &uri) { - return nullptr; + return uri; } /** @@ -1121,8 +1203,9 @@ AbilityLifecycleExecutor::LifecycleState Ability::GetState() */ void Ability::StartAbility(const Want &want) { - APP_LOGI("Ability::StartAbility called"); + APP_LOGI("%{public}s begin.", __func__); AbilityContext::StartAbility(want, -1); + APP_LOGI("%{public}s end.", __func__); } /** @@ -1132,8 +1215,9 @@ void Ability::StartAbility(const Want &want) */ void Ability::TerminateAbility() { - APP_LOGI("Ability::TerminateAbility called"); + APP_LOGI("%{public}s begin.", __func__); AbilityContext::TerminateAbility(); + APP_LOGI("%{public}s end.", __func__); } /** @@ -1244,10 +1328,82 @@ bool Ability::StopAbility(const AAFwk::Want &want) */ void Ability::PostTask(std::function task, long delayTime) { - APP_LOGI("Ability::PostTask called"); + APP_LOGI("%{public}s begin.", __func__); TaskHandlerClient::GetInstance()->PostTask(task, delayTime); + APP_LOGI("%{public}s end.", __func__); +} + +/** + * @brief Migrates this ability to another device on the same distributed network. If there are multiple candidate + * devices, a pop-up will be displayed for users to choose the desired one. The ability to migrate and its ability + * slices must implement the IAbilityContinuation interface. + * + */ +void Ability::ContinueAbility() +{ +} + +/** + * @brief Migrates this ability to the given device on the same distributed network. The ability to migrate and its + * ability slices must implement the IAbilityContinuation interface. + * + * @param deviceId Indicates the ID of the target device where this ability will be migrated to. If this parameter + * is null, this method has the same effect as continueAbility(). + * + */ +void Ability::ContinueAbility(const std::string &deviceId) +{ } +/** + * @brief Callback function to ask the user whether to start the migration . + * + * @return If the user allows migration, it returns true; otherwise, it returns false. + */ +bool Ability::OnStartContinuation() +{ + return false; +} + +/** + * @brief Save user data of local Ability generated at runtime. + * + * @param saveData Indicates the user data to be saved. + * @return If the data is saved successfully, it returns true; otherwise, it returns false. + */ +bool Ability::OnSaveData(WantParams &saveData) +{ + return false; +} + +/** + * @brief After creating the Ability on the remote device, + * immediately restore the user data saved during the migration of the Ability on the remote device. + * @param restoreData Indicates the user data to be restored. + * @return If the data is restored successfully, it returns true; otherwise, it returns false . + */ +bool Ability::OnRestoreData(WantParams &restoreData) +{ + return false; +} + +/** + * @brief This function can be used to implement the processing logic after the migration is completed. + * + * @param result Migration result code. 0 means the migration was successful, -1 means the migration failed. + * @return None. + */ +void Ability::OnCompleteContinuation(int result) +{} + +/** + * @brief Used to notify the local Ability that the remote Ability has been destroyed. + * + * @return None. + */ +void Ability::OnRemoteTerminated() +{} + /** * @brief Called when this ability gains or loses window focus. * @@ -1281,12 +1437,1075 @@ Uri Ability::OnSetCaller() */ void Ability::TerminateAndRemoveMission() { + APP_LOGI("%{public}s begin.", __func__); auto state = GetState(); if (state > AbilityLifecycleExecutor::LifecycleState::INITIAL) { APP_LOGI("Ability::TerminateAndRemoveMission the GetState retval is %d", state); return; } AbilityContext::TerminateAndRemoveMission(); + APP_LOGI("%{public}s end.", __func__); +} + +/** + * @brief Create a PostEvent timeout task. The default delay is 5000ms + * + * @return Return a smart pointer to a timeout object + */ +std::shared_ptr Ability::CreatePostEventTimeouter(std::string taskstr) +{ + // std::shared_ptr eventhandler = handler_; + return std::make_shared(taskstr, handler_); +} + +/** + * Releases an obtained form by its ID. + * + *

After this method is called, the form won't be available for use by the application, but the Form Manager + * Service still keeps the cache information about the form, so that the application can quickly obtain it based on + * the {@code formId}.

+ *

Permission: {@link ohos.security.SystemPermission#REQUIRE_FORM}

+ * + * @param formId Indicates the form ID. + * @return Returns {@code true} if the form is successfully released; returns {@code false} otherwise. + * + *
    + *
  • The passed {@code formId} is invalid. Its value must be larger than 0.
  • + *
  • The specified form has not been added by the application.
  • + *
  • An error occurred when connecting to the Form Manager Service.
  • + *
  • The application is not granted with the {@link ohos.security.SystemPermission#REQUIRE_FORM} permission.
  • + *
  • The form has been obtained by another application and cannot be released by the current application.
  • + *
  • The form is being restored.
  • + *
+ */ +bool Ability::ReleaseForm(const int64_t formId) +{ + APP_LOGI("%{public}s called.", __func__); + + // release form by formId and do not release cache + return ReleaseForm(formId, false); +} + +/** + * Releases an obtained form by its ID. + * + *

After this method is called, the form won't be available for use by the application, if isReleaseCache is + * false, this method is same as {@link #releaseForm(int)}, otherwise the Form Manager Service still store this + * form in the cache.

+ *

Permission: {@link ohos.security.SystemPermission#REQUIRE_FORM}

+ * + * @param formId Indicates the form ID. + * @param isReleaseCache Indicates whether to clear cache in service. + * @return Returns {@code true} if the form is successfully released; returns {@code false} otherwise. + * + *
    + *
  • The passed {@code formId} is invalid. Its value must be larger than 0.
  • + *
  • The specified form has not been added by the application.
  • + *
  • An error occurred when connecting to the Form Manager Service.
  • + *
  • The application is not granted with the {@link ohos.security.SystemPermission#REQUIRE_FORM} permission.
  • + *
  • The form has been obtained by another application and cannot be released by the current application.
  • + *
  • The form is being restored.
  • + *
+ */ +bool Ability::ReleaseForm(const int64_t formId, const bool isReleaseCache) +{ + APP_LOGI("%{public}s called.", __func__); + + // release form with formId and specifies whether to release the cache + return DeleteForm(formId, isReleaseCache ? RELEASE_CACHED_FORM : RELEASE_FORM); +} + +/** + * Deletes an obtained form by its ID. + * + *

After this method is called, the form won't be available for use by the application and the Form Manager + * Service no longer keeps the cache information about the form.

+ *

Permission: {@link ohos.security.SystemPermission#REQUIRE_FORM}

+ * + * @param formId Indicates the form ID. + * @return Returns {@code true} if the form is successfully deleted; returns {@code false} otherwise. + * + *
    + *
  • The passed {@code formId} is invalid. Its value must be larger than 0.
  • + *
  • The specified form has not been added by the application.
  • + *
  • An error occurred when connecting to the Form Manager Service.
  • + *
  • The application is not granted with the {@link ohos.security.SystemPermission#REQUIRE_FORM} permission.
  • + *
  • The form has been obtained by another application and cannot be deleted by the current application.
  • + *
  • The form is being restored.
  • + *
+ */ +bool Ability::DeleteForm(const int64_t formId) +{ + APP_LOGI("%{public}s called.", __func__); + + // delete form with formId + return DeleteForm(formId, DELETE_FORM); +} + +/** + * @brief Cast temp form with formId. + * + * @param formId Indicates the form's ID. + * + * @return Returns {@code true} if the form is successfully casted; returns {@code false} otherwise. + */ +bool Ability::CastTempForm(const int64_t formId) +{ + APP_LOGI("%{public}s start",__func__); + if (formId <= 0) { + APP_LOGE("%{public}s error, passing in form id can't be negative.", __func__); + return false; + } + + APP_LOGI("%{public}s, castTempForm begin of temp form %{public}lld", __func__, formId); + + bool result = FormMgr::GetInstance().CastTempForm(formId, FormHostClient::GetInstance()); + + if (!result) { + APP_LOGE("%{public}s error, some internal server occurs, error code is %{public}d.", __func__, result); + return false; + } + + userReqParams_[formId].SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + + APP_LOGI("%{public}s end",__func__); + return true; +} + +/** + * @brief Obtains a specified form that matches the application bundle name, module name, form name, and + * other related information specified in the passed {@code Want}. + * + *

This method is asynchronous. After the {@link FormJsInfo} instance is obtained. + * + * @param formId Indicates the form ID. + * @param want Indicates the detailed information about the form to be obtained, including the bundle name, + * module name, ability name, form name, form id, tempForm flag, form dimension, and form customize data. + * @param callback Indicates the callback to be invoked whenever the {@link FormJsInfo} instance is obtained. + * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise. + */ +bool Ability::AcquireForm(const int64_t formId, const Want &want, const std::shared_ptr callback) +{ + APP_LOGI("%{public}s called.", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + APP_LOGI("%{public}s begin, current time: %{public}ld", __func__, currentTime); + + // check fms recover status + if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) { + APP_LOGE("%{public}s error, form is in recover status, can't do action on form.", __func__); + return false; + } + + // check form id + APP_LOGD("%{public}s, param of formId %{public}lld.", __func__, formId); + if (formId < 0) { + APP_LOGE("%{public}s error, form id should not be negative.", __func__); + return false; + } + + // check param of want + if (!CheckWantValid(formId, want)) { + APP_LOGE("%{public}s error, failed to check param of want.", __func__); + return false; + }; + + ElementName elementName = want.GetElement(); + std::string bundleName = elementName.GetBundleName(); + std::string abilityName = elementName.GetAbilityName(); + APP_LOGI("%{public}s, begin to acquire form, bundleName is %{public}s, abilityName is %{public}s, formId is %{public}lld.",__func__, bundleName.c_str(), abilityName.c_str(), formId); + + // hostClient init + sptr formHostClient = FormHostClient::GetInstance(); + if (formHostClient == nullptr) { + APP_LOGE("%{public}s error, formHostClient == nullptr.", __func__); + return false; + } + + // acquire form request to fms + FormJsInfo formJsInfo; + if (FormMgr::GetInstance().AddForm(formId, want, formHostClient, formJsInfo) != ERR_OK) { + APP_LOGE("%{public}s error, acquire form for fms failed.", __func__); + return false; + } + APP_LOGI("%{public}s, end to acquire form, the formId returned from the fms is %{public}lld.", + __func__, formJsInfo.formId); + + // check for form presence in hostForms + if (formHostClient->ContainsForm(formJsInfo.formId)) { + APP_LOGE("%{public}s error, form has already acquired, do not support acquire twice.", __func__); + return false; + } + + // add ability of form to hostForms + std::shared_ptr thisAbility = this->shared_from_this(); + formHostClient->AddForm(thisAbility, formJsInfo.formId); + + // post the async task of handleAcquireResult + PostTask([this, want, formJsInfo, callback]() {HandleAcquireResult(want, formJsInfo, callback);}, 0L); + + // the acquire form is successfully + return true; +} + +/** + * @brief Updates the content of a specified JS form. + * + *

This method is called by a form provider to update JS form data as needed. + * + * @param formId Indicates the form ID. + * @param formProviderData The data used to update the JS form displayed on the client. + * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise. + */ +bool Ability::UpdateForm(const int64_t formId, const FormProviderData &formProviderData) +{ + APP_LOGI("%{public}s called.", __func__); + + // check fms recover status + if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) { + APP_LOGE("%{public}s error, form is in recover status, can't do action on form.", __func__); + return false; + } + + // check formId + if (formId <= 0) { + APP_LOGE("%{public}s error, the passed in formId can't be negative or zero.", __func__); + return false; + } + + // check formProviderData + if (formProviderData.GetDataString().empty()) { + APP_LOGE("%{public}s error, the formProviderData is null.", __func__); + return false; + } + + // update form request to fms + if (FormMgr::GetInstance().UpdateForm(formId, abilityInfo_->bundleName, formProviderData) != ERR_OK) { + APP_LOGE("%{public}s error, update form for fms failed.", __func__); + return false; + } + + // the update form is successfully + return true; +} + +/** + * @brief Sends a notification to the form framework to make the specified forms visible. + * + *

After this method is successfully called, {@link Ability#OnVisibilityChanged(std::map)} + * will be called to notify the form provider of the form visibility change event.

+ * + * @param formIds Indicates the IDs of the forms to be made visible. + * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise. + */ +bool Ability::NotifyVisibleForms(const std::vector &formIds) +{ + APP_LOGI("%{public}s called.", __func__); + + return NotifyWhetherVisibleForms(formIds, Constants::FORM_VISIBLE); +} + +/** + * @brief Sends a notification to the form framework to make the specified forms invisible. + * + *

After this method is successfully called, {@link Ability#OnVisibilityChanged(std::map)} + * will be called to notify the form provider of the form visibility change event.

+ * + * @param formIds Indicates the IDs of the forms to be made invisible. + * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise. + */ +bool Ability::NotifyInvisibleForms(const std::vector &formIds) +{ + APP_LOGI("%{public}s called.", __func__); + + return NotifyWhetherVisibleForms(formIds, Constants::FORM_INVISIBLE); +} + +/** +* @brief Set form next refresh time. +* +*

This method is called by a form provider to set refresh time. +* +* @param formId Indicates the ID of the form to set refresh time. +* @param nextTime Indicates the next time gap now in seconds, can not be litter than 300 seconds. +* @return Returns {@code true} if seting succeed; returns {@code false} otherwise. +*/ +bool Ability::SetFormNextRefreshTime(const int64_t formId, const int64_t nextTime) +{ + APP_LOGI("%{public}s called.", __func__); + + if (nextTime < MIN_NEXT_TIME) { + APP_LOGE("next time litte than 300 seconds."); + return false; + } + + if (FormMgr::GetInstance().GetRecoverStatus() == Constants::IN_RECOVERING) { + APP_LOGE("%{public}s, formManager is in recovering", __func__); + return false; + } + + int result = FormMgr::GetInstance().SetNextRefreshTime(formId, nextTime); + if (result != ERR_OK) { + APP_LOGE("%{public}s, internal error:[%{public}d]", __func__, result); + return false; + } + + return true; +} +/** + * @brief Requests for form data update. + * + * This method must be called when the application has detected that a system setting item (such as the language, + * resolution, or screen orientation) being listened for has changed. Upon receiving the update request, the form + * provider automatically updates the form data (if there is any update) through the form framework, with the update + * process being unperceivable by the application. + * + * @param formId Indicates the ID of the form to update. + * @return Returns true if the update request is successfully initiated, returns false otherwise. + */ +bool Ability::RequestForm(const int64_t formId) +{ + APP_LOGI("%{public}s called.", __func__); + Want want; + return RequestForm(formId, want); +} + +/** + * @brief Update form. + * + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ +void Ability::ProcessFormUpdate(const FormJsInfo &formJsInfo) +{ + APP_LOGI("%{public}s called.", __func__); + + // post the async task of handleFormMessage + int32_t msgCode = OHOS_FORM_UPDATE_FORM; + PostTask([this, msgCode, formJsInfo]() {HandleFormMessage(msgCode, formJsInfo);}, 0L); +} +/** + * @brief Uninstall form. + * + * @param formId Indicates the ID of the form to uninstall. + */ +void Ability::ProcessFormUninstall(const int64_t formId) { + APP_LOGI("%{public}s start.", __func__); + std::shared_ptr formCallback = nullptr; + { + std::lock_guard lock(formLock); + // get callback iterator by formId + std::map>::iterator appCallbackIterator = + appCallbacks_.find(formId); + + + // call the callback function when you need to be notified + if (appCallbackIterator == appCallbacks_.end()) { + APP_LOGE("%{public}s failed, callback not find, formId: %{public}lld.", __func__, formId); + return; + } + formCallback = appCallbackIterator->second; + CleanFormResource(formId); + } + if ( formCallback == nullptr) { + APP_LOGE("%{public}s failed, callback is nullptr.", __func__); + return; + } + + formCallback->OnFormUninstall(formId); + + APP_LOGI("%{public}s end.", __func__); +} + +/** + * @brief Called to return a FormProviderInfo object. + * + *

You must override this method if your ability will serve as a form provider to provide a form for clients. + * The default implementation returns nullptr.

+ * + * @param want Indicates the detailed information for creating a FormProviderInfo. + * The Want object must include the form ID, form name of the form, + * which can be obtained from Ability#PARAM_FORM_IDENTITY_KEY, + * Ability#PARAM_FORM_NAME_KEY, and Ability#PARAM_FORM_DIMENSION_KEY, + * respectively. Such form information must be managed as persistent data for further form + * acquisition, update, and deletion. + * + * @return Returns the created FormProviderInfo object. + */ +FormProviderInfo Ability::OnCreate(const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + FormProviderInfo formProviderInfo; + return formProviderInfo; +} + +/** + * @brief Called to notify the form provider that a specified form has been deleted. Override this method if + * you want your application, as the form provider, to be notified of form deletion. + * + * @param formId Indicates the ID of the deleted form. + * @return None. + */ +void Ability::OnDelete(const int64_t formId) +{} + +/** + * @brief Called to notify the form provider to update a specified form. + * + * @param formId Indicates the ID of the form to update. + * @return none. + */ +void Ability::OnUpdate(const int64_t formId) +{ +} + +/** + * @brief Called when the form provider is notified that a temporary form is successfully converted to a normal form. + * + * @param formId Indicates the ID of the form. + * @return None. + */ +void Ability::OnCastTemptoNormal(const int64_t formId) +{} + +/** + * @brief Called when the form provider receives form events from the fms. + * + * @param formEventsMap Indicates the form events occurred. The key in the Map object indicates the form ID, + * and the value indicates the event type, which can be either FORM_VISIBLE + * or FORM_INVISIBLE. FORM_VISIBLE means that the form becomes visible, + * and FORM_INVISIBLE means that the form becomes invisible. + * @return none. + */ +void Ability::OnVisibilityChanged(const std::map &formEventsMap) +{ +} +/** + * @brief Called to notify the form provider to update a specified form. + * + * @param formId Indicates the ID of the form to update. + * @param message Form event message. + */ +void Ability::OnTriggerEvent(const int64_t formId, const std::string &message) +{ } +/** + * @brief Delete or release form with formId. + * + * @param formId Indicates the form's ID. + * @param deleteType Indicates the type of delete or release. + * @return Returns {@code true} if the form is successfully deleted; returns {@code false} otherwise. + */ +bool Ability::DeleteForm(const int64_t formId, const int32_t deleteType) +{ + APP_LOGI("%{public}s called.", __func__); + // check fms recover status + if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) { + APP_LOGE("%{public}s error, form is in recover status, can't do action on form.", __func__); + return false; + } + // check formId + if (formId <= 0) { + APP_LOGE("%{public}s error, the passed in formId can't be negative or zero.", __func__); + return false; + } + + APP_LOGI("%{public}s, delete form begin, formId is %{public}lld and deleteType is %{public}d.", + __func__, formId, deleteType); + { + // form lock + std::lock_guard lock(formLock); + // clean form resource when form is temp form + if (std::find( + lostedByReconnectTempForms_.begin(), + lostedByReconnectTempForms_.end(), + formId) != lostedByReconnectTempForms_.end()) { + CleanFormResource(formId); + // the delete temp form is successfully + return true; + } + } + + // hostClient init + sptr formHostClient = FormHostClient::GetInstance(); + // delete or release request to fms + int result; + if (deleteType == DELETE_FORM) { + result = FormMgr::GetInstance().DeleteForm(formId, formHostClient); + } else { + result = FormMgr::GetInstance().ReleaseForm( + formId, + formHostClient, + (deleteType == RELEASE_CACHED_FORM) ? true : false); + } + if (result != ERR_OK) { + APP_LOGE("%{public}s error, some internal server occurs, error code is %{public}d.", __func__, result); + return false; + } + { + // form lock + std::lock_guard lock(formLock); + // clean form resource + CleanFormResource(formId); + } + // the delete form is successfully + return true; +} + +/** + * @brief Clean form resource with formId. + * + * @param formId Indicates the form's ID. + */ +void Ability::CleanFormResource(const int64_t formId) +{ + APP_LOGI("%{public}s called.", __func__); + // compatible with int form id + int64_t cleanId {-1L}; + for (auto param : userReqParams_) { + if ((param.first & 0x00000000ffffffffL) == (formId & 0x00000000ffffffffL)) { + cleanId = param.first; + break; + } + } + if (cleanId == -1L) { + return; + } + + APP_LOGD("%{public}s. clean id is %{public}lld.", __func__, cleanId); + // remove wantParam, callback and lostedByReconnectTempForms + appCallbacks_.erase(cleanId); + userReqParams_.erase(cleanId); + auto tempForm = std::find(lostedByReconnectTempForms_.begin(), lostedByReconnectTempForms_.end(), cleanId); + if (tempForm != lostedByReconnectTempForms_.end()) { + lostedByReconnectTempForms_.erase(tempForm); + } + + // remove ability + std::shared_ptr thisAbility = this->shared_from_this(); + FormHostClient::GetInstance()->RemoveForm(thisAbility, cleanId); + + + // unregister death callback when appCallbacks is empty + if (appCallbacks_.empty()) { + std::shared_ptr thisAbility = this->shared_from_this(); + FormMgr::GetInstance().UnRegisterDeathCallback(thisAbility); + } + APP_LOGI("%{public}s end.", __func__); +} + +/** + * @brief Handle acquire result of the obtained form instance. + * + * @param want Indicates the detailed information about the form to be obtained, including the bundle name, + * module name, ability name, form name, form id, tempForm flag, form dimension, and form customize data. + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + * @param callback Indicates the callback to be invoked whenever the {@link FormJsInfo} instance is obtained. + */ +void Ability::HandleAcquireResult( + const Want &want, + const FormJsInfo &formJsInfo, + const std::shared_ptr callback) +{ + APP_LOGI("%{public}s called.", __func__); + { + // form lock + std::lock_guard lock(formLock); + + // register death when userReqParams is empty + if (userReqParams_.empty()) { + std::shared_ptr thisAbility = this->shared_from_this(); + FormMgr::GetInstance().RegisterDeathCallback(thisAbility); + } + + // save wantParam and callback + userReqParams_.insert(std::make_pair(formJsInfo.formId, want)); + appCallbacks_.insert(std::make_pair(formJsInfo.formId, callback)); + } + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + APP_LOGI("%{public}s, AcquireForm end, current time: %{public}ld", __func__, currentTime); + + // handle acquire message of the obtained form instance + callback->OnAcquired(FormCallback::OHOS_FORM_ACQUIRE_SUCCESS, formJsInfo); +} + +/** + * @brief Handle acquire message of the obtained form instance. + * + * @param msgCode Indicates the code of message type. + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ +void Ability::HandleFormMessage(const int32_t msgCode, const FormJsInfo &formJsInfo) +{ + APP_LOGI("%{public}s called.", __func__); + std::shared_ptr formCallback = nullptr; + { + std::lock_guard lock(formLock); + // get callback iterator by formId + std::map>::iterator appCallbackIterator = + appCallbacks_.find(formJsInfo.formId); + + + // call the callback function when you need to be notified + if (appCallbackIterator == appCallbacks_.end()) { + APP_LOGE("%{public}s failed, callback not find, formId: %{public}lld.", __func__, formJsInfo.formId); + return; + } + formCallback = appCallbackIterator->second; + } + if ( formCallback == nullptr) { + APP_LOGE("%{public}s failed, callback is nullptr.", __func__); + return; + } + + APP_LOGI("%{public}s, call user implement of form %{public}lld.", __func__, formJsInfo.formId); + + if (msgCode == OHOS_FORM_ACQUIRE_FORM) { + formCallback->OnAcquired(FormCallback::OHOS_FORM_ACQUIRE_SUCCESS, formJsInfo); + } else { + formCallback->OnUpdate(FormCallback::OHOS_FORM_UPDATE_SUCCESS, formJsInfo); + } +} + +/** + * @brief Notify the forms visibility change event. + * + * @param formIds Indicates the IDs of the forms to be made visible or invisible. + * @param eventType Indicates the form events occurred. FORM_VISIBLE means that the form becomes visible, + * and FORM_INVISIBLE means that the form becomes invisible. + * @return Returns {@code true} if the request is successfully initiated; returns {@code false} otherwise. + */ +bool Ability::NotifyWhetherVisibleForms(const std::vector &formIds, int32_t eventType) +{ + APP_LOGI("%{public}s called.", __func__); + + if (formIds.empty() || formIds.size() > Constants::MAX_VISIBLE_NOTIFY_LIST) { + APP_LOGE("%{public}s, formIds is empty or exceed 32.", __func__); + return false; + } + + if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) { + APP_LOGE("%{public}s error, form is in recover status, can't do action on form.", __func__); + return false; + } + + int resultCode = FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, FormHostClient::GetInstance(), eventType); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s error, internal error occurs, error code:%{public}d.", __func__, resultCode); + return false; + } + return true; +} + +/** + * @brief Check the param of want. + * + * @param formId Indicates the form's ID. + * @param want Indicates the detailed information about the form to be obtained, including the bundle name, + * module name, ability name, form name, form id, tempForm flag, form dimension, and form customize data. + * @return Returns {@code true} if the check result is ok; returns {@code false} ng. + */ +bool Ability::CheckWantValid(const int64_t formId, const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + + // get want parameters + int32_t formDimension = want.GetIntParam(Constants::PARAM_FORM_DIMENSION_KEY, 1); + std::string moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY); + + ElementName elementName = want.GetElement(); + std::string bundleName = elementName.GetBundleName(); + std::string abilityName = elementName.GetAbilityName(); + + bool tempFormFlg = want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + + APP_LOGD("%{public}s, param of formDimension %{public}d in want.", __func__, formDimension); + APP_LOGD("%{public}s, param of moduleName %{public}s in want.", __func__, moduleName.c_str()); + APP_LOGD("%{public}s, param of bundleName %{public}s in want.", __func__, bundleName.c_str()); + APP_LOGD("%{public}s, param of abilityName %{public}s in want.", __func__, abilityName.c_str()); + APP_LOGD("%{public}s, param of tempFormFlg %{public}d in want.", __func__, tempFormFlg); + + // check want parameters + if (bundleName.empty() || abilityName.empty() || moduleName.empty()) { + APP_LOGE("%{public}s error, bundleName or abilityName or moduleName is not set in want.", __func__); + return false; + } + if (FormHostClient::GetInstance()->ContainsForm(formId)) { + APP_LOGE("%{public}s error, form has already acquired, do not support acquire twice.", __func__); + return false; + } + if (formDimension <= 0) { + APP_LOGE("%{public}s error, dimension should not be zero or negative in want.", __func__); + return false; + } + if (tempFormFlg && formId != 0) { + APP_LOGE("%{public}s error, can not select form id when acquire temporary form.", __func__); + return false; + } + + // the check is successfully + return true; +} + +/** + * @brief Enable form update. + * + * @param formIds FormIds of hostclient. + */ +bool Ability::EnableUpdateForm(const std::vector &formIds) +{ + APP_LOGI("%{public}s called.", __func__); + return LifecycleUpdate(formIds, ENABLE_FORM_UPDATE); +} + +/** + * @brief Disable form update. + * + * @param formIds FormIds of hostclient. + */ +bool Ability::DisableUpdateForm(const std::vector &formIds) +{ + APP_LOGI("%{public}s called.", __func__); + return LifecycleUpdate(formIds, DISABLE_FORM_UPDATE); +} + +bool Ability::LifecycleUpdate(std::vector formIds, int32_t updateType) +{ + if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) { + APP_LOGE("%{public}s error, form is in recover status, can't do action on form.", __func__); + return false; + } + + // hostClient init + sptr formHostClient = FormHostClient::GetInstance(); + if (formHostClient == nullptr) { + APP_LOGE("%{public}s error, formHostClient == nullptr.", __func__); + return false; + } + + int result = FormMgr::GetInstance().LifecycleUpdate(formIds, formHostClient, updateType); + if (result != ERR_OK) { + APP_LOGE("%{public}s error, internal error.", __func__); + return false; + } + + return true; +} + +/** + * @brief Requests for form data update, by passing a set of parameters (using Want) to the form provider. + * + * This method must be called when the application has detected that a system setting item (such as the language, + * resolution, or screen orientation) being listened for has changed. Upon receiving the update request, the form + * provider automatically updates the form data (if there is any update) through the form framework, with the update + * process being unperceivable by the application. + * + * @param formId Indicates the ID of the form to update. + * @param want Indicates a set of parameters to be transparently passed to the form provider. + * @return Returns true if the update request is successfully initiated, returns false otherwise. + */ +bool Ability::RequestForm(const int64_t formId, const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + + if (formId <= 0) { + APP_LOGE("%{public}s error, The passed formid is invalid. Its value must be larger than 0.", __func__); + return false; + } + + if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) { + APP_LOGE("%{public}s error, form is in recover status, can't do action on form.", __func__); + return false; + } + + // requestForm request to fms + int resultCode = FormMgr::GetInstance().RequestForm(formId, FormHostClient::GetInstance(), want); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s error, failed to notify the form service that the form user's lifecycle is updated, error code is %{public}d.", __func__, resultCode); + return false; + } + + return true; +} + +/** + * @brief Called to reacquire form and update the form host after the death callback is received. + * + */ +void Ability::OnDeathReceived() +{ + APP_LOGI("%{public}s called.", __func__); + + int64_t formId; + std::map &userReqParams = userReqParams_; + std::vector &lostedTempForms = lostedByReconnectTempForms_; + for (const auto &userReqRaram : userReqParams) { + formId = userReqRaram.first; + Want want; + { + std::lock_guard lock(formLock); + want = userReqRaram.second; + if (want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false) + && std::find(lostedTempForms.begin(), lostedTempForms.end(), + formId) == lostedTempForms.end()) { + lostedTempForms.emplace_back(formId); + continue; + } + } + + bool result = ReAcquireForm(formId, want); + if (!result) { + APP_LOGI("%{public}s error, reacquire form failed, formId:%{public}lld.", __func__, formId); + std::shared_ptr formCallback = nullptr; + { + std::lock_guard lock(formLock); + // get callback iterator by formId + std::map>::iterator appCallbackIterator = appCallbacks_.find(formId); + + if (appCallbackIterator == appCallbacks_.end()) { + APP_LOGW("%{public}s error, lack of form callback for form, formId:%{public}lld.", __func__, formId); + continue; + } + formCallback = appCallbackIterator->second; + } + if(formCallback == nullptr) { + APP_LOGW("%{public}s failed, callback is nullptr.", __func__); + continue; + } + + FormJsInfo formJsInfo; + formJsInfo.formId = formId; + formCallback->OnAcquired(FormCallback::OHOS_FORM_RESTORE_FAILURE, formJsInfo); + } + } +} + +/** + * @brief Reacquire a specified form when the death callback is received. + * + * @param formId Indicates the form ID. + * @param want Indicates the detailed information about the form to be obtained. + * @return Returns true if the request is successfully initiated; returns false otherwise. + */ +bool Ability::ReAcquireForm(const int64_t formId, const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + + // get the form host client + sptr formHostClient = FormHostClient::GetInstance(); + if (formHostClient == nullptr) { + APP_LOGE("%{public}s error, formHostClient is nullptr, formId:%{public}lld.", __func__, formId); + return false; + } + + // reacquire form + FormJsInfo formJsInfo; + if (FormMgr::GetInstance().AddForm(formId, want, formHostClient, formJsInfo) != ERR_OK + || formJsInfo.formId <= 0 || formJsInfo.formId != formId) { + APP_LOGE("%{public}s error, fms reacquire form failed, formId:%{public}lld.", __func__, formId); + return false; + } + + // handle update message of the obtained form instance. + ProcessFormUpdate(formJsInfo); + + return true; +} + +/** + * @brief Check form manager service ready. + * + * @return Returns true if form manager service ready; returns false otherwise. + */ +bool Ability::CheckFMSReady() +{ + APP_LOGI("%{public}s called.", __func__); + + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + auto remoteObject = systemAbilityManager->GetSystemAbility(FORM_MGR_SERVICE_ID); + if (remoteObject == nullptr) { + APP_LOGI("%{public}s, form manager service is not ready.", __func__); + return false; + } + + return true; +} + +/** + * @brief Get All FormsInfo. + * + * @param formInfos Returns the forms' information of all forms provided. + * @return Returns true if the request is successfully initiated; returns false otherwise. + */ +bool Ability::GetAllFormsInfo(std::vector &formInfos) +{ + APP_LOGI("%{public}s called.", __func__); + + sptr iBundleMgr = GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("%{public}s error, failed to get IBundleMgr.", __func__); + return false; + } + + if (!CheckPermission()) { + return false; + } + + return iBundleMgr->GetAllFormsInfo(formInfos); +} + +/** + * @brief Get forms info by application name. + * + * @param bundleName Application name. + * @param formInfos Returns the forms' information of the specify application name. + * @return Returns true if the request is successfully initiated; returns false otherwise. + */ +bool Ability::GetFormsInfoByApp(std::string &bundleName, std::vector &formInfos) +{ + APP_LOGI("%{public}s called.", __func__); + bool IsGetFormsInfoByApp = false; + if (bundleName.empty()) { + APP_LOGW("save info fail, empty bundle name"); + return IsGetFormsInfoByApp; + } + + sptr iBundleMgr = GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("%{public}s error, failed to get IBundleMgr.", __func__); + return IsGetFormsInfoByApp; + } + + if (!CheckPermission()) { + return IsGetFormsInfoByApp; + } + + IsGetFormsInfoByApp = iBundleMgr->GetFormsInfoByApp(bundleName, formInfos); + if (formInfos.size() == 0){ + return IsGetFormsInfoByApp; + } + + return IsGetFormsInfoByApp; +} + + + /** + * @brief Get forms info by application name and module name. + * + * @param bundleName Application name. + * @param moduleName Module name of hap. + * @param formInfos Returns the forms' information of the specify application name and module name. + * @return Returns true if the request is successfully initiated; returns false otherwise. + */ +bool Ability::GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, std::vector &formInfos) +{ + APP_LOGI("%{public}s called.", __func__); + + bool IsGetFormsInfoByModule = false; + if (bundleName.empty() || moduleName.empty()) { + APP_LOGW("save info fail, empty bundle name"); + return IsGetFormsInfoByModule; + } + + sptr iBundleMgr = GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("%{public}s error, failed to get IBundleMgr.", __func__); + return IsGetFormsInfoByModule; + } + + if (!CheckPermission()) { + return IsGetFormsInfoByModule; + } + + IsGetFormsInfoByModule = iBundleMgr->GetFormsInfoByModule(bundleName, moduleName, formInfos); + + return IsGetFormsInfoByModule; +} + +/** + * @brief Acquire a bundle manager, if it not existed. + * @return returns the bundle manager ipc object, or nullptr for failed. + */ +sptr Ability::GetBundleMgr() +{ + APP_LOGI("%{public}s called.", __func__); + + if (iBundleMgr_ == nullptr) { + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + auto remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + APP_LOGE("%{public}s error, failed to get bundle manager service.", __func__); + return nullptr; + } + + iBundleMgr_ = iface_cast(remoteObject); + if (iBundleMgr_ == nullptr) { + APP_LOGE("%{public}s error, failed to get bundle manager service", __func__); + return nullptr; + } + } + + return iBundleMgr_; +} + +/** + * @brief check permission of bundle, if it not existed. + * @return returns the permission is vaild, or false for failed. + */ +bool Ability::CheckPermission() { + APP_LOGI("%{public}s called.", __func__); + + int32_t uid = IPCSkeleton::GetCallingUid(); + if (!iBundleMgr_->CheckIsSystemAppByUid(uid)) { + APP_LOGE("%{public}s fail, form is not system app. uid:%{public}d", __func__, uid); + return false; + } + + std::string bundleName; + bool result = iBundleMgr_->GetBundleNameForUid(uid, bundleName); + if (!result || bundleName.empty()) { + APP_LOGE("%{public}s failed, cannot get bundle name by uid:%{public}d", __func__, uid); + return false; + } + + return true; +} + +/** + * @brief Add the bundle manager instance for debug. + * @param bundleManager the bundle manager ipc object. + */ +void Ability::SetBundleManager(const sptr &bundleManager) +{ + APP_LOGI("%{public}s called.", __func__); + + iBundleMgr_ = bundleManager; +} +/** + * @brief Acquire a form provider remote object. + * @return Returns form provider remote object. + */ +sptr Ability::GetFormRemoteObject() +{ + APP_LOGI("%{public}s start", __func__); + if(providerRemoteObject_ == nullptr) { + sptr providerClient = new (std::nothrow) FormProviderClient(); + std::shared_ptr thisAbility = this->shared_from_this(); + if(thisAbility == nullptr) { + APP_LOGE("%{public}s failed, thisAbility is nullptr", __func__); + } + providerClient->SetOwner(thisAbility); + providerRemoteObject_ = providerClient->AsObject(); + } + APP_LOGI("%{public}s end", __func__); + return providerRemoteObject_; +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/src/ability_context.cpp b/frameworks/kits/ability/native/src/ability_context.cpp index b6392ee630e..f2d7584623e 100755 --- a/frameworks/kits/ability/native/src/ability_context.cpp +++ b/frameworks/kits/ability/native/src/ability_context.cpp @@ -43,6 +43,7 @@ int AbilityContext::ABILITY_CONTEXT_DEFAULT_REQUEST_CODE(0); */ void AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode) { + APP_LOGI("%{public}s begin.", __func__); APP_LOGI("AbilityContext::StartAbility called, requestCode = %{public}d", requestCode); AppExecFwk::AbilityType type = GetAbilityInfoType(); @@ -52,7 +53,9 @@ void AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode) } if (CheckIfOperateRemote(want)) { + APP_LOGI("%{public}s. Start calling GetDistributedSchedServiceProxy.", __func__); std::shared_ptr dms = GetDistributedSchedServiceProxy(); + APP_LOGI("%{public}s. End calling GetDistributedSchedServiceProxy.", __func__); if (dms != nullptr) { AppExecFwk::AbilityInfo abilityInfo; APP_LOGI("AbilityContext::StartAbility. try to StartRemoteAbility"); @@ -66,11 +69,14 @@ void AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode) return; } } else { + APP_LOGI("%{public}s. Start calling ams->StartAbility.", __func__); ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, requestCode); + APP_LOGI("%{public}s. End calling ams->StartAbility. ret=%{public}d", __func__, err); if (err != ERR_OK) { APP_LOGE("AbilityContext::StartAbility is failed %{public}d", err); } } + APP_LOGI("%{public}s end.", __func__); } /** @@ -84,11 +90,13 @@ void AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode) */ void AbilityContext::StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting) { + APP_LOGI("%{public}s begin.", __func__); AppExecFwk::AbilityType type = GetAbilityInfoType(); if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) { APP_LOGE("AbilityContext::StartAbility AbilityType = %{public}d", type); return; } + APP_LOGI("%{public}s end.", __func__); } /** @@ -100,10 +108,12 @@ void AbilityContext::StartAbility(const Want &want, int requestCode, const Abili */ void AbilityContext::TerminateAbility(int requestCode) { + APP_LOGI("%{public}s begin.", __func__); ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, requestCode); if (err != ERR_OK) { APP_LOGE("AbilityContext::TerminateAbility is failed %{public}d", err); } + APP_LOGI("%{public}s end.", __func__); } /** @@ -112,6 +122,7 @@ void AbilityContext::TerminateAbility(int requestCode) */ void AbilityContext::TerminateAbility() { + APP_LOGI("%{public}s begin.", __func__); std::shared_ptr info = GetAbilityInfo(); if (info == nullptr) { APP_LOGE("AbilityContext::TerminateAbility info == nullptr"); @@ -122,10 +133,14 @@ void AbilityContext::TerminateAbility() switch (info->type) { case AppExecFwk::AbilityType::PAGE: + APP_LOGI("%{public}s begin ams->TerminateAbility for PAGE.", __func__); err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, resultCode_, &resultWant_); + APP_LOGI("%{public}s end ams->TerminateAbility for PAGE, ret=%{public}d", __func__, err); break; case AppExecFwk::AbilityType::SERVICE: + APP_LOGI("%{public}s begin ams->TerminateAbility for SERVICE.", __func__); err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, -1, nullptr); + APP_LOGI("%{public}s end ams->TerminateAbility for SERVICE, ret=%{public}d", __func__, err); break; default: APP_LOGE("AbilityContext::TerminateAbility info type error is %{public}d", info->type); @@ -135,7 +150,8 @@ void AbilityContext::TerminateAbility() if (err != ERR_OK) { APP_LOGE("AbilityContext::TerminateAbility is failed %{public}d", err); } -} // namespace AppExecFwk + APP_LOGI("%{public}s end.", __func__); +} /** * @brief Obtains the bundle name of the ability that called the current ability. @@ -157,6 +173,7 @@ std::string AbilityContext::GetCallingBundle() */ std::shared_ptr AbilityContext::GetElementName() { + APP_LOGI("%{public}s begin.", __func__); std::shared_ptr info = GetAbilityInfo(); if (info == nullptr) { APP_LOGE("AbilityContext::GetElementName info == nullptr"); @@ -171,6 +188,7 @@ std::shared_ptr AbilityContext::GetElementName() elementName->SetAbilityName(info->name); elementName->SetBundleName(info->bundleName); elementName->SetDeviceID(info->deviceId); + APP_LOGI("%{public}s end.", __func__); return elementName; } @@ -181,6 +199,7 @@ std::shared_ptr AbilityContext::GetElementName() */ std::shared_ptr AbilityContext::GetCallingAbility() { + APP_LOGI("%{public}s begin.", __func__); std::shared_ptr elementName = std::make_shared(); if (elementName == nullptr) { @@ -190,6 +209,7 @@ std::shared_ptr AbilityContext::GetCallingAbility() elementName->SetAbilityName(callingAbilityName_); elementName->SetBundleName(callingBundleName_); elementName->SetDeviceID(callingDeviceId_); + APP_LOGI("%{public}s end.", __func__); return elementName; } @@ -204,7 +224,7 @@ std::shared_ptr AbilityContext::GetCallingAbility() */ bool AbilityContext::ConnectAbility(const Want &want, const sptr &conn) { - APP_LOGD("AbilityContext::ConnectAbility called"); + APP_LOGI("%{public}s begin.", __func__); AppExecFwk::AbilityType type = GetAbilityInfoType(); if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) { @@ -212,11 +232,14 @@ bool AbilityContext::ConnectAbility(const Want &want, const sptrConnectAbility", __func__); ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, conn, token_); + APP_LOGI("%{public}s end ams->ConnectAbility, ret=%{public}d", __func__, ret); bool value = ((ret == ERR_OK) ? true : false); if (!value) { APP_LOGE("AbilityContext::ConnectAbility ErrorCode = %{public}d", ret); } + APP_LOGI("%{public}s end.", __func__); return value; } @@ -227,7 +250,7 @@ bool AbilityContext::ConnectAbility(const Want &want, const sptr &conn) { - APP_LOGD("AbilityContext::DisconnectAbility called"); + APP_LOGD("AbilityContext::DisconnectAbility begin"); AppExecFwk::AbilityType type = GetAbilityInfoType(); if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) { @@ -235,10 +258,13 @@ void AbilityContext::DisconnectAbility(const sptr &co return; } + APP_LOGI("%{public}s begin ams->DisconnectAbility", __func__); ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(conn); + APP_LOGI("%{public}s end ams->ConnectAbility, ret=%{public}d", __func__, ret); if (ret != ERR_OK) { APP_LOGE("AbilityContext::DisconnectAbility error"); } + APP_LOGD("AbilityContext::DisconnectAbility end"); } /** @@ -253,18 +279,22 @@ void AbilityContext::DisconnectAbility(const sptr &co */ bool AbilityContext::StopAbility(const AAFwk::Want &want) { + APP_LOGI("%{public}s begin.", __func__); AppExecFwk::AbilityType type = GetAbilityInfoType(); if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) { APP_LOGE("AbilityContext::StopAbility AbilityType = %{public}d", type); return false; } + APP_LOGI("%{public}s begin ams->StopServiceAbility", __func__); ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StopServiceAbility(want); + APP_LOGI("%{public}s end ams->StopServiceAbility, ret=%{public}d", __func__, err); if (err != ERR_OK) { APP_LOGE("AbilityContext::StopAbility is failed %{public}d", err); return false; } + APP_LOGI("%{public}s end.", __func__); return true; } @@ -502,18 +532,21 @@ std::shared_ptr AbilityContext::CreateBundleContext(std::string bundleN */ std::shared_ptr AbilityContext::GetResourceManager() const { + APP_LOGI("%{public}s begin.", __func__); std::shared_ptr appcontext = GetApplicationContext(); if (appcontext == nullptr) { APP_LOGE("AbilityContext::GetResourceManager appcontext is nullptr"); return nullptr; } + APP_LOGI("%{public}s begin appcontext->GetResourceManager.", __func__); std::shared_ptr resourceManager = appcontext->GetResourceManager(); + APP_LOGI("%{public}s end appcontext->GetResourceManager.", __func__); if (resourceManager == nullptr) { APP_LOGE("AbilityContext::GetResourceManager resourceManager is nullptr"); return nullptr; } - + APP_LOGI("%{public}s end.", __func__); return resourceManager; } @@ -529,6 +562,7 @@ std::shared_ptr AbilityContext::GetResourceMa */ int AbilityContext::VerifySelfPermission(const std::string &permission) { + APP_LOGI("%{public}s begin. permission=%{public}s", __func__, permission.c_str()); if (permission.empty()) { APP_LOGE("VerifySelfPermission permission invalid"); return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; @@ -545,7 +579,12 @@ int AbilityContext::VerifySelfPermission(const std::string &permission) APP_LOGE("VerifySelfPermission failed to get bundle manager service"); return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; } - return ptr->CheckPermission(bundle_name, permission); + + APP_LOGI("%{public}s start bms->CheckPermission. bundle_name=%{public}s", __func__, bundle_name.c_str()); + int ret = ptr->CheckPermission(bundle_name, permission); + APP_LOGI("%{public}s end bms->CheckPermission, ret=%{public}d", __func__, ret); + APP_LOGI("%{public}s end.", __func__); + return ret; } /** @@ -559,6 +598,7 @@ int AbilityContext::VerifySelfPermission(const std::string &permission) */ int AbilityContext::VerifyCallingPermission(const std::string &permission) { + APP_LOGI("%{public}s begin. permission=%{public}s", __func__, permission.c_str()); if (permission.empty()) { APP_LOGE("VerifyCallingPermission permission invalid"); return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; @@ -575,7 +615,12 @@ int AbilityContext::VerifyCallingPermission(const std::string &permission) APP_LOGE("VerifyCallingPermission failed to get bundle manager service"); return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; } - return ptr->CheckPermission(bundle_name, permission); + + APP_LOGI("%{public}s start bms->CheckPermission. bundle_name=%{public}s", __func__, bundle_name.c_str()); + int ret = ptr->CheckPermission(bundle_name, permission); + APP_LOGI("%{public}s end bms->CheckPermission, ret=%{public}d", __func__, ret); + APP_LOGI("%{public}s end.", __func__); + return ret; } /** @@ -592,6 +637,7 @@ int AbilityContext::VerifyCallingPermission(const std::string &permission) */ bool AbilityContext::CanRequestPermission(const std::string &permission) { + APP_LOGI("%{public}s begin. permission=%{public}s", __func__, permission.c_str()); if (permission.empty()) { APP_LOGE("CanRequestPermission permission invalid"); return true; @@ -609,7 +655,11 @@ bool AbilityContext::CanRequestPermission(const std::string &permission) return true; } - return ptr->CanRequestPermission(bundle_name, permission, 0); + APP_LOGI("%{public}s start bms->CanRequestPermission. bundle_name=%{public}s", __func__, bundle_name.c_str()); + bool ret = ptr->CanRequestPermission(bundle_name, permission, 0); + APP_LOGI("%{public}s end bms->CanRequestPermission, ret=%{public}s", __func__, ret ? "true" : "false"); + APP_LOGI("%{public}s end.", __func__); + return ret; } /** @@ -622,11 +672,7 @@ bool AbilityContext::CanRequestPermission(const std::string &permission) */ int AbilityContext::VerifyCallingOrSelfPermission(const std::string &permission) { - if (VerifyCallingPermission(permission) != AppExecFwk::Constants::PERMISSION_GRANTED) { - return VerifySelfPermission(permission); - } else { - return AppExecFwk::Constants::PERMISSION_GRANTED; - } + return VerifySelfPermission(permission); } /** @@ -640,6 +686,11 @@ int AbilityContext::VerifyCallingOrSelfPermission(const std::string &permission) */ int AbilityContext::VerifyPermission(const std::string &permission, int pid, int uid) { + APP_LOGI("%{public}s begin. permission=%{public}s, pid=%{public}d, uid=%{public}d", + __func__, + permission.c_str(), + pid, + uid); if (permission.empty()) { APP_LOGE("VerifyPermission permission invalid"); return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; @@ -657,7 +708,11 @@ int AbilityContext::VerifyPermission(const std::string &permission, int pid, int return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; } - return ptr->CheckPermission(bundle_name, permission); + APP_LOGI("%{public}s start bms->CheckPermission. bundle_name=%{public}s", __func__, bundle_name.c_str()); + int ret = ptr->CheckPermission(bundle_name, permission); + APP_LOGI("%{public}s end bms->CheckPermission, ret=%{public}d", __func__, ret); + APP_LOGI("%{public}s end.", __func__); + return ret; } void AbilityContext::GetPermissionDes(const std::string &permissionName, std::string &des) @@ -669,9 +724,11 @@ void AbilityContext::GetPermissionDes(const std::string &permissionName, std::st } PermissionDef permissionDef; + APP_LOGI("%{public}s start bms->GetPermissionDef. permissionName=%{public}s", __func__, permissionName.c_str()); if (ptr->GetPermissionDef(permissionName, permissionDef)) { des = permissionDef.description; } + APP_LOGI("%{public}s end bms->GetPermissionDef.", __func__); } /** @@ -685,6 +742,7 @@ void AbilityContext::GetPermissionDes(const std::string &permissionName, std::st */ void AbilityContext::RequestPermissionsFromUser(std::vector &permissions, int requestCode) { + APP_LOGI("%{public}s begin.", __func__); if (permissions.size() == 0) { APP_LOGE("AbilityContext::RequestPermissionsFromUser permissions is empty"); return; @@ -712,6 +770,7 @@ void AbilityContext::RequestPermissionsFromUser(std::vector &permis want.SetParam(OHOS_REQUEST_CALLER_BUNDLERNAME, GetBundleName()); StartAbility(want, requestCode); + APP_LOGI("%{public}s end.", __func__); } /* @brief Deletes the specified private file associated with the application. @@ -982,17 +1041,21 @@ int AbilityContext::GetThemeId() */ bool AbilityContext::TerminateAbilityResult(int startId) { + APP_LOGI("%{public}s begin.", __func__); auto abilityClient = AAFwk::AbilityManagerClient::GetInstance(); if (abilityClient == nullptr) { APP_LOGE("AbilityContext::TerminateAbilityResult abilityClient is nullptr"); return false; } + APP_LOGI("%{public}s begin ams->TerminateAbilityResult, startId=%{public}d.", __func__, startId); ErrCode errval = abilityClient->TerminateAbilityResult(token_, startId); + APP_LOGI("%{public}s end ams->TerminateAbilityResult, ret=%{public}d.", __func__, errval); if (errval != ERR_OK) { APP_LOGE("AbilityContext::TerminateAbilityResult TerminateAbilityResult retval is %d", errval); } + APP_LOGI("%{public}s end.", __func__); return (errval == ERR_OK) ? true : false; } @@ -1063,9 +1126,11 @@ void AbilityContext::TerminateAndRemoveMission() */ void AbilityContext::StartAbilities(const std::vector &wants) { + APP_LOGI("%{public}s begin.", __func__); for (auto want : wants) { StartAbility(want, ABILITY_CONTEXT_DEFAULT_REQUEST_CODE); } + APP_LOGI("%{public}s end.", __func__); } /** @@ -1075,15 +1140,19 @@ void AbilityContext::StartAbilities(const std::vector &wants) */ bool AbilityContext::IsFirstInMission() { + APP_LOGI("%{public}s begin.", __func__); auto abilityClient = AAFwk::AbilityManagerClient::GetInstance(); if (abilityClient == nullptr) { APP_LOGE("AbilityContext::IsFirstInMission abilityClient is nullptr"); return false; } + APP_LOGI("%{public}s begin ams->IsFirstInMission.", __func__); ErrCode errval = abilityClient->IsFirstInMission(token_); + APP_LOGI("%{public}s end ams->IsFirstInMission, ret=%{public}d", __func__, errval); if (errval != ERR_OK) { APP_LOGE("AbilityContext::IsFirstInMission IsFirstInMission retval is %d", errval); } + APP_LOGI("%{public}s end.", __func__); return (errval == ERR_OK) ? true : false; } @@ -1110,6 +1179,7 @@ bool AbilityContext::CheckIfOperateRemote(const Want &want) */ std::shared_ptr AbilityContext::GetDistributedSchedServiceProxy() { + APP_LOGI("%{public}s begin.", __func__); auto remoteObject = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(DISTRIBUTED_SCHED_SA_ID); if (remoteObject == nullptr) { APP_LOGE("failed to get dms service"); @@ -1119,6 +1189,7 @@ std::shared_ptr AbilityContext APP_LOGI("get dms proxy success."); std::shared_ptr proxy = nullptr; proxy = std::make_shared(remoteObject); + APP_LOGI("%{public}s end.", __func__); return proxy; } diff --git a/frameworks/kits/ability/native/src/ability_impl.cpp b/frameworks/kits/ability/native/src/ability_impl.cpp old mode 100755 new mode 100644 index 18989695c5a..348cc23d811 --- a/frameworks/kits/ability/native/src/ability_impl.cpp +++ b/frameworks/kits/ability/native/src/ability_impl.cpp @@ -15,6 +15,8 @@ #include "ability_impl.h" #include "app_log_wrapper.h" +#include "ability_keyevent.h" +#include "ability_touchevent.h" namespace OHOS { namespace AppExecFwk { @@ -39,6 +41,13 @@ void AbilityImpl::Init(std::shared_ptr &application, const std: abilityLifecycleCallbacks_ = application; contextDeal_ = contextDeal; + // Multimodal Events +#ifdef MMI_COMPILE + abilityKeyEventHandle_ = sptr(new (std::nothrow) AbilityKeyEventHandle(shared_from_this())); + abilityTouchEventHandle_ = + sptr(new (std::nothrow) AbilityTouchEventHandle(shared_from_this())); +#endif + APP_LOGI("AbilityImpl::init end"); } @@ -50,12 +59,12 @@ void AbilityImpl::Init(std::shared_ptr &application, const std: */ void AbilityImpl::Start(const Want &want) { + APP_LOGI("%{public}s begin.", __func__); if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { APP_LOGE("AbilityImpl::Start ability_ or abilityLifecycleCallbacks_ is nullptr"); return; } - APP_LOGI("AbilityImpl::Start"); ability_->OnStart(want); if (ability_->GetAbilityInfo()->type == AbilityType::DATA) { lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE; @@ -64,6 +73,10 @@ void AbilityImpl::Start(const Want &want) } abilityLifecycleCallbacks_->OnAbilityStart(ability_); + + // Multimodal Events Register + MMIRegister(); + APP_LOGI("%{public}s end.", __func__); } /** @@ -73,15 +86,20 @@ void AbilityImpl::Start(const Want &want) */ void AbilityImpl::Stop() { + APP_LOGI("%{public}s begin.", __func__); if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { APP_LOGE("AbilityImpl::Stop ability_ or abilityLifecycleCallbacks_ is nullptr"); return; } - APP_LOGD("AbilityImpl::Stop"); + APP_LOGI("AbilityImpl::Stop"); ability_->OnStop(); lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL; abilityLifecycleCallbacks_->OnAbilityStop(ability_); + + // Multimodal Events UnRegister + MMIUnRegister(); + APP_LOGI("%{public}s end.", __func__); } /** @@ -91,12 +109,13 @@ void AbilityImpl::Stop() */ void AbilityImpl::Active() { + APP_LOGI("%{public}s begin.", __func__); if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { APP_LOGE("AbilityImpl::Active ability_ or abilityLifecycleCallbacks_ is nullptr"); return; } - APP_LOGD("AbilityImpl::Active"); + APP_LOGI("AbilityImpl::Active"); ability_->OnActive(); if ((lifecycleState_ == AAFwk::ABILITY_STATE_INACTIVE) && (ability_->GetAbilityInfo()->type == AbilityType::PAGE)) { @@ -106,6 +125,7 @@ void AbilityImpl::Active() lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE; abilityLifecycleCallbacks_->OnAbilityActive(ability_); + APP_LOGI("%{public}s end.", __func__); } /** @@ -115,12 +135,13 @@ void AbilityImpl::Active() */ void AbilityImpl::Inactive() { + APP_LOGI("%{public}s begin.", __func__); if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { APP_LOGE("AbilityImpl::Inactive ability_ or abilityLifecycleCallbacks_ is nullptr"); return; } - APP_LOGD("AbilityImpl::Inactive"); + APP_LOGI("AbilityImpl::Inactive"); ability_->OnInactive(); if ((lifecycleState_ == AAFwk::ABILITY_STATE_ACTIVE) && (ability_->GetAbilityInfo()->type == AbilityType::PAGE)) { @@ -130,6 +151,7 @@ void AbilityImpl::Inactive() lifecycleState_ = AAFwk::ABILITY_STATE_INACTIVE; abilityLifecycleCallbacks_->OnAbilityInactive(ability_); + APP_LOGI("%{public}s end.", __func__); } /** @@ -140,15 +162,17 @@ void AbilityImpl::Inactive() */ void AbilityImpl::Foreground(const Want &want) { + APP_LOGI("%{public}s begin.", __func__); if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { APP_LOGE("AbilityImpl::Foreground ability_ or abilityLifecycleCallbacks_ is nullptr"); return; } - APP_LOGD("AbilityImpl::Foreground"); + APP_LOGI("AbilityImpl::Foreground"); ability_->OnForeground(want); lifecycleState_ = AAFwk::ABILITY_STATE_INACTIVE; abilityLifecycleCallbacks_->OnAbilityForeground(ability_); + APP_LOGI("%{public}s end.", __func__); } /** @@ -158,16 +182,18 @@ void AbilityImpl::Foreground(const Want &want) */ void AbilityImpl::Background() { + APP_LOGI("%{public}s begin.", __func__); if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { APP_LOGE("AbilityImpl::Background ability_ or abilityLifecycleCallbacks_ is nullptr"); return; } - APP_LOGD("AbilityImpl::Background"); + APP_LOGI("AbilityImpl::Background"); ability_->OnLeaveForeground(); ability_->OnBackground(); lifecycleState_ = AAFwk::ABILITY_STATE_BACKGROUND; abilityLifecycleCallbacks_->OnAbilityBackground(ability_); + APP_LOGI("%{public}s end.", __func__); } /** @@ -178,14 +204,16 @@ void AbilityImpl::Background() */ void AbilityImpl::DispatchSaveAbilityState(PacMap &outState) { + APP_LOGI("%{public}s begin.", __func__); if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { APP_LOGE("AbilityImpl::DispatchSaveAbilityState ability_ or abilityLifecycleCallbacks_ is nullptr"); return; } - APP_LOGD("AbilityImpl::DispatchSaveAbilityState"); + APP_LOGI("AbilityImpl::DispatchSaveAbilityState"); ability_->OnSaveAbilityState(outState); abilityLifecycleCallbacks_->OnAbilitySaveState(outState); + APP_LOGI("%{public}s end.", __func__); } /** @@ -196,13 +224,15 @@ void AbilityImpl::DispatchSaveAbilityState(PacMap &outState) */ void AbilityImpl::DispatchRestoreAbilityState(const PacMap &inState) { + APP_LOGI("%{public}s begin.", __func__); if (ability_ == nullptr) { APP_LOGE("AbilityImpl::DispatchRestoreAbilityState ability_ is nullptr"); return; } - APP_LOGD("AbilityImpl:: DispatchRestoreAbilityState"); - ability_->OnRestoreAbilityState(inState); + hasSaveData_ = true; + restoreData_ = inState; + APP_LOGI("%{public}s end.", __func__); } void AbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState) @@ -216,15 +246,17 @@ void AbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::LifeCy */ sptr AbilityImpl::ConnectAbility(const Want &want) { + APP_LOGI("%{public}s begin.", __func__); if (ability_ == nullptr) { APP_LOGE("AbilityImpl::ConnectAbility ability_ is nullptr"); return nullptr; } - APP_LOGD("AbilityImpl:: ConnectAbility"); + APP_LOGI("AbilityImpl:: ConnectAbility"); sptr object = ability_->OnConnect(want); lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE; abilityLifecycleCallbacks_->OnAbilityActive(ability_); + APP_LOGI("%{public}s end.", __func__); return object; } @@ -236,12 +268,14 @@ sptr AbilityImpl::ConnectAbility(const Want &want) */ void AbilityImpl::DisconnectAbility(const Want &want) { + APP_LOGI("%{public}s begin.", __func__); if (ability_ == nullptr) { APP_LOGE("AbilityImpl::DisconnectAbility ability_ is nullptr"); return; } ability_->OnDisconnect(want); + APP_LOGI("%{public}s end.", __func__); } /** @@ -258,15 +292,17 @@ void AbilityImpl::DisconnectAbility(const Want &want) */ void AbilityImpl::CommandAbility(const Want &want, bool restart, int startId) { + APP_LOGI("%{public}s begin.", __func__); if (ability_ == nullptr) { APP_LOGE("AbilityImpl::CommandAbility ability_ is nullptr"); return; } - APP_LOGD("AbilityImpl:: CommandAbility"); + APP_LOGI("AbilityImpl:: CommandAbility"); ability_->OnCommand(want, restart, startId); lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE; abilityLifecycleCallbacks_->OnAbilityActive(ability_); + APP_LOGI("%{public}s end.", __func__); } /** @@ -289,7 +325,7 @@ int AbilityImpl::GetCurrentState() */ bool AbilityImpl::DoKeyDown(int keyCode, const KeyEvent &keyEvent) { - APP_LOGD("AbilityImpl::DoKeyDown called"); + APP_LOGI("AbilityImpl::DoKeyDown called"); return false; } @@ -304,7 +340,7 @@ bool AbilityImpl::DoKeyDown(int keyCode, const KeyEvent &keyEvent) */ bool AbilityImpl::DoKeyUp(int keyCode, const KeyEvent &keyEvent) { - APP_LOGD("AbilityImpl::DoKeyUp called"); + APP_LOGI("AbilityImpl::DoKeyUp called"); return false; } @@ -318,7 +354,7 @@ bool AbilityImpl::DoKeyUp(int keyCode, const KeyEvent &keyEvent) */ bool AbilityImpl::DoTouchEvent(const TouchEvent &touchEvent) { - APP_LOGD("AbilityImpl::DoTouchEvent called"); + APP_LOGI("AbilityImpl::DoTouchEvent called"); return false; } @@ -335,6 +371,7 @@ bool AbilityImpl::DoTouchEvent(const TouchEvent &touchEvent) */ void AbilityImpl::SendResult(int requestCode, int resultCode, const Want &resultData) { + APP_LOGI("%{public}s begin.", __func__); if (ability_ == nullptr) { APP_LOGE("AbilityImpl::SendResult ability_ is nullptr"); return; @@ -359,13 +396,16 @@ void AbilityImpl::SendResult(int requestCode, int resultCode, const Want &result } grantResult.push_back(intOK); } + APP_LOGI("%{public}s begin OnRequestPermissionsFromUserResult.", __func__); ability_->OnRequestPermissionsFromUserResult(requestCode, permissions, grantResult); + APP_LOGI("%{public}s end OnRequestPermissionsFromUserResult.", __func__); } else { - APP_LOGE("AbilityImpl::SendResult user cancel permissions"); + APP_LOGI("%{public}s user cancel permissions.", __func__); } } else { ability_->OnAbilityResult(requestCode, resultCode, resultData); } + APP_LOGI("%{public}s end.", __func__); } /** @@ -376,12 +416,14 @@ void AbilityImpl::SendResult(int requestCode, int resultCode, const Want &result */ void AbilityImpl::NewWant(const Want &want) { + APP_LOGI("%{public}s begin.", __func__); if (ability_ == nullptr) { APP_LOGE("AbilityImpl::NewWant ability_ is nullptr"); return; } ability_->SetWant(want); ability_->OnNewWant(want); + APP_LOGI("%{public}s end.", __func__); } /** @@ -532,11 +574,13 @@ int AbilityImpl::BatchInsert(const Uri &uri, const std::vector &va */ void AbilityImpl::SerUriString(const std::string &uri) { + APP_LOGI("%{public}s begin.", __func__); if (contextDeal_ == nullptr) { APP_LOGE("AbilityImpl::SerUriString contextDeal_ is nullptr"); return; } contextDeal_->SerUriString(uri); + APP_LOGI("%{public}s end.", __func__); } /** @@ -553,6 +597,31 @@ void AbilityImpl::SetLifeCycleStateInfo(const AAFwk::LifeCycleStateInfo &info) contextDeal_->SetLifeCycleStateInfo(info); } +/** + * @brief Check if it needs to restore the data to the ability. + * + * @return Return true if need and success, otherwise return false. + */ +bool AbilityImpl::CheckAndRestore() +{ + APP_LOGI("AbilityImpl::CheckAndRestore called start"); + if (!hasSaveData_) { + APP_LOGE("AbilityImpl::CheckAndRestore hasSaveData_ is false"); + return false; + } + + if (ability_ == nullptr) { + APP_LOGE("AbilityImpl::CheckAndRestore ability_ is nullptr"); + return false; + } + + APP_LOGI("AbilityImpl::CheckAndRestore ready to restore"); + ability_->OnRestoreAbilityState(restoreData_); + + APP_LOGI("AbilityImpl::CheckAndRestore called end"); + return true; +} + /** * @brief Set deviceId/bundleName/abilityName of the calling ability * @@ -569,5 +638,123 @@ void AbilityImpl::SetCallingContext( ability_->SetCallingContext(deviceId, bundleName, abilityName); } } + +/** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the + * context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to any + * method that is called on the Data ability must require normalization verification and denormalization. The default + * implementation of this method returns null, indicating that this Data ability does not support URI normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ +Uri AbilityImpl::NormalizeUri(const Uri &uri) +{ + return uri; +} + +/** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed to + * this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found in the + * current environment. + */ +Uri AbilityImpl::DenormalizeUri(const Uri &uri) +{ + return uri; +} +/* + * @brief ScheduleUpdateConfiguration, scheduling update configuration. + */ +void AbilityImpl::ScheduleUpdateConfiguration(const AAFwk::DummyConfiguration &config) +{ + APP_LOGI("%{public}s begin.", __func__); + if (ability_ == nullptr) { + APP_LOGE("AbilityImpl::ScheduleUpdateConfiguration ability_ is nullptr"); + } + + Configuration configtest; + ability_->OnConfigurationUpdated(configtest); + // ability_->OnConfigurationUpdated(config); + APP_LOGI("%{public}s end.", __func__); +} +/** + * @brief Multimodal Events Register. + */ +void AbilityImpl::MMIRegister() +{ +#ifdef MMI_COMPILE + APP_LOGI("%{public}s called.", __func__); + int32_t ret = 0; + int32_t windowID = 0; + if (ability_->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE) { + if (ability_->GetWindow() != nullptr) { + windowID = ability_->GetWindow()->GetWindowID(); + } + } + + // register keyEvent + ret = MMIEventHdl->RegisterStandardizedEventHandle(token_, windowID, abilityKeyEventHandle_); + APP_LOGI("MMIRegister :token:%{public}p windowID:%{public}d", token_.GetRefPtr(), windowID); + APP_LOGI("MMIRegister :keyEventHandler:%{public}p", abilityKeyEventHandle_.GetRefPtr()); + APP_LOGI("MMIRegister :RegisterkeyEventHandler ret:%{public}d", ret); + + // register touchEvent + ret = MMIEventHdl->RegisterStandardizedEventHandle(token_, windowID, abilityTouchEventHandle_); + APP_LOGI("MMIRegister :token:%{public}p windowID:%{public}d", token_.GetRefPtr(), windowID); + APP_LOGI("MMIRegister :touchEventHandler:%{public}p", abilityTouchEventHandle_.GetRefPtr()); + APP_LOGI("MMIRegister :RegistertouchEventHandler ret:%{public}d", ret); +#endif +} + +/** + * @brief Multimodal Events UnRegister. + */ +void AbilityImpl::MMIUnRegister() +{ +#ifdef MMI_COMPILE + APP_LOGI("%{public}s called.", __func__); + int32_t ret = 0; + int32_t windowID = 0; + if (ability_->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE) { + if (ability_->GetWindow() != nullptr) { + windowID = ability_->GetWindow()->GetWindowID(); + } + } + // unregister keyEvent + ret = MMIEventHdl->UnregisterStandardizedEventHandle(token_, windowID, abilityKeyEventHandle_); + APP_LOGI("MMIUnRegister :token:%{public}p windowID:%{public}d", token_.GetRefPtr(), windowID); + APP_LOGI("MMIUnRegister :keyEventHandler:%{public}p", abilityKeyEventHandle_.GetRefPtr()); + APP_LOGI("MMIUnRegister :UnRegisterkeyEventHandler ret:%{public}d", ret); + + // unregister touchEvent + ret = MMIEventHdl->UnregisterStandardizedEventHandle(token_, windowID, abilityTouchEventHandle_); + APP_LOGI("MMIUnRegister :token:%{public}p windowID:%{public}d", token_.GetRefPtr(), windowID); + APP_LOGI("MMIUnRegister :touchEventHandler:%{public}p", abilityTouchEventHandle_.GetRefPtr()); + APP_LOGI("MMIUnRegister :UnRegistertouchEventHandler ret:%{public}d", ret); +#endif +} + +/** + * @brief Create a PostEvent timeout task. The default delay is 5000ms + * + * @return Return a smart pointer to a timeout object + */ +std::shared_ptr AbilityImpl::CreatePostEventTimeouter(std::string taskstr) +{ + if (ability_ == nullptr) { + APP_LOGE("AbilityImpl::CreatePostEventTimeouter ability_ is nullptr"); + return nullptr; + } + + return ability_->CreatePostEventTimeouter(taskstr); +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_keyevent.cpp b/frameworks/kits/ability/native/src/ability_keyevent.cpp new file mode 100644 index 00000000000..f56205b9de9 --- /dev/null +++ b/frameworks/kits/ability/native/src/ability_keyevent.cpp @@ -0,0 +1,82 @@ +/* + * 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_keyevent.h" +#include "ability_impl.h" +#include "app_log_wrapper.h" +#include "ability_post_event_timeout.h" + +namespace OHOS { +namespace AppExecFwk { +AbilityKeyEventHandle::AbilityKeyEventHandle(const std::shared_ptr &abilityImpl) + : abilityImpl_(abilityImpl) +{ + APP_LOGI("AbilityKeyEventHandle is created"); +} + +AbilityKeyEventHandle::~AbilityKeyEventHandle() +{ + APP_LOGI("AbilityKeyEventHandle is destroyed"); +} + +#ifdef MMI_COMPILE +/** + * @brief Called back when on key. + */ +bool AbilityKeyEventHandle::OnKey(const KeyEvent &keyEvent) +{ + APP_LOGI("AbilityKeyEventHandle::OnKey called."); + bool ret = false; + if (abilityImpl_ == nullptr) { + APP_LOGE("AbilityImpl::OnKey abilityImpl_ is nullptr. KeyCode %{public}d.", keyEvent.GetKeyCode()); + return ret; + } + + if (keyEvent.IsKeyDown()) { + std::string taskHead("OnKey"); + std::string taskCode = std::to_string(keyEvent.GetKeyCode()); + std::string taskTail("Down"); + auto timeOut = abilityImpl_->CreatePostEventTimeouter(taskHead + taskCode + taskTail); + if (timeOut == nullptr) { + APP_LOGW("AbilityKeyEventHandle::OnKeyDown timeouter Create return nullptr"); + ret = abilityImpl_->DoKeyDown(keyEvent.GetKeyCode(), keyEvent); + } else { + timeOut->TimingBegin(); + ret = abilityImpl_->DoKeyDown(keyEvent.GetKeyCode(), keyEvent); + timeOut->TimeEnd(); + } + APP_LOGI("AbilityImpl::OnKeyDown keyCode: %{public}d.", keyEvent.GetKeyCode()); + } else { + std::string taskHead("OnKey"); + std::string taskCode = std::to_string(keyEvent.GetKeyCode()); + std::string taskTail("Up"); + auto timeOut = abilityImpl_->CreatePostEventTimeouter(taskHead + taskCode + taskTail); + if (timeOut == nullptr) { + APP_LOGW("AbilityKeyEventHandle::OnKeyUp timeouter Create return nullptr"); + ret = abilityImpl_->DoKeyUp(keyEvent.GetKeyCode(), keyEvent); + } else { + timeOut->TimingBegin(); + ret = abilityImpl_->DoKeyUp(keyEvent.GetKeyCode(), keyEvent); + timeOut->TimeEnd(); + } + APP_LOGI("AbilityImpl::DoKeyUp keyCode: %{public}d.", keyEvent.GetKeyCode()); + } + + APP_LOGI("AbilityKeyEventHandle::OnKey called end. return %{public}s", ret ? "true" : "false"); + return ret; +} +#endif +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_post_event_timeout.cpp b/frameworks/kits/ability/native/src/ability_post_event_timeout.cpp new file mode 100644 index 00000000000..dfa995b6bf4 --- /dev/null +++ b/frameworks/kits/ability/native/src/ability_post_event_timeout.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 "app_log_wrapper.h" +#include "ability_post_event_timeout.h" + +// #include "event_handler.h" +#include "ability_handler.h" + +namespace OHOS { +namespace AppExecFwk { + +const int64_t AbilityPostEventTimeout::defalutDelayTime = 5000; + +std::atomic AbilityPostEventTimeout::allocationId_ = 0; + +AbilityPostEventTimeout::AbilityPostEventTimeout(std::string str, std::shared_ptr &eventHandler) +{ + // uint32_t taskId = allocationId_.fetch_add(1); + uint32_t taskId = allocationId_++; + std::string strId = std::to_string(taskId); + task_ = str + strId; + taskExec_ = false; + handler_ = eventHandler; + APP_LOGI("AbilityPostEventTimeout::AbilityPostEventTimeout() call %{public}s", task_.c_str()); +} +AbilityPostEventTimeout::~AbilityPostEventTimeout() +{ + APP_LOGI("AbilityPostEventTimeout::~AbilityPostEventTimeout() call %{public}s", task_.c_str()); + handler_.reset(); +} + +void AbilityPostEventTimeout::TimingBegin(int64_t delaytime) +{ + APP_LOGI("AbilityPostEventTimeout::TimingBegin() call %{public}s", task_.c_str()); + if (handler_ == nullptr) { + APP_LOGE("AbilityPostEventTimeout::TimingBegin %{public}s handler_ is nullptr", task_.c_str()); + return; + } + + auto task = [timeOutTask = shared_from_this()]() { timeOutTask->TimeOutProc(); }; + handler_->PostTask(task, task_, delaytime); +} +void AbilityPostEventTimeout::TimeEnd() +{ + APP_LOGI("AbilityPostEventTimeout::TimeEnd() call %{public}s", task_.c_str()); + if (handler_ == nullptr) { + APP_LOGE("AbilityPostEventTimeout::TimeEnd %{public}s handler_ is nullptr", task_.c_str()); + return; + } + + std::lock_guard lck(mtx_); + if (!taskExec_) { + taskExec_ = true; + handler_->RemoveTask(task_); + } +} + +void AbilityPostEventTimeout::TimeOutProc() +{ + APP_LOGI("AbilityPostEventTimeout::TimeOutProc() call %{public}s", task_.c_str()); + if (handler_ == nullptr) { + APP_LOGE("AbilityPostEventTimeout::TimeEnd %{public}s handler_ is nullptr", task_.c_str()); + return; + } + + std::lock_guard lck(mtx_); + if (!taskExec_) { + taskExec_ = true; + APP_LOGW("TimeOutProc %{public}s Event TimeOut", task_.c_str()); + handler_->RemoveTask(task_); + } else { + APP_LOGW("AbilityPostEventTimeout::TimeOutProc Exec Failed, The Event is %{public}s", task_.c_str()); + } +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_process.cpp b/frameworks/kits/ability/native/src/ability_process.cpp index 2ee8d325929..98145c22704 100755 --- a/frameworks/kits/ability/native/src/ability_process.cpp +++ b/frameworks/kits/ability/native/src/ability_process.cpp @@ -15,9 +15,17 @@ #include "ability_process.h" #include "app_log_wrapper.h" - +#include namespace OHOS { namespace AppExecFwk { +static void *g_handle = nullptr; +constexpr char SHARED_LIBRARY_FEATURE_ABILITY[] = "/system/lib/module/ability/libfeatureability.z.so"; +constexpr char FUNC_CALL_ON_ABILITY_RESULT[] = "CallOnAbilityResult"; +using NAPICallOnAbilityResult = void (*)(int requestCode, int resultCode, const Want &resultData, CallbackInfo cb); +constexpr char FUNC_CALL_ON_REQUEST_PERMISSIONS_FROM_USERRESULT[] = "CallOnRequestPermissionsFromUserResult"; +using NAPICallOnRequestPermissionsFromUserResult = void (*)(int requestCode, + const std::vector &permissions, const std::vector &grantResults, CallbackInfo callbackInfo); + std::shared_ptr AbilityProcess::instance_ = nullptr; std::map> AbilityProcess::abilityResultMap_; std::map> AbilityProcess::abilityRequestPermissionsForUserMap_; @@ -41,7 +49,7 @@ AbilityProcess::~AbilityProcess() void AbilityProcess::StartAbility(Ability *ability, CallAbilityParam param, CallbackInfo callback) { - APP_LOGI("AbilityProcess::StartAbility called"); + APP_LOGI("AbilityProcess::StartAbility begin"); if (ability == nullptr) { APP_LOGE("AbilityProcess::StartAbility ability is nullptr"); return; @@ -74,11 +82,12 @@ void AbilityProcess::StartAbility(Ability *ability, CallAbilityParam param, Call ability->StartAbility(param.want, *(param.setting.get())); } } + APP_LOGI("AbilityProcess::StartAbility end"); } void AbilityProcess::OnAbilityResult(Ability *ability, int requestCode, int resultCode, const Want &resultData) { - APP_LOGI("AbilityProcess::OnAbilityResult called"); + APP_LOGI("AbilityProcess::OnAbilityResult begin"); std::lock_guard lock_l(mutex_); @@ -96,17 +105,39 @@ void AbilityProcess::OnAbilityResult(Ability *ability, int requestCode, int resu } CallbackInfo callbackInfo = callback->second; - CallOnAbilityResult(requestCode, resultCode, resultData, callbackInfo); + // start open featureability lib + if (g_handle == nullptr) { + g_handle = dlopen(SHARED_LIBRARY_FEATURE_ABILITY, RTLD_LAZY); + if (g_handle == nullptr) { + APP_LOGE("%{public}s, dlopen failed %{public}s. %{public}s", + __func__, + SHARED_LIBRARY_FEATURE_ABILITY, + dlerror()); + return; + } + } + + // get function + auto func = reinterpret_cast(dlsym(g_handle, FUNC_CALL_ON_ABILITY_RESULT)); + if (func == nullptr) { + APP_LOGE("%{public}s, dlsym failed %{public}s. %{public}s", __func__, FUNC_CALL_ON_ABILITY_RESULT, dlerror()); + dlclose(g_handle); + g_handle = nullptr; + return; + } + func(requestCode, resultCode, resultData, callbackInfo); + // CallOnAbilityResult(requestCode, resultCode, resultData, callbackInfo); map.erase(requestCode); abilityResultMap_[ability] = map; + APP_LOGI("AbilityProcess::OnAbilityResult end"); } void AbilityProcess::RequestPermissionsFromUser( Ability *ability, CallAbilityPermissionParam ¶m, CallbackInfo callbackInfo) { - APP_LOGI("AbilityProcess::RequestPermissionsFromUser called"); + APP_LOGI("AbilityProcess::RequestPermissionsFromUser begin"); if (ability == nullptr) { APP_LOGE("AbilityProcess::RequestPermissionsFromUser ability is nullptr"); return; @@ -132,11 +163,13 @@ void AbilityProcess::RequestPermissionsFromUser( map[param.requestCode] = callbackInfo; abilityRequestPermissionsForUserMap_[ability] = map; } + APP_LOGI("AbilityProcess::RequestPermissionsFromUser end"); } void AbilityProcess::OnRequestPermissionsFromUserResult(Ability *ability, int requestCode, const std::vector &permissions, const std::vector &grantResults) { + APP_LOGI("AbilityProcess::OnRequestPermissionsFromUserResult begin"); if (ability == nullptr) { APP_LOGE("AbilityProcess::OnRequestPermissionsFromUserResult ability is nullptr"); return; @@ -160,10 +193,37 @@ void AbilityProcess::OnRequestPermissionsFromUserResult(Ability *ability, int re return; } CallbackInfo callbackInfo = callback->second; - CallOnRequestPermissionsFromUserResult(requestCode, permissions, grantResults, callbackInfo); + + // start open featureability lib + if (g_handle == nullptr) { + g_handle = dlopen(SHARED_LIBRARY_FEATURE_ABILITY, RTLD_LAZY); + if (g_handle == nullptr) { + APP_LOGE("%{public}s, dlopen failed %{public}s. %{public}s", + __func__, + SHARED_LIBRARY_FEATURE_ABILITY, + dlerror()); + return; + } + } + + // get function + auto func = reinterpret_cast( + dlsym(g_handle, FUNC_CALL_ON_REQUEST_PERMISSIONS_FROM_USERRESULT)); + if (func == nullptr) { + APP_LOGE("%{public}s, dlsym failed %{public}s. %{public}s", + __func__, + FUNC_CALL_ON_REQUEST_PERMISSIONS_FROM_USERRESULT, + dlerror()); + dlclose(g_handle); + g_handle = nullptr; + return; + } + func(requestCode, permissions, grantResults, callbackInfo); + // CallOnRequestPermissionsFromUserResult(requestCode, permissions, grantResults, callbackInfo); map.erase(requestCode); abilityRequestPermissionsForUserMap_[ability] = map; + APP_LOGI("AbilityProcess::OnRequestPermissionsFromUserResult end"); } } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_thread.cpp b/frameworks/kits/ability/native/src/ability_thread.cpp old mode 100755 new mode 100644 index 62491181f17..db87af94789 --- a/frameworks/kits/ability/native/src/ability_thread.cpp +++ b/frameworks/kits/ability/native/src/ability_thread.cpp @@ -28,6 +28,8 @@ namespace OHOS { namespace AppExecFwk { using AbilityManagerClient = OHOS::AAFwk::AbilityManagerClient; constexpr static char ACE_ABILITY_NAME[] = "AceAbility"; +constexpr static char ACE_SERVICE_ABILITY_NAME[] = "AceServiceAbility"; +constexpr static char ACE_DATA_ABILITY_NAME[] = "AceDataAbility"; /** * @brief Default constructor used to create a AbilityThread instance. @@ -52,7 +54,7 @@ AbilityThread::~AbilityThread() std::string AbilityThread::CreateAbilityName(const std::shared_ptr &abilityRecord) { std::string abilityName; - APP_LOGI("AbilityThread::CreateAbilityName called"); + APP_LOGI("AbilityThread::CreateAbilityName begin"); if (abilityRecord == nullptr) { APP_LOGE("AbilityThread::CreateAbilityName failed,abilityRecord is nullptr"); return abilityName; @@ -64,14 +66,24 @@ std::string AbilityThread::CreateAbilityName(const std::shared_ptrtype); APP_LOGI("AbilityThread::ability attach the ability is Native %{public}d", abilityInfo->isNativeAbility); - if ((abilityInfo->type == AbilityType::PAGE) && (abilityInfo->isNativeAbility == false)) { - APP_LOGI("AbilityThread::ability attach the ability is Ace"); - isAceAbility = true; - } - abilityName = isAceAbility ? ACE_ABILITY_NAME : abilityInfo->name; + + if (abilityInfo->isNativeAbility == false) { + if (abilityInfo->type == AbilityType::PAGE) { + abilityName = ACE_ABILITY_NAME; + } else if (abilityInfo->type == AbilityType::SERVICE) { + abilityName = ACE_SERVICE_ABILITY_NAME; + } else if (abilityInfo->type == AbilityType::DATA) { + abilityName = ACE_DATA_ABILITY_NAME; + } else { + abilityName = abilityInfo->name; + } + } else { + abilityName = abilityInfo->name; + } + + APP_LOGI("AbilityThread::CreateAbilityName end"); return abilityName; } @@ -88,6 +100,7 @@ std::string AbilityThread::CreateAbilityName(const std::shared_ptr AbilityThread::CreateAndInitContextDeal(std::shared_ptr &application, const std::shared_ptr &abilityRecord, const std::shared_ptr &abilityObject) { + APP_LOGI("AbilityThread::CreateAndInitContextDeal begin"); std::shared_ptr contextDeal = nullptr; APP_LOGI("AbilityThread::CreateAndInitContextDeal called"); if ((application == nullptr) || (abilityRecord == nullptr) || (abilityObject == nullptr)) { @@ -111,7 +124,7 @@ std::shared_ptr AbilityThread::CreateAndInitContextDeal(std::shared contextDeal->SetBundleCodePath(abilityRecord->GetAbilityInfo()->codePath); contextDeal->SetContext(abilityObject); contextDeal->SetRunner(abilityHandler_->GetEventRunner()); - + APP_LOGI("AbilityThread::CreateAndInitContextDeal end"); return contextDeal; } @@ -124,7 +137,7 @@ std::shared_ptr AbilityThread::CreateAndInitContextDeal(std::shared void AbilityThread::Attach(std::shared_ptr &application, const std::shared_ptr &abilityRecord, const std::shared_ptr &mainRunner) { - APP_LOGI("AbilityThread:: attach begin"); + APP_LOGI("AbilityThread::Attach begin"); if ((application == nullptr) || (abilityRecord == nullptr) || (mainRunner == nullptr)) { APP_LOGE("AbilityThread::ability attach failed,context or record is nullptr"); return; @@ -162,16 +175,19 @@ void AbilityThread::Attach(std::shared_ptr &application, APP_LOGE("AbilityThread::ability abilityImpl_ == nullptr"); return; } + APP_LOGI("AbilityThread::Attach before abilityImpl_->Init"); abilityImpl_->Init(application, abilityRecord, currentAbility_, abilityHandler_, token_, contextDeal); - + APP_LOGI("AbilityThread::Attach after abilityImpl_->Init"); // 4. ability attach : ipc + APP_LOGI("AbilityThread::Attach before AttachAbilityThread"); ErrCode err = AbilityManagerClient::GetInstance()->AttachAbilityThread(this, token_); + APP_LOGI("AbilityThread::Attach after AttachAbilityThread"); if (err != ERR_OK) { APP_LOGE("AbilityThread:: attach success faile err = %{public}d", err); return; } - APP_LOGI("AbilityThread:: attach success"); + APP_LOGI("AbilityThread::Attach end"); } /** @@ -182,7 +198,7 @@ void AbilityThread::Attach(std::shared_ptr &application, void AbilityThread::Attach( std::shared_ptr &application, const std::shared_ptr &abilityRecord) { - APP_LOGI("AbilityThread:: attach begin"); + APP_LOGI("AbilityThread::Attach begin"); if ((application == nullptr) || (abilityRecord == nullptr)) { APP_LOGE("AbilityThread::ability attach failed,context or record is nullptr"); return; @@ -224,16 +240,19 @@ void AbilityThread::Attach( APP_LOGE("AbilityThread::ability abilityImpl_ == nullptr"); return; } + APP_LOGI("AbilityThread::Attach before abilityImpl_->Init"); abilityImpl_->Init(application, abilityRecord, currentAbility_, abilityHandler_, token_, contextDeal); - + APP_LOGI("AbilityThread::Attach after abilityImpl_->Init"); // 4. ability attach : ipc + APP_LOGI("AbilityThread::Attach before AttachAbilityThread"); ErrCode err = AbilityManagerClient::GetInstance()->AttachAbilityThread(this, token_); + APP_LOGI("AbilityThread::Attach after AttachAbilityThread"); if (err != ERR_OK) { APP_LOGE("AbilityThread:: attach success faile err = %{public}d", err); return; } - APP_LOGI("AbilityThread:: attach success"); + APP_LOGI("AbilityThread::Attach end"); } /** @@ -243,15 +262,21 @@ void AbilityThread::Attach( */ void AbilityThread::HandleAbilityTransaction(const Want &want, const LifeCycleStateInfo &lifeCycleStateInfo) { + APP_LOGI("AbilityThread::HandleAbilityTransaction begin"); if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::HandleAbilityTransaction abilityImpl_ == nullptr"); return; } + APP_LOGI("AbilityThread::HandleAbilityTransaction before abilityImpl_->SetCallingContext"); abilityImpl_->SetCallingContext(lifeCycleStateInfo.caller.deviceId, lifeCycleStateInfo.caller.bundleName, lifeCycleStateInfo.caller.abilityName); + APP_LOGI("AbilityThread::HandleAbilityTransaction after abilityImpl_->SetCallingContext"); + APP_LOGI("AbilityThread::HandleAbilityTransaction before abilityImpl_->HandleAbilityTransaction"); abilityImpl_->HandleAbilityTransaction(want, lifeCycleStateInfo); + APP_LOGI("AbilityThread::HandleAbilityTransaction after abilityImpl_->HandleAbilityTransaction"); + APP_LOGI("AbilityThread::HandleAbilityTransaction end"); } /** @@ -260,17 +285,22 @@ void AbilityThread::HandleAbilityTransaction(const Want &want, const LifeCycleSt */ void AbilityThread::HandleConnectAbility(const Want &want) { - APP_LOGI("AbilityThread::HandleConnectAbility called"); + APP_LOGI("AbilityThread::HandleConnectAbility begin"); if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::HandleConnectAbility abilityImpl_ == nullptr"); return; } + APP_LOGI("AbilityThread::HandleConnectAbility before abilityImpl_->ConnectAbility"); sptr service = abilityImpl_->ConnectAbility(want); + APP_LOGI("AbilityThread::HandleConnectAbility after abilityImpl_->ConnectAbility"); + APP_LOGI("AbilityThread::HandleConnectAbility before ScheduleConnectAbilityDone"); ErrCode err = AbilityManagerClient::GetInstance()->ScheduleConnectAbilityDone(token_, service); + APP_LOGI("AbilityThread::HandleConnectAbility after ScheduleConnectAbilityDone"); if (err != ERR_OK) { APP_LOGE("AbilityThread:: HandleConnectAbility faile err = %{public}d", err); } + APP_LOGI("AbilityThread::HandleConnectAbility end"); } /** @@ -278,17 +308,22 @@ void AbilityThread::HandleConnectAbility(const Want &want) */ void AbilityThread::HandleDisconnectAbility(const Want &want) { - APP_LOGI("AbilityThread::HandleDisconnectAbility called"); + APP_LOGI("AbilityThread::HandleDisconnectAbility begin"); if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::HandleDisconnectAbility abilityImpl_ == nullptr"); return; } + APP_LOGI("AbilityThread::HandleDisconnectAbility before abilityImpl_->DisconnectAbility"); abilityImpl_->DisconnectAbility(want); + APP_LOGI("AbilityThread::HandleDisconnectAbility after abilityImpl_->DisconnectAbility"); + APP_LOGI("AbilityThread::HandleDisconnectAbility before ScheduleDisconnectAbilityDone"); ErrCode err = AbilityManagerClient::GetInstance()->ScheduleDisconnectAbilityDone(token_); + APP_LOGI("AbilityThread::HandleDisconnectAbility after ScheduleDisconnectAbilityDone"); if (err != ERR_OK) { APP_LOGE("AbilityThread:: HandleDisconnectAbility faile err = %{public}d", err); } + APP_LOGI("AbilityThread::HandleDisconnectAbility end"); } /** @@ -305,12 +340,17 @@ void AbilityThread::HandleDisconnectAbility(const Want &want) */ void AbilityThread::HandleCommandAbility(const Want &want, bool restart, int startId) { - APP_LOGI("AbilityThread::HandleCommandAbility called"); + APP_LOGI("AbilityThread::HandleCommandAbility begin"); + APP_LOGI("AbilityThread::HandleCommandAbility before abilityImpl_->CommandAbility"); abilityImpl_->CommandAbility(want, restart, startId); + APP_LOGI("AbilityThread::HandleCommandAbility after abilityImpl_->CommandAbility"); + APP_LOGI("AbilityThread::HandleCommandAbility before ScheduleCommandAbilityDone"); ErrCode err = AbilityManagerClient::GetInstance()->ScheduleCommandAbilityDone(token_); + APP_LOGI("AbilityThread::HandleCommandAbility after ScheduleCommandAbilityDone"); if (err != ERR_OK) { APP_LOGE("AbilityThread:: HandleCommandAbility faile err = %{public}d", err); } + APP_LOGI("AbilityThread::HandleCommandAbility end"); } /** @@ -319,13 +359,16 @@ void AbilityThread::HandleCommandAbility(const Want &want, bool restart, int sta */ void AbilityThread::HandleSaveAbilityState(PacMap &state) { - APP_LOGI("AbilityThread::HandleSaveAbilityState called"); + APP_LOGI("AbilityThread::HandleSaveAbilityState begin"); if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::HandleSaveAbilityState abilityImpl_ == nullptr"); return; } + APP_LOGI("AbilityThread::HandleSaveAbilityState before abilityImpl_->DispatchSaveAbilityState"); abilityImpl_->DispatchSaveAbilityState(state); + APP_LOGI("AbilityThread::HandleSaveAbilityState after abilityImpl_->DispatchSaveAbilityState"); + APP_LOGI("AbilityThread::HandleSaveAbilityState end"); } /** @@ -334,13 +377,16 @@ void AbilityThread::HandleSaveAbilityState(PacMap &state) */ void AbilityThread::HandleRestoreAbilityState(const PacMap &state) { - APP_LOGI("AbilityThread::HandleRestoreAbilityState called"); + APP_LOGI("AbilityThread::HandleRestoreAbilityState begin"); if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::HandleRestoreAbilityState abilityImpl_ == nullptr"); return; } + APP_LOGI("AbilityThread::HandleRestoreAbilityState before abilityImpl_->DispatchRestoreAbilityState"); abilityImpl_->DispatchRestoreAbilityState(state); + APP_LOGI("AbilityThread::HandleRestoreAbilityState after abilityImpl_->DispatchRestoreAbilityState"); + APP_LOGI("AbilityThread::HandleRestoreAbilityState end"); } /** @@ -349,24 +395,16 @@ void AbilityThread::HandleRestoreAbilityState(const PacMap &state) */ void AbilityThread::ScheduleSaveAbilityState(PacMap &state) { - APP_LOGI("AbilityThread::ScheduleSaveAbilityState called"); - + APP_LOGI("AbilityThread::ScheduleSaveAbilityState begin"); if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::ScheduleSaveAbilityState abilityImpl_ == nullptr"); return; } - auto task = [abilityThread = this, &state]() { abilityThread->HandleSaveAbilityState(state); }; - - if (abilityHandler_ == nullptr) { - APP_LOGE("AbilityThread::ScheduleSaveAbilityState abilityHandler_ == nullptr"); - return; - } - - bool ret = abilityHandler_->PostTask(task); - if (!ret) { - APP_LOGE("AbilityThread::ScheduleSaveAbilityState PostTask error"); - } + APP_LOGI("AbilityThread::ScheduleSaveAbilityState before abilityImpl_->DispatchSaveAbilityState"); + abilityImpl_->DispatchSaveAbilityState(state); + APP_LOGI("AbilityThread::ScheduleSaveAbilityState after abilityImpl_->DispatchSaveAbilityState"); + APP_LOGI("AbilityThread::ScheduleSaveAbilityState end"); } /** @@ -375,22 +413,57 @@ void AbilityThread::ScheduleSaveAbilityState(PacMap &state) */ void AbilityThread::ScheduleRestoreAbilityState(const PacMap &state) { - APP_LOGI("AbilityThread::ScheduleRestoreAbilityState called"); + APP_LOGI("AbilityThread::ScheduleRestoreAbilityState begin"); if (abilityImpl_ == nullptr) { - APP_LOGE("ScheduleRestoreAbilityState::failed"); + APP_LOGE("AbilityThread::ScheduleRestoreAbilityState abilityImpl_ == nullptr"); + return; + } + APP_LOGI("AbilityThread::ScheduleRestoreAbilityState before abilityImpl_->DispatchRestoreAbilityState"); + abilityImpl_->DispatchRestoreAbilityState(state); + APP_LOGI("AbilityThread::ScheduleRestoreAbilityState after abilityImpl_->DispatchRestoreAbilityState"); + APP_LOGI("AbilityThread::ScheduleRestoreAbilityState end"); +} + +/* + * @brief ScheduleUpdateConfiguration, scheduling update configuration. + */ +void AbilityThread::ScheduleUpdateConfiguration(const DummyConfiguration &config) +{ + APP_LOGI("AbilityThread::ScheduleUpdateConfiguration begin"); + if (abilityImpl_ == nullptr) { + APP_LOGE("AbilityThread::ScheduleUpdateConfiguration abilityImpl_ is nullptr"); return; } - auto task = [abilityThread = this, state]() { abilityThread->HandleRestoreAbilityState(state); }; + + auto task = [abilitThread = this, config]() { abilitThread->HandleUpdateConfiguration(config); }; if (abilityHandler_ == nullptr) { - APP_LOGE("AbilityThread::ScheduleRestoreAbilityState abilityHandler_ == nullptr"); + APP_LOGE("AbilityThread::ScheduleUpdateConfiguration abilityHandler_ is nullptr"); return; } bool ret = abilityHandler_->PostTask(task); if (!ret) { - APP_LOGE("AbilityThread::ScheduleRestoreAbilityState PostTask error"); + APP_LOGE("AbilityThread::ScheduleUpdateConfiguration PostTask error"); } + APP_LOGI("AbilityThread::ScheduleUpdateConfiguration end"); +} + +/* + * @brief Handle the scheduling update configuration. + */ +void AbilityThread::HandleUpdateConfiguration(const DummyConfiguration &config) +{ + APP_LOGI("AbilityThread::HandleUpdateConfiguration begin"); + if (abilityImpl_ == nullptr) { + APP_LOGE("AbilityThread::HandleUpdateConfiguration abilityImpl_ is nullptr"); + return; + } + + APP_LOGI("AbilityThread::HandleUpdateConfiguration before abilityImpl_->ScheduleUpdateConfiguration"); + abilityImpl_->ScheduleUpdateConfiguration(config); + APP_LOGI("AbilityThread::HandleUpdateConfiguration after abilityImpl_->ScheduleUpdateConfiguration"); + APP_LOGI("AbilityThread::HandleUpdateConfiguration end"); } /** @@ -400,7 +473,7 @@ void AbilityThread::ScheduleRestoreAbilityState(const PacMap &state) */ void AbilityThread::ScheduleAbilityTransaction(const Want &want, const LifeCycleStateInfo &lifeCycleStateInfo) { - APP_LOGI("ScheduleAbilityTransaction::enter, targeState = %{public}d, isNewWant = %{public}d", + APP_LOGI("ScheduleAbilityTransaction begin: targeState = %{public}d, isNewWant = %{public}d", lifeCycleStateInfo.state, lifeCycleStateInfo.isNewWant); @@ -423,6 +496,7 @@ void AbilityThread::ScheduleAbilityTransaction(const Want &want, const LifeCycle if (!ret) { APP_LOGE("AbilityThread::ScheduleAbilityTransaction PostTask error"); } + APP_LOGI("ScheduleAbilityTransaction end"); } /** @@ -431,7 +505,7 @@ void AbilityThread::ScheduleAbilityTransaction(const Want &want, const LifeCycle */ void AbilityThread::ScheduleConnectAbility(const Want &want) { - APP_LOGI("AbilityThread::ScheduleConnectAbility called"); + APP_LOGI("AbilityThread::ScheduleConnectAbility begin"); auto task = [abilityThread = this, want]() { abilityThread->HandleConnectAbility(want); }; if (abilityHandler_ == nullptr) { @@ -443,6 +517,7 @@ void AbilityThread::ScheduleConnectAbility(const Want &want) if (!ret) { APP_LOGE("AbilityThread::ScheduleConnectAbility PostTask error"); } + APP_LOGI("AbilityThread::ScheduleConnectAbility end"); } /** @@ -451,7 +526,7 @@ void AbilityThread::ScheduleConnectAbility(const Want &want) */ void AbilityThread::ScheduleDisconnectAbility(const Want &want) { - APP_LOGI("AbilityThread::ScheduleDisconnectAbility called"); + APP_LOGI("AbilityThread::ScheduleDisconnectAbility begin"); auto task = [abilityThread = this, want]() { abilityThread->HandleDisconnectAbility(want); }; if (abilityHandler_ == nullptr) { @@ -463,6 +538,7 @@ void AbilityThread::ScheduleDisconnectAbility(const Want &want) if (!ret) { APP_LOGE("AbilityThread::ScheduleDisconnectAbility PostTask error"); } + APP_LOGI("AbilityThread::ScheduleDisconnectAbility end"); } /** @@ -479,7 +555,7 @@ void AbilityThread::ScheduleDisconnectAbility(const Want &want) */ void AbilityThread::ScheduleCommandAbility(const Want &want, bool restart, int startId) { - APP_LOGI("AbilityThread::ScheduleCommandAbility called"); + APP_LOGI("AbilityThread::ScheduleCommandAbility begin"); auto task = [abilityThread = this, want, restart, startId]() { abilityThread->HandleCommandAbility(want, restart, startId); }; @@ -493,6 +569,7 @@ void AbilityThread::ScheduleCommandAbility(const Want &want, bool restart, int s if (!ret) { APP_LOGE("AbilityThread::ScheduleCommandAbility PostTask error"); } + APP_LOGI("AbilityThread::ScheduleCommandAbility end"); } /** @@ -508,14 +585,18 @@ void AbilityThread::ScheduleCommandAbility(const Want &want, bool restart, int s */ void AbilityThread::SendResult(int requestCode, int resultCode, const Want &want) { + APP_LOGI("AbilityThread::SendResult begin"); if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::SendResult abilityImpl_ == nullptr"); return; } if (requestCode != -1) { + APP_LOGI("AbilityThread::SendResult before abilityImpl_->SendResult"); abilityImpl_->SendResult(requestCode, resultCode, want); + APP_LOGI("AbilityThread::SendResult after abilityImpl_->SendResult"); } + APP_LOGI("AbilityThread::SendResult end"); } /** @@ -528,13 +609,17 @@ void AbilityThread::SendResult(int requestCode, int resultCode, const Want &want */ std::vector AbilityThread::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) { + APP_LOGI("AbilityThread::GetFileTypes begin"); std::vector types; if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::GetFileTypes abilityImpl_ is nullptr"); return types; } + APP_LOGI("AbilityThread::GetFileTypes before abilityImpl_->GetFileTypes"); types = abilityImpl_->GetFileTypes(uri, mimeTypeFilter); + APP_LOGI("AbilityThread::GetFileTypes after abilityImpl_->GetFileTypes"); + APP_LOGI("AbilityThread::GetFileTypes end"); return types; } @@ -551,13 +636,17 @@ std::vector AbilityThread::GetFileTypes(const Uri &uri, const std:: */ int AbilityThread::OpenFile(const Uri &uri, const std::string &mode) { + APP_LOGI("AbilityThread::OpenFile begin"); int fd = -1; if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::OpenFile abilityImpl_ is nullptr"); return fd; } + APP_LOGI("AbilityThread::OpenFile before abilityImpl_->OpenFile"); fd = abilityImpl_->OpenFile(uri, mode); + APP_LOGI("AbilityThread::OpenFile after abilityImpl_->OpenFile"); + APP_LOGI("AbilityThread::OpenFile end"); return fd; } @@ -575,13 +664,17 @@ int AbilityThread::OpenFile(const Uri &uri, const std::string &mode) */ int AbilityThread::OpenRawFile(const Uri &uri, const std::string &mode) { + APP_LOGI("AbilityThread::OpenRawFile begin"); int fd = -1; if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::OpenRawFile abilityImpl_ is nullptr"); return fd; } + APP_LOGI("AbilityThread::OpenRawFile before abilityImpl_->OpenRawFile"); fd = abilityImpl_->OpenRawFile(uri, mode); + APP_LOGI("AbilityThread::OpenRawFile after abilityImpl_->OpenRawFile"); + APP_LOGI("AbilityThread::OpenRawFile end"); return fd; } @@ -595,13 +688,17 @@ int AbilityThread::OpenRawFile(const Uri &uri, const std::string &mode) */ int AbilityThread::Insert(const Uri &uri, const ValuesBucket &value) { + APP_LOGI("AbilityThread::Insert begin"); int index = -1; if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::Insert abilityImpl_ is nullptr"); return index; } + APP_LOGI("AbilityThread::Insert before abilityImpl_->Insert"); index = abilityImpl_->Insert(uri, value); + APP_LOGI("AbilityThread::Insert after abilityImpl_->Insert"); + APP_LOGI("AbilityThread::Insert end"); return index; } @@ -616,13 +713,17 @@ int AbilityThread::Insert(const Uri &uri, const ValuesBucket &value) */ int AbilityThread::Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) { + APP_LOGI("AbilityThread::Update begin"); int index = -1; if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::Update abilityImpl_ is nullptr"); return index; } + APP_LOGI("AbilityThread::Update before abilityImpl_->Update"); index = abilityImpl_->Update(uri, value, predicates); + APP_LOGI("AbilityThread::Update after abilityImpl_->Update"); + APP_LOGI("AbilityThread::Update end"); return index; } @@ -636,13 +737,16 @@ int AbilityThread::Update(const Uri &uri, const ValuesBucket &value, const DataA */ int AbilityThread::Delete(const Uri &uri, const DataAbilityPredicates &predicates) { + APP_LOGI("AbilityThread::Delete begin"); int index = -1; if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::Delete abilityImpl_ is nullptr"); return index; } - + APP_LOGI("AbilityThread::Delete before abilityImpl_->Delete"); index = abilityImpl_->Delete(uri, predicates); + APP_LOGI("AbilityThread::Delete after abilityImpl_->Delete"); + APP_LOGI("AbilityThread::Delete end"); return index; } @@ -658,13 +762,17 @@ int AbilityThread::Delete(const Uri &uri, const DataAbilityPredicates &predicate std::shared_ptr AbilityThread::Query( const Uri &uri, std::vector &columns, const DataAbilityPredicates &predicates) { + APP_LOGI("AbilityThread::Query begin"); std::shared_ptr resultSet = nullptr; if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::Query abilityImpl_ is nullptr"); return resultSet; } + APP_LOGI("AbilityThread::Query before abilityImpl_->Query"); resultSet = abilityImpl_->Query(uri, columns, predicates); + APP_LOGI("AbilityThread::Query after abilityImpl_->Query"); + APP_LOGI("AbilityThread::Query end"); return resultSet; } @@ -678,13 +786,17 @@ std::shared_ptr AbilityThread::Query( */ std::string AbilityThread::GetType(const Uri &uri) { + APP_LOGI("AbilityThread::GetType begin"); std::string type; if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::GetType abilityImpl_ is nullptr"); return type; } + APP_LOGI("AbilityThread::GetType before abilityImpl_->GetType"); type = abilityImpl_->GetType(uri); + APP_LOGI("AbilityThread::GetType after abilityImpl_->GetType"); + APP_LOGI("AbilityThread::GetType end"); return type; } @@ -700,13 +812,16 @@ std::string AbilityThread::GetType(const Uri &uri) */ bool AbilityThread::Reload(const Uri &uri, const PacMap &extras) { + APP_LOGI("AbilityThread::Reload begin"); bool ret = false; if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::Reload abilityImpl_ is nullptr"); return ret; } - + APP_LOGI("AbilityThread::Reload before abilityImpl_->Reload"); ret = abilityImpl_->Reload(uri, extras); + APP_LOGI("AbilityThread::Reload after abilityImpl_->Reload"); + APP_LOGI("AbilityThread::Reload end"); return ret; } @@ -720,16 +835,32 @@ bool AbilityThread::Reload(const Uri &uri, const PacMap &extras) */ int AbilityThread::BatchInsert(const Uri &uri, const std::vector &values) { + APP_LOGI("AbilityThread::BatchInsert begin"); int ret = -1; if (abilityImpl_ == nullptr) { APP_LOGE("AbilityThread::BatchInsert​ abilityImpl_ is nullptr"); return ret; } + APP_LOGI("AbilityThread::BatchInsert before abilityImpl_->BatchInsert"); ret = abilityImpl_->BatchInsert(uri, values); + APP_LOGI("AbilityThread::BatchInsert after abilityImpl_->BatchInsert"); + APP_LOGI("AbilityThread::BatchInsert end"); return ret; } +void AbilityThread::NotifyMultiWinModeChanged(int32_t winModeKey, bool flag) +{ + APP_LOGI("NotifyMultiWinModeChanged.key:%{public}d,flag:%{public}d", winModeKey, flag); + return; +} + +void AbilityThread::NotifyTopActiveAbilityChanged(bool flag) +{ + APP_LOGI("NotifyTopActiveAbilityChanged,flag:%{public}d", flag); + return; +} + /** * @description: Attach The ability thread to the main process. * @param application Indicates the main process. @@ -739,13 +870,14 @@ int AbilityThread::BatchInsert(const Uri &uri, const std::vector & void AbilityThread::AbilityThreadMain(std::shared_ptr &application, const std::shared_ptr &abilityRecord, const std::shared_ptr &mainRunner) { - APP_LOGI("AbilityThread::AbilityThreadMain::begin"); + APP_LOGI("AbilityThread::AbilityThreadMain begin"); sptr thread = sptr(new (std::nothrow) AbilityThread()); if (thread == nullptr) { APP_LOGE("AbilityThread::AbilityThreadMain failed,thread is nullptr"); return; } thread->Attach(application, abilityRecord, mainRunner); + APP_LOGI("AbilityThread::AbilityThreadMain end"); } /** @@ -756,13 +888,67 @@ void AbilityThread::AbilityThreadMain(std::shared_ptr &applicat void AbilityThread::AbilityThreadMain( std::shared_ptr &application, const std::shared_ptr &abilityRecord) { - APP_LOGI("AbilityThread::AbilityThreadMain::begin"); + APP_LOGI("AbilityThread::AbilityThreadMain begin"); sptr thread = sptr(new (std::nothrow) AbilityThread()); if (thread == nullptr) { APP_LOGE("AbilityThread::AbilityThreadMain failed,thread is nullptr"); return; } thread->Attach(application, abilityRecord); + APP_LOGI("AbilityThread::AbilityThreadMain end"); +} +/** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the + * context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to any + * method that is called on the Data ability must require normalization verification and denormalization. The default + * implementation of this method returns null, indicating that this Data ability does not support URI normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ +Uri AbilityThread::NormalizeUri(const Uri &uri) +{ + APP_LOGI("AbilityThread::NormalizeUri begin"); + Uri urivalue(""); + if (abilityImpl_ == nullptr) { + APP_LOGE("DataAbilityHelper::normalizeUri failed dataAbility == nullptr"); + return urivalue; + } + + APP_LOGI("AbilityThread::NormalizeUri before abilityImpl_->NormalizeUri"); + urivalue = abilityImpl_->NormalizeUri(uri); + APP_LOGI("AbilityThread::NormalizeUri after abilityImpl_->NormalizeUri"); + APP_LOGI("AbilityThread::NormalizeUri end"); + return urivalue; +} + +/** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed to + * this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found in the + * current environment. + */ +Uri AbilityThread::DenormalizeUri(const Uri &uri) +{ + APP_LOGI("AbilityThread::DenormalizeUri begin"); + Uri urivalue(""); + if (abilityImpl_ == nullptr) { + APP_LOGE("DataAbilityHelper::denormalizeUri failed dataAbility == nullptr"); + return urivalue; + } + + APP_LOGI("AbilityThread::DenormalizeUri before abilityImpl_->DenormalizeUri"); + urivalue = abilityImpl_->DenormalizeUri(uri); + APP_LOGI("AbilityThread::DenormalizeUri after abilityImpl_->DenormalizeUri"); + APP_LOGI("AbilityThread::DenormalizeUri end"); + return urivalue; } } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_touchevent.cpp b/frameworks/kits/ability/native/src/ability_touchevent.cpp new file mode 100644 index 00000000000..6109b60ae92 --- /dev/null +++ b/frameworks/kits/ability/native/src/ability_touchevent.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 "ability_touchevent.h" +#include "ability_impl.h" +#include "app_log_wrapper.h" +#include "ability_post_event_timeout.h" + +namespace OHOS { +namespace AppExecFwk { +AbilityTouchEventHandle::AbilityTouchEventHandle(std::shared_ptr abilityImpl) : abilityImpl_(abilityImpl) +{ + APP_LOGI("AbilityTouchEventHandle is created"); +} + +AbilityTouchEventHandle::~AbilityTouchEventHandle() +{ + APP_LOGI("AbilityTouchEventHandle is destroyed"); +} + +#ifdef MMI_COMPILE +/** + * @brief Called back when on touch. + */ +bool AbilityTouchEventHandle::OnTouch(const TouchEvent &touchEvent) +{ + APP_LOGI("AbilityTouchEventHandle::OnTouch called."); + bool ret = false; + if (abilityImpl_ == nullptr) { + APP_LOGE("AbilityTouchEventHandle::OnTouch abilityImpl_ is nullptr"); + return ret; + } + + std::string taskHead("OnTouch"); + std::string taskCodeAction = std::to_string(touchEvent.GetAction()); + std::string taskCodePhase = std::to_string(touchEvent.GetPhase()); + std::string taskSplit("-"); + auto timeOut = + abilityImpl_->CreatePostEventTimeouter(taskHead + taskCodeAction + taskSplit + taskCodePhase + taskSplit); + if (timeOut == nullptr) { + APP_LOGW("AbilityTouchEventHandle::OnTouch timeouter Create return nullptr"); + ret = abilityImpl_->DoTouchEvent(touchEvent); + } else { + timeOut->TimingBegin(); + ret = abilityImpl_->DoTouchEvent(touchEvent); + timeOut->TimeEnd(); + } + + APP_LOGI("AbilityImpl::DoTouchEvent action: %{public}d phase: %{public}d.", + touchEvent.GetAction(), + touchEvent.GetPhase()); + return ret; +} +#endif +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_window.cpp b/frameworks/kits/ability/native/src/ability_window.cpp index eb7d4cf3f2b..4910cfa2b02 100755 --- a/frameworks/kits/ability/native/src/ability_window.cpp +++ b/frameworks/kits/ability/native/src/ability_window.cpp @@ -33,7 +33,7 @@ AbilityWindow::~AbilityWindow() */ void AbilityWindow::Init(std::shared_ptr &handler, std::shared_ptr ability) { - APP_LOGI("AbilityWindow::Init called."); + APP_LOGI("%{public}s begin.", __func__); handler_ = handler; ability_ = std::weak_ptr(ability); @@ -48,6 +48,7 @@ void AbilityWindow::Init(std::shared_ptr &handler, std::shared_p APP_LOGE("AbilityWindow::Init WindowManager::Init() return %d", wret); return; } + APP_LOGI("%{public}s end.", __func__); } /** @@ -57,7 +58,7 @@ void AbilityWindow::Init(std::shared_ptr &handler, std::shared_p */ bool AbilityWindow::SetWindowConfig(const sptr &config) { - APP_LOGI("AbilityWindow::SetWindowConfig called."); + APP_LOGI("%{public}s begin.", __func__); APP_LOGI("config width = %{public}d, height = %{public}d.", config->GetWidth(), config->GetHeight()); APP_LOGI("config pos_x = %{public}d, pos_y = %{public}d, type = %{public}d.", @@ -76,6 +77,7 @@ bool AbilityWindow::SetWindowConfig(const sptr &config) APP_LOGE("AbilityWindow::SetWindowConfig WindowManager::CreateWindow() return %d", retvalCreate); return false; } + if (windowNew_ == nullptr) { APP_LOGE("AbilityWindow::SetWindowConfig the window is nullptr."); return false; @@ -91,7 +93,7 @@ bool AbilityWindow::SetWindowConfig(const sptr &config) } isWindowAttached = true; - APP_LOGI("AbilityWindow::SetWindowConfig end."); + APP_LOGI("%{public}s end.", __func__); return true; } @@ -106,7 +108,8 @@ bool AbilityWindow::SetWindowConfig(const sptr &config) */ bool AbilityWindow::OnKeyEvent(KeyEvent event) { - APP_LOGI("AbilityWindow::OnKeyEvent called."); + APP_LOGI("%{public}s begin.", __func__); + bool ret = false; std::shared_ptr ability = nullptr; ability = ability_.lock(); @@ -115,7 +118,11 @@ bool AbilityWindow::OnKeyEvent(KeyEvent event) return ret; } switch (event.GetKeyCode()) { +#ifdef MMI_COMPILE + case OHOS::KeyEventEnum::KEY_BACK: +#else case KeyEvent::CODE_BACK: +#endif APP_LOGI("AbilityWindow::OnKeyEvent Back key pressed."); if (!event.IsKeyDown()) { ret = OnBackPressed(ability); @@ -125,6 +132,7 @@ bool AbilityWindow::OnKeyEvent(KeyEvent event) APP_LOGI("AbilityWindow::OnKeyEvent the key event is %{public}d.", event.GetKeyCode()); break; } + APP_LOGI("%{public}s end.", __func__); return ret; } @@ -138,13 +146,14 @@ bool AbilityWindow::OnKeyEvent(KeyEvent event) */ bool AbilityWindow::OnBackPressed(std::shared_ptr &ability) { - APP_LOGI("AbilityWindow::OnBackPressed called."); + APP_LOGI("%{public}s begin.", __func__); if (handler_ == nullptr) { APP_LOGE("AbilityWindow::OnBackPressed handler_ is nullptr."); return false; } auto task = [abilityRun = ability]() { abilityRun->OnBackPressed(); }; handler_->PostTask(task); + APP_LOGI("%{public}s end.", __func__); return true; } @@ -154,7 +163,7 @@ bool AbilityWindow::OnBackPressed(std::shared_ptr &ability) */ void AbilityWindow::OnPostAbilityStart() { - APP_LOGI("AbilityWindow::OnPostAbilityStart called."); + APP_LOGI("%{public}s begin.", __func__); if (!isWindowAttached) { APP_LOGE("AbilityWindow::OnPostAbilityStart window not attached."); return; @@ -166,7 +175,7 @@ void AbilityWindow::OnPostAbilityStart() APP_LOGI("%{public}s end windowNew_->Hide.", __func__); } - APP_LOGI("AbilityWindow::OnPostAbilityStart end."); + APP_LOGI("%{public}s end.", __func__); } /** @@ -185,6 +194,7 @@ void AbilityWindow::OnPostAbilityActive() APP_LOGI("%{public}s begin windowNew_->SwitchTop.", __func__); windowNew_->SwitchTop(); APP_LOGI("%{public}s end windowNew_->SwitchTop.", __func__); + APP_LOGI("%{public}s begin windowNew_->Show.", __func__); windowNew_->Show(); APP_LOGI("%{public}s end windowNew_->Show.", __func__); @@ -298,4 +308,4 @@ const sptr &AbilityWindow::GetWindow() return windowNew_; } } // namespace AppExecFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/data_ability_helper.cpp b/frameworks/kits/ability/native/src/data_ability_helper.cpp index 702e018fafd..696c0d7e5c8 100644 --- a/frameworks/kits/ability/native/src/data_ability_helper.cpp +++ b/frameworks/kits/ability/native/src/data_ability_helper.cpp @@ -26,17 +26,72 @@ using AbilityManagerClient = OHOS::AAFwk::AbilityManagerClient; DataAbilityHelper::DataAbilityHelper(const std::shared_ptr &context, const std::shared_ptr &uri, const sptr &dataAbilityProxy, bool tryBind) { + APP_LOGI("DataAbilityHelper::DataAbilityHelper start"); token_ = context->GetToken(); context_ = std::weak_ptr(context); uri_ = uri; tryBind_ = tryBind; dataAbilityProxy_ = dataAbilityProxy; + APP_LOGI("DataAbilityHelper::DataAbilityHelper end"); } DataAbilityHelper::DataAbilityHelper(const std::shared_ptr &context) { + APP_LOGI("DataAbilityHelper::DataAbilityHelper only with context start"); token_ = context->GetToken(); context_ = std::weak_ptr(context); + APP_LOGI("DataAbilityHelper::DataAbilityHelper only with context end"); +} + +DataAbilityHelper::DataAbilityHelper(const sptr &token, const std::shared_ptr &uri, + const sptr &dataAbilityProxy) +{ + APP_LOGI("DataAbilityHelper::DataAbilityHelper start"); + token_ = token; + uri_ = uri; + tryBind_ = false; + dataAbilityProxy_ = dataAbilityProxy; + isSystemCaller_ = true; + if (isSystemCaller_ && dataAbilityProxy_) { + AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + } + APP_LOGI("DataAbilityHelper::DataAbilityHelper end"); +} + +DataAbilityHelper::DataAbilityHelper(const sptr &token) +{ + APP_LOGI("DataAbilityHelper::DataAbilityHelper only with token_start"); + token_ = token; + isSystemCaller_ = true; + APP_LOGI("DataAbilityHelper::DataAbilityHelper only with token end"); +} + +void DataAbilityHelper::AddDataAbilityDeathRecipient(const sptr &token) +{ + APP_LOGI("DataAbilityHelper::AddDataAbilityDeathRecipient start."); + if (token != nullptr && callerDeathRecipient_ != nullptr) { + APP_LOGI("token RemoveDeathRecipient."); + token->RemoveDeathRecipient(callerDeathRecipient_); + } + if (callerDeathRecipient_ == nullptr) { + callerDeathRecipient_ = + new DataAbilityDeathRecipient(std::bind(&DataAbilityHelper::OnSchedulerDied, this, std::placeholders::_1)); + } + if (token != nullptr) { + APP_LOGI("token AddDeathRecipient."); + token->AddDeathRecipient(callerDeathRecipient_); + } + APP_LOGI("DataAbilityHelper::AddDataAbilityDeathRecipient end."); +} + +void DataAbilityHelper::OnSchedulerDied(const wptr &remote) +{ + APP_LOGI("'%{public}s start':", __func__); + auto object = remote.promote(); + object = nullptr; + dataAbilityProxy_ = nullptr; + uri_ = nullptr; + APP_LOGI("DataAbilityHelper::OnSchedulerDied end."); } /** @@ -48,6 +103,7 @@ DataAbilityHelper::DataAbilityHelper(const std::shared_ptr &context) */ std::shared_ptr DataAbilityHelper::Creator(const std::shared_ptr &context) { + APP_LOGI("DataAbilityHelper::Creator with context start."); if (context == nullptr) { APP_LOGE("DataAbilityHelper::Creator (context, uri, tryBind) failed, context == nullptr"); return nullptr; @@ -59,6 +115,7 @@ std::shared_ptr DataAbilityHelper::Creator(const std::shared_ return nullptr; } + APP_LOGI("DataAbilityHelper::Creator with context end."); return std::shared_ptr(ptrDataAbilityHelper); } @@ -73,6 +130,7 @@ std::shared_ptr DataAbilityHelper::Creator(const std::shared_ std::shared_ptr DataAbilityHelper::Creator( const std::shared_ptr &context, const std::shared_ptr &uri) { + APP_LOGI("DataAbilityHelper::Creator with context uri called."); return DataAbilityHelper::Creator(context, uri, false); } @@ -91,6 +149,7 @@ std::shared_ptr DataAbilityHelper::Creator( std::shared_ptr DataAbilityHelper::Creator( const std::shared_ptr &context, const std::shared_ptr &uri, const bool tryBind) { + APP_LOGI("DataAbilityHelper::Creator with context uri tryBind called start."); if (context == nullptr) { APP_LOGE("DataAbilityHelper::Creator (context, uri, tryBind) failed, context == nullptr"); return nullptr; @@ -108,12 +167,14 @@ std::shared_ptr DataAbilityHelper::Creator( return nullptr; } + APP_LOGI("DataAbilityHelper::Creator before AcquireDataAbility."); sptr dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(*uri.get(), tryBind, context->GetToken()); if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::Creator failed get dataAbilityProxy"); return nullptr; } + APP_LOGI("DataAbilityHelper::Creator after AcquireDataAbility."); DataAbilityHelper *ptrDataAbilityHelper = new (std::nothrow) DataAbilityHelper(context, uri, dataAbilityProxy, tryBind); @@ -122,6 +183,82 @@ std::shared_ptr DataAbilityHelper::Creator( return nullptr; } + APP_LOGI("DataAbilityHelper::Creator with context uri tryBind called end."); + return std::shared_ptr(ptrDataAbilityHelper); +} + +/** + * @brief Creates a DataAbilityHelper instance without specifying the Uri based. + * + * @param token Indicates the System token. + * + * @return Returns the created DataAbilityHelper instance where Uri is not specified. + */ +std::shared_ptr DataAbilityHelper::Creator(const sptr &token) +{ + APP_LOGI("DataAbilityHelper::Creator with token start."); + if (token == nullptr) { + APP_LOGE("DataAbilityHelper::Creator (token) failed, token == nullptr"); + return nullptr; + } + + DataAbilityHelper *ptrDataAbilityHelper = new (std::nothrow) DataAbilityHelper(token); + if (ptrDataAbilityHelper == nullptr) { + APP_LOGE("DataAbilityHelper::Creator (token) failed, create DataAbilityHelper failed"); + return nullptr; + } + + APP_LOGI("DataAbilityHelper::Creator with token end."); + return std::shared_ptr(ptrDataAbilityHelper); +} + +/** + * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship + * between the ability using the Data template (Data ability for short) and the associated client process in + * a DataAbilityHelper instance. + * + * @param token Indicates the System token. + * @param uri Indicates the database table or disk file to operate. + * + * @return Returns the created DataAbilityHelper instance. + */ +std::shared_ptr DataAbilityHelper::Creator( + const sptr &token, const std::shared_ptr &uri) +{ + APP_LOGI("DataAbilityHelper::Creator with token uri called start."); + if (token == nullptr) { + APP_LOGE("DataAbilityHelper::Creator (token, uri) failed, token == nullptr"); + return nullptr; + } + + if (uri == nullptr) { + APP_LOGE("DataAbilityHelper::Creator (token, uri) failed, uri == nullptr"); + return nullptr; + } + + if (uri->GetScheme() != SchemeOhos) { + APP_LOGE("DataAbilityHelper::Creator (token, uri) failed, the Scheme is not dataability, Scheme: " + "%{public}s", + uri->GetScheme().c_str()); + return nullptr; + } + + APP_LOGI("DataAbilityHelper::Creator before AcquireDataAbility."); + sptr dataAbilityProxy = + AbilityManagerClient::GetInstance()->AcquireDataAbility(*uri.get(), false, token); + if (dataAbilityProxy == nullptr) { + APP_LOGE("DataAbilityHelper::Creator failed get dataAbilityProxy"); + return nullptr; + } + APP_LOGI("DataAbilityHelper::Creator after AcquireDataAbility."); + + DataAbilityHelper *ptrDataAbilityHelper = new (std::nothrow) DataAbilityHelper(token, uri, dataAbilityProxy); + if (ptrDataAbilityHelper == nullptr) { + APP_LOGE("DataAbilityHelper::Creator (token, uri) failed, create DataAbilityHelper failed"); + return nullptr; + } + + APP_LOGI("DataAbilityHelper::Creator with token uri called end."); return std::shared_ptr(ptrDataAbilityHelper); } @@ -133,17 +270,22 @@ std::shared_ptr DataAbilityHelper::Creator( */ bool DataAbilityHelper::Release() { + APP_LOGI("DataAbilityHelper::Release start."); if (uri_ == nullptr) { APP_LOGE("DataAbilityHelper::Release failed, uri_ is nullptr"); return false; } + APP_LOGI("DataAbilityHelper::Release before ReleaseDataAbility."); int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::GetFileTypes failed to ReleaseDataAbility err = %{public}d", err); return false; } - + APP_LOGI("DataAbilityHelper::Release after ReleaseDataAbility."); + dataAbilityProxy_ = nullptr; + uri_.reset(); + APP_LOGI("DataAbilityHelper::Release end."); return true; } @@ -157,28 +299,40 @@ bool DataAbilityHelper::Release() */ std::vector DataAbilityHelper::GetFileTypes(Uri &uri, const std::string &mimeTypeFilter) { + APP_LOGI("DataAbilityHelper::GetFileTypes start."); std::vector matchedMIMEs; - if ((uri_ == nullptr) || (!uri_->Equals(uri))) { - if (uri.GetScheme() == SchemeOhos) { - sptr dataAbilityProxy = - AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); - if (dataAbilityProxy == nullptr) { - APP_LOGE("DataAbilityHelper::GetFileTypes failed dataAbility == nullptr"); - return matchedMIMEs; - } - - matchedMIMEs = dataAbilityProxy->GetFileTypes(uri, mimeTypeFilter); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return matchedMIMEs; + } - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); - if (err != ERR_OK) { - APP_LOGE("DataAbilityHelper::GetFileTypes failed to ReleaseDataAbility err = %{public}d", err); - } + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::GetFileTypes before AcquireDataAbility."); + dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + APP_LOGI("DataAbilityHelper::GetFileTypes after AcquireDataAbility."); + if (dataAbilityProxy_ == nullptr) { + APP_LOGE("DataAbilityHelper::GetFileTypes failed dataAbility == nullptr"); + return matchedMIMEs; } - } else { - if (dataAbilityProxy_ != nullptr) { - matchedMIMEs = dataAbilityProxy_->GetFileTypes(uri, mimeTypeFilter); + if (isSystemCaller_) { + AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); } } + + APP_LOGI("DataAbilityHelper::GetFileTypes before dataAbilityProxy_->GetFileTypes."); + matchedMIMEs = dataAbilityProxy_->GetFileTypes(uri, mimeTypeFilter); + APP_LOGI("DataAbilityHelper::GetFileTypes after dataAbilityProxy_->GetFileTypes."); + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::GetFileTypes before ReleaseDataAbility."); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + APP_LOGI("DataAbilityHelper::GetFileTypes after ReleaseDataAbility."); + if (err != ERR_OK) { + APP_LOGE("DataAbilityHelper::GetFileTypes failed to ReleaseDataAbility err = %{public}d", err); + } + dataAbilityProxy_ = nullptr; + } + + APP_LOGI("DataAbilityHelper::GetFileTypes end."); return matchedMIMEs; } @@ -195,28 +349,39 @@ std::vector DataAbilityHelper::GetFileTypes(Uri &uri, const std::st */ int DataAbilityHelper::OpenFile(Uri &uri, const std::string &mode) { + APP_LOGI("DataAbilityHelper::OpenFile start."); int fd = -1; - if ((uri_ == nullptr) || (!uri_->Equals(uri))) { - if (uri.GetScheme() == SchemeOhos) { - sptr dataAbilityProxy = - AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); - if (dataAbilityProxy == nullptr) { - APP_LOGE("DataAbilityHelper::OpenFile failed dataAbility == nullptr"); - return fd; - } - - fd = dataAbilityProxy->OpenFile(uri, mode); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return fd; + } - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); - if (err != ERR_OK) { - APP_LOGE("AbilityThread::OpenFile failed to ReleaseDataAbility err = %{public}d", err); - } + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::OpenFile before AcquireDataAbility."); + dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + APP_LOGI("DataAbilityHelper::OpenFile after AcquireDataAbility."); + if (dataAbilityProxy_ == nullptr) { + APP_LOGE("DataAbilityHelper::OpenFile failed dataAbility == nullptr"); + return fd; + } + if (isSystemCaller_) { + AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); } - } else { - if (dataAbilityProxy_ != nullptr) { - fd = dataAbilityProxy_->OpenFile(uri, mode); + } + + APP_LOGI("DataAbilityHelper::OpenFile before dataAbilityProxy_->OpenFile."); + fd = dataAbilityProxy_->OpenFile(uri, mode); + APP_LOGI("DataAbilityHelper::OpenFile after dataAbilityProxy_->OpenFile."); + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::OpenFile before ReleaseDataAbility."); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + APP_LOGI("DataAbilityHelper::OpenFile after ReleaseDataAbility."); + if (err != ERR_OK) { + APP_LOGE("DataAbilityHelper::OpenFile failed to ReleaseDataAbility err = %{public}d", err); } + dataAbilityProxy_ = nullptr; } + APP_LOGI("DataAbilityHelper::OpenFile end."); return fd; } @@ -234,28 +399,38 @@ int DataAbilityHelper::OpenFile(Uri &uri, const std::string &mode) */ int DataAbilityHelper::OpenRawFile(Uri &uri, const std::string &mode) { + APP_LOGI("DataAbilityHelper::OpenRawFile start."); int fd = -1; - if ((uri_ == nullptr) || (!uri_->Equals(uri))) { - if (uri.GetScheme() == SchemeOhos) { - sptr dataAbilityProxy = - AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); - if (dataAbilityProxy == nullptr) { - APP_LOGE("DataAbilityHelper::OpenRawFile failed dataAbility == nullptr"); - return fd; - } - - fd = dataAbilityProxy->OpenRawFile(uri, mode); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return fd; + } - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); - if (err != ERR_OK) { - APP_LOGE("AbilityThread::OpenRawFile failed to ReleaseDataAbility err = %{public}d", err); - } + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::OpenRawFile before AcquireDataAbility."); + dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + APP_LOGI("DataAbilityHelper::OpenRawFile after AcquireDataAbility."); + if (dataAbilityProxy_ == nullptr) { + APP_LOGE("DataAbilityHelper::OpenRawFile failed dataAbility == nullptr"); + return fd; } - } else { - if (dataAbilityProxy_ != nullptr) { - fd = dataAbilityProxy_->OpenRawFile(uri, mode); + if (isSystemCaller_) { + AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + } + } + APP_LOGI("DataAbilityHelper::OpenRawFile before dataAbilityProxy_->OpenRawFile."); + fd = dataAbilityProxy_->OpenRawFile(uri, mode); + APP_LOGI("DataAbilityHelper::OpenRawFile after dataAbilityProxy_->OpenRawFile."); + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::OpenRawFile before ReleaseDataAbility."); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + APP_LOGI("DataAbilityHelper::OpenRawFile after ReleaseDataAbility."); + if (err != ERR_OK) { + APP_LOGE("DataAbilityHelper::OpenRawFile failed to ReleaseDataAbility err = %{public}d", err); } + dataAbilityProxy_ = nullptr; } + APP_LOGI("DataAbilityHelper::OpenRawFile end."); return fd; } @@ -269,28 +444,38 @@ int DataAbilityHelper::OpenRawFile(Uri &uri, const std::string &mode) */ int DataAbilityHelper::Insert(Uri &uri, const ValuesBucket &value) { + APP_LOGI("DataAbilityHelper::Insert start."); int index = -1; - if ((uri_ == nullptr) || (!uri_->Equals(uri))) { - if (uri.GetScheme() == SchemeOhos) { - sptr dataAbilityProxy = - AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); - if (dataAbilityProxy == nullptr) { - APP_LOGE("DataAbilityHelper::Insert failed dataAbility == nullptr"); - return index; - } - - index = dataAbilityProxy->Insert(uri, value); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return index; + } - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); - if (err != ERR_OK) { - APP_LOGE("AbilityThread::Insert failed to ReleaseDataAbility err = %{public}d", err); - } + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::Insert before AcquireDataAbility."); + dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + APP_LOGI("DataAbilityHelper::Insert after AcquireDataAbility."); + if (dataAbilityProxy_ == nullptr) { + APP_LOGE("DataAbilityHelper::Insert failed dataAbility == nullptr"); + return index; } - } else { - if (dataAbilityProxy_ != nullptr) { - index = dataAbilityProxy_->Insert(uri, value); + if (isSystemCaller_) { + AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + } + } + APP_LOGI("DataAbilityHelper::Insert before dataAbilityProxy_->Insert."); + index = dataAbilityProxy_->Insert(uri, value); + APP_LOGI("DataAbilityHelper::Insert after dataAbilityProxy_->Insert."); + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::Insert before ReleaseDataAbility."); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + APP_LOGI("DataAbilityHelper::Insert after ReleaseDataAbility."); + if (err != ERR_OK) { + APP_LOGE("DataAbilityHelper::Insert failed to ReleaseDataAbility err = %{public}d", err); } + dataAbilityProxy_ = nullptr; } + APP_LOGI("DataAbilityHelper::Insert end."); return index; } @@ -305,28 +490,38 @@ int DataAbilityHelper::Insert(Uri &uri, const ValuesBucket &value) */ int DataAbilityHelper::Update(Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) { + APP_LOGI("DataAbilityHelper::Update start."); int index = -1; - if ((uri_ == nullptr) || (!uri_->Equals(uri))) { - if (uri.GetScheme() == SchemeOhos) { - sptr dataAbilityProxy = - AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); - if (dataAbilityProxy == nullptr) { - APP_LOGE("DataAbilityHelper::Insert failed dataAbility == nullptr"); - return index; - } - - index = dataAbilityProxy->Update(uri, value, predicates); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return index; + } - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); - if (err != ERR_OK) { - APP_LOGE("AbilityThread::Insert failed to ReleaseDataAbility err = %{public}d", err); - } + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::Update before AcquireDataAbility."); + dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + APP_LOGI("DataAbilityHelper::Update after AcquireDataAbility."); + if (dataAbilityProxy_ == nullptr) { + APP_LOGE("DataAbilityHelper::Update failed dataAbility == nullptr"); + return index; } - } else { - if (dataAbilityProxy_ != nullptr) { - index = dataAbilityProxy_->Update(uri, value, predicates); + if (isSystemCaller_) { + AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); } } + APP_LOGI("DataAbilityHelper::Update before dataAbilityProxy_->Update."); + index = dataAbilityProxy_->Update(uri, value, predicates); + APP_LOGI("DataAbilityHelper::Update after dataAbilityProxy_->Update."); + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::Update before ReleaseDataAbility."); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + APP_LOGI("DataAbilityHelper::Update after ReleaseDataAbility."); + if (err != ERR_OK) { + APP_LOGE("DataAbilityHelper::Update failed to ReleaseDataAbility err = %{public}d", err); + } + dataAbilityProxy_ = nullptr; + } + APP_LOGI("DataAbilityHelper::Update end."); return index; } @@ -340,28 +535,38 @@ int DataAbilityHelper::Update(Uri &uri, const ValuesBucket &value, const DataAbi */ int DataAbilityHelper::Delete(Uri &uri, const DataAbilityPredicates &predicates) { + APP_LOGI("DataAbilityHelper::Delete start."); int index = -1; - if ((uri_ == nullptr) || (!uri_->Equals(uri))) { - if (uri.GetScheme() == SchemeOhos) { - sptr dataAbilityProxy = - AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); - if (dataAbilityProxy == nullptr) { - APP_LOGE("DataAbilityHelper::Delete failed dataAbility == nullptr"); - return index; - } - - index = dataAbilityProxy->Delete(uri, predicates); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return index; + } - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); - if (err != ERR_OK) { - APP_LOGE("AbilityThread::Delete failed to ReleaseDataAbility err = %{public}d", err); - } + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::Delete before AcquireDataAbility."); + dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + APP_LOGI("DataAbilityHelper::Delete after AcquireDataAbility."); + if (dataAbilityProxy_ == nullptr) { + APP_LOGE("DataAbilityHelper::Delete failed dataAbility == nullptr"); + return index; + } + if (isSystemCaller_) { + AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); } - } else { - if (dataAbilityProxy_ != nullptr) { - index = dataAbilityProxy_->Delete(uri, predicates); + } + APP_LOGI("DataAbilityHelper::Delete before dataAbilityProxy_->Delete."); + index = dataAbilityProxy_->Delete(uri, predicates); + APP_LOGI("DataAbilityHelper::Delete after dataAbilityProxy_->Delete."); + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::Delete before ReleaseDataAbility."); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + APP_LOGI("DataAbilityHelper::Delete after ReleaseDataAbility."); + if (err != ERR_OK) { + APP_LOGE("DataAbilityHelper::Delete failed to ReleaseDataAbility err = %{public}d", err); } + dataAbilityProxy_ = nullptr; } + APP_LOGI("DataAbilityHelper::Delete end."); return index; } @@ -377,28 +582,38 @@ int DataAbilityHelper::Delete(Uri &uri, const DataAbilityPredicates &predicates) std::shared_ptr DataAbilityHelper::Query( Uri &uri, std::vector &columns, const DataAbilityPredicates &predicates) { + APP_LOGI("DataAbilityHelper::Query start."); std::shared_ptr resultset = nullptr; - if ((uri_ == nullptr) || (!uri_->Equals(uri))) { - if (uri.GetScheme() == SchemeOhos) { - sptr dataAbilityProxy = - AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); - if (dataAbilityProxy == nullptr) { - APP_LOGE("DataAbilityHelper::Query failed dataAbility == nullptr"); - return resultset; - } - - resultset = dataAbilityProxy->Query(uri, columns, predicates); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return resultset; + } - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); - if (err != ERR_OK) { - APP_LOGE("AbilityThread::Query failed to ReleaseDataAbility err = %{public}d", err); - } + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::Query before AcquireDataAbility."); + dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + APP_LOGI("DataAbilityHelper::Query after AcquireDataAbility."); + if (dataAbilityProxy_ == nullptr) { + APP_LOGE("DataAbilityHelper::Query failed dataAbility == nullptr"); + return resultset; + } + if (isSystemCaller_) { + AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); } - } else { - if (dataAbilityProxy_ != nullptr) { - resultset = dataAbilityProxy_->Query(uri, columns, predicates); + } + APP_LOGI("DataAbilityHelper::Query before dataAbilityProxy_->Query."); + resultset = dataAbilityProxy_->Query(uri, columns, predicates); + APP_LOGI("DataAbilityHelper::Query after dataAbilityProxy_->Query."); + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::Query before ReleaseDataAbility."); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + APP_LOGI("DataAbilityHelper::Query after ReleaseDataAbility."); + if (err != ERR_OK) { + APP_LOGE("DataAbilityHelper::Query failed to ReleaseDataAbility err = %{public}d", err); } + dataAbilityProxy_ = nullptr; } + APP_LOGI("DataAbilityHelper::Query end."); return resultset; } @@ -412,28 +627,38 @@ std::shared_ptr DataAbilityHelper::Query( */ std::string DataAbilityHelper::GetType(Uri &uri) { + APP_LOGI("DataAbilityHelper::GetType start."); std::string type; - if ((uri_ == nullptr) || (!uri_->Equals(uri))) { - if (uri.GetScheme() == SchemeOhos) { - sptr dataAbilityProxy = - AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); - if (dataAbilityProxy == nullptr) { - APP_LOGE("DataAbilityHelper::GetType failed dataAbility == nullptr"); - return type; - } - - type = dataAbilityProxy->GetType(uri); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return type; + } - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); - if (err != ERR_OK) { - APP_LOGE("AbilityThread::GetType failed to ReleaseDataAbility err = %{public}d", err); - } + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::GetType before AcquireDataAbility."); + dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + APP_LOGI("DataAbilityHelper::GetType after AcquireDataAbility."); + if (dataAbilityProxy_ == nullptr) { + APP_LOGE("DataAbilityHelper::GetType failed dataAbility == nullptr"); + return type; + } + if (isSystemCaller_) { + AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); } - } else { - if (dataAbilityProxy_ != nullptr) { - type = dataAbilityProxy_->GetType(uri); + } + APP_LOGI("DataAbilityHelper::GetType before dataAbilityProxy_->GetType."); + type = dataAbilityProxy_->GetType(uri); + APP_LOGI("DataAbilityHelper::GetType after dataAbilityProxy_->GetType."); + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::GetType before ReleaseDataAbility."); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + APP_LOGI("DataAbilityHelper::GetType after ReleaseDataAbility."); + if (err != ERR_OK) { + APP_LOGE("DataAbilityHelper::GetType failed to ReleaseDataAbility err = %{public}d", err); } + dataAbilityProxy_ = nullptr; } + APP_LOGI("DataAbilityHelper::GetType end."); return type; } @@ -449,28 +674,38 @@ std::string DataAbilityHelper::GetType(Uri &uri) */ bool DataAbilityHelper::Reload(Uri &uri, const PacMap &extras) { + APP_LOGI("DataAbilityHelper::Reload start."); bool ret = false; - if ((uri_ == nullptr) || (!uri_->Equals(uri))) { - if (uri.GetScheme() == SchemeOhos) { - sptr dataAbilityProxy = - AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); - if (dataAbilityProxy == nullptr) { - APP_LOGE("DataAbilityHelper::Reload failed dataAbility == nullptr"); - return ret; - } - - ret = dataAbilityProxy->Reload(uri, extras); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return ret; + } - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); - if (err != ERR_OK) { - APP_LOGE("AbilityThread::Reload failed to ReleaseDataAbility err = %{public}d", err); - } + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::Reload before AcquireDataAbility."); + dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + APP_LOGI("DataAbilityHelper::Reload after AcquireDataAbility."); + if (dataAbilityProxy_ == nullptr) { + APP_LOGE("DataAbilityHelper::Reload failed dataAbility == nullptr"); + return ret; } - } else { - if (dataAbilityProxy_ != nullptr) { - ret = dataAbilityProxy_->Reload(uri, extras); + if (isSystemCaller_) { + AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); } } + APP_LOGI("DataAbilityHelper::Reload before dataAbilityProxy_->Reload."); + ret = dataAbilityProxy_->Reload(uri, extras); + APP_LOGI("DataAbilityHelper::Reload after dataAbilityProxy_->Reload."); + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::Reload before ReleaseDataAbility."); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + APP_LOGI("DataAbilityHelper::Reload after ReleaseDataAbility."); + if (err != ERR_OK) { + APP_LOGE("DataAbilityHelper::Reload failed to ReleaseDataAbility err = %{public}d", err); + } + dataAbilityProxy_ = nullptr; + } + APP_LOGI("DataAbilityHelper::Reload end."); return ret; } @@ -484,29 +719,204 @@ bool DataAbilityHelper::Reload(Uri &uri, const PacMap &extras) */ int DataAbilityHelper::BatchInsert(Uri &uri, const std::vector &values) { + APP_LOGI("DataAbilityHelper::BatchInsert start."); int ret = -1; - if ((uri_ == nullptr) || (!uri_->Equals(uri))) { - if (uri.GetScheme() == SchemeOhos) { - sptr dataAbilityProxy = - AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); - if (dataAbilityProxy == nullptr) { - APP_LOGE("DataAbilityHelper::BatchInsert​ failed dataAbility == nullptr"); - return ret; - } - - ret = dataAbilityProxy->BatchInsert(uri, values); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return ret; + } - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); - if (err != ERR_OK) { - APP_LOGE("AbilityThread::BatchInsert​ failed to ReleaseDataAbility err = %{public}d", err); - } + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::BatchInsert before AcquireDataAbility."); + dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + APP_LOGI("DataAbilityHelper::BatchInsert after AcquireDataAbility."); + if (dataAbilityProxy_ == nullptr) { + APP_LOGE("DataAbilityHelper::BatchInsert failed dataAbility == nullptr"); + return ret; + } + if (isSystemCaller_) { + AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); } - } else { - if (dataAbilityProxy_ != nullptr) { - ret = dataAbilityProxy_->BatchInsert(uri, values); + } + APP_LOGI("DataAbilityHelper::BatchInsert before dataAbilityProxy_->BatchInsert."); + ret = dataAbilityProxy_->BatchInsert(uri, values); + APP_LOGI("DataAbilityHelper::BatchInsert after dataAbilityProxy_->BatchInsert."); + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::BatchInsert before ReleaseDataAbility."); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + APP_LOGI("DataAbilityHelper::BatchInsert after ReleaseDataAbility."); + if (err != ERR_OK) { + APP_LOGE("DataAbilityHelper::BatchInsert failed to ReleaseDataAbility err = %{public}d", err); } + dataAbilityProxy_ = nullptr; } + APP_LOGI("DataAbilityHelper::BatchInsert end."); return ret; } + +bool DataAbilityHelper::CheckUriParam(const Uri &uri) +{ + APP_LOGI("DataAbilityHelper::CheckUriParam start."); + Uri checkUri(uri.ToString()); + if (!CheckOhosUri(checkUri)) { + APP_LOGE("DataAbilityHelper::CheckUriParam failed. CheckOhosUri uri failed"); + return false; + } + + if (uri_ != nullptr) { + if (!CheckOhosUri(*uri_)) { + APP_LOGE("DataAbilityHelper::CheckUriParam failed. CheckOhosUri uri_ failed"); + return false; + } + + std::vector checkSegments; + checkUri.GetPathSegments(checkSegments); + + std::vector segments; + uri_->GetPathSegments(segments); + + if (checkSegments[0] != segments[0]) { + APP_LOGE("DataAbilityHelper::CheckUriParam failed. the dataability in uri doesn't equal the one in uri_."); + return false; + } + } + APP_LOGI("DataAbilityHelper::CheckUriParam end."); + return true; +} + +bool DataAbilityHelper::CheckOhosUri(const Uri &uri) +{ + APP_LOGI("DataAbilityHelper::CheckOhosUri start."); + Uri checkUri(uri.ToString()); + if (checkUri.GetScheme() != SchemeOhos) { + APP_LOGE("DataAbilityHelper::CheckOhosUri failed. uri is not a dataability one."); + return false; + } + + std::vector segments; + checkUri.GetPathSegments(segments); + if (segments.empty()) { + APP_LOGE("DataAbilityHelper::CheckOhosUri failed. There is no segments in the uri."); + return false; + } + + if (checkUri.GetPath() == "") { + APP_LOGE("DataAbilityHelper::CheckOhosUri failed. The path in the uri is empty."); + return false; + } + APP_LOGI("DataAbilityHelper::CheckOhosUri end."); + return true; +} + +/** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the + * context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to any + * method that is called on the Data ability must require normalization verification and denormalization. The default + * implementation of this method returns null, indicating that this Data ability does not support URI normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ +Uri DataAbilityHelper::NormalizeUri(Uri &uri) +{ + APP_LOGI("DataAbilityHelper::NormalizeUri start."); + Uri urivalue(""); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return urivalue; + } + + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::NormalizeUri before AcquireDataAbility."); + dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + APP_LOGI("DataAbilityHelper::NormalizeUri after AcquireDataAbility."); + if (dataAbilityProxy_ == nullptr) { + APP_LOGE("DataAbilityHelper::NormalizeUri failed dataAbility == nullptr"); + return urivalue; + } + if (isSystemCaller_) { + AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + } + } + APP_LOGI("DataAbilityHelper::NormalizeUri before dataAbilityProxy_->NormalizeUri."); + urivalue = dataAbilityProxy_->NormalizeUri(uri); + APP_LOGI("DataAbilityHelper::NormalizeUri after dataAbilityProxy_->NormalizeUri."); + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::NormalizeUri before ReleaseDataAbility."); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + APP_LOGI("DataAbilityHelper::NormalizeUri after ReleaseDataAbility."); + if (err != ERR_OK) { + APP_LOGE("DataAbilityHelper::NormalizeUri failed to ReleaseDataAbility err = %{public}d", err); + } + dataAbilityProxy_ = nullptr; + } + APP_LOGI("DataAbilityHelper::NormalizeUri end."); + return urivalue; +} + +/** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed to + * this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found in the + * current environment. + */ +Uri DataAbilityHelper::DenormalizeUri(Uri &uri) +{ + APP_LOGI("DataAbilityHelper::DenormalizeUri start."); + Uri urivalue(""); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return urivalue; + } + + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::DenormalizeUri before AcquireDataAbility."); + dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + APP_LOGI("DataAbilityHelper::DenormalizeUri after AcquireDataAbility."); + if (dataAbilityProxy_ == nullptr) { + APP_LOGE("DataAbilityHelper::DenormalizeUri failed dataAbility == nullptr"); + return urivalue; + } + if (isSystemCaller_) { + AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + } + } + APP_LOGI("DataAbilityHelper::DenormalizeUri before dataAbilityProxy_->DenormalizeUri."); + urivalue = dataAbilityProxy_->DenormalizeUri(uri); + APP_LOGI("DataAbilityHelper::DenormalizeUri after dataAbilityProxy_->DenormalizeUri."); + if (uri_ == nullptr) { + APP_LOGI("DataAbilityHelper::DenormalizeUri before ReleaseDataAbility."); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + APP_LOGI("DataAbilityHelper::DenormalizeUri after ReleaseDataAbility."); + if (err != ERR_OK) { + APP_LOGE("DataAbilityHelper::DenormalizeUri failed to ReleaseDataAbility err = %{public}d", err); + } + dataAbilityProxy_ = nullptr; + } + APP_LOGI("DataAbilityHelper::DenormalizeUri end."); + return urivalue; +} + +void DataAbilityDeathRecipient::OnRemoteDied(const wptr &remote) +{ + APP_LOGI("recv DataAbilityDeathRecipient death notice"); + if (handler_) { + handler_(remote); + } + APP_LOGI("DataAbilityHelper::OnRemoteDied end."); +} + +DataAbilityDeathRecipient::DataAbilityDeathRecipient(RemoteDiedHandler handler) : handler_(handler) +{} + +DataAbilityDeathRecipient::~DataAbilityDeathRecipient() +{} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/data_ability_impl.cpp b/frameworks/kits/ability/native/src/data_ability_impl.cpp index aa17b5486bb..163c362d1d4 100644 --- a/frameworks/kits/ability/native/src/data_ability_impl.cpp +++ b/frameworks/kits/ability/native/src/data_ability_impl.cpp @@ -266,5 +266,50 @@ int DataAbilityImpl::BatchInsert(const Uri &uri, const std::vector ret = ability_->BatchInsert(uri, values); return ret; } +/** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the + * context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to any + * method that is called on the Data ability must require normalization verification and denormalization. The default + * implementation of this method returns null, indicating that this Data ability does not support URI normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ +Uri DataAbilityImpl::NormalizeUri(const Uri &uri) +{ + Uri urivalue(""); + if (ability_ == nullptr) { + APP_LOGE("DataAbilityImpl::NormalizeUri ability_ is nullptr"); + return urivalue; + } + urivalue = ability_->NormalizeUri(uri); + return urivalue; +} + +/** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the + * context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to any + * method that is called on the Data ability must require normalization verification and denormalization. The default + * implementation of this method returns null, indicating that this Data ability does not support URI normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ +Uri DataAbilityImpl::DenormalizeUri(const Uri &uri) +{ + Uri urivalue(""); + if (ability_ == nullptr) { + APP_LOGE("DataAbilityImpl::DenormalizeUri ability_ is nullptr"); + return urivalue; + } + urivalue = ability_->DenormalizeUri(uri); + return urivalue; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/src/data_ability_operation.cpp b/frameworks/kits/ability/native/src/data_ability_operation.cpp index 4c00183ed5c..36a96821894 100644 --- a/frameworks/kits/ability/native/src/data_ability_operation.cpp +++ b/frameworks/kits/ability/native/src/data_ability_operation.cpp @@ -360,7 +360,7 @@ bool DataAbilityOperation::ReadFromParcel(Parcel &in) if (!in.ReadInt32(type_)) { return false; } - int empty; + int empty = VALUE_NULL; if (in.ReadInt32(empty)) { return false; } diff --git a/frameworks/kits/ability/native/src/data_ability_operation_builder.cpp b/frameworks/kits/ability/native/src/data_ability_operation_builder.cpp index a0c4b003b92..1ef39a4c0c7 100644 --- a/frameworks/kits/ability/native/src/data_ability_operation_builder.cpp +++ b/frameworks/kits/ability/native/src/data_ability_operation_builder.cpp @@ -23,6 +23,7 @@ DataAbilityOperationBuilder::DataAbilityOperationBuilder(const int type, const s type_ = type; uri_ = uri; expectedCount_ = 0; + interrupted_ = false; valuesBucket_ = nullptr; dataAbilityPredicates_ = nullptr; valuesBucketReferences_ = nullptr; diff --git a/frameworks/kits/ability/native/src/data_ability_result.cpp b/frameworks/kits/ability/native/src/data_ability_result.cpp index 4431789dae3..ccbb9d07054 100644 --- a/frameworks/kits/ability/native/src/data_ability_result.cpp +++ b/frameworks/kits/ability/native/src/data_ability_result.cpp @@ -85,6 +85,9 @@ int DataAbilityResult::GetCount() DataAbilityResult *DataAbilityResult::CreateFromParcel(Parcel &parcel) { DataAbilityResult *dataAbilityResult = new (std::nothrow) DataAbilityResult(parcel); + if(dataAbilityResult == nullptr){ + APP_LOGE("DataAbilityResult::CreateFromParcel dataAbilityResult is nullptr"); + } return dataAbilityResult; } diff --git a/frameworks/kits/ability/native/src/data_uri_utils.cpp b/frameworks/kits/ability/native/src/data_uri_utils.cpp index 0c4b5d25d79..936f36617f6 100644 --- a/frameworks/kits/ability/native/src/data_uri_utils.cpp +++ b/frameworks/kits/ability/native/src/data_uri_utils.cpp @@ -23,8 +23,8 @@ namespace AppExecFwk { namespace { const string EMPTY = ""; -const std::regex INTEGER_REGEX("^[0-9]+$"); -const int BUFFER_LEN = 32; +const std::regex INTEGER_REGEX("^[-+]?([0-9]+)([.]([0-9]+))?$"); +const int BUFFER_LEN = 64; const char *SEPARATOR = "/"; }; // namespace @@ -48,7 +48,7 @@ DataUriUtils::~DataUriUtils() * @param id * @return Uri( scheme://authority/path1/path2/path3/updateIDNumber....) */ -Uri DataUriUtils::AttachId(const Uri &dataUri, long id) +Uri DataUriUtils::AttachId(const Uri &dataUri, long long id) { // 1. get Path string path = const_cast(dataUri).GetPath(); @@ -67,7 +67,7 @@ Uri DataUriUtils::AttachId(const Uri &dataUri, long id) char longBuffer[BUFFER_LEN] = {0}; - int ret = sprintf_s(longBuffer, sizeof(longBuffer), "%ld", id); + int ret = sprintf_s(longBuffer, sizeof(longBuffer), "%lld", id); if (ret == -1) { return dataUri; } @@ -89,7 +89,7 @@ Uri DataUriUtils::AttachId(const Uri &dataUri, long id) * @param dataUri based on RFC 2396( Uniform Resource Identifier ). * @return long ID */ -long DataUriUtils::GetId(const Uri &dataUri) +long long DataUriUtils::GetId(const Uri &dataUri) { // 1. get Path string path = const_cast(dataUri).GetPath(); @@ -105,8 +105,7 @@ long DataUriUtils::GetId(const Uri &dataUri) if (!IsNumber(lastPath)) { return -1; } - - return atoi(lastPath.c_str()); + return std::atoll(lastPath.c_str()); } /** @@ -125,10 +124,10 @@ Uri DataUriUtils::DeleteId(const Uri &dataUri) * @param id indiates Update attached to the end of the path component of the given URI * @return Uri return is the URI after path is updated */ -Uri DataUriUtils::UpdateId(const Uri &dataUri, long id) +Uri DataUriUtils::UpdateId(const Uri &dataUri, long long id) { char longBuffer[BUFFER_LEN] = {0}; - int ret = sprintf_s(longBuffer, sizeof(longBuffer), "%ld", id); + int ret = sprintf_s(longBuffer, sizeof(longBuffer), "%lld", id); if (ret == -1) { return dataUri; } diff --git a/frameworks/kits/ability/native/src/form_js_event_handler.cpp b/frameworks/kits/ability/native/src/form_js_event_handler.cpp new file mode 100644 index 00000000000..8891cf34f16 --- /dev/null +++ b/frameworks/kits/ability/native/src/form_js_event_handler.cpp @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_host_client.h" +#include "form_js_event_handler.h" +#include "form_mgr.h" +#include "ipc_skeleton.h" + +namespace OHOS { +namespace AppExecFwk { +FormJsEventHandler::FormJsEventHandler(const std::shared_ptr &runner, const std::shared_ptr& ability, + const FormJsInfo& formJsInfo) : EventHandler(runner), formJsInfo_(formJsInfo), ability_(ability) +{ + APP_LOGI("%{public}s called.", __func__); +} + +/** +* Process the event. Developers should override this method. +* +* @param event The event should be processed. +*/ +void FormJsEventHandler::ProcessEvent(const InnerEvent::Pointer &event) +{ + APP_LOGI("%{public}s called.", __func__); + if(!event) { + APP_LOGE("%{public}s, param illegal, event is nullptr", __func__); + return; + } + APP_LOGD("%{public}s, inner event id obtained: %u.", __func__, event->GetInnerEventId()); + + switch (event->GetInnerEventId()) { + case FORM_ROUTE_EVENT: { + auto object = event->GetUniqueObject(); + Want want = *object; + ProcessRouterEvent(want); + break; + } + case FORM_MESSAGE_EVENT: { + auto object = event->GetUniqueObject(); + Want want = *object; + ProcessMessageEvent(want); + break; + } + default: { + APP_LOGW("unsupported event."); + break; + } + } +} + +/** + * @brief Process js router event. + * @param want Indicates the event to be processed. + */ +void FormJsEventHandler::ProcessRouterEvent(Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + + if (!IsSystemApp()) { + APP_LOGW("%{public}s, not system application, cannot mixture package router", __func__); + return; + } + if(!want.HasParameter(Constants::PARAM_FORM_ABILITY_NAME_KEY)) { + APP_LOGE("%{public}s, param illegal, abilityName is not exist", __func__); + return; + } + + std::string abilityName = want.GetStringParam(Constants::PARAM_FORM_ABILITY_NAME_KEY); + want.SetElementName(formJsInfo_.bundleName, abilityName); + want.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, std::to_string(formJsInfo_.formId)); + ability_->StartAbility(want); + // AddUsageRecord(form.getBundleName(), form.getAbilityName()); +} +/** + * @brief Process js message event. + * @param want Indicates the event to be processed. + */ +void FormJsEventHandler::ProcessMessageEvent(const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + + if(!want.HasParameter(Constants::PARAM_FORM_IDENTITY_KEY)) { + APP_LOGE("%{public}s, formid is not exist", __func__); + return; + } + std::string strFormId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY); + int64_t formId = std::stoll(strFormId); + if (formId <= 0) { + APP_LOGE("%{public}s error, The passed formid is invalid. Its value must be larger than 0.", __func__); + return; + } + + if (!want.HasParameter(Constants::PARAM_MESSAGE_KEY)) { + APP_LOGE("%{public}s, message info is not exist", __func__); + return; + } + + if (FormMgr::GetRecoverStatus() == Constants::IN_RECOVERING) { + APP_LOGE("%{public}s error, form is in recover status, can't do action on form.", __func__); + return; + } + + // requestForm request to fms + int resultCode = FormMgr::GetInstance().MessageEvent(formId, want, FormHostClient::GetInstance()); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s error, failed to notify the form service that the form user's lifecycle is updated, error code is %{public}d.", __func__, resultCode); + return; + } +} + +bool FormJsEventHandler::IsSystemApp() const +{ + APP_LOGI("%{public}s called.", __func__); + + int32_t callingUid = IPCSkeleton::GetCallingUid(); + if (callingUid > Constants::MAX_SYSTEM_APP_UID) { + APP_LOGW("%{public}s warn, callingUid is %{public}d, which is larger than %{public}d.", __func__, callingUid, + Constants::MAX_SYSTEM_APP_UID); + return false; + } else { + APP_LOGD("%{public}s, callingUid = %{public}d.", __func__, callingUid); + return true; + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/form_provider_client.cpp b/frameworks/kits/ability/native/src/form_provider_client.cpp new file mode 100755 index 00000000000..dbac630ef74 --- /dev/null +++ b/frameworks/kits/ability/native/src/form_provider_client.cpp @@ -0,0 +1,475 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "form_provider_client.h" +#include "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_supply_proxy.h" +#include "ipc_skeleton.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +using PermissionKit = OHOS::Security::Permission::PermissionKit; +using PermissionState = OHOS::Security::Permission::PermissionState; + +/** + * @brief Acquire to give back an ProviderFormInfo. This is sync API. + * @param formId The Id of the form. + * @param want The want of the form to create. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderClient::AcquireProviderFormInfo( + const int64_t formId, + const Want &want, + const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + + // avoid the user modify the number in onCreate + Want newWant = BuildNewWant(want); + std::shared_ptr ownerAbility = GetOwner(); + if (ownerAbility == nullptr) { + APP_LOGE("%{public}s error, ownerAbility is nullptr.", __func__); + FormProviderInfo formProviderInfo; + newWant.SetParam(Constants::PROVIDER_FLAG, ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY); + return HandleAcquire(formProviderInfo, newWant, callerToken); + } + + APP_LOGI("%{public}s come, %{public}s.", __func__, ownerAbility->GetAbilityName().c_str()); + + if (!CheckIsSystemApp()) { + APP_LOGW("%{public}s warn, AcquireProviderFormInfo caller permission denied.", __func__); + FormProviderInfo formProviderInfo; + newWant.SetParam(Constants::PROVIDER_FLAG, ERR_APPEXECFWK_FORM_PERMISSION_DENY); + return HandleAcquire(formProviderInfo, newWant, callerToken); + } + + Want cloneWant = Want(want); + cloneWant.RemoveParam(Constants::FORM_CONNECT_ID); + cloneWant.RemoveParam(Constants::ACQUIRE_TYPE); + cloneWant.RemoveParam(Constants::FORM_SUPPLY_INFO); + cloneWant.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, std::to_string(formId)); + FormProviderInfo formProviderInfo = ownerAbility->OnCreate(cloneWant); + formProviderInfo.SetFormId(formId); + newWant.SetParam(Constants::PROVIDER_FLAG, ERR_OK); + APP_LOGD("%{public}s, formId: %{public}lld, data: %{public}s", + __func__, formProviderInfo.GetFormId(), formProviderInfo.GetFormDataString().c_str()); + return HandleAcquire(formProviderInfo, newWant, callerToken); +} + +/** + * @brief Notify provider when the form was deleted. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderClient::NotifyFormDelete(const int64_t formId, const Want &want, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + // The error code for business operation. + int errorCode = ERR_OK; + do { + APP_LOGI("%{public}s called.", __func__); + std::shared_ptr ownerAbility = GetOwner(); + if (ownerAbility == nullptr) { + APP_LOGE("%{public}s error, ownerAbility is nullptr.", __func__); + errorCode = ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY; + break; + } + if (!CheckIsSystemApp()) { + APP_LOGW("%{public}s caller permission denied", __func__); + errorCode = ERR_APPEXECFWK_FORM_PERMISSION_DENY; + break; + } + + APP_LOGI("%{public}s come, %{public}s", __func__, ownerAbility->GetAbilityName().c_str()); + ownerAbility->OnDelete(formId); + } while (false); + + // The error code for disconnect. + int disconnectErrorCode = HandleDisconnect(want, callerToken); + if (errorCode != ERR_OK) { + // If errorCode is not ERR_OK,return errorCode. + return errorCode; + } else { + // If errorCode is ERR_OK,return disconnectErrorCode. + if (disconnectErrorCode != ERR_OK) { + APP_LOGE("%{public}s, disconnect error.", __func__); + } + return disconnectErrorCode; + } +} + +/** + * @brief Notify provider when the forms was deleted. + * + * @param formIds The id list of forms. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderClient::NotifyFormsDelete( + const std::vector &formIds, + const Want &want, + const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + // The error code for business operation. + int errorCode = ERR_OK; + do { + APP_LOGI("%{public}s called.", __func__); + std::shared_ptr ownerAbility = GetOwner(); + if (ownerAbility == nullptr) { + APP_LOGE("%{public}s error, ownerAbility is nullptr.", __func__); + errorCode = ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY; + break; + } + if (!CheckIsSystemApp()) { + APP_LOGW("%{public}s caller permission denied", __func__); + errorCode = ERR_APPEXECFWK_FORM_PERMISSION_DENY; + break; + } + + APP_LOGI("%{public}s come,formIds size=%{public}d, abilityName:%{public}s", + __func__, formIds.size(), ownerAbility->GetAbilityName().c_str()); + for (int64_t formId : formIds) { + ownerAbility->OnDelete(formId); + } + } while (false); + + // The error code for disconnect. + int disconnectErrorCode = HandleDisconnect(want, callerToken); + if (errorCode != ERR_OK) { + // If errorCode is not ERR_OK,return errorCode. + return errorCode; + } else { + // If errorCode is ERR_OK,return disconnectErrorCode. + if (disconnectErrorCode != ERR_OK) { + APP_LOGE("%{public}s, disconnect error.", __func__); + } + return disconnectErrorCode; + } +} + +/** + * @brief Notify provider when the form need update. + * + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderClient::NotifyFormUpdate( + const int64_t formId, + const Want &want, + const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + + // The error code for business operation. + int errorCode = ERR_OK; + do { + std::shared_ptr ownerAbility = GetOwner(); + if (ownerAbility == nullptr) { + APP_LOGE("%{public}s error, owner ability is nullptr.", __func__); + errorCode = ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY; + break; + } + + if (!CheckIsSystemApp()) { + APP_LOGE("%{public}s warn, caller permission denied.", __func__); + errorCode = ERR_APPEXECFWK_FORM_PERMISSION_DENY; + break; + } + + APP_LOGI("%{public}s come, %{public}s.", __func__, ownerAbility->GetAbilityName().c_str()); + ownerAbility->OnUpdate(formId); + } while (false); + + // The error code for disconnect. + int disconnectErrorCode = HandleDisconnect(want, callerToken); + if (errorCode != ERR_OK) { + // If errorCode is not ERR_OK,return errorCode. + return errorCode; + } else { + // If errorCode is ERR_OK,return disconnectErrorCode. + if (disconnectErrorCode != ERR_OK) { + APP_LOGE("%{public}s, disconnect error.", __func__); + } + return disconnectErrorCode; + } +} + +/** + * @brief Event notify when change the form visible. + * + * @param formIds The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderClient::EventNotify( + const std::vector &formIds, + const int32_t formVisibleType, const Want &want, + const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + + // The error code for business operation. + int errorCode = ERR_OK; + do { + std::shared_ptr ownerAbility = GetOwner(); + if (ownerAbility == nullptr) { + APP_LOGE("%{public}s error, owner ability is nullptr.", __func__); + errorCode = ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY; + break; + } + + if (!CheckIsSystemApp()) { + APP_LOGW("%{public}s warn, caller permission denied.", __func__); + errorCode = ERR_APPEXECFWK_FORM_PERMISSION_DENY; + break; + } + + std::map formEventsMap; + for (const auto &formId : formIds) { + formEventsMap.insert(std::make_pair(formId, formVisibleType)); + } + + APP_LOGI("%{public}s come, %{public}s.", __func__, ownerAbility->GetAbilityName().c_str()); + ownerAbility->OnVisibilityChanged(formEventsMap); + } while (false); + + // The error code for disconnect. + int disconnectErrorCode = HandleDisconnect(want, callerToken); + if (errorCode != ERR_OK) { + // If errorCode is not ERR_OK,return errorCode. + return errorCode; + } else { + // If errorCode is ERR_OK,return disconnectErrorCode. + if (disconnectErrorCode != ERR_OK) { + APP_LOGE("%{public}s, disconnect error.", __func__); + } + return disconnectErrorCode; + } +} + +/** + * @brief Notify provider when the temp form was cast to normal form. + * @param formId The Id of the form to update. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderClient::NotifyFormCastTempForm( + const int64_t formId, + const Want &want, + const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + // The error code for business operation. + int errorCode = ERR_OK; + do { + std::shared_ptr ownerAbility = GetOwner(); + if (ownerAbility == nullptr) { + APP_LOGE("%{public}s error, ownerAbility is nullptr.", __func__); + errorCode = ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY; + break; + } + if (!CheckIsSystemApp()) { + APP_LOGW("%{public}s caller permission denied", __func__); + errorCode = ERR_APPEXECFWK_FORM_PERMISSION_DENY; + break; + } + + APP_LOGI("%{public}s come, %{public}s", __func__, ownerAbility->GetAbilityName().c_str()); + ownerAbility->OnCastTemptoNormal(formId); + } while (false); + + // The error code for disconnect. + int disconnectErrorCode = HandleDisconnect(want, callerToken); + if (errorCode != ERR_OK) { + // If errorCode is not ERR_OK,return errorCode. + return errorCode; + } else { + // If errorCode is ERR_OK,return disconnectErrorCode. + if (disconnectErrorCode != ERR_OK) { + APP_LOGE("%{public}s, disconnect error.", __func__); + } + return disconnectErrorCode; + } +} +/** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderClient::FireFormEvent( + const int64_t formId, + const std::string &message, + const Want &want, + const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + // The error code for business operation. + int errorCode = ERR_OK; + do { + std::shared_ptr ownerAbility = GetOwner(); + if (ownerAbility == nullptr) { + APP_LOGE("%{public}s error, ownerAbility is nullptr.", __func__); + errorCode = ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY; + break; + } + if (!CheckIsSystemApp()) { + APP_LOGW("%{public}s caller permission denied", __func__); + errorCode = ERR_APPEXECFWK_FORM_PERMISSION_DENY; + break; + } + + APP_LOGI("%{public}s come, %{public}s", __func__, ownerAbility->GetAbilityName().c_str()); + ownerAbility->OnTriggerEvent(formId, message); + } while (false); + + // The error code for disconnect. + int disconnectErrorCode = HandleDisconnect(want, callerToken); + if (errorCode != ERR_OK) { + // If errorCode is not ERR_OK,return errorCode. + return errorCode; + } else { + // If errorCode is ERR_OK,return disconnectErrorCode. + if (disconnectErrorCode != ERR_OK) { + APP_LOGE("%{public}s, disconnect error.", __func__); + } + return disconnectErrorCode; + } +} +/** + * @brief Set the owner ability of the form provider client. + * + * @param ability The owner ability of the form provider client. + */ +void FormProviderClient::SetOwner(const std::shared_ptr ability) +{ + if (ability == nullptr) { + return; + } + + { + std::lock_guard lock(abilityMutex_); + owner_ = ability; + } +} + +/** + * @brief Clear the owner ability of the form provider client. + * + * @param ability The owner ability of the form provider client. + */ +void FormProviderClient::ClearOwner(const std::shared_ptr ability) +{ + if (ability == nullptr) { + return; + } + + { + std::lock_guard lock(abilityMutex_); + if (!owner_.expired()) { + std::shared_ptr ownerAbility = owner_.lock(); + if (ability == ownerAbility) { + owner_.reset(); + } + } + } +} + +Want FormProviderClient::BuildNewWant(const Want &want) +{ + Want newWant; + newWant + .SetParam(Constants::ACQUIRE_TYPE, want.GetIntParam(Constants::ACQUIRE_TYPE, 0)) + .SetParam(Constants::FORM_CONNECT_ID, want.GetLongParam(Constants::FORM_CONNECT_ID, 0)) + .SetParam(Constants::PARAM_FORM_IDENTITY_KEY, want.GetLongParam(Constants::PARAM_FORM_IDENTITY_KEY, 0)) + .SetParam(Constants::FORM_SUPPLY_INFO, want.GetStringParam(Constants::FORM_SUPPLY_INFO)) + .SetParam(Constants::PROVIDER_FLAG, true); + return newWant; +} + +std::shared_ptr FormProviderClient::GetOwner() +{ + std::shared_ptr ownerAbility = nullptr; + { + std::lock_guard lock(abilityMutex_); + if (!owner_.expired()) { + ownerAbility = owner_.lock(); + } + } + return ownerAbility; +} + +bool FormProviderClient::CheckIsSystemApp() const +{ + APP_LOGI("%{public}s called.", __func__); + + int32_t callingUid = IPCSkeleton::GetCallingUid(); + if (callingUid > Constants::MAX_SYSTEM_APP_UID) { + APP_LOGW("%{public}s warn, callingUid is %{public}d, which is larger than %{public}d.", __func__, callingUid, + Constants::MAX_SYSTEM_APP_UID); + return false; + } else { + APP_LOGD("%{public}s, callingUid = %{public}d.", __func__, callingUid); + return true; + } +} + +int FormProviderClient::HandleAcquire( + const FormProviderInfo &formProviderInfo, + const Want &newWant, + const sptr &callerToken) +{ + APP_LOGI("%{public}s start", __func__); + sptr formSupplyClient = iface_cast(callerToken); + if (formSupplyClient == nullptr) { + APP_LOGW("%{public}s warn, IFormSupply is nullptr", __func__); + return ERR_APPEXECFWK_FORM_BIND_FORMSUPPLY_FAILED; + } + formSupplyClient->OnAcquire(formProviderInfo, newWant); + APP_LOGI("%{public}s end", __func__); + return ERR_OK; +} + +int FormProviderClient::HandleDisconnect(const Want &want, const sptr &callerToken) +{ + sptr formSupplyClient = iface_cast(callerToken); + if (formSupplyClient == nullptr) { + APP_LOGW("%{public}s warn, IFormSupply is nullptr", __func__); + return ERR_APPEXECFWK_FORM_BIND_FORMSUPPLY_FAILED; + } + + APP_LOGD("%{public}s come, connectId: %{public}ld.", __func__, + want.GetLongParam(Constants::FORM_CONNECT_ID, 0L)); + + formSupplyClient->OnEventHandle(want); + return ERR_OK; +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/page_ability_impl.cpp b/frameworks/kits/ability/native/src/page_ability_impl.cpp index 6e5b840dadc..f46dbcb5908 100755 --- a/frameworks/kits/ability/native/src/page_ability_impl.cpp +++ b/frameworks/kits/ability/native/src/page_ability_impl.cpp @@ -28,7 +28,8 @@ using AbilityManagerClient = OHOS::AAFwk::AbilityManagerClient; */ void PageAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState) { - APP_LOGI("PageAbilityImpl::sourceState:%{public}d; targetState: %{public}d; isNewWant: %{public}d", + APP_LOGI("PageAbilityImpl::HandleAbilityTransaction begin sourceState:%{public}d; targetState: %{public}d; " + "isNewWant: %{public}d", lifecycleState_, targetState.state, targetState.isNewWant); @@ -41,6 +42,7 @@ void PageAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::Li if (lifecycleState_ == AAFwk::ABILITY_STATE_INITIAL) { Start(want); + CheckAndRestore(); } if (lifecycleState_ == AAFwk::ABILITY_STATE_ACTIVE) { @@ -50,8 +52,11 @@ void PageAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::Li bool ret = false; ret = AbilityTransaction(want, targetState); if (ret) { + APP_LOGI("AbilityThread::HandleAbilityTransaction before AbilityManagerClient->AbilityTransitionDone"); AbilityManagerClient::GetInstance()->AbilityTransitionDone(token_, targetState.state); + APP_LOGI("AbilityThread::HandleAbilityTransaction after AbilityManagerClient->AbilityTransitionDone"); } + APP_LOGI("PageAbilityImpl::HandleAbilityTransaction end"); } /** @@ -65,7 +70,7 @@ void PageAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::Li */ bool PageAbilityImpl::AbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState) { - APP_LOGE("PageAbilityImpl::AbilityTransaction called."); + APP_LOGI("PageAbilityImpl::AbilityTransaction begin"); bool ret = true; switch (targetState.state) { case AAFwk::ABILITY_STATE_INITIAL: { @@ -105,6 +110,7 @@ bool PageAbilityImpl::AbilityTransaction(const Want &want, const AAFwk::LifeCycl break; } } + APP_LOGI("PageAbilityImpl::AbilityTransaction end: retVal = %{public}d", (int)ret); return ret; } @@ -119,11 +125,17 @@ bool PageAbilityImpl::AbilityTransaction(const Want &want, const AAFwk::LifeCycl */ bool PageAbilityImpl::DoKeyDown(int keyCode, const KeyEvent &keyEvent) { + APP_LOGI("PageAbilityImpl::DoKeyDown begin"); if (ability_ == nullptr) { APP_LOGE("PageAbilityImpl::DoKeyDown ability_ == nullptr"); return false; } + auto abilitInfo = ability_->GetAbilityInfo(); + APP_LOGI("PageAbilityImpl::DoKeyDown called %{public}s And Focus is %{public}s", + abilitInfo->name.c_str(), + ability_->HasWindowFocus() ? "true" : "false"); + APP_LOGI("PageAbilityImpl::DoKeyDown end"); return ability_->OnKeyDown(keyCode, keyEvent); } @@ -138,11 +150,17 @@ bool PageAbilityImpl::DoKeyDown(int keyCode, const KeyEvent &keyEvent) */ bool PageAbilityImpl::DoKeyUp(int keyCode, const KeyEvent &keyEvent) { + APP_LOGI("PageAbilityImpl::DoKeyUp begin"); if (ability_ == nullptr) { APP_LOGE("PageAbilityImpl::DoKeyUp ability_ == nullptr"); return false; } + auto abilitInfo = ability_->GetAbilityInfo(); + APP_LOGI("PageAbilityImpl::DoKeyUp called %{public}s And Focus is %{public}s", + abilitInfo->name.c_str(), + ability_->HasWindowFocus() ? "true" : "false"); + APP_LOGI("PageAbilityImpl::DoKeyUp end"); return ability_->OnKeyUp(keyCode, keyEvent); } @@ -156,11 +174,17 @@ bool PageAbilityImpl::DoKeyUp(int keyCode, const KeyEvent &keyEvent) */ bool PageAbilityImpl::DoTouchEvent(const TouchEvent &touchEvent) { + APP_LOGI("PageAbilityImpl::DoTouchEvent begin"); if (ability_ == nullptr) { APP_LOGE("PageAbilityImpl::DoTouchEvent ability_ == nullptr"); return false; } + auto abilitInfo = ability_->GetAbilityInfo(); + APP_LOGI("PageAbilityImpl::OnTouchEvent called %{public}s And Focus is %{public}s", + abilitInfo->name.c_str(), + ability_->HasWindowFocus() ? "true" : "false"); + APP_LOGI("PageAbilityImpl::DoTouchEvent end"); return ability_->OnTouchEvent(touchEvent); } } // namespace AppExecFwk diff --git a/frameworks/kits/ability/native/src/service_ability_impl.cpp b/frameworks/kits/ability/native/src/service_ability_impl.cpp index dd9373ae39c..f4de8d11af4 100644 --- a/frameworks/kits/ability/native/src/service_ability_impl.cpp +++ b/frameworks/kits/ability/native/src/service_ability_impl.cpp @@ -28,7 +28,8 @@ using AbilityManagerClient = OHOS::AAFwk::AbilityManagerClient; */ void ServiceAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState) { - APP_LOGI("ServiceAbilityImpl::sourceState:%{public}d; targetState: %{public}d; isNewWant: %{public}d", + APP_LOGI("ServiceAbilityImpl::HandleAbilityTransaction begin sourceState:%{public}d; targetState: %{public}d; " + "isNewWant: %{public}d", lifecycleState_, targetState.state, targetState.isNewWant); @@ -63,8 +64,11 @@ void ServiceAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk: } if (ret) { + APP_LOGI("ServiceAbilityImpl::HandleAbilityTransaction before AbilityManagerClient->AbilityTransitionDone"); AbilityManagerClient::GetInstance()->AbilityTransitionDone(token_, targetState.state); + APP_LOGI("ServiceAbilityImpl::HandleAbilityTransaction after AbilityManagerClient->AbilityTransitionDone"); } + APP_LOGI("ServiceAbilityImpl::HandleAbilityTransaction end"); } } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/test/BUILD.gn b/frameworks/kits/ability/native/test/BUILD.gn index 2f172931786..ed8f608debd 100755 --- a/frameworks/kits/ability/native/test/BUILD.gn +++ b/frameworks/kits/ability/native/test/BUILD.gn @@ -33,6 +33,7 @@ config("module_private_config") { "//foundation/aafwk/standard/services/abilitymgr/include", "//utils/system/safwk/native/include", "//foundation/appexecfwk/standard/kits/appkit/native/app/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", @@ -89,7 +90,6 @@ config("module_ability_context_config") { ohos_unittest("ability_test") { module_out_path = module_output_path sources = [ - "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ability_start_setting.cpp", "//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp", "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp", @@ -347,26 +347,19 @@ ohos_unittest("service_ability_impl_test") { ohos_unittest("data_ability_helper_test") { module_out_path = module_output_path - sources = [ - "mock/include/mock_ability_manager_client.cpp", - "unittest/data_ability_helper_test.cpp", - ] + include_dirs = [ "//foundation/aafwk/standard/services/abilitymgr/include" ] - configs = [ ":module_private_config" ] + sources = [ "unittest/data_ability_helper_test.cpp" ] + + configs = [ ":module_ability_context_config" ] deps = [ "${INNERKITS_PATH}/want:want", - "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", - "//foundation/aafwk/standard/interfaces/innerkits/base:base", - "//foundation/appexecfwk/standard/common:libappexecfwk_common", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - "//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", "//utils/native/base:utils", @@ -524,6 +517,45 @@ ohos_unittest("ability_thread_test") { ] } +ohos_unittest("form_provider_client_test") { + module_out_path = module_output_path + include_dirs = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/appexecfwk/appexecfwk_lite/interfaces/kits/bundle_lite", + ] + + sources = [ + "mock/include/mock_form_supply_callback.cpp", + "unittest/form_provider_client_test.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${INNERKITS_PATH}/want:want", + "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//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/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/graphic/standard:libwmclient", + "//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + ohos_unittest("data_ability_impl_test") { module_out_path = module_output_path sources = [ @@ -740,14 +772,7 @@ ohos_unittest("data_uri_utils_test") { ohos_unittest("pac_map_test") { module_out_path = module_output_path - sources = [ - "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/pac_map_test.cpp", - "//foundation/aafwk/standard/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node.cpp", - "//foundation/aafwk/standard/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_array.cpp", - "//foundation/aafwk/standard/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_base.cpp", - "//foundation/aafwk/standard/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_user_object.cpp", - "//foundation/aafwk/standard/frameworks/kits/content/cpp/src/ohos/aafwk/content/pac_map.cpp", - ] + sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/pac_map_test.cpp" ] configs = [ ":module_private_config" ] @@ -815,6 +840,30 @@ ohos_unittest("task_handler_client_test") { external_deps = [ "hiviewdfx_hilog_native:libhilog" ] } +ohos_unittest("ability_thread_for_ability_on_configuration_update") { + module_out_path = module_output_path + + sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/ability_thread_for_ability_on_configuration_update.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + ohos_unittest("data_ability_result_test") { module_out_path = module_output_path sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/data_ability_result_test.cpp" ] @@ -834,6 +883,46 @@ ohos_unittest("data_ability_result_test") { ] } +ohos_unittest("form_host_client_test") { + module_out_path = module_output_path + sources = [ + "//foundation/aafwk/standard/services/abilitymgr/src/ability_start_setting.cpp", + "//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp", + "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", + "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp", + "mock/include/mock_bundle_manager_form.cpp", + "unittest/form_host_client_test.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${INNERKITS_PATH}/want:want", + "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit:fmskit_native", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", + "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/graphic/standard:libwmclient", + "//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + ############################################################################### group("unittest") { @@ -856,6 +945,8 @@ group("unittest") { ":data_ability_operation_test", ":data_ability_result_test", ":data_uri_utils_test", + ":form_host_client_test", + ":form_provider_client_test", ":pac_map_test", ":page_ability_impl_test", ":service_ability_impl_test", diff --git a/frameworks/kits/ability/native/test/mock/include/bundle_mgr_interface.h b/frameworks/kits/ability/native/test/mock/include/bundle_mgr_interface.h index 4f841ec4b75..7d5c9febf86 100644 --- a/frameworks/kits/ability/native/test/mock/include/bundle_mgr_interface.h +++ b/frameworks/kits/ability/native/test/mock/include/bundle_mgr_interface.h @@ -25,6 +25,7 @@ #include "hap_module_info.h" #include "ohos/aafwk/content/want.h" #include "permission_def.h" +#include "module_usage_record.h" using OHOS::AAFwk::Want; @@ -54,6 +55,7 @@ struct InstallParam : public Parcelable { int userId = -1; // Is keep user data while uninstall. bool isKeepData = false; + bool noCheckSignature = false; // the parcel object function is not const. bool ReadFromParcel(Parcel &parcel); @@ -166,6 +168,7 @@ public: virtual bool CheckIsSystemAppByUid(const int uid) = 0; virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) = 0; virtual bool QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) = 0; + virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) = 0; virtual bool QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) = 0; virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) = 0; virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) = 0; @@ -203,7 +206,10 @@ public: const std::vector &uids, const sptr &callback) = 0; virtual bool UnregisterPermissionsChanged(const sptr &callback) = 0; virtual sptr GetBundleInstaller() = 0; - + virtual bool GetModuleUsageRecords( + const int32_t number, std::vector &moduleUsageRecords) = 0; + virtual bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) = 0; enum class Message { GET_APPLICATION_INFO, GET_APPLICATION_INFOS, diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h index 610fd1598d9..712f657ab86 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h @@ -37,6 +37,7 @@ namespace OHOS { namespace AppExecFwk { +using DummyConfiguration = AAFwk::DummyConfiguration; class MockAbility : public AbilityContext { public: MockAbility() = default; @@ -63,6 +64,9 @@ public: void ScheduleRestoreAbilityState(const PacMap &inState) {} + void ScheduleUpdateConfiguration(const DummyConfiguration &config) + {} + void ScheduleDisconnectAbility(const Want &want) {} @@ -133,6 +137,24 @@ public: { return "Type1"; } + + Uri NormalizeUri(const Uri &uri) + { + Uri urireturn("dataability:///test.aaa"); + return urireturn; + } + + Uri DenormalizeUri(const Uri &uri) + { + Uri urireturn("dataability:///test.aaa"); + return urireturn; + } + + void NotifyMultiWinModeChanged(int32_t winModeKey, bool flag) + {} + + void NotifyTopActiveAbilityChanged(bool flag) + {} }; } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_for_data_ability_observer.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_for_data_ability_observer.h new file mode 100644 index 00000000000..82a2ea44893 --- /dev/null +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_for_data_ability_observer.h @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APPEXECFWK_MOCK_ABILITY_MANAGER_CLIENT_FOR_DATA_ABILITY_OBSERVER_STUB_H +#define OHOS_APPEXECFWK_MOCK_ABILITY_MANAGER_CLIENT_FOR_DATA_ABILITY_OBSERVER_STUB_H + +#include "gmock/gmock.h" + +#include "ability_manager_client.h" +#include "ability_scheduler_proxy.h" +#include "ability_thread.h" + +#include +#include + +#include "mock_ability_scheduler_for_observer.h" + +namespace OHOS { +namespace AppExecFwk { + +class MockAbilitySchedulerTools { +public: + MockAbilitySchedulerTools():mockStatus(false){}; + ~MockAbilitySchedulerTools() = default; + + // return Copy AbilityThread class Smart pointer + std::shared_ptr GetMockAbilityScheduler() + { + if (mockAbilitySchedulerStubInstance == nullptr) { + mockAbilitySchedulerStubInstance = std::make_shared(); + } + return mockAbilitySchedulerStubInstance; + }; + + // return access proxy class sptr pointer + sptr GetAbilitySchedulerProxy() + { + if (mockStatus) { + if (abilitySchedulerProxyInstance1 == nullptr) { + if (mockAbilitySchedulerStubInstance == nullptr) { + mockAbilitySchedulerStubInstance = std::make_shared(); + } + abilitySchedulerProxyInstance1 = sptr( + new (std::nothrow) AAFwk::AbilitySchedulerProxy(mockAbilitySchedulerStubInstance->AsObject())); + } + return abilitySchedulerProxyInstance1; + } else { + if (abilitySchedulerProxyInstance2 == nullptr) { + if (abilityThreadInstance == nullptr) { + abilityThreadInstance = std::make_shared(); + } + abilitySchedulerProxyInstance2 = sptr( + new (std::nothrow) AAFwk::AbilitySchedulerProxy(abilityThreadInstance->AsObject())); + } + return abilitySchedulerProxyInstance2; + } + }; + + void SetMockStatus(bool nflag) { + mockStatus = nflag; + } + + static std::shared_ptr GetInstance() + { + if (instance_ == nullptr) { + instance_ = std::make_shared(); + } + return instance_; + }; + + static void DestoryInstance() + { + instance_ = nullptr; + } + +private: + static std::shared_ptr instance_; + sptr abilitySchedulerProxyInstance1; + std::shared_ptr mockAbilitySchedulerStubInstance; + sptr abilitySchedulerProxyInstance2; + std::shared_ptr abilityThreadInstance; + bool mockStatus; +}; + +std::shared_ptr MockAbilitySchedulerTools::instance_ = nullptr; + +} // namespace AppExecFwk +} // namespace OHOS + +namespace OHOS { +namespace AAFwk { + +sptr AAFwk::AbilityManagerClient::AcquireDataAbility( + const Uri &uri, bool tryBind, const sptr &callerToken) +{ + return AppExecFwk::MockAbilitySchedulerTools::GetInstance()->GetAbilitySchedulerProxy(); +} + +ErrCode AbilityManagerClient::ReleaseDataAbility( + sptr dataAbilityScheduler, const sptr &callerToken) +{ + return ERR_OK; +} + +} // namespace AAFwk +} // namespace OHOS +#endif /* OHOS_APPEXECFWK_MOCK_ABILITY_MANAGER_CLIENT_FOR_DATA_ABILITY_OBSERVER_STUB_H */ \ No newline at end of file diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h index 78da7367065..b688370c379 100755 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h @@ -81,6 +81,11 @@ public: return 0; } + int UpdateConfiguration(const DummyConfiguration &config) + { + return 0; + } + MOCK_METHOD1(GetAllStackInfo, int(StackInfo &stackInfo)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo &wantSenderInfo, const sptr &callerToken)); @@ -94,6 +99,20 @@ public: MOCK_METHOD2(RegisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(UnregisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); + + MOCK_METHOD4(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode)); + MOCK_METHOD1(MoveMissionToFloatingStack, int(const MissionOption &missionOption)); + MOCK_METHOD1(MoveMissionToSplitScreenStack, int(const MissionOption &missionOption)); + MOCK_METHOD2( + ChangeFocusAbility, int(const sptr &lostFocusToken, const sptr &getFocusToken)); + MOCK_METHOD1(MinimizeMultiWindow, int(int missionId)); + MOCK_METHOD1(MaximizeMultiWindow, int(int missionId)); + MOCK_METHOD1(GetFloatingMissions, int(std::vector &list)); + MOCK_METHOD1(CloseMultiWindow, int(int missionId)); + MOCK_METHOD1(SetMissionStackSetting, int(const StackSetting &stackSetting)); + MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id)); + int RemoveMission(int id) override; int RemoveStack(int id) override; diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h new file mode 100644 index 00000000000..904d9dda79d --- /dev/null +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APPEXECFWK_MOCK_ABILITY_SCHEDULER_FOR_OBESERVER_H +#define OHOS_APPEXECFWK_MOCK_ABILITY_SCHEDULER_FOR_OBESERVER_H + +#include "gmock/gmock.h" + +#include "ability_scheduler_stub.h" + +#include +#include + +namespace OHOS { +namespace AppExecFwk { + +// copy AbilityThread class +class MockAbilitySchedulerStub : public AAFwk::AbilitySchedulerStub { +public: + MockAbilitySchedulerStub() = default; + virtual ~MockAbilitySchedulerStub() = default; + + MOCK_METHOD2(ScheduleAbilityTransaction, void(const AAFwk::Want &, const AAFwk::LifeCycleStateInfo &)); + MOCK_METHOD3(SendResult, void(int, int, const AAFwk::Want &)); + MOCK_METHOD1(ScheduleConnectAbility, void(const AAFwk::Want &)); + MOCK_METHOD1(ScheduleDisconnectAbility, void(const AAFwk::Want &)); + MOCK_METHOD3(ScheduleCommandAbility, void(const AAFwk::Want &, bool, int)); + MOCK_METHOD1(ScheduleSaveAbilityState, void(PacMap &)); + MOCK_METHOD1(ScheduleRestoreAbilityState, void(const PacMap &)); + MOCK_METHOD1(ScheduleUpdateConfiguration, void(const AAFwk::DummyConfiguration &)); + MOCK_METHOD2(GetFileTypes, std::vector(const Uri &, const std::string &)); + MOCK_METHOD2(OpenFile, int(const Uri &, const std::string &)); + MOCK_METHOD2(OpenRawFile, int(const Uri &, const std::string &)); + MOCK_METHOD2(Insert, int(const Uri &, const ValuesBucket &)); + MOCK_METHOD3(Update, int(const Uri &, const ValuesBucket &, const DataAbilityPredicates &)); + MOCK_METHOD2(Delete, int(const Uri &, const DataAbilityPredicates &)); + MOCK_METHOD3( + Query, std::shared_ptr(const Uri &, std::vector &, const DataAbilityPredicates &)); + MOCK_METHOD1(GetType, std::string(const Uri &)); + MOCK_METHOD2(Reload, bool(const Uri &, const PacMap &)); + MOCK_METHOD2(BatchInsert, int(const Uri &, const std::vector &)); + MOCK_METHOD1(DenormalizeUri, Uri(const Uri &)); + MOCK_METHOD1(NormalizeUri, Uri(const Uri &)); + MOCK_METHOD1(NotifyTopActiveAbilityChanged, void(bool flag)); + MOCK_METHOD2(NotifyMultiWinModeChanged, void(int32_t winModeKey, bool flag)); +}; + +} // namespace AppExecFwk +} // namespace OHOS + +#endif /* OHOS_APPEXECFWK_MOCK_ABILITY_SCHEDULER_FOR_OBESERVER_H */ \ No newline at end of file diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_thread_for_ability_on_configuration_update.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_thread_for_ability_on_configuration_update.h new file mode 100644 index 00000000000..ef3d6d49cf8 --- /dev/null +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_thread_for_ability_on_configuration_update.h @@ -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. + */ + +#ifndef OHOS_APPEXECFWK_MOCK_ABILITY_THREAD_FOR_ABILITY_ON_CONFIGURATION_UPDATE_H +#define OHOS_APPEXECFWK_MOCK_ABILITY_THREAD_FOR_ABILITY_ON_CONFIGURATION_UPDATE_H + +#include "gtest/gtest.h" +#include "gmock/gmock.h" + +#include "ability.h" + +namespace OHOS { +namespace AppExecFwk { + +class AbilityTest : public Ability { +public: + AbilityTest() = default; + virtual ~AbilityTest() = default; + + MOCK_METHOD1(OnConfigurationUpdated, void(const Configuration &)); + + static std::shared_ptr GetInstance() + { + return abilitTest_; + }; + + static void InitInstance() + { + AbilityTest::abilitTest_ = std::make_shared(); + }; + + static void UnInitInstance() + { + AbilityTest::abilitTest_ = nullptr; + }; + + static std::shared_ptr abilitTest_; +}; + +std::shared_ptr AbilityTest::abilitTest_ = nullptr; + +} // namespace AppExecFwk +} // namespace OHOS + +#endif // OHOS_APPEXECFWK_MOCK_ABILITY_THREAD_FOR_ABILITY_ON_CONFIGURATION_UPDATE_H diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp index 76c11e2e798..ad5672e844c 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp @@ -27,6 +27,7 @@ bool BundleMgrProxy::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abil if (eleName.GetBundleName().empty()) { return false; } + abilityInfo.visible = true; abilityInfo.name = eleName.GetAbilityName(); abilityInfo.bundleName = eleName.GetBundleName(); abilityInfo.applicationName = "Helloworld"; @@ -69,6 +70,7 @@ bool BundleMgrService::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &ab if (std::string::npos != elementName.GetBundleName().find("service")) { abilityInfo.type = AppExecFwk::AbilityType::SERVICE; } + abilityInfo.visible = true; abilityInfo.name = elementName.GetAbilityName(); abilityInfo.bundleName = elementName.GetBundleName(); abilityInfo.applicationName = elementName.GetBundleName(); diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h index e6dfd0de37a..e190b5ca745 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h @@ -45,6 +45,10 @@ public: { return true; }; + bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) override + { + return true; + }; bool CheckIsSystemAppByUid(const int uid) override { return true; @@ -215,6 +219,16 @@ public: { return true; } + virtual bool GetModuleUsageRecords( + const int32_t number, std::vector &moduleUsageRecords) override + { + return true; + } + virtual bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) override + { + return true; + } }; class BundleMgrStub : public IRemoteStub { @@ -238,6 +252,10 @@ public: { return true; }; + virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) override + { + return true; + }; virtual bool CheckIsSystemAppByUid(const int uid) override { return true; @@ -408,6 +426,16 @@ public: { return true; } + virtual bool GetModuleUsageRecords( + const int32_t number, std::vector &moduleUsageRecords) override + { + return true; + } + virtual bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) override + { + return true; + } }; } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.cpp b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.cpp new file mode 100644 index 00000000000..7e69ee3513b --- /dev/null +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.cpp @@ -0,0 +1,172 @@ +/* + * 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 "mock_bundle_manager_form.h" +#include +#include "ability_info.h" +#include "application_info.h" +#include "form_info.h" + +namespace OHOS { +namespace AppExecFwk { +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; +const std::string FORM_JS_COMPOMENT_NAME= "jsComponentName"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; +const std::string DEVICE_ID = "ohos-phone1"; + +bool BundleMgrProxy::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) +{ + return true; +} + +int BundleMgrService::GetUidByBundleName(const std::string &bundleName, const int userId) +{ + if (bundleName.compare("com.form.host.app600") == 0) { + return 600; + } + return 0; +} + +bool BundleMgrProxy::GetAllFormsInfo(std::vector &formInfo) +{ + return true; +} +bool BundleMgrProxy::GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfo) +{ + return true; +} +bool BundleMgrProxy::GetFormsInfoByModule( + const std::string &bundleName, + const std::string &moduleName, + std::vector &formInfo) +{ + return true; +} + +int BundleMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + return 0; +} + +bool BundleMgrService::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) +{ + return true; +} + +bool BundleMgrService::QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) +{ + return false; +} + +bool BundleMgrService::GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) +{ + return true; +} + +std::string BundleMgrService::GetAppType(const std::string &bundleName) +{ + return "system"; +} + +bool BundleMgrService::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) +{ + std::vector abilityInfos; + ApplicationInfo applicationInfo; + ModuleInfo moduleInfo; + + moduleInfo.moduleSourceDir = FORM_PROVIDER_MODULE_SOURCE_DIR; + moduleInfo.moduleName = PARAM_PROVIDER_MODULE_NAME; + bundleInfo.name = bundleName; + applicationInfo.bundleName = bundleName; + applicationInfo.moduleInfos.emplace_back(moduleInfo); + bundleInfo.applicationInfo = applicationInfo; + + bundleInfo.moduleNames.emplace_back(PARAM_PROVIDER_MODULE_NAME); + + AbilityInfo abilityInfo; + abilityInfo.name = FORM_PROVIDER_ABILITY_NAME; + abilityInfo.package = PARAM_PROVIDER_PACKAGE_NAME; + abilityInfo.moduleName = PARAM_PROVIDER_MODULE_NAME; + abilityInfo.deviceId = DEVICE_ID; + bundleInfo.abilityInfos.emplace_back(abilityInfo); + + return true; +} +bool BundleMgrService::GetBundleGids(const std::string &bundleName, std::vector &gids) +{ + return true; +} + +bool BundleMgrService::GetAllFormsInfo(std::vector &formInfo) +{ + FormInfo form; + form.abilityName = FORM_PROVIDER_ABILITY_NAME; + form.moduleName = PARAM_PROVIDER_MODULE_NAME; + form.name = PARAM_FORM_NAME; + form.updateEnabled = true; + form.updateDuration = 1; + form.scheduledUpateTime = "06:06"; + form.jsComponentName = FORM_JS_COMPOMENT_NAME; + form.formVisibleNotify = true; + form.supportDimensions = {1, 2}; + form.defaultDimension = 1; + formInfo.emplace_back(form); + return true; +} +bool BundleMgrService::GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfo) +{ + FormInfo form; + form.bundleName = bundleName; + form.abilityName = FORM_PROVIDER_ABILITY_NAME; + form.moduleName = PARAM_PROVIDER_MODULE_NAME; + form.name = PARAM_FORM_NAME; + form.updateEnabled = true; + form.updateDuration = 1; + form.scheduledUpateTime = "06:06"; + form.jsComponentName = FORM_JS_COMPOMENT_NAME; + form.formVisibleNotify = true; + form.supportDimensions = {1, 2}; + form.defaultDimension = 1; + formInfo.emplace_back(form); + return true; +} +bool BundleMgrService::GetFormsInfoByModule( + const std::string &bundleName, + const std::string &moduleName, + std::vector &formInfo) +{ + FormInfo form; + form.bundleName = bundleName; + form.abilityName = FORM_PROVIDER_ABILITY_NAME; + form.moduleName = PARAM_PROVIDER_MODULE_NAME; + form.name = PARAM_FORM_NAME; + form.updateEnabled = true; + form.updateDuration = 1; + form.scheduledUpateTime = "06:06"; + form.jsComponentName = FORM_JS_COMPOMENT_NAME; + form.formVisibleNotify = true; + form.supportDimensions = {1, 2}; + form.defaultDimension = 1; + formInfo.emplace_back(form); + return true; +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h new file mode 100644 index 00000000000..d901417307e --- /dev/null +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h @@ -0,0 +1,527 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H +#define OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H + +#include + +#include "ability_info.h" +#include "application_info.h" +#include "foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h" +#include "gmock/gmock.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" +#include "ohos/aafwk/content/want.h" + +namespace OHOS { +namespace AppExecFwk { +class BundleMgrProxy : public IRemoteProxy { +public: + explicit BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) + {} + virtual ~BundleMgrProxy() + {} + + bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override + { + return true; + } + bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override + { + return true; + } + + std::string GetAppType(const std::string &bundleName) override + { + return "system"; + } + + virtual bool GetApplicationInfo( + const std::string &appName, + const ApplicationFlag flag, + const int userId, + ApplicationInfo &appInfo) override + { + return true; + } + virtual bool GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) override + { + return true; + } + + virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) override + { + return true; + } + virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override + { + if (bundleName.compare("com.form.host.app600") == 0) { + return 600; + } + return 0; + } + virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) override + { + return ""; + } + virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override + { + bundleName = "com.form.provider.service"; + return true; + } + virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) override + { + return true; + } + virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) override + { + return true; + } + virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) override + { + return true; + } + virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override + { + return ""; + } + + virtual bool GetBundleArchiveInfo( + const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override + { + return true; + } + + virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) override + { + return true; + } + + virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) override + { + return 0; + } + + virtual int CheckPermission(const std::string &bundleName, const std::string &permission) override + { + return 0; + } + virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) override + { + return true; + } + virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) override + { + return true; + } + virtual bool GetAppsGrantedPermissions( + const std::vector &permissions, std::vector &appNames) override + { + return true; + } + virtual bool HasSystemCapability(const std::string &capName) override + { + return true; + } + virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override + { + return true; + } + virtual bool IsSafeMode() override + { + return true; + } + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + } + virtual bool CleanBundleDataFiles(const std::string &bundleName) override + { + return true; + } + virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + } + virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + } + // unregister callback of all application + virtual bool UnregisterBundleStatusCallback() override + { + return true; + } + virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) override + { + return true; + } + virtual sptr GetBundleInstaller() override + { + return nullptr; + } + + /** + * @brief Obtains information about the shortcuts of the application. + * @param bundleName Indicates the name of the bundle to shortcut. + * @param form Indicates the callback a list to shortcutinfo. + * @return Returns true if shortcutinfo get success + */ + virtual bool GetShortcutInfos(const std::string &bundleName,std::vector &shortcut) override{ + return true; + } + // /** + // * @brief Starts a shortcut based on the given shortcut ID and bundle name. + // * @param bundleName BundleName Indicates the bundle name of the application to which the shortcut belongs. + // * @param shortcutId Starts a shortcut based on the given shortcut ID and bundle name. + // * @return Returns true if StartShortcut get success + // */ + // virtual bool StartShortcut(const std::string &shortcutId, const std::string &bundleName) override{ + // return true; + // } + /** + * @brief Disables specified home-screen shortcuts that are no longer used. + * @param shortcutIds Indicates the list of shortcut IDs to be disabled. + * @return Returns true if disableHomeShortcuts get success + */ + // virtual bool DisableHomeShortcuts(std::vector &shortcutIds) override{ + // return true; + // } + // /** + // * @brief Enables specified home-screen shortcuts. + // * @param shortcutIds Indicates the list of shortcut IDs to be enabled. + // * @return Returns true if enableHomeShortcuts? get success + // */ + // virtual bool EnableHomeShortcuts(std::vector &shortcutIds) override{ + // return true; + // } + // /** + // * @brief Checks whether a shortcut can be added to the home screen where the application is located. + // * @return Returns true if a shortcut can be added to the home screen; returns false otherwise. + // */ + // virtual bool IsHomeShortcutSupportes() override{ + // return true; + // } + // /** + // * @brief Adds a home-screen shortcut that will be fixed on the home screen. + // * @param shortcutInfo Indicates the ShortcutInfo object containing information about the home-screen shortcut to add. The id, label, and intent attributes of this parameter must be specified. + // * @return Returns true if the shortcut is successfully added; returns false otherwise. + // */ + // virtual bool AddHomeShortcut(ShortcutInfo &shortcutInfo) override{ + // return true; + // } + // /** + // * @brief Updates information about specified home-screen shortcuts that have been added. + // * @param shortcutInfos Updates information about specified home-screen shortcuts that have been added. + // * @return Returns true if the operation is successful; returns false otherwise. + // */ + // virtual bool UpdateShortcuts(std::vector &shortcutInfos) override{ + // return true; + // } + // /** + // * @brief Checks whether a specified shortcut is available. + // * @param shortcutId Indicates the ID of the shortcut to check. + // * @param flag Indicates the type of the shortcut to check. Currently, only the home-screen shortcut IBundleManager#QUERY_SHORTCUT_HOME is available. + // * @return Returns IBundleManager#SHORTCUT_EXISTENCE_EXISTS if the specified shortcut is available; returns IBundleManager#SHORTCUT_EXISTENCE_NOT_EXISTS if it is not available; returns IBundleManager.SHORTCUT_EXISTENCE_UNKNOW if an error occurs. + // */ + // virtual int IsShortcutExist(const std::string &shortcutId, const int &flag) override{ + // return 0; + // } + /** + * @brief Obtain the HAP module info of a specific ability. + * @param abilityInfo Indicates the ability. + * @param hapModuleInfo Indicates the obtained HapModuleInfo object. + * @return Returns true if the HapModuleInfo is successfully obtained; returns false otherwise. + */ + virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) override + { + return true; + } + + virtual bool CheckIsSystemAppByUid(const int uid) override + { + if (uid == 600) { + return true; + } + return false; + } + virtual bool IsApplicationEnabled(const std::string &bundleName)override + { + return true; + } + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + } + + virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override; + virtual bool GetAllFormsInfo(std::vector &formInfo) override; + virtual bool GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfo) override; + virtual bool GetFormsInfoByModule( + const std::string &bundleName, + const std::string &moduleName, + std::vector &formInfo) override; +}; + +class BundleMgrStub : public IRemoteStub { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"IBundleMgr"); + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; +}; + +class BundleMgrService : public BundleMgrStub { +public: + MOCK_METHOD2(GetAppIdByBundleName, std::string(const std::string &bundleName, const int userId)); + MOCK_METHOD2(CheckPermission, int(const std::string &bundleName, const std::string &permission)); + MOCK_METHOD1(CleanBundleDataFiles, bool(const std::string &bundleName)); + MOCK_METHOD3( + CanRequestPermission, bool(const std::string &bundleName, const std::string &permissionName, const int userId)); + MOCK_METHOD3(RequestPermissionFromUser, + 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)); + MOCK_METHOD2(RegisterPermissionsChanged, + bool(const std::vector &uids, const sptr &callback)); + MOCK_METHOD1(UnregisterPermissionsChanged, bool(const sptr &callback)); + bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override; + bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override; + + std::string GetAppType(const std::string &bundleName) override; + virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override; + + virtual bool GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; + virtual bool GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) override + { + return true; + }; + virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override; + virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) override + { + return true; + }; + virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override + { + bundleName = "com.form.provider.service"; + return true; + }; + virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) override; + virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) override + { + return true; + }; + virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) override + { + return true; + }; + virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override + { + return ""; + }; + // obtains information about an application bundle contained in a ohos Ability Package (HAP). + virtual bool GetBundleArchiveInfo( + const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override + { + return true; + }; + virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) override + { + return true; + } + // obtains the Want for starting the main ability of an application based on the given bundle name. + virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) override + { + return true; + }; + // checks whether the publickeys of two bundles are the same. + virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) override + { + return 0; + }; + // checks whether a specified bundle has been granted a specific permission. + virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) override + { + return true; + }; + virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) override + { + return true; + }; + virtual bool GetAppsGrantedPermissions( + const std::vector &permissions, std::vector &appNames) override + { + return true; + }; + virtual bool HasSystemCapability(const std::string &capName) override + { + return true; + }; + virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override + { + return true; + }; + virtual bool IsSafeMode() override + { + return true; + }; + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + }; + + virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + }; + virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + }; + // unregister callback of all application + virtual bool UnregisterBundleStatusCallback() override + { + return true; + }; + virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) override + { + return true; + }; + virtual sptr GetBundleInstaller() override + { + return nullptr; + }; + virtual bool IsApplicationEnabled(const std::string &bundleName) override + { + return true; + }; + virtual bool CheckIsSystemAppByUid(const int uid) override + { + if (uid == 600) { + return false; + } + + return true; + }; + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + }; + + /** + * @brief Obtains information about the shortcuts of the application. + * @param bundleName Indicates the name of the bundle to shortcut. + * @param form Indicates the callback a list to shortcutinfo. + * @return Returns true if shortcutinfo get success + */ + virtual bool GetShortcutInfos(const std::string &bundleName,std::vector &shortcut) override{ + return true; + } + // /** + // * @brief Starts a shortcut based on the given shortcut ID and bundle name. + // * @param bundleName BundleName Indicates the bundle name of the application to which the shortcut belongs. + // * @param shortcutId Starts a shortcut based on the given shortcut ID and bundle name. + // * @return Returns true if StartShortcut get success + // */ + // virtual bool StartShortcut(const std::string &shortcutId, const std::string &bundleName) override{ + // return true; + // } + // /** + // * @brief Disables specified home-screen shortcuts that are no longer used. + // * @param shortcutIds Indicates the list of shortcut IDs to be disabled. + // * @return Returns true if disableHomeShortcuts get success + // */ + // virtual bool DisableHomeShortcuts(std::vector &shortcutIds) override{ + // return true; + // } + // /** + // * @brief Enables specified home-screen shortcuts. + // * @param shortcutIds Indicates the list of shortcut IDs to be enabled. + // * @return Returns true if enableHomeShortcuts? get success + // */ + // virtual bool EnableHomeShortcuts(std::vector &shortcutIds) override{ + // return true; + // } + /** + * @brief Checks whether a shortcut can be added to the home screen where the application is located. + * @return Returns true if a shortcut can be added to the home screen; returns false otherwise. + */ + // virtual bool IsHomeShortcutSupportes() override{ + // return true; + // } + // /** + // * @brief Adds a home-screen shortcut that will be fixed on the home screen. + // * @param shortcutInfo Indicates the ShortcutInfo object containing information about the home-screen shortcut to add. The id, label, and intent attributes of this parameter must be specified. + // * @return Returns true if the shortcut is successfully added; returns false otherwise. + // */ + // virtual bool AddHomeShortcut(ShortcutInfo &shortcutInfo) override{ + // return true; + // } + // /** + // * @brief Updates information about specified home-screen shortcuts that have been added. + // * @param shortcutInfos Updates information about specified home-screen shortcuts that have been added. + // * @return Returns true if the operation is successful; returns false otherwise. + // */ + // virtual bool UpdateShortcuts(std::vector &shortcutInfos) override{ + // return true; + // } + // /** + // * @brief Checks whether a specified shortcut is available. + // * @param shortcutId Indicates the ID of the shortcut to check. + // * @param flag Indicates the type of the shortcut to check. Currently, only the home-screen shortcut IBundleManager#QUERY_SHORTCUT_HOME is available. + // * @return Returns IBundleManager#SHORTCUT_EXISTENCE_EXISTS if the specified shortcut is available; returns IBundleManager#SHORTCUT_EXISTENCE_NOT_EXISTS if it is not available; returns IBundleManager.SHORTCUT_EXISTENCE_UNKNOW if an error occurs. + // */ + // virtual int IsShortcutExist(const std::string &shortcutId, const int &flag) override{ + // return 0; + // } + + virtual bool GetAllFormsInfo(std::vector &formInfo) override; + virtual bool GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfo) override; + virtual bool GetFormsInfoByModule( + const std::string &bundleName, + const std::string &moduleName, + std::vector &formInfo) override; + virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) override + { + return true; + }; + virtual bool GetModuleUsageRecords( + const int32_t number, std::vector &moduleUsageRecords) override + { + return true; + } + virtual bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) override + { + return true; + } + +}; + +} // namespace AppExecFwk +} // namespace OHOS + +#endif // OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H diff --git a/frameworks/kits/ability/native/test/mock/include/mock_form_mgr_service.h b/frameworks/kits/ability/native/test/mock/include/mock_form_mgr_service.h new file mode 100755 index 00000000000..ba866ffae5a --- /dev/null +++ b/frameworks/kits/ability/native/test/mock/include/mock_form_mgr_service.h @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_MOCK_FORM_MGR_SERVICE_H +#define FOUNDATION_APPEXECFWK_SERVICES_MOCK_FORM_MGR_SERVICE_H + +#include +#include +#include +#include +#include +#include + +#include "event_handler.h" +#include "form_constants.h" +#include "form_mgr_stub.h" +#include "form_js_info.h" +#include "form_provider_data.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class MockFormMgrService. + * The mockFormMgrService for ability test. + */ +class MockFormMgrService : public IFormMgr { +public: + MockFormMgrService(){}; + virtual ~MockFormMgrService(){}; + + sptr AsObject() + { + return nullptr; + } + + /** + * @brief Start envent for the form manager service. + */ + void OnStart(){} + + /** + * @brief Stop envent for the form manager service. + */ + void OnStop(){} + + /** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, FormJsInfo &formInfo) + { + // int64_t formId = want.GetLongParam(Constants::PARAM_FORM_IDENTITY_KEY, 0L); + if (formId == 300L) { + formInfo.formId = formId; + } + return 0; + } + + /** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int DeleteForm(const int64_t formId, const sptr &callerToken) + { + return 0; + } + + /** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ + int ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) + { + return 0; + } + + /** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param formBindingData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ + int UpdateForm(const int64_t formId, const std::string& bundleName, const FormProviderData& formBindingData) + { + if (formId == 300L){ + return -1; + } + return 0; + } + + /** + * @brief Request form with formId and want, send formId and want to form manager service. + * @param formId The Id of the form to update. + * @param callerToken Caller ability token. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + int RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) + { + return 0; + } + + /** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int NotifyWhetherVisibleForms( + const std::vector &formIds, + const sptr &callerToken, + const int32_t formVisibleType) + { + if (formIds.size() == 1) { + return 0; + } + return 1; + } + + /** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int CastTempForm(const int64_t formId, const sptr &callerToken) + { + if (formId == 175L)return 0; + return 1; + } + + /** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpStorageFormInfos(std::string& formInfos) + { + return 0; + } + + /** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) + { + return 0; + } + + /** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) + { + return 0; + } + + /** + * @brief Set next refresh time. + * @param formId The Id of the form. + * @param nextTime The next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ + int SetNextRefreshTime(const int64_t formId, const int64_t nextTime) + { + if (formId >= 1) { + return ERR_OK; + } else { + return ERR_INVALID_VALUE; + } + } + + /** + * @brief Lifecycle Update. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param updateType The update type. + * @return Returns ERR_OK on success, others on failure. + */ + int LifecycleUpdate( + const std::vector &formIds, + const sptr &callerToken, + const int32_t updateType) + { + if (formIds.size() == 0) { + return ERR_INVALID_VALUE; + } + return ERR_OK; + } + + /** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ + int MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) + { + return 0; + } +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_MOCK_FORM_MGR_SERVICE_H diff --git a/frameworks/kits/ability/native/test/mock/include/mock_form_supply_callback.cpp b/frameworks/kits/ability/native/test/mock/include/mock_form_supply_callback.cpp new file mode 100644 index 00000000000..e96381a697c --- /dev/null +++ b/frameworks/kits/ability/native/test/mock/include/mock_form_supply_callback.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_log_wrapper.h" +#include "mock_form_supply_callback.h" + +namespace OHOS { +namespace AppExecFwk { +sptr MockFormSupplyCallback::instance = nullptr; +std::mutex MockFormSupplyCallback::mutex; + +sptr MockFormSupplyCallback::GetInstance() +{ + if (instance == nullptr) { + std::lock_guard lockl(mutex); + if (instance == nullptr) { + instance = new MockFormSupplyCallback(); + } + } + return instance; +} + +/** + * onAcquire + * + * @param formInfo Form Provider Info. + * @param want data + */ +int MockFormSupplyCallback::OnAcquire(const FormProviderInfo &formProviderInfo, const Want& want) +{ + APP_LOGI("MockFormSupplyCallback::OnAcquire called."); + return 1; +} + + +/** + * onEventHandle + * + * @param want data + */ +int MockFormSupplyCallback::OnEventHandle(const Want& want) +{ + APP_LOGI("MockFormSupplyCallback::OnEventHandle called."); + return 1; +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/test/mock/include/mock_form_supply_callback.h b/frameworks/kits/ability/native/test/mock/include/mock_form_supply_callback.h new file mode 100644 index 00000000000..4c1b5198dfe --- /dev/null +++ b/frameworks/kits/ability/native/test/mock/include/mock_form_supply_callback.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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H + +#include "form_supply_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormSupplyStub + * FormSupplyStub. + */ +class MockFormSupplyCallback : public FormSupplyStub { +public: + MockFormSupplyCallback() = default; + virtual ~MockFormSupplyCallback() = default; + static sptr GetInstance(); + + /** + * onAcquire + * + * @param providerFormInfo providerFormInfo + * @param want data + */ + virtual int OnAcquire(const FormProviderInfo &formInfo, const Want& want) override; + + /** + * onEventHandle + * + * @param want data + */ + virtual int OnEventHandle(const Want& want) override; + +private: + static std::mutex mutex; + static sptr instance; + + DISALLOW_COPY_AND_MOVE(MockFormSupplyCallback); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H diff --git a/frameworks/kits/ability/native/test/mock/include/mock_resourceManager_interface1.cpp b/frameworks/kits/ability/native/test/mock/include/mock_resourceManager_interface1.cpp index 9f1cbeb88ff..f06f2782128 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_resourceManager_interface1.cpp +++ b/frameworks/kits/ability/native/test/mock/include/mock_resourceManager_interface1.cpp @@ -1,4 +1,17 @@ - +/* + * 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 "gmock/gmock.h" diff --git a/frameworks/kits/ability/native/test/unittest/ability_thread_for_ability_on_configuration_update.cpp b/frameworks/kits/ability/native/test/unittest/ability_thread_for_ability_on_configuration_update.cpp new file mode 100644 index 00000000000..ad43df2970b --- /dev/null +++ b/frameworks/kits/ability/native/test/unittest/ability_thread_for_ability_on_configuration_update.cpp @@ -0,0 +1,130 @@ +/* + * 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 "gtest/gtest.h" +#include "gmock/gmock.h" + +#include "ability_thread.h" +#include "ability.h" +#include "ability_impl.h" + +#include "mock_ability_thread_for_ability_on_configuration_update.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; + +class AbilityThreadTest : public testing::Test { +public: + AbilityThreadTest() : abilitythread_(nullptr) + {} + ~AbilityThreadTest() + { + abilitythread_ = nullptr; + } + AbilityThread *abilitythread_; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AbilityThreadTest::SetUpTestCase(void) +{ + AbilityTest::InitInstance(); +} + +void AbilityThreadTest::TearDownTestCase(void) +{ + AbilityTest::UnInitInstance(); +} + +void AbilityThreadTest::SetUp(void) +{} + +void AbilityThreadTest::TearDown(void) +{} + +AbilityThread::AbilityThread() + : abilityImpl_(nullptr), token_(nullptr), currentAbility_(nullptr), abilityHandler_(nullptr), runner_(nullptr) +{ + abilityImpl_ = std::make_shared(); + abilityHandler_ = std::make_shared(EventRunner::Create("AbilityTest"), this); + + std::shared_ptr application = nullptr; + std::shared_ptr ability = AbilityTest::GetInstance(); + std::shared_ptr contextDeal = nullptr; + abilityImpl_->Init(application, nullptr, ability, abilityHandler_, nullptr, contextDeal); +} + +void AbilityImpl::Init(std::shared_ptr &application, const std::shared_ptr &record, + std::shared_ptr &ability, std::shared_ptr &handler, const sptr &token, + std::shared_ptr &contextDeal) +{ + ability_ = ability; +} + +/** + * @tc.number: AaFwk_AbilityThread_ScheduleUpdateConfiguration_0100 + * @tc.name: ScheduleUpdateConfiguration + * @tc.desc: Simulate successful test cases + */ +HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleUpdateConfiguration_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleUpdateConfiguration_0100 start"; + std::shared_ptr abilityThread = std::make_shared(); + + DummyConfiguration config; + uint32_t code = OHOS::AAFwk::IAbilityScheduler::SCHEDULE_UPDATE_CONFIGURATION; + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(AbilityThread::GetDescriptor())) { + EXPECT_TRUE(false); + GTEST_LOG_(ERROR) << "---------- data.WriteInterfaceToken retval is false"; + return; + } + + if (!data.WriteParcelable(&config)) { + EXPECT_TRUE(false); + GTEST_LOG_(ERROR) << "---------- data.WriteParcelable retval is false"; + return; + } + + if (AbilityTest::GetInstance() == nullptr) { + EXPECT_TRUE(false); + GTEST_LOG_(ERROR) << "---------- AbilityTest::GetInstance() is nullptr"; + return; + } + + auto call = [](const Configuration &) { GTEST_LOG_(INFO) << "---------- OnConfigurationUpdated Call Success"; }; + + EXPECT_CALL(*AbilityTest::GetInstance(), OnConfigurationUpdated(testing::_)) + .Times(1) + .WillOnce(testing::Invoke(call)); + + abilityThread->OnRemoteRequest(code, data, reply, option); + + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleUpdateConfiguration_0100 end"; +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/test/unittest/data_ability_helper_test.cpp b/frameworks/kits/ability/native/test/unittest/data_ability_helper_test.cpp index 4c1e0094bc6..9b7c33d737d 100644 --- a/frameworks/kits/ability/native/test/unittest/data_ability_helper_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/data_ability_helper_test.cpp @@ -13,27 +13,24 @@ * limitations under the License. */ -#include "data_ability_helper.h" -#include -#include -#include +#include "gtest/gtest.h" + +#include "mock_ability_manager_client_for_data_ability_observer.h" +#include "mock_ability_scheduler_for_observer.h" #include "mock_ability_manager_client.h" -#include "mock_ability_token.h" +#include "context.h" +#include "ability_context.h" +#include "data_ability_helper.h" namespace OHOS { namespace AppExecFwk { using namespace testing::ext; -using namespace OHOS; -using namespace OHOS::AppExecFwk; -using testing::_; -using testing::Invoke; -using testing::Return; -class DataAbilityHelperTest : public testing::Test { +class DataAbilityHelperForObserverTest : public testing::Test { public: - DataAbilityHelperTest() + DataAbilityHelperForObserverTest() {} - ~DataAbilityHelperTest() + virtual ~DataAbilityHelperForObserverTest() {} static void SetUpTestCase(void); @@ -42,133 +39,51 @@ public: void TearDown(); }; -void DataAbilityHelperTest::SetUpTestCase(void) -{} - -void DataAbilityHelperTest::TearDownTestCase(void) -{} - -void DataAbilityHelperTest::SetUp(void) +void DataAbilityHelperForObserverTest::SetUpTestCase(void) {} -void DataAbilityHelperTest::TearDown(void) -{} - -/** - * @tc.number: AaFwk_DataAbilityHelper_Create_0100 - * @tc.name: DataAbilityHelper - * @tc.desc: Test the dataabilityhelper object. - */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Create_0100, Function | MediumTest | Level1) +void DataAbilityHelperForObserverTest::TearDownTestCase(void) { - GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Create_0100 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper1 = DataAbilityHelper::Creator(nullptr); - EXPECT_EQ(helper1, nullptr); - std::shared_ptr helper2 = DataAbilityHelper::Creator(context); - EXPECT_NE(helper2, nullptr); - std::shared_ptr helper3 = DataAbilityHelper::Creator(nullptr, uri); - EXPECT_EQ(helper3, nullptr); - std::shared_ptr helper4 = DataAbilityHelper::Creator(nullptr, nullptr); - EXPECT_EQ(helper4, nullptr); - std::shared_ptr helper5 = DataAbilityHelper::Creator(context, nullptr); - EXPECT_EQ(helper5, nullptr); - std::shared_ptr helper6 = DataAbilityHelper::Creator(context, uri); - EXPECT_NE(helper6, nullptr); - std::shared_ptr helper7 = DataAbilityHelper::Creator(nullptr, nullptr, false); - EXPECT_EQ(helper7, nullptr); - std::shared_ptr helper8 = DataAbilityHelper::Creator(context, nullptr, false); - EXPECT_EQ(helper8, nullptr); - std::shared_ptr helper9 = DataAbilityHelper::Creator(nullptr, uri, false); - EXPECT_EQ(helper9, nullptr); - std::shared_ptr helper10 = DataAbilityHelper::Creator(context, uri, false); - EXPECT_NE(helper10, nullptr); - std::shared_ptr helper11 = DataAbilityHelper::Creator(nullptr, nullptr, true); - EXPECT_EQ(helper11, nullptr); - std::shared_ptr helper12 = DataAbilityHelper::Creator(context, nullptr, true); - EXPECT_EQ(helper12, nullptr); - std::shared_ptr helper13 = DataAbilityHelper::Creator(nullptr, uri, true); - EXPECT_EQ(helper13, nullptr); - std::shared_ptr helper14 = DataAbilityHelper::Creator(context, uri, true); - EXPECT_NE(helper14, nullptr); - - GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Create_0100 end"; + MockAbilitySchedulerTools::GetInstance()->SetMockStatus(false); } -/** - * @tc.number: AaFwk_DataAbilityHelper_Release_0100 - * @tc.name: Release - * @tc.desc: Test whether the return value of release is true when the parameter passed by Creator is true. - */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Release_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Release_0100 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - EXPECT_EQ(true, helper->Release()); - } - - GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Release_0100 end"; -} +void DataAbilityHelperForObserverTest::SetUp(void) +{} -/** - * @tc.number: AaFwk_DataAbilityHelper_Release_0200 - * @tc.name: Release - * @tc.desc: Test whether the return value of release is false when the parameter passed by Creator is false. - */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Release_0200, Function | MediumTest | Level3) +void DataAbilityHelperForObserverTest::TearDown(void) { - GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Release_0200 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr helper = DataAbilityHelper::Creator(context); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - EXPECT_EQ(false, helper->Release()); - } - - GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Release_0200 end"; + MockAbilitySchedulerTools::DestoryInstance(); } /** * @tc.number: AaFwk_DataAbilityHelper_GetFileTypes_0100 * @tc.name: GetFileTypes - * @tc.desc: When the parameter passed by Creator is true, test whether the return value of getfiletypes is correct. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetFileTypes_0100, Function | MediumTest | Level1) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_GetFileTypes_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_0100 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::string mimeTypeFilter("mimeTypeFiltertest"); - std::vector result = helper->GetFileTypes(uri2, mimeTypeFilter); - - int count = result.size(); - EXPECT_EQ(count, 3); - - std::vector list; - list.push_back("Types1"); - list.push_back("Types2"); - list.push_back("Types3"); - - for (int i = 0; i < count; i++) { - EXPECT_STREQ(result.at(i).c_str(), list.at(i).c_str()); - } - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + std::string mimeTypeFilter("mimeTypeFiltertest"); + // Test to AbilityThread interface + auto returnGetFileTypes = [&](const Uri &uri, const std::string &mimeTypeFilter) { + std::vector matchedMIMEs; + matchedMIMEs.push_back("test1"); + matchedMIMEs.push_back("test2"); + matchedMIMEs.push_back("test3"); + return matchedMIMEs; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), GetFileTypes(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnGetFileTypes)); + + dataAbilityHelper->GetFileTypes(*uri, mimeTypeFilter); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_0100 end"; } @@ -176,25 +91,32 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetFileTypes_0100, Funct /** * @tc.number: AaFwk_DataAbilityHelper_GetFileTypes_0200 * @tc.name: GetFileTypes - * @tc.desc: Test whether the return value of GetFileTypes is 0 when the parameter passed by Creator is false. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetFileTypes_0200, Function | MediumTest | Level3) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_GetFileTypes_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_0200 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, false); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest"); - std::string mimeTypeFilter("mimeTypeFiltertest"); - std::vector result = helper->GetFileTypes(uri2, mimeTypeFilter); - - int count = result.size(); - EXPECT_EQ(count, 0); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + std::string mimeTypeFilter("mimeTypeFiltertest"); + // Test to AbilityThread interface + auto returnGetFileTypes = [&](const Uri &uri, const std::string &mimeTypeFilter) { + std::vector matchedMIMEs; + matchedMIMEs.push_back("test1"); + matchedMIMEs.push_back("test2"); + matchedMIMEs.push_back("test3"); + return matchedMIMEs; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), GetFileTypes(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnGetFileTypes)); + + dataAbilityHelper->GetFileTypes(*uri, mimeTypeFilter); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_0200 end"; } @@ -202,24 +124,29 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetFileTypes_0200, Funct /** * @tc.number: AaFwk_DataAbilityHelper_OpenFile_0100 * @tc.name: OpenFile - * @tc.desc: Test whether the return value of OpenFile is 1246 when the parameter passed by Creator is true. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenFile_0100, Function | MediumTest | Level1) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_OpenFile_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_0100 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::string mode("modetest"); - int fd = helper->OpenFile(uri2, mode); - - EXPECT_EQ(fd, 1246); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + std::string mode("modetest"); + // Test to AbilityThread interface + auto returnOpenFile = [&](const Uri &uri, const std::string &mode) { + int fd = 1234; + return fd; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), OpenFile(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnOpenFile)); + + dataAbilityHelper->OpenFile(*uri, mode); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_0100 end"; } @@ -227,24 +154,29 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenFile_0100, Function /** * @tc.number: AaFwk_DataAbilityHelper_OpenFile_0200 * @tc.name: OpenFile - * @tc.desc: Test whether the return value of OpenFile is -1 when the parameter passed by Creator is false. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenFile_0200, Function | MediumTest | Level3) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_OpenFile_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_0200 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, false); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest"); - std::string mode("modetest"); - int fd = helper->OpenFile(uri2, mode); - - EXPECT_EQ(fd, -1); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + std::string mode("modetest"); + // Test to AbilityThread interface + auto returnOpenFile = [&](const Uri &uri, const std::string &mode) { + int fd = 1234; + return fd; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), OpenFile(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnOpenFile)); + + dataAbilityHelper->OpenFile(*uri, mode); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_0200 end"; } @@ -252,24 +184,29 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenFile_0200, Function /** * @tc.number: AaFwk_DataAbilityHelper_Insert_0100 * @tc.name: Insert - * @tc.desc: Test whether the return value of Insert is 2345 when the parameter passed by Creator is true. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Insert_0100, Function | MediumTest | Level1) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Insert_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_0100 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - ValuesBucket val("valtest"); - int index = helper->Insert(uri2, val); - - EXPECT_EQ(index, 2345); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + ValuesBucket val("valtest"); + // Test to AbilityThread interface + auto returnInsert = [&](const Uri &uri, const ValuesBucket &val) { + int index = 1234; + return index; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), Insert(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnInsert)); + + dataAbilityHelper->Insert(*uri, val); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_0100 end"; } @@ -277,24 +214,29 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Insert_0100, Function | /** * @tc.number: AaFwk_DataAbilityHelper_Insert_0200 * @tc.name: Insert - * @tc.desc: Test whether the return value of Insert is -1 when the parameter passed by Creator is false. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Insert_0200, Function | MediumTest | Level3) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Insert_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_0200 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, false); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest"); - ValuesBucket val("valtest"); - int index = helper->Insert(uri2, val); - - EXPECT_EQ(index, -1); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + ValuesBucket val("valtest"); + // Test to AbilityThread interface + auto returnInsert = [&](const Uri &uri, const ValuesBucket &val) { + int index = 1234; + return index; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), Insert(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnInsert)); + + dataAbilityHelper->Insert(*uri, val); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_0200 end"; } @@ -302,25 +244,30 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Insert_0200, Function | /** * @tc.number: AaFwk_DataAbilityHelper_Update_0100 * @tc.name: Update - * @tc.desc: Test whether the return value of Update is 3456 when the parameter passed by Creator is true. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Update_0100, Function | MediumTest | Level1) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Update_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Update_0100 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - ValuesBucket val("valtest"); - DataAbilityPredicates predicates("predicatestest"); - int index = helper->Update(uri2, val, predicates); - - EXPECT_EQ(index, 3456); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + ValuesBucket val("valtest"); + DataAbilityPredicates predicates("predicatestest"); + // Test to AbilityThread interface + auto returnUpdate = [&](const Uri &uri, const ValuesBucket &val, const DataAbilityPredicates &predicates) { + int index = 1234; + return index; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), Update(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnUpdate)); + + dataAbilityHelper->Update(*uri, val, predicates); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Update_0100 end"; } @@ -328,25 +275,30 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Update_0100, Function | /** * @tc.number: AaFwk_DataAbilityHelper_Update_0200 * @tc.name: Update - * @tc.desc: Test whether the return value of Update is -1 when the parameter passed by Creator is false. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Update_0200, Function | MediumTest | Level3) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Update_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Update_0200 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, false); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest"); - ValuesBucket val("valtest"); - DataAbilityPredicates predicates("predicatestest"); - int index = helper->Update(uri2, val, predicates); - - EXPECT_EQ(index, -1); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + ValuesBucket val("valtest"); + DataAbilityPredicates predicates("predicatestest"); + // Test to AbilityThread interface + auto returnUpdate = [&](const Uri &uri, const ValuesBucket &val, const DataAbilityPredicates &predicates) { + int index = 1234; + return index; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), Update(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnUpdate)); + + dataAbilityHelper->Update(*uri, val, predicates); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Update_0200 end"; } @@ -354,24 +306,29 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Update_0200, Function | /** * @tc.number: AaFwk_DataAbilityHelper_Delete_0100 * @tc.name: Delete - * @tc.desc: Test whether the return value of Delete is 6789 when the parameter passed by Creator is true. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Delete_0100, Function | MediumTest | Level1) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Delete_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_0100 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - DataAbilityPredicates predicates("predicatestest"); - int index = helper->Delete(uri2, predicates); - - EXPECT_EQ(index, 6789); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + DataAbilityPredicates predicates("predicatestest"); + // Test to AbilityThread interface + auto returnDelete = [&](const Uri &uri, const DataAbilityPredicates &predicates) { + int index = 1234; + return index; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), Delete(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnDelete)); + + dataAbilityHelper->Delete(*uri, predicates); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_0100 end"; } @@ -379,24 +336,29 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Delete_0100, Function | /** * @tc.number: AaFwk_DataAbilityHelper_Delete_0200 * @tc.name: Delete - * @tc.desc: Test whether the return value of Delete is -1 when the parameter passed by Creator is false. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Delete_0200, Function | MediumTest | Level3) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Delete_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_0200 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, false); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest"); - DataAbilityPredicates predicates("predicatestest"); - int index = helper->Delete(uri2, predicates); - - EXPECT_EQ(index, -1); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + DataAbilityPredicates predicates("predicatestest"); + // Test to AbilityThread interface + auto returnDelete = [&](const Uri &uri, const DataAbilityPredicates &predicates) { + int index = 1234; + return index; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), Delete(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnDelete)); + + dataAbilityHelper->Delete(*uri, predicates); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_0200 end"; } @@ -404,25 +366,31 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Delete_0200, Function | /** * @tc.number: AaFwk_DataAbilityHelper_Query_0100 * @tc.name: Query - * @tc.desc: Test whether the return value of Query is null when the parameter passed by Creator is true. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Query_0100, Function | MediumTest | Level1) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Query_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_0100 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::vector columns; - DataAbilityPredicates predicates("predicatestest"); - std::shared_ptr set = helper->Query(uri2, columns, predicates); - - EXPECT_NE(set, nullptr); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + std::vector columns; + DataAbilityPredicates predicates("predicatestest"); + // Test to AbilityThread interface + auto returnQuery = + [&](const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) { + std::shared_ptr set = std::make_shared("resultset"); + return set; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), Query(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnQuery)); + + dataAbilityHelper->Query(*uri, columns, predicates); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_0100 end"; } @@ -430,25 +398,31 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Query_0100, Function | M /** * @tc.number: AaFwk_DataAbilityHelper_Query_0200 * @tc.name: Query - * @tc.desc: Test whether the return value of Query is null when the parameter passed by Creator is false. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Query_0200, Function | MediumTest | Level3) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Query_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_0200 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, false); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest"); - std::vector columns; - DataAbilityPredicates predicates("predicatestest"); - std::shared_ptr set = helper->Query(uri2, columns, predicates); - - EXPECT_EQ(set, nullptr); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + std::vector columns; + DataAbilityPredicates predicates("predicatestest"); + // Test to AbilityThread interface + auto returnQuery = + [&](const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) { + std::shared_ptr set = std::make_shared("resultset"); + return set; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), Query(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnQuery)); + + dataAbilityHelper->Query(*uri, columns, predicates); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_0200 end"; } @@ -456,23 +430,28 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Query_0200, Function | M /** * @tc.number: AaFwk_DataAbilityHelper_GetType_0100 * @tc.name: GetType - * @tc.desc: Test whether the return value of GetType is Type1 when the parameter passed by Creator is true. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetType_0100, Function | MediumTest | Level1) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_GetType_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_0100 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::string type = helper->GetType(uri2); - - EXPECT_STREQ(type.c_str(), "Type1"); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + // Test to AbilityThread interface + auto returnGetType = [&](const Uri &uri) { + std::string type("Type1"); + return type; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), GetType(testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnGetType)); + + dataAbilityHelper->GetType(*uri); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_0100 end"; } @@ -480,23 +459,28 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetType_0100, Function | /** * @tc.number: AaFwk_DataAbilityHelper_GetType_0200 * @tc.name: GetType - * @tc.desc: Test whether the return value of GetType is Type1 when the parameter passed by Creator is false. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetType_0200, Function | MediumTest | Level1) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_GetType_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_0200 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, false); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest"); - std::string type = helper->GetType(uri2); - - EXPECT_STRNE(type.c_str(), "Type1"); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + // Test to AbilityThread interface + auto returnGetType = [&](const Uri &uri) { + std::string type("Type1"); + return type; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), GetType(testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnGetType)); + + dataAbilityHelper->GetType(*uri); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_0200 end"; } @@ -504,24 +488,29 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetType_0200, Function | /** * @tc.number: AaFwk_DataAbilityHelper_OpenRawFile_0100 * @tc.name: OpenRawFile - * @tc.desc: Test whether the return value of OpenRawFile is 5678 when the parameter passed by Creator is true. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenRawFile_0100, Function | MediumTest | Level1) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_OpenRawFile_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_0100 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::string mode("modetest"); - int fd = helper->OpenRawFile(uri2, mode); - - EXPECT_EQ(fd, 5678); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + // Test to AbilityThread interface + std::string mode("modetest"); + auto returnOpenRawFile = [&](const Uri &uri, const std::string &mode) { + int fd = 1234; + return fd; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), OpenRawFile(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnOpenRawFile)); + + dataAbilityHelper->OpenRawFile(*uri, mode); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_0100 end"; } @@ -529,24 +518,29 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenRawFile_0100, Functi /** * @tc.number: AaFwk_DataAbilityHelper_OpenRawFile_0200 * @tc.name: OpenRawFile - * @tc.desc: Test whether the return value of OpenRawFile is -1 when the parameter passed by Creator is false. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenRawFile_0200, Function | MediumTest | Level3) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_OpenRawFile_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_0200 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, false); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest"); - std::string mode("modetest"); - int fd = helper->OpenRawFile(uri2, mode); - - EXPECT_EQ(fd, -1); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + // Test to AbilityThread interface + std::string mode("modetest"); + auto returnOpenRawFile = [&](const Uri &uri, const std::string &mode) { + int fd = 1234; + return fd; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), OpenRawFile(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnOpenRawFile)); + + dataAbilityHelper->OpenRawFile(*uri, mode); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_0200 end"; } @@ -554,24 +548,26 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenRawFile_0200, Functi /** * @tc.number: AaFwk_DataAbilityHelper_Reload_0100 * @tc.name: Reload - * @tc.desc: Test whether the return value of Reload is true when the parameter passed by Creator is true. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Reload_0100, Function | MediumTest | Level1) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Reload_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_0100 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - PacMap extras; - bool ret = helper->Reload(uri2, extras); - - EXPECT_EQ(ret, true); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + // Test to AbilityThread interface + PacMap extras; + auto returnReload = [&](const Uri &uri, const PacMap &extras) { return true; }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), Reload(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnReload)); + + dataAbilityHelper->Reload(*uri, extras); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_0100 end"; } @@ -579,24 +575,26 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Reload_0100, Function | /** * @tc.number: AaFwk_DataAbilityHelper_Reload_0200 * @tc.name: Reload - * @tc.desc: Test whether the return value of Reload is false when the parameter passed by Creator is false. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Reload_0200, Function | MediumTest | Level3) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_Reload_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_0200 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, false); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest"); - PacMap extras; - bool ret = helper->Reload(uri2, extras); - - EXPECT_EQ(ret, false); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + // Test to AbilityThread interface + PacMap extras; + auto returnReload = [&](const Uri &uri, const PacMap &extras) { return true; }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), Reload(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnReload)); + + dataAbilityHelper->Reload(*uri, extras); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_0200 end"; } @@ -604,24 +602,26 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Reload_0200, Function | /** * @tc.number: AaFwk_DataAbilityHelper_BatchInsert_0100 * @tc.name: BatchInsert - * @tc.desc: Test whether the return value of BatchInsert is 789 when the parameter passed by Creator is true. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_BatchInsert_0100, Function | MediumTest | Level1) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_BatchInsert_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_0100 start"; - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::vector values; - int ret = helper->BatchInsert(uri2, values); - - EXPECT_EQ(ret, 789); - } + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + // Test to AbilityThread interface + std::vector values; + auto returnBatchInsert = [&](const Uri &uri, const std::vector &values) { return true; }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), BatchInsert(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnBatchInsert)); + + dataAbilityHelper->BatchInsert(*uri, values); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_0100 end"; } @@ -629,26 +629,145 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_BatchInsert_0100, Functi /** * @tc.number: AaFwk_DataAbilityHelper_BatchInsert_0200 * @tc.name: BatchInsert - * @tc.desc: Test whether the return value of BatchInsert is -1 when the parameter passed by Creator is false. + * @tc.desc: Simulate successful test cases */ -HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_BatchInsert_0200, Function | MediumTest | Level3) +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_BatchInsert_0200, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_0200 start"; + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + // Test to AbilityThread interface + std::vector values; + auto returnBatchInsert = [&](const Uri &uri, const std::vector &values) { return true; }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), BatchInsert(testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnBatchInsert)); + + dataAbilityHelper->BatchInsert(*uri, values); - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, false); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_0200 end"; +} - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest"); - std::vector values; - int ret = helper->BatchInsert(uri2, values); +/** + * @tc.number: AaFwk_DataAbilityHelper_NormalizeUri_0100 + * @tc.name: NormalizeUri + * @tc.desc: Simulate successful test cases + */ +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_NormalizeUri_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_NormalizeUri_0100 start"; + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + // Test to AbilityThread interface + auto returnNormalizeUri = [&](const Uri &uri) { + Uri uriValue("dataability://device_id/com.domainname.dataability."); + return uriValue; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), NormalizeUri(testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnNormalizeUri)); + + dataAbilityHelper->NormalizeUri(*uri); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_NormalizeUri_0100 end"; +} - EXPECT_EQ(ret, -1); - } +/** + * @tc.number: AaFwk_DataAbilityHelper_NormalizeUri_0200 + * @tc.name: NormalizeUri + * @tc.desc: Simulate successful test cases + */ +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_NormalizeUri_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_NormalizeUri_0200 start"; + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + // Test to AbilityThread interface + auto returnNormalizeUri = [&](const Uri &uri) { + Uri uriValue("dataability://device_id/com.domainname.dataability."); + return uriValue; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), NormalizeUri(testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnNormalizeUri)); + + dataAbilityHelper->NormalizeUri(*uri); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_NormalizeUri_0200 end"; +} - GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_0200 end"; +/** + * @tc.number: AaFwk_DataAbilityHelper_DenormalizeUri_0100 + * @tc.name: DenormalizeUri + * @tc.desc: Simulate successful test cases + */ +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_DenormalizeUri_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_DenormalizeUri_0100 start"; + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + // Test to AbilityThread interface + auto returnDenormalizeUri = [&](const Uri &uri) { + Uri uriValue("dataability://device_id/com.domainname.dataability."); + return uriValue; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), DenormalizeUri(testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnDenormalizeUri)); + + dataAbilityHelper->DenormalizeUri(*uri); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_DenormalizeUri_0100 end"; } + +/** + * @tc.number: AaFwk_DataAbilityHelper_DenormalizeUri_0200 + * @tc.name: DenormalizeUri + * @tc.desc: Simulate successful test cases + */ +HWTEST_F(DataAbilityHelperForObserverTest, AaFwk_DataAbilityHelper_DenormalizeUri_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_DenormalizeUri_0200 start"; + + std::shared_ptr mockTools = MockAbilitySchedulerTools::GetInstance(); + mockTools->SetMockStatus(true); + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + // Test to AbilityThread interface + auto returnDenormalizeUri = [&](const Uri &uri) { + Uri uriValue("dataability://device_id/com.domainname.dataability."); + return uriValue; + }; + EXPECT_CALL(*mockTools->GetMockAbilityScheduler(), DenormalizeUri(testing::_)) + .Times(1) + .WillOnce(testing::Invoke(returnDenormalizeUri)); + + dataAbilityHelper->DenormalizeUri(*uri); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_DenormalizeUri_0200 end"; +} + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/test/unittest/data_uri_utils_test.cpp b/frameworks/kits/ability/native/test/unittest/data_uri_utils_test.cpp index f8dcf912f3d..42ef7219443 100644 --- a/frameworks/kits/ability/native/test/unittest/data_uri_utils_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/data_uri_utils_test.cpp @@ -61,7 +61,7 @@ HWTEST_F(DataUriUtilsTest, AaFwk_DataUriUtils_AttachId_Get001, Function | Medium Uri uri("scheme://authority/path1/path2/path3?id = 1&name = mingming&old#fragment"); Uri uriRet1 = DataUriUtils::AttachId(uri, 1000); - long ret1 = DataUriUtils::GetId(uriRet1); + long long ret1 = DataUriUtils::GetId(uriRet1); EXPECT_EQ(ret1, 1000); GTEST_LOG_(INFO) << "AaFwk_DataUriUtils_001 end"; @@ -70,7 +70,7 @@ HWTEST_F(DataUriUtilsTest, AaFwk_DataUriUtils_AttachId_Get001, Function | Medium /** * @tc.number: AaFwk_DataUriUtils_AttachId_GetId_0100 * @tc.name: AttachId/DeleteId/IsAttachedId - * @tc.desc: Test whether the return values of attachid, deleteid and isattachedidare correct. + * @tc.desc: Test whether the return values of attachid, deleteid and isattachedidare correct. */ HWTEST_F(DataUriUtilsTest, AaFwk_DataUriUtils_DeleteId_IsAttachedId001, Function | MediumTest | Level1) { @@ -87,6 +87,44 @@ HWTEST_F(DataUriUtilsTest, AaFwk_DataUriUtils_DeleteId_IsAttachedId001, Function GTEST_LOG_(INFO) << "AaFwk_DataUriUtils_DeleteId_IsAttachedId001 end"; } +/** + * @tc.number: AaFwk_DataUriUtils_DeleteId_IsAttachedId002 + * @tc.name: AttachId/DeleteId/IsAttachedId + * @tc.desc: Test whether the return values of attachid, deleteid and isattachedidare correct. + */ +HWTEST_F(DataUriUtilsTest, AaFwk_DataUriUtils_DeleteId_IsAttachedId002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataUriUtils_DeleteId_IsAttachedId002 start"; + + Uri uri("scheme://authority/path1/path2/path3?id = 1&name = mingming&old#fragment"); + Uri uriRet1 = DataUriUtils::AttachId(uri, -1000); + Uri uriRet2 = DataUriUtils::DeleteId(uriRet1); + bool ret2 = DataUriUtils::IsAttachedId(uriRet2); + EXPECT_EQ(ret2, false); + + GTEST_LOG_(INFO) << "AaFwk_DataUriUtils_DeleteId_IsAttachedId002 end"; +} +/** + * @tc.number: AaFwk_DataUriUtils_DeleteId_IsAttachedId003 + * @tc.name: AttachId/DeleteId/IsAttachedId + * @tc.desc: Test whether the return values of attachid, deleteid and isattachedidare correct. + */ +HWTEST_F(DataUriUtilsTest, AaFwk_DataUriUtils_DeleteId_IsAttachedId003, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataUriUtils_DeleteId_IsAttachedId003 start"; + + Uri uri("scheme://authority/path1/path2/path3?id = 1&name = mingming&old#fragment"); + Uri uriRet1 = DataUriUtils::AttachId(uri, 123456789011); + + long long id = DataUriUtils::GetId(uriRet1); + EXPECT_EQ(id, 123456789011); + Uri uriRet2 = DataUriUtils::DeleteId(uriRet1); + + bool ret2 = DataUriUtils::IsAttachedId(uriRet2); + EXPECT_EQ(ret2, false); + + GTEST_LOG_(INFO) << "AaFwk_DataUriUtils_DeleteId_IsAttachedId003 end"; +} /** * @tc.number: AaFwk_DataUriUtils_AttachIdUpdateId_0100 * @tc.name: AttachId/UpdateId/GetId diff --git a/frameworks/kits/ability/native/test/unittest/form_ability_test.cpp b/frameworks/kits/ability/native/test/unittest/form_ability_test.cpp new file mode 100755 index 00000000000..5e2296e088d --- /dev/null +++ b/frameworks/kits/ability/native/test/unittest/form_ability_test.cpp @@ -0,0 +1,1260 @@ +/* + * 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 + +#define private public +#include "ability.h" +#undef private +#include "ability_info.h" +#include "ability_handler.h" +#include "ability_local_record.h" +#include "ability_start_setting.h" +#include "context_deal.h" +#include "form_mgr.h" +#include "mock_form_mgr_service.h" +#include "mock_page_ability.h" +// #include "form_info.h" +#include "mock_bundle_manager_form.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using OHOS::Parcel; + +class FormAbilityTest : public testing::Test { +public: + FormAbilityTest() : ability_(nullptr) + {} + ~FormAbilityTest() + {} + std::shared_ptr ability_; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + +protected: + sptr mockBundleMgr_; +}; + +void FormAbilityTest::SetUpTestCase(void) +{} + +void FormAbilityTest::TearDownTestCase(void) +{} + +void FormAbilityTest::SetUp(void) +{ + ability_ = std::make_shared(); + FormMgr::GetInstance().SetFormMgrService(sptr(new (std::nothrow) MockFormMgrService())); + FormMgr::SetRecoverStatus(Constants::NOT_IN_RECOVERY); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + ability_->SetBundleManager(mockBundleMgr_); +} + +void FormAbilityTest::TearDown(void) +{} + +/** + * @tc.number: AaFwk_Ability_AcquireForm_0100 + * @tc.name: AcquireForm + * @tc.desc: Test whether acquireForm is called normally when want is nothing. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_AcquireForm_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_AcquireForm_0100 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + Want want; + std::shared_ptr callback; + + EXPECT_EQ(false, ability_->AcquireForm(0, want, callback)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_AcquireForm_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_AcquireForm_0200 + * @tc.name: AcquireForm + * @tc.desc: Test whether acquireForm is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_AcquireForm_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_AcquireForm_0200 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::string formName = "Form0200"; + std::string moduleName = "ModuleName0200"; + std::string deviceId = "DeviceId0200"; + std::string bundleName = "Bundle0200"; + std::string abilityName = "Ability0200"; + bool tempFormFlg = false; + Want want; + want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName) + .SetElementName(deviceId, bundleName, abilityName) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg); + std::shared_ptr callback; + + EXPECT_EQ(true, ability_->AcquireForm(0, want, callback)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_AcquireForm_0200 end"; +} + +/** + * @tc.number: AaFwk_Ability_AcquireForm_0300 + * @tc.name: AcquireForm + * @tc.desc: Test whether acquireForm is called normally when the same id is requested twice in succession. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_AcquireForm_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_AcquireForm_0300 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::string formName = "Form0300"; + std::string moduleName = "ModuleName0300"; + std::string deviceId = "DeviceId0300"; + std::string bundleName = "Bundle0300"; + std::string abilityName = "Ability0300"; + bool tempFormFlg = false; + Want want; + want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName) + .SetElementName(deviceId, bundleName, abilityName) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg); + std::shared_ptr callback; + + // first request + ability_->AcquireForm(300, want, callback); + // second request by same want + EXPECT_EQ(false, ability_->AcquireForm(300, want, callback)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_AcquireForm_0300 end"; +} + +/** + * @tc.number: AaFwk_Ability_AcquireForm_0400 + * @tc.name: AcquireForm + * @tc.desc: Test whether acquireForm is called normally when form id is negative in want + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_AcquireForm_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_AcquireForm_0400 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::string formName = "Form0400"; + std::string moduleName = "ModuleName0400"; + std::string deviceId = "DeviceId0400"; + std::string bundleName = "Bundle0400"; + std::string abilityName = "Ability0400"; + bool tempFormFlg = false; + Want want; + want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName) + .SetElementName(deviceId, bundleName, abilityName) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg); + std::shared_ptr callback; + + EXPECT_EQ(false, ability_->AcquireForm(-150, want, callback)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_AcquireForm_0400 end"; +} + +/** + * @tc.number: AaFwk_Ability_AcquireForm_0500 + * @tc.name: AcquireForm + * @tc.desc: Test whether acquireForm is called normally when select form id when acquire temporary form + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_AcquireForm_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_AcquireForm_0500 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::string formName = "Form0500"; + std::string moduleName = "ModuleName0500"; + std::string deviceId = "DeviceId0500"; + std::string bundleName = "Bundle0500"; + std::string abilityName = "Ability0500"; + bool tempFormFlg = true; + Want want; + want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName) + .SetElementName(deviceId, bundleName, abilityName) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg); + std::shared_ptr callback; + + EXPECT_EQ(false, ability_->AcquireForm(60, want, callback)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_AcquireForm_0500 end"; +} + +/** + * @tc.number: AaFwk_Ability_AcquireForm_0600 + * @tc.name: AcquireForm + * @tc.desc: Test whether acquireForm is called normally when dimension is zero or negative in want + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_AcquireForm_0600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_AcquireForm_0600 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::string formName = "Form0600"; + std::string moduleName = "ModuleName0600"; + std::string deviceId = "DeviceId0600"; + std::string bundleName = "Bundle0600"; + std::string abilityName = "Ability0600"; + bool tempFormFlg = false; + Want want; + want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName) + .SetElementName(deviceId, bundleName, abilityName) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg) + .SetParam(Constants::PARAM_FORM_DIMENSION_KEY, -1); + std::shared_ptr callback; + + EXPECT_EQ(false, ability_->AcquireForm(0, want, callback)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_AcquireForm_0600 end"; +} + +/** + * @tc.number: AaFwk_Ability_UpdateForm_0100 + * @tc.name: UpdateForm + * @tc.desc: Test whether updateForm is called normally when jsonFormProviderData is empty. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_UpdateForm_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_UpdateForm_0100 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + int64_t formId = 100; + FormProviderData formProviderData; + + EXPECT_EQ(false, ability_->UpdateForm(formId, formProviderData)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_UpdateForm_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_UpdateForm_0200 + * @tc.name: UpdateForm + * @tc.desc: Test whether updateForm is called normally when recoverStatus is recovering. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_UpdateForm_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_UpdateForm_0200 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + int64_t formId = 200L; + FormProviderData formProviderData = FormProviderData(std::string("{\"city\": \"beijing200\"}")); + FormMgr::SetRecoverStatus(Constants::IN_RECOVERING); + + EXPECT_EQ(false, ability_->UpdateForm(formId, formProviderData)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_UpdateForm_0200 end"; +} + +/** + * @tc.number: AaFwk_Ability_UpdateForm_0300 + * @tc.name: UpdateForm + * @tc.desc: Test whether updateForm is called normally when fms is error. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_UpdateForm_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_UpdateForm_0300 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + int64_t formId = 300L; + FormProviderData formProviderData = FormProviderData(std::string("{\"city\": \"beijing300\"}")); + FormMgr::SetRecoverStatus(Constants::NOT_IN_RECOVERY); + + EXPECT_EQ(false, ability_->UpdateForm(formId, formProviderData)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_UpdateForm_0300 end"; +} + +/** + * @tc.number: AaFwk_Ability_UpdateForm_0400 + * @tc.name: UpdateForm + * @tc.desc: Test whether updateForm is called normally when fms is ok. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_UpdateForm_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_UpdateForm_0400 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + int64_t formId = 400L; + FormProviderData formProviderData = FormProviderData(std::string("{\"city\": \"beijing400\"}")); + + EXPECT_EQ(true, ability_->UpdateForm(formId, formProviderData)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_UpdateForm_0400 end"; +} +/** + * @tc.number: AaFwk_Ability_DeleteForm_0100 + * @tc.name: DeleteForm + * @tc.desc: Test whether DeleteForm is called normally + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_DeleteForm_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_DeleteForm_0100 start"; + + std::string formName1 = "Form0101"; + std::string moduleName1 = "ModuleName0101"; + std::string deviceId1 = "DeviceId0101"; + std::string bundleName1 = "Bundle0101"; + std::string abilityName1 = "Ability0101"; + bool tempFormFlg1 = false; + Want want1; + want1.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 120L) + .SetParam(Constants::PARAM_FORM_NAME_KEY, formName1) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName1) + .SetElementName(deviceId1, bundleName1, abilityName1) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg1); + std::shared_ptr callback1; + + std::string formName2 = "Form0102"; + std::string moduleName2 = "ModuleName0102"; + std::string deviceId2 = "DeviceId0102"; + std::string bundleName2 = "Bundle0102"; + std::string abilityName2 = "Ability0102"; + bool tempFormFlg2 = false; + Want want2; + want2.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 121L) + .SetParam(Constants::PARAM_FORM_NAME_KEY, formName2) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName2) + .SetElementName(deviceId2, bundleName2, abilityName2) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg2); + std::shared_ptr callback_2; + + ability_->appCallbacks_.insert(std::make_pair(120L, callback1)); + ability_->userReqParams_.insert(std::make_pair(120L, want1)); + ability_->appCallbacks_.insert(std::make_pair(121L, callback_2)); + ability_->userReqParams_.insert(std::make_pair(121L, want2)); + + int64_t formId = 120L; + ability_->DeleteForm(formId); + + + size_t cnt {1}; + EXPECT_EQ(cnt, ability_->appCallbacks_.size()); + + GTEST_LOG_(INFO) << "AaFwk_Ability_DeleteForm_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_DeleteForm_0200 + * @tc.name: DeleteForm + * @tc.desc: Test whether DeleteForm is called normally when form id is negative + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_DeleteForm_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_DeleteForm_0200 start"; + + int64_t formId = -26; + EXPECT_EQ(false, ability_->DeleteForm(formId)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_DeleteForm_0200 end"; +} + +/** + * @tc.number: AaFwk_Ability_DeleteForm_0300 + * @tc.name: DeleteForm + * @tc.desc: Test whether DeleteForm is called normally when form is in recover status + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_DeleteForm_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_DeleteForm_0300 start"; + + int64_t formId = 26; + FormMgr::SetRecoverStatus(Constants::IN_RECOVERING); + + EXPECT_EQ(false, ability_->DeleteForm(formId)); + FormMgr::SetRecoverStatus(Constants::NOT_IN_RECOVERY); + + GTEST_LOG_(INFO) << "AaFwk_Ability_DeleteForm_0300 end"; +} + +/** + * @tc.number: AaFwk_Ability_DeleteForm_0400 + * @tc.name: DeleteForm + * @tc.desc: Test whether DeleteForm is called normally when form is temp form + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_DeleteForm_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_DeleteForm_0400 start"; + + std::string formName1 = "Form0401"; + std::string moduleName1 = "ModuleName0401"; + std::string deviceId1 = "DeviceId0401"; + std::string bundleName1 = "Bundle0401"; + std::string abilityName1 = "Ability0401"; + bool tempFormFlg1 = true; + Want want1; + want1.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 120L) + .SetParam(Constants::PARAM_FORM_NAME_KEY, formName1) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName1) + .SetElementName(deviceId1, bundleName1, abilityName1) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg1); + std::shared_ptr callback1; + + std::string formName2 = "Form0402"; + std::string moduleName2 = "ModuleName0402"; + std::string deviceId2 = "DeviceId0402"; + std::string bundleName2 = "Bundle0402"; + std::string abilityName2 = "Ability0402"; + bool tempFormFlg2 = true; + Want want2; + want2.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 121L) + .SetParam(Constants::PARAM_FORM_NAME_KEY, formName2) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName2) + .SetElementName(deviceId2, bundleName2, abilityName2) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg2); + std::shared_ptr callback2; + + ability_->appCallbacks_.insert(std::make_pair(120L, callback1)); + ability_->userReqParams_.insert(std::make_pair(120L, want1)); + ability_->appCallbacks_.insert(std::make_pair(121L, callback2)); + ability_->userReqParams_.insert(std::make_pair(121L, want2)); + ability_->lostedByReconnectTempForms_.push_back(120L); + ability_->lostedByReconnectTempForms_.push_back(121L); + + int64_t formId = 121L; + ability_->DeleteForm(formId); + + size_t cnt {1}; + EXPECT_EQ(cnt, ability_->lostedByReconnectTempForms_.size()); + + ability_->userReqParams_.clear(); + + GTEST_LOG_(INFO) << "AaFwk_Ability_DeleteForm_0400 end"; +} + +/** + * @tc.number: AaFwk_Ability_CastTempForm_0100 + * @tc.name: CastTempForm + * @tc.desc: Test whether CastTempForm is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_CastTempForm_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_CastTempForm_0100 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + int64_t formId = 170L; + + EXPECT_EQ(true, ability_->CastTempForm(formId)); + EXPECT_EQ(false, ability_->userReqParams_[formId].GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, true)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_CastTempForm_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_CastTempForm_0200 + * @tc.name: CastTempForm + * @tc.desc: Test whether CastTempForm is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_CastTempForm_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_CastTempForm_0200 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + int64_t formId = 175L; + + EXPECT_EQ(false, ability_->CastTempForm(formId)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_CastTempForm_0200 end"; +} + +/** + * @tc.number: AaFwk_Ability_CastTempForm_0300 + * @tc.name: CastTempForm + * @tc.desc: Test whether CastTempForm is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_CastTempForm_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_CastTempForm_0300 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + int64_t formId = -175L; + + EXPECT_EQ(false, ability_->CastTempForm(formId)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_CastTempForm_0300 end"; +} + +/** + * @tc.number: AaFwk_Ability_EnableUpdateForm_0100 + * @tc.name: EnableUpdateForm + * @tc.desc: Test whether enableUpdateForm is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_EnableUpdateForm_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_EnableUpdateForm_0100 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + std::vector formIds; + EXPECT_EQ(false, ability_->EnableUpdateForm(formIds)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_EnableUpdateForm_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_EnableUpdateForm_0200 + * @tc.name: EnableUpdateForm + * @tc.desc: Test whether enableUpdateForm is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_EnableUpdateForm_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_EnableUpdateForm_0200 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::vector formIds; + formIds.push_back(200); + EXPECT_EQ(true, ability_->EnableUpdateForm(formIds)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_EnableUpdateForm_0200 end"; +} + +/** + * @tc.number: AaFwk_Ability_DisableUpdateForm_0100 + * @tc.name: DisableUpdateForm + * @tc.desc: Test whether disableUpdateForm is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_DisableUpdateForm_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_DisableUpdateForm_0100 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + std::vector formIds; + EXPECT_EQ(false, ability_->DisableUpdateForm(formIds)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_DisableUpdateForm_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_DisableUpdateForm_0200 + * @tc.name: DisableUpdateForm + * @tc.desc: Test whether disableUpdateForm is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_DisableUpdateForm_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_DisableUpdateForm_0200 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + std::vector formIds; + formIds.push_back(200); + EXPECT_EQ(true, ability_->DisableUpdateForm(formIds)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_DisableUpdateForm_0200 end"; +} + +/** + * @tc.number: AaFwk_Ability_DisableUpdateForm_0300 + * @tc.name: EnableUpdateForm + * @tc.desc: Test whether enableUpdateForm is called normally.(RecoverStatus is IN_RECOVERING) + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_DisableUpdateForm_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_DisableUpdateForm_0300 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::vector formIds; + formIds.push_back(300); + + // SetRecoverStatus IN_RECOVERING + volatile int recoverStatus = Constants::IN_RECOVERING; + FormMgr::GetInstance().SetRecoverStatus(recoverStatus); + + EXPECT_EQ(false, ability_->DisableUpdateForm(formIds)); + + // SetRecoverStatus NOT_IN_RECOVERY + recoverStatus = Constants::NOT_IN_RECOVERY; + FormMgr::GetInstance().SetRecoverStatus(recoverStatus); + + GTEST_LOG_(INFO) << "AaFwk_Ability_DisableUpdateForm_0300 end"; +} + +/** + * @tc.number: AaFwk_Ability_SetFormNextRefreshTime_0100 + * @tc.name: SetFormNextRefreshTime + * @tc.desc: Test whether SetFormNextRefreshTime is called normally.(next time litte than 5 mins) + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_SetFormNextRefreshTime_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_SetFormNextRefreshTime_0100 start"; + int64_t formId = 100; + int64_t nextTime = Constants::MIN_NEXT_TIME - 1; + EXPECT_EQ(false, ability_->SetFormNextRefreshTime(formId, nextTime)); + GTEST_LOG_(INFO) << "AaFwk_Ability_SetFormNextRefreshTime_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_SetFormNextRefreshTime_0200 + * @tc.name: SetFormNextRefreshTime + * @tc.desc: Test whether SetFormNextRefreshTime is called normally.(RecoverStatus is IN_RECOVERING) + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_SetFormNextRefreshTime_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_SetFormNextRefreshTime_0200 start"; + int64_t formId = 200; + int64_t nextTime = Constants::MIN_NEXT_TIME; + + // SetRecoverStatus IN_RECOVERING + volatile int recoverStatus = Constants::IN_RECOVERING; + FormMgr::GetInstance().SetRecoverStatus(recoverStatus); + + EXPECT_EQ(false, ability_->SetFormNextRefreshTime(formId, nextTime)); + GTEST_LOG_(INFO) << "AaFwk_Ability_SetFormNextRefreshTime_0200 end"; +} + +/** + * @tc.number: AaFwk_Ability_SetFormNextRefreshTime_0300 + * @tc.name: SetFormNextRefreshTime + * @tc.desc: Test whether SetFormNextRefreshTime is called normally.(SetNextRefreshTime reply false) + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_SetFormNextRefreshTime_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_SetFormNextRefreshTime_0300 start"; + int64_t invalidFormId = 0; + int64_t nextTime = Constants::MIN_NEXT_TIME; + + // SetRecoverStatus NOT_IN_RECOVERY + int recoverStatus = Constants::NOT_IN_RECOVERY; + FormMgr::GetInstance().SetRecoverStatus(recoverStatus); + + EXPECT_EQ(false, ability_->SetFormNextRefreshTime(invalidFormId, nextTime)); + GTEST_LOG_(INFO) << "AaFwk_Ability_SetFormNextRefreshTime_0300 end"; +} + +/** + * @tc.number: AaFwk_Ability_SetFormNextRefreshTime_0400 + * @tc.name: SetFormNextRefreshTime + * @tc.desc: Test whether SetFormNextRefreshTime is called normally.(SetNextRefreshTime reply true) + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_SetFormNextRefreshTime_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_SetFormNextRefreshTime_0400 start"; + int64_t formId = 400; + int64_t nextTime = Constants::MIN_NEXT_TIME; + + // SetRecoverStatus NOT_IN_RECOVERY + int recoverStatus = Constants::NOT_IN_RECOVERY; + FormMgr::GetInstance().SetRecoverStatus(recoverStatus); + + EXPECT_EQ(true, ability_->SetFormNextRefreshTime(formId, nextTime)); + GTEST_LOG_(INFO) << "AaFwk_Ability_SetFormNextRefreshTime_0400 end"; +} + +/** + * @tc.number: AaFwk_Ability_RequestForm_0100 + * @tc.name: RequestForm + * @tc.desc: Normal case: test whether RequestForm is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_RequestForm_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_RequestForm_0100 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + int64_t formId = 100L; + + EXPECT_EQ(true, ability_->RequestForm(formId)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_RequestForm_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_RequestForm_0200 + * @tc.name: RequestForm + * @tc.desc: Abnormal case: test whether return fasle when formId is 0. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_RequestForm_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_RequestForm_0200 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + int64_t formId = 0; + + EXPECT_EQ(false, ability_->RequestForm(formId)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_RequestForm_0200 end"; +} + +/** + * @tc.number: AaFwk_Ability_RequestForm_0300 + * @tc.name: RequestForm + * @tc.desc: Abnormal case: test whether return fasle when RecoverStatus is IN_RECOVERING. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_RequestForm_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_RequestForm_0300 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + FormMgr::SetRecoverStatus(Constants::IN_RECOVERING); + int64_t formId = 300L; + + EXPECT_EQ(false, ability_->RequestForm(formId)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_RequestForm_0300 end"; +} + +/** + * @tc.number: AaFwk_Ability_NotifyInvisibleForms_0100 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Normal case: test whether NotifyInvisibleForms is called normally.(formId is illegal) + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_NotifyInvisibleForms_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyInvisibleForms_0100 start"; + std::vector formIds; + ability_->NotifyInvisibleForms(formIds); + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyInvisibleForms_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_NotifyInvisibleForms_0200 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Normal case: test whether NotifyInvisibleForms is called normally.(RecoverStatus is IN_RECOVERING) + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_NotifyInvisibleForms_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyInvisibleForms_0200 start"; + std::vector formIds; + formIds.push_back(1); + FormMgr::SetRecoverStatus(Constants::IN_RECOVERING); + ability_->NotifyInvisibleForms(formIds); + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyInvisibleForms_0200 end"; +} + +/** + * @tc.number: AaFwk_Ability_NotifyInvisibleForms_0300 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Normal case: test whether NotifyInvisibleForms is called normally.(FormMgr reply 0) + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_NotifyInvisibleForms_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyInvisibleForms_0300 start"; + std::vector formIds; + formIds.push_back(1); + FormMgr::SetRecoverStatus(Constants::NOT_IN_RECOVERY); + ability_->NotifyInvisibleForms(formIds); + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyInvisibleForms_0300 end"; +} + +/** + * @tc.number: AaFwk_Ability_NotifyInvisibleForms_0400 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Normal case: test whether NotifyInvisibleForms is called normally.(FormMgr reply 1) + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_NotifyInvisibleForms_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyInvisibleForms_0400 start"; + std::vector formIds; + formIds.push_back(1); + formIds.push_back(2); + FormMgr::SetRecoverStatus(Constants::NOT_IN_RECOVERY); + ability_->NotifyInvisibleForms(formIds); + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyInvisibleForms_0400 end"; +} + +/** + * @tc.number: AaFwk_Ability_NotifyVisibleForms_0100 + * @tc.name: NotifyVisibleForms + * @tc.desc: Normal case: test whether NotifyVisibleForms is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_NotifyVisibleForms_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyVisibleForms_0100 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::vector formIds; + formIds.push_back(100); + formIds.push_back(101); + ability_->NotifyVisibleForms(formIds); + + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyVisibleForms_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_NotifyVisibleForms_0200 + * @tc.name: NotifyVisibleForms + * @tc.desc: Abnormal case: test whether NotifyVisibleForms is called with + * specified error log when the size of formIds is empty. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_NotifyVisibleForms_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyVisibleForms_0200 start"; + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::vector formIds; + ability_->NotifyVisibleForms(formIds); + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyVisibleForms_0200 end"; +} + +/** + * @tc.number: AaFwk_Ability_NotifyVisibleForms_0300 + * @tc.name: NotifyVisibleForms + * @tc.desc: Normal case: test whether NotifyVisibleForms is called with + * specified error log when the size of formIds is larger than 32. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_NotifyVisibleForms_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyVisibleForms_0300 start"; + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::vector formIds; + for (int64_t formId = 300L; formId < 333L; formId++) { + formIds.push_back(formId); + } + ability_->NotifyVisibleForms(formIds); + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyVisibleForms_0300 end"; +} + +/** + * @tc.number: AaFwk_Ability_NotifyVisibleForms_0400 + * @tc.name: NotifyVisibleForms + * @tc.desc: Normal case: test whether NotifyVisibleForms is called with + * specified error log when the recover status is in recovering. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_NotifyVisibleForms_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyVisibleForms_0400 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::vector formIds; + formIds.push_back(100); + formIds.push_back(101); + FormMgr::SetRecoverStatus(Constants::IN_RECOVERING); + ability_->NotifyVisibleForms(formIds); + + GTEST_LOG_(INFO) << "AaFwk_Ability_NotifyVisibleForms_0400 end"; +} + +/** + * @tc.number: AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0100 + * @tc.name: OnDeathReceived + * @tc.desc: Normal case: test whether OnDeathReceived is called normally with a form. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0100 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::string formName = "formName0100"; + std::string moduleName = "moduleName0100"; + std::string deviceId = "deviceId0100"; + std::string bundleName = "bundleName0100"; + std::string abilityName = "abilityName0100"; + bool tempFormFlg = false; + Want want; + want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName) + .SetElementName(deviceId, bundleName, abilityName) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg); + std::shared_ptr callback; + + FormMgr::GetInstance().RegisterDeathCallback(ability_); + + int64_t formId = 100L; + ability_->userReqParams_.emplace(formId, want); + ability_->appCallbacks_.emplace(formId, callback); + + EXPECT_EQ(true, ability_->lostedByReconnectTempForms_.empty()); + ability_->OnDeathReceived(); + EXPECT_EQ(true, ability_->lostedByReconnectTempForms_.empty()); + GTEST_LOG_(INFO) << "AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0200 + * @tc.name: OnDeathReceived + * @tc.desc: Normal case: test whether OnDeathReceived is called normally with a form and a temp form. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0200 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::string formName1 = "formName0200"; + std::string moduleName1 = "moduleName0200"; + std::string deviceId1 = "deviceId0200"; + std::string bundleName1 = "bundleName0200"; + std::string abilityName1 = "abilityName0200"; + bool tempFormFlg1 = false; + Want want1; + want1.SetParam(Constants::PARAM_FORM_NAME_KEY, formName1) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName1) + .SetElementName(deviceId1, bundleName1, abilityName1) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg1); + std::shared_ptr callback1; + + std::string formName2 = "formName0201"; + std::string moduleName2 = "moduleName0201"; + std::string deviceId2 = "deviceId0201"; + std::string bundleName2 = "bundleName0201"; + std::string abilityName2 = "abilityName0201"; + bool tempFormFlg2 = true; + Want want2; + want2.SetParam(Constants::PARAM_FORM_NAME_KEY, formName2) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName2) + .SetElementName(deviceId2, bundleName2, abilityName2) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg2); + std::shared_ptr callback2; + + FormMgr::GetInstance().RegisterDeathCallback(ability_); + + int64_t formId1 = 200L; + int64_t formId2 = 201L; + ability_->userReqParams_.emplace(formId1, want1); + ability_->userReqParams_.emplace(formId2, want2); + ability_->appCallbacks_.emplace(formId1, callback1); + ability_->appCallbacks_.emplace(formId2, callback2); + + EXPECT_EQ(true, ability_->lostedByReconnectTempForms_.empty()); + ability_->OnDeathReceived(); + EXPECT_EQ(true, ability_->lostedByReconnectTempForms_.size() == 1); + EXPECT_EQ(formId2, ability_->lostedByReconnectTempForms_[0]); + GTEST_LOG_(INFO) << "AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0200 end"; +} + +/** + * @tc.number: AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0300 + * @tc.name: OnDeathReceived + * @tc.desc: Normal case: test whether OnDeathReceived is called normally with two temp form. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0300 start"; + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + sptr abilityThread = sptr(new (std::nothrow) AbilityThread()); + std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); + + ability_->Init(abilityInfo, nullptr, handler, nullptr); + + std::string formName1 = "formName0300"; + std::string moduleName1 = "moduleName0300"; + std::string deviceId1 = "deviceId0300"; + std::string bundleName1 = "bundleName0300"; + std::string abilityName1 = "abilityName0300"; + bool tempFormFlg1 = true; + Want want1; + want1.SetParam(Constants::PARAM_FORM_NAME_KEY, formName1) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName1) + .SetElementName(deviceId1, bundleName1, abilityName1) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg1); + std::shared_ptr callback1; + + std::string formName2 = "formName0301"; + std::string moduleName2 = "moduleName0301"; + std::string deviceId2 = "deviceId0301"; + std::string bundleName2 = "bundleName0301"; + std::string abilityName2 = "abilityName0301"; + bool tempFormFlg2 = true; + Want want2; + want2.SetParam(Constants::PARAM_FORM_NAME_KEY, formName2) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, moduleName2) + .SetElementName(deviceId2, bundleName2, abilityName2) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, tempFormFlg2); + std::shared_ptr callback2; + + FormMgr::GetInstance().RegisterDeathCallback(ability_); + + int64_t formId1 = 200L; + int64_t formId2 = 201L; + ability_->userReqParams_.emplace(formId1, want1); + ability_->userReqParams_.emplace(formId2, want2); + ability_->appCallbacks_.emplace(formId1, callback1); + ability_->appCallbacks_.emplace(formId2, callback2); + + EXPECT_EQ(true, ability_->lostedByReconnectTempForms_.empty()); + ability_->OnDeathReceived(); + EXPECT_EQ(true, ability_->lostedByReconnectTempForms_.size() == 2); + EXPECT_EQ(formId1, ability_->lostedByReconnectTempForms_[0]); + EXPECT_EQ(formId2, ability_->lostedByReconnectTempForms_[1]); + + GTEST_LOG_(INFO) << "AaFwk_Ability_FmsDeathCallback_OnDeathReceived_0300 end"; +} + +/** + * @tc.number: AaFwk_Ability_CheckFMSReady_0100 + * @tc.name: CheckFMSReady + * @tc.desc: Test whether CheckFMSReady is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_CheckFMSReady_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_CheckFMSReady_0100 start"; + + std::string bundleName = "Bundle"; + std::vector formInfos; + formInfos.clear(); + EXPECT_EQ(true, ability_->CheckFMSReady()); + + GTEST_LOG_(INFO) << "AaFwk_Ability_CheckFMSReady_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_GetAllFormsInfo_0100 + * @tc.name: GetAllFormsInfo + * @tc.desc: Test whether GetAllFormsInfo is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_GetAllFormsInfo_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_GetAllFormsInfo_0100 start"; + + std::string bundleName = "Bundle"; + std::vector formInfos; + formInfos.clear(); + EXPECT_EQ(true, ability_->GetAllFormsInfo(formInfos)); + size_t dataSize {1}; + EXPECT_EQ(dataSize, formInfos.size()); + + GTEST_LOG_(INFO) << "AaFwk_Ability_GetAllFormsInfo_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_GetFormsInfoByApp_0100 + * @tc.name: GetFormsInfoByApp + * @tc.desc: Test whether GetFormsInfoByApp is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_GetFormsInfoByApp_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_GetFormsInfoByApp_0100 start"; + + std::string bundleName = "Bundle"; + std::vector formInfos; + formInfos.clear(); + EXPECT_EQ(true, ability_->GetFormsInfoByApp(bundleName, formInfos)); + size_t dataSize {1}; + EXPECT_EQ(dataSize, formInfos.size()); + bundleName = ""; + EXPECT_EQ(false, ability_->GetFormsInfoByApp(bundleName, formInfos)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_GetFormsInfoByApp_0100 end"; +} + +/** + * @tc.number: AaFwk_Ability_GetFormsInfoByModule_0100 + * @tc.name: GetFormsInfoByModule + * @tc.desc: Test whether GetFormsInfoByModule is called normally. + */ +HWTEST_F(FormAbilityTest, AaFwk_Ability_GetFormsInfoByModule_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_Ability_GetFormsInfoByModule_0100 start"; + + std::string bundleName = "Bundle"; + std::string moduleName = "Module"; + std::vector formInfos; + formInfos.clear(); + EXPECT_EQ(true, ability_->GetFormsInfoByModule(bundleName, moduleName, formInfos)); + size_t dataSize {1}; + EXPECT_EQ(dataSize, formInfos.size()); + bundleName = ""; + EXPECT_EQ(false, ability_->GetFormsInfoByModule(bundleName, moduleName, formInfos)); + + GTEST_LOG_(INFO) << "AaFwk_Ability_GetFormsInfoByModule_0100 end"; +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/test/unittest/form_host_client_test.cpp b/frameworks/kits/ability/native/test/unittest/form_host_client_test.cpp new file mode 100644 index 00000000000..3900a34b744 --- /dev/null +++ b/frameworks/kits/ability/native/test/unittest/form_host_client_test.cpp @@ -0,0 +1,157 @@ +/* + * 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 "ability.h" +#include "ability_handler.h" +#include "ability_info.h" +#include "ability_local_record.h" +#include "ability_start_setting.h" +#include "context_deal.h" +#include "form_host_client.h" +#include "mock_page_ability.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using OHOS::Parcel; + +class FormHostClientTest : public testing::Test { +public: + FormHostClientTest() + {} + ~FormHostClientTest() + {} + sptr instance_; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void FormHostClientTest::SetUpTestCase(void) +{} + +void FormHostClientTest::TearDownTestCase(void) +{} + +void FormHostClientTest::SetUp(void) +{ + instance_ = FormHostClient::GetInstance(); +} + +void FormHostClientTest::TearDown(void) +{ + instance_ = nullptr; +} + +/** + * @tc.number: AaFwk_FormHostClient_AddForm_0100 + * @tc.name: AddForm + * @tc.desc: Verify that the return value of AddForm is correct. + */ +HWTEST_F(FormHostClientTest, AaFwk_formHostClientAddForm_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormHostClient_AddForm_0100 start"; + std::shared_ptr ability = std::make_shared(); + int64_t formId = 0; + instance_->AddForm(ability, formId); + formId = 1; + instance_->AddForm(ability, formId); + formId = 2; + instance_->AddForm(ability, formId); + + GTEST_LOG_(INFO) << "AaFwk_FormHostClient_AddForm_0100 end"; +} + +/** + * @tc.number: AaFwk_FormHostClient_RemoveForm_0100 + * @tc.name: RemoveForm + * @tc.desc: Verify that the return value of RemoveForm is correct. + */ +HWTEST_F(FormHostClientTest, AaFwk_FormHostClient_RemoveForm_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormHostClient_RemoveForm_0100 start"; + std::shared_ptr ability = std::make_shared(); + int64_t formId = 0; + instance_->RemoveForm(ability, formId); + instance_->AddForm(ability, formId); + instance_->RemoveForm(ability, formId); + + GTEST_LOG_(INFO) << "AaFwk_FormHostClient_RemoveForm_0100 end"; +} + +/** + * @tc.number: AaFwk_FormHostClient_ContainsForm_0100 + * @tc.name: ContainsForm + * @tc.desc: Verify that the return value of ContainsForm is correct. + */ +HWTEST_F(FormHostClientTest, AaFwk_FormHostClient_ContainsForm_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormHostClient_ContainsForm_0100 start"; + int64_t formId = 0; + EXPECT_EQ(false, instance_->ContainsForm(formId)); + std::shared_ptr ability = std::make_shared(); + formId = 1; + instance_->AddForm(ability, formId); + EXPECT_EQ(true, instance_->ContainsForm(formId)); + + GTEST_LOG_(INFO) << "AaFwk_FormHostClient_ContainsForm_0100 end"; +} + +/** + * @tc.number: AaFwk_FormHostClient_OnAcquired_0100 + * @tc.name: OnAcquired + * @tc.desc: Verify that the return value of OnAcquired is correct. + */ +HWTEST_F(FormHostClientTest, AaFwk_FormHostClient_OnAcquired_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormHostClient_OnAcquired_0100 start"; + FormJsInfo formInfo; + formInfo.formId = -1; + instance_->OnAcquired(formInfo); + int64_t formId = 1; + std::shared_ptr ability = std::make_shared(); + instance_->AddForm(ability, formId); + formInfo.formId = 1; + instance_->OnAcquired(formInfo); + + GTEST_LOG_(INFO) << "AaFwk_FormHostClient_OnAcquired_0100 end"; +} + +/** + * @tc.number: AaFwk_FormHostClient_OnUpdate_0100 + * @tc.name: OnUpdate + * @tc.desc: Verify that the return value of OnUpdate is correct. + */ +HWTEST_F(FormHostClientTest, AaFwk_FormHostClient_OnUpdate_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormHostClient_OnUpdate_0100 start"; + FormJsInfo formInfo; + formInfo.formId = -1; + instance_->OnUpdate(formInfo); + int64_t formId = 1; + std::shared_ptr ability = std::make_shared(); + instance_->AddForm(ability, formId); + formInfo.formId = 1; + instance_->OnUpdate(formInfo); + + GTEST_LOG_(INFO) << "AaFwk_FormHostClient_OnUpdate_0100 end"; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/test/unittest/form_provider_client_test.cpp b/frameworks/kits/ability/native/test/unittest/form_provider_client_test.cpp new file mode 100644 index 00000000000..d4203d0a9f5 --- /dev/null +++ b/frameworks/kits/ability/native/test/unittest/form_provider_client_test.cpp @@ -0,0 +1,512 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "appexecfwk_errors.h" +#include +#include "form_constants.h" +#include "form_provider_client.h" +#include "mock_form_supply_callback.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string FORM_MANAGER_SERVICE_BUNDLE_NAME = "com.form.fms.app"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; +const std::string FORM_SUPPLY_INFO = "com.form.supply.info.test"; + +class FormProviderClientTest : public testing::Test { +public: + FormProviderClientTest() + {} + ~FormProviderClientTest() + {} + sptr instance_; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void FormProviderClientTest::SetUpTestCase(void) +{} + +void FormProviderClientTest::TearDownTestCase(void) +{} + +void FormProviderClientTest::SetUp(void) +{ + instance_ = new FormProviderClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_MANAGER_SERVICE_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions( + FORM_MANAGER_SERVICE_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission( + FORM_MANAGER_SERVICE_BUNDLE_NAME, + PERMISSION_NAME_REQUIRE_FORM, + 0); +} + +void FormProviderClientTest::TearDown(void) +{ + instance_ = nullptr; +} + +/** + * @tc.number: AaFwk_FormProviderClient_AcquireProviderFormInfo_0100 + * @tc.name: AcquireProviderFormInfo + * @tc.desc: Verify that the return value of AddForm is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_AcquireProviderFormInfo_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_AcquireProviderFormInfo_0100 start"; + + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(ability); + + const sptr callerToken = MockFormSupplyCallback::GetInstance(); + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::ACQUIRE_TYPE, 100) + .SetParam(Constants::FORM_CONNECT_ID, 100L) + .SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 100L) + .SetParam(Constants::FORM_SUPPLY_INFO, FORM_SUPPLY_INFO); + int64_t formId = 1001L; + instance_->AcquireProviderFormInfo(formId, want, callerToken); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_AcquireProviderFormInfo_0100 end"; +} + +/** + * @tc.number: AaFwk_FormProviderClient_AcquireProviderFormInfo_0200 + * @tc.name: AcquireProviderFormInfo + * @tc.desc: Verify that the return value of AddForm is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_AcquireProviderFormInfo_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_AcquireProviderFormInfo_0200 start"; + + instance_->SetOwner(nullptr); + + const sptr callerToken = MockFormSupplyCallback::GetInstance(); + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::ACQUIRE_TYPE, 200) + .SetParam(Constants::FORM_CONNECT_ID, 200L) + .SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 200L) + .SetParam(Constants::FORM_SUPPLY_INFO, FORM_SUPPLY_INFO); + + int64_t formId = 1002L; + instance_->AcquireProviderFormInfo(formId, want, callerToken); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_AcquireProviderFormInfo_0200 end"; +} + +/** + * @tc.number: AaFwk_FormProviderClient_AcquireProviderFormInfo_0300 + * @tc.name: AcquireProviderFormInfo + * @tc.desc: Verify that the return value of AddForm is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_AcquireProviderFormInfo_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_AcquireProviderFormInfo_0300 start"; + + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(ability); + + const sptr callerToken = MockFormSupplyCallback::GetInstance(); + Want want; + want.SetParam(Constants::ACQUIRE_TYPE, 300) + .SetParam(Constants::FORM_CONNECT_ID, 300L) + .SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 300L) + .SetParam(Constants::FORM_SUPPLY_INFO, FORM_SUPPLY_INFO); + + int64_t formId = 1003L; + instance_->AcquireProviderFormInfo(formId, want, callerToken); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_AcquireProviderFormInfo_0300 end"; +} + +/** + * @tc.number: AaFwk_FormProviderClient_AcquireProviderFormInfo_0400 + * @tc.name: AcquireProviderFormInfo + * @tc.desc: Verify that the return value of AddForm is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_AcquireProviderFormInfo_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_AcquireProviderFormInfo_0400 start"; + + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(ability); + instance_->ClearOwner(ability); + + const sptr callerToken = MockFormSupplyCallback::GetInstance(); + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::ACQUIRE_TYPE, 400) + .SetParam(Constants::FORM_CONNECT_ID, 400L) + .SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 400L) + .SetParam(Constants::FORM_SUPPLY_INFO, FORM_SUPPLY_INFO); + + int64_t formId = 1004L; + instance_->AcquireProviderFormInfo(formId, want, callerToken); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_AcquireProviderFormInfo_0400 end"; +} + +/** + * @tc.number: AaFwk_FormProviderClient_AcquireProviderFormInfo_0500 + * @tc.name: AcquireProviderFormInfo + * @tc.desc: Verify that the return value of AddForm is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_AcquireProviderFormInfo_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_AcquireProviderFormInfo_0500 start"; + + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(ability); + + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::ACQUIRE_TYPE, 500) + .SetParam(Constants::FORM_CONNECT_ID, 500L) + .SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 500L) + .SetParam(Constants::FORM_SUPPLY_INFO, FORM_SUPPLY_INFO); + + const sptr callerToken = nullptr; + int64_t formId = 1005L; + EXPECT_EQ(ERR_APPEXECFWK_FORM_BIND_FORMSUPPLY_FAILED, instance_->AcquireProviderFormInfo(formId, want, callerToken)); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_AcquireProviderFormInfo_0500 end"; +} + +/** + * @tc.number: AaFwk_FormProviderClient_EventNotify_0100 + * @tc.name: EventNotify + * @tc.desc: Verify that the return value of EventNotify is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_EventNotify_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_EventNotify_0100 start"; + + // Ability + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(ability); + + // callerToken + const sptr callerToken = MockFormSupplyCallback::GetInstance(); + + // want + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::ACQUIRE_TYPE, 100) + .SetParam(Constants::FORM_CONNECT_ID, 100L) + .SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 100L) + .SetParam(Constants::FORM_SUPPLY_INFO, FORM_SUPPLY_INFO); + + // formEvents + int64_t formId = 100; + std::vector formEvents; + formEvents.push_back(formId); + + int32_t formVisibleType = Constants::FORM_INVISIBLE; + + EXPECT_EQ(ERR_OK, instance_->EventNotify(formEvents, formVisibleType, want, callerToken )); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_EventNotify_0100 end"; +} + +/** + * @tc.number: AaFwk_FormProviderClient_EventNotify_0200 + * @tc.name: EventNotify + * @tc.desc: Verify that the return value of EventNotify is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_EventNotify_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_EventNotify_0200 start"; + + // Ability is nullptr + instance_->SetOwner(nullptr); + + // callerToken + const sptr callerToken = MockFormSupplyCallback::GetInstance(); + + // want + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::ACQUIRE_TYPE, 100) + .SetParam(Constants::FORM_CONNECT_ID, 100L) + .SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 100L) + .SetParam(Constants::FORM_SUPPLY_INFO, FORM_SUPPLY_INFO); + + // formEvents + int64_t formId = 100; + std::vector formEvents; + formEvents.push_back(formId); + + int32_t formVisibleType = Constants::FORM_INVISIBLE; + + EXPECT_EQ(ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY, + instance_->EventNotify(formEvents, formVisibleType, want, callerToken )); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_EventNotify_0200 end"; +} + + +/** + * @tc.number: AaFwk_FormProviderClient_NotifyFormCastTempForm_0100 + * @tc.name: NotifyFormCastTempForm + * @tc.desc: Verify that the return value of AddForm is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_NotifyFormCastTempForm_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_NotifyFormCastTempForm_0100 start"; + + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(ability); + + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::ACQUIRE_TYPE, 101) + .SetParam(Constants::FORM_CONNECT_ID, 101L) + .SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 101L) + .SetParam(Constants::FORM_SUPPLY_INFO, FORM_SUPPLY_INFO); + + int64_t formId = 720L; + const sptr callerToken = MockFormSupplyCallback::GetInstance(); + + EXPECT_EQ(ERR_OK, instance_->NotifyFormCastTempForm(formId, want, callerToken)); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_NotifyFormCastTempForm_0100 end"; +} + +/** + * @tc.number: AaFwk_FormProviderClient_NotifyFormCastTempForm_0100 + * @tc.name: NotifyFormCastTempForm + * @tc.desc: Verify that the return value of AddForm is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_NotifyFormCastTempForm_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_NotifyFormCastTempForm_0200 start"; + + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(nullptr); + + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::ACQUIRE_TYPE, 102) + .SetParam(Constants::FORM_CONNECT_ID, 102L) + .SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 102L) + .SetParam(Constants::FORM_SUPPLY_INFO, FORM_SUPPLY_INFO); + + int64_t formId = 722L; + const sptr callerToken = MockFormSupplyCallback::GetInstance(); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY, instance_->NotifyFormCastTempForm(formId, want, callerToken)); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_NotifyFormCastTempForm_0200 end"; +} + + +/** + * @tc.number: AaFwk_FormProviderClient_NotifyFormCastTempForm_0100 + * @tc.name: NotifyFormCastTempForm + * @tc.desc: Verify that the return value of AddForm is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_NotifyFormCastTempForm_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_NotifyFormCastTempForm_0300 start"; + + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(ability); + + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::ACQUIRE_TYPE, 103) + .SetParam(Constants::FORM_CONNECT_ID, 103L) + .SetParam(Constants::PARAM_FORM_IDENTITY_KEY, 103L) + .SetParam(Constants::FORM_SUPPLY_INFO, FORM_SUPPLY_INFO); + + int64_t formId = 723L; + const sptr callerToken = nullptr; + + EXPECT_EQ(ERR_APPEXECFWK_FORM_BIND_FORMSUPPLY_FAILED, instance_->NotifyFormCastTempForm(formId, want, callerToken)); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_NotifyFormCastTempForm_0300 end"; +} + +/** + * @tc.number: AaFwk_FormProviderClient_FireFormEvent_0100 + * @tc.name: FireFormEvent + * @tc.desc: Verify that the return value of FireFormEvent is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_FireFormEvent_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_FireFormEvent_0100 start"; + + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(ability); + + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::FORM_CONNECT_ID, 104L); + + int64_t formId = 724L; + std::string message = "event message"; + const sptr callerToken = MockFormSupplyCallback::GetInstance(); + + EXPECT_EQ(ERR_OK, instance_->FireFormEvent(formId, message, want, callerToken)); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_FireFormEvent_0100 end"; +} + +/** + * @tc.number: AaFwk_FormProviderClient_FireFormEvent_0200 + * @tc.name: FireFormEvent + * @tc.desc: Verify that the return value of FireFormEvent is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_FireFormEvent_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_FireFormEvent_0200 start"; + + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(nullptr); + + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::FORM_CONNECT_ID, 105L); + int64_t formId = 725L; + std::string message = "event message"; + const sptr callerToken = MockFormSupplyCallback::GetInstance(); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY, instance_->FireFormEvent(formId, message, want, callerToken)); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_FireFormEvent_0200 end"; +} +/** + * @tc.number: AaFwk_FormProviderClient_FireFormEvent_0300 + * @tc.name: NotifyFormCastTempForm + * @tc.desc: Verify that the return value of AddForm is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_FireFormEvent_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_FireFormEvent_0300 start"; + + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(ability); + + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::FORM_CONNECT_ID, 106L); + + int64_t formId = 726L; + std::string message = "event message"; + const sptr callerToken = nullptr; + + EXPECT_EQ(ERR_APPEXECFWK_FORM_BIND_FORMSUPPLY_FAILED, instance_->FireFormEvent(formId, message, want, callerToken)); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_FireFormEvent_0300 end"; +} + +/** + * @tc.number: AaFwk_FormProviderClient_NotifyFormsDelete_0100 + * @tc.name: FireFormEvent + * @tc.desc: Verify that the return value of FireFormEvent is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_NotifyFormsDelete_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_NotifyFormsDelete_0100 start"; + + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(ability); + + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::FORM_CONNECT_ID, 107L); + + std::vector formIds = {727L, 728L, 729L}; + const sptr callerToken = MockFormSupplyCallback::GetInstance(); + + EXPECT_EQ(ERR_OK, instance_->NotifyFormsDelete(formIds, want, callerToken)); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_NotifyFormsDelete_0100 end"; +} +/** + * @tc.number: AaFwk_FormProviderClient_NotifyFormsDelete_0200 + * @tc.name: FireFormEvent + * @tc.desc: Verify that the return value of FireFormEvent is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_NotifyFormsDelete_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_NotifyFormsDelete_0200 start"; + + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(nullptr); + + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::FORM_CONNECT_ID, 108L); + std::vector formIds = {730L, 731L, 732L}; + const sptr callerToken = MockFormSupplyCallback::GetInstance(); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY, instance_->NotifyFormsDelete(formIds, want, callerToken)); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_NotifyFormsDelete_0200 end"; +} +/** + * @tc.number: AaFwk_FormProviderClient_NotifyFormsDelete_0300 + * @tc.name: NotifyFormCastTempForm + * @tc.desc: Verify that the return value of AddForm is correct. + */ +HWTEST_F(FormProviderClientTest, AaFwk_FormProviderClient_NotifyFormsDelete_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_NotifyFormsDelete_0300 start"; + + const std::shared_ptr ability = std::make_shared(); + instance_->SetOwner(ability); + + Want want; + want.SetParam(Constants::PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY, FORM_MANAGER_SERVICE_BUNDLE_NAME) + .SetParam(Constants::FORM_CONNECT_ID, 109L); + + std::vector formIds = {730L, 731L, 732L}; + const sptr callerToken = nullptr; + + EXPECT_EQ(ERR_APPEXECFWK_FORM_BIND_FORMSUPPLY_FAILED, instance_->NotifyFormsDelete(formIds, want, callerToken)); + + GTEST_LOG_(INFO) << "AaFwk_FormProviderClient_NotifyFormsDelete_0300 end"; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/test/unittest/pac_map_test.cpp b/frameworks/kits/ability/native/test/unittest/pac_map_test.cpp index 8a2300fcd55..08b15de9a21 100755 --- a/frameworks/kits/ability/native/test/unittest/pac_map_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/pac_map_test.cpp @@ -15,9 +15,9 @@ #include #include +#include #include "pac_map.h" -#include "ohos/aafwk/base/pac_map_node_user_object.h" - +#include "ohos/aafwk/base/user_object_base.h" namespace OHOS { namespace AppExecFwk { using namespace testing::ext; @@ -28,26 +28,63 @@ using namespace OHOS::AppExecFwk; #define PAC_MAP_TEST_LONG -1000 #define PAC_MAP_TEST_FLOAT 1.0f #define PAC_MAP_TEST_DOUBLE 3.1415926 - -class TUserObjectTest : public TUserMapObject { +namespace { +const std::regex INTEGER_REGEX("^[-+]?([0-9]+)([.]([0-9]+))?$"); +}; +class TUserObjectTest : public UserObjectBase { public: - TUserObjectTest() : TUserMapObject("TUserObjectTest"), str_data_("用户自定义对象"), int_data_(0) + TUserObjectTest() : UserObjectBase("TUserObjectTest"), str_data_("用户自定义对象"), int_data_(0) {} virtual ~TUserObjectTest() {} - virtual bool Equals(const TUserMapObject *other) override + virtual std::string ToString() const override + { + std::string tostring = str_data_; + tostring += "#" + std::to_string(int_data_); + return tostring; + } + + virtual void Parse(const std::string &str) override + { + std::vector elems; + + std::size_t splitPos = str.find("#"); + if (splitPos == std::string::npos) { + return; + } + std::string str_data = str.substr(0, splitPos); + std::string intdata = str.substr(str_data.length() + 1, str.length() - 1); + if (str_data.length() + 1 + intdata.length() != str.length()) { + return; + } + bool isNumber = std::regex_match(intdata, INTEGER_REGEX); + if (isNumber) { + str_data_ = str_data; + int_data_ = std::stoi(intdata); + } + } + + virtual bool Equals(std::shared_ptr &other) override { - TUserObjectTest *pobject = (TUserObjectTest *)other; + if (other->GetClassName() != GetClassName()) { + return false; + } + + TUserObjectTest *pobject = static_cast(other.get()); if (pobject == nullptr) { return false; } return ((str_data_ == pobject->str_data_) && (int_data_ == pobject->int_data_)); } - virtual void DeepCopy(const TUserMapObject *other) override + virtual void DeepCopy(std::shared_ptr &other) override { - TUserObjectTest *pobject = (TUserObjectTest *)other; + if (other->GetClassName() != GetClassName()) { + return; + } + + TUserObjectTest *pobject = static_cast(other.get()); if (pobject != nullptr) { str_data_ = pobject->str_data_; int_data_ = pobject->int_data_; @@ -68,7 +105,7 @@ private: std::string str_data_ = ""; int int_data_ = 0; }; -REGISTER_USER_MAP_OBJECT(TUserObjectTest); +REGISTER_USER_OBJECT_BASE(TUserObjectTest); /* * Description:Test for data type of base: like int, short, long std::string etc. @@ -81,8 +118,9 @@ public: {} std::shared_ptr pacmap_ = nullptr; - + std::shared_ptr pacmap2_ = nullptr; static void FillData(PacMap &pacmap); + static void FillData2(PacMap &pacmap, const PacMap ¶m_map); static void SetUpTestCase(void); static void TearDownTestCase(void); @@ -99,6 +137,7 @@ void PacMapTest::TearDownTestCase(void) void PacMapTest::SetUp() { pacmap_ = std::make_shared(); + pacmap2_ = std::make_shared(); } void PacMapTest::TearDown() @@ -146,6 +185,46 @@ void PacMapTest::FillData(PacMap &pacmap) pacmap.PutStringValueArray("key_string_array", arrayString); } +void PacMapTest::FillData2(PacMap &pacmap, const PacMap ¶m_map) +{ + std::vector arrayShort; + std::vector arrayInt; + std::vector arrayLong; + std::vector arrayByte; + std::vector arrayBool; + std::vector arrayFloat; + std::vector arrayDouble; + std::vector arrayString; + + arrayShort.push_back(PAC_MPA_TEST_INT); + arrayInt.push_back(PAC_MPA_TEST_INT); + arrayLong.push_back(PAC_MAP_TEST_LONG); + arrayByte.push_back('a'); + arrayBool.push_back(true); + arrayFloat.push_back(PAC_MAP_TEST_FLOAT); + arrayDouble.push_back(PAC_MAP_TEST_DOUBLE); + arrayString.push_back("<~!@#$%^&*()_+>特殊字符"); + + pacmap.PutShortValue("key_short", PAC_MPA_TEST_INT); + pacmap.PutIntValue("key_int", PAC_MPA_TEST_INT); + pacmap.PutLongValue("key_long", PAC_MAP_TEST_LONG); + pacmap.PutByteValue("key_byte", 'A'); + pacmap.PutBooleanValue("key_boolean", true); + pacmap.PutFloatValue("key_float", PAC_MAP_TEST_FLOAT); + pacmap.PutDoubleValue("key_double", PAC_MAP_TEST_DOUBLE); + pacmap.PutStringValue("key_string", "test clone"); + + pacmap.PutPacMap("key_map", param_map); + + pacmap.PutShortValueArray("key_short_array", arrayShort); + pacmap.PutIntValueArray("key_int_array", arrayInt); + pacmap.PutLongValueArray("key_long_array", arrayLong); + pacmap.PutByteValueArray("key_byte_array", arrayByte); + pacmap.PutFloatValueArray("key_float_array", arrayFloat); + pacmap.PutBooleanValueArray("key_boolean_array", arrayBool); + pacmap.PutDoubleValueArray("key_double_array", arrayDouble); + pacmap.PutStringValueArray("key_string_array", arrayString); +} /** * @tc.number: AppExecFwk_PacMap_PutShortValue_0100 * @tc.name: PutShortValue @@ -259,7 +338,8 @@ HWTEST_F(PacMapTest, AppExecFwk_PacMap_PutStringValue_0100, Function | MediumTes GTEST_LOG_(INFO) << "AppExecFwk_PacMap_PutStringValue_0100 start"; std::string value("AppExecFwk_PacMap_PutStringValue_0100 PACMAP测试"); pacmap_->PutStringValue("key_string", value); - EXPECT_STREQ(value.c_str(), pacmap_->GetStringValue("key_string").c_str()); + std::string getStr = pacmap_->GetStringValue("key_string"); + EXPECT_STREQ(value.c_str(), getStr.c_str()); GTEST_LOG_(INFO) << "AppExecFwk_PacMap_PutStringValue_0100 end"; } @@ -442,10 +522,10 @@ HWTEST_F(PacMapTest, AppExecFwk_PacMap_PutObject_0100, Function | MediumTest | L std::shared_ptr putObject = std::make_shared(); pacmap_->PutObject("key_object", putObject); - std::shared_ptr getObject = pacmap_->GetObject("key_object"); + std::shared_ptr getObject = pacmap_->GetObject("key_object"); bool isEqual = false; if (getObject.get() != nullptr) { - isEqual = getObject->Equals(getObject.get()); + isEqual = getObject->Equals(getObject); } EXPECT_EQ(true, isEqual); @@ -529,9 +609,9 @@ HWTEST_F(PacMapTest, AppExecFwk_PacMap_GetAll_0100, Function | MediumTest | Leve GTEST_LOG_(INFO) << "AppExecFwk_PacMap_GetAll_0100 start"; FillData(*pacmap_.get()); - std::map data = pacmap_->GetAll(); + std::map data = pacmap_->GetAll(); - EXPECT_EQ((int)data.size(), pacmap_->GetSize()); + EXPECT_EQ(data.size(), (std::size_t)pacmap_->GetSize()); GTEST_LOG_(INFO) << "AppExecFwk_PacMap_GetAll_0100 end"; } @@ -623,5 +703,45 @@ HWTEST_F(PacMapTest, AppExecFwk_PacMap_Marshalling_0100, Function | MediumTest | } GTEST_LOG_(INFO) << "AppExecFwk_PacMap_Marshalling_0100 end"; } +/** + * @tc.number: AppExecFwk_PacMap_Marshalling_0200 + * @tc.name: Marshalling and Unmarshalling + * @tc.desc: Verify Marshalling() and Unmarshalling(). + */ +HWTEST_F(PacMapTest, AppExecFwk_PacMap_Marshalling_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_PacMap_Marshalling_0200 start"; + + Parcel parcel; + FillData(*pacmap_.get()); + FillData2(*pacmap2_.get(), *pacmap_.get()); + + EXPECT_EQ(true, pacmap2_->Marshalling(parcel)); + PacMap *unmarshingMap = PacMap::Unmarshalling(parcel); + + EXPECT_EQ(true, unmarshingMap != nullptr); + if (unmarshingMap != nullptr) { + EXPECT_EQ(true, pacmap2_->Equals(unmarshingMap)); + delete unmarshingMap; + unmarshingMap = nullptr; + } + GTEST_LOG_(INFO) << "AppExecFwk_PacMap_Marshalling_0200 end"; +} +/** + * @tc.number: AppExecFwk_PacMap_Marshalling_0300 + * @tc.name: Marshalling and Unmarshalling + * @tc.desc: Verify Marshalling() and Unmarshalling(). + */ +HWTEST_F(PacMapTest, AppExecFwk_PacMap_Marshalling_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_PacMap_Marshalling_0300 start"; + + Parcel parcel; + EXPECT_EQ(true, pacmap2_->Marshalling(parcel)); + PacMap *unmarshingMap = PacMap::Unmarshalling(parcel); + + EXPECT_EQ(true, unmarshingMap != nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_PacMap_Marshalling_0300 end"; +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/base/cpp/src/ohos/aafwk/base/base.cpp b/frameworks/kits/base/cpp/src/ohos/aafwk/base/base.cpp old mode 100644 new mode 100755 index 7e688dac790..336fc825507 --- a/frameworks/kits/base/cpp/src/ohos/aafwk/base/base.cpp +++ b/frameworks/kits/base/cpp/src/ohos/aafwk/base/base.cpp @@ -54,5 +54,11 @@ const InterfaceID g_IID_IString = { const InterfaceID g_IID_IArray = { 0x875b9da6, 0x9913, 0x4370, 0x8847, {0xe, 0x1, 0x9, 0x6, 0x1, 0xb, 0xe, 0x6, 0xe, 0x5, 0x6, 0x0}}; + +const InterfaceID g_IID_IPacMap = { + 0xf92066fd, 0xfd0c, 0x401b, 0xa3f6, {0x6, 0x2, 0x6, 0xd, 0xa, 0x3, 0xb, 0xa, 0xc, 0x9, 0xd, 0x5}}; + +const InterfaceID g_IID_IUserObject = { + 0x4edb325d, 0x8532, 0x4af7, 0xb42e, {0x8, 0x2, 0xf, 0x4, 0xf, 0x2, 0x9, 0xd, 0xf, 0xd, 0xe, 0xa}}; } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_array.cpp b/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_array.cpp deleted file mode 100755 index 9a26d0987ba..00000000000 --- a/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_array.cpp +++ /dev/null @@ -1,688 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include "ohos/aafwk/base/pac_map_node_array.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -#define IS_STORED_ARRAY_DATA_TYPE(id, value) \ - do { \ - if (value.GetRefPtr() != nullptr) { \ - return AAFwk::Array::Is##id##Array(value); \ - } \ - return false; \ - } while (0) - -#define EQUALS_ARRAY_DATA(id, dataType, right) \ - do { \ - if (Is##id() && right->Is##id()) { \ - std::vector left_value; \ - std::vector right_value; \ - Get##id##ValueArray(left_value); \ - right->Get##id##ValueArray(right_value); \ - return (left_value == right_value); \ - } \ - } while (0) - -#define READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(type, parcel, data) \ - do { \ - if (!(parcel).Read##type(data)) { \ - return false; \ - } \ - } while (0) - -#define WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(type, parcel, data) \ - do { \ - if (!(parcel).Write##type(data)) { \ - return false; \ - } \ - } while (0) - -#define INNER_DEEP_COPY(id, dataType, obj) \ - do { \ - std::vector array; \ - obj->Get##id##ValueArray(array); \ - Put##id##ValueArray(array); \ - } while (0) - -template -static void PacMapSetArray(const AAFwk::InterfaceID &id, const std::vector &value, sptr &ao) -{ - typename std::vector::size_type size = value.size(); - ao = new (std::nothrow) AAFwk::Array(size, id); - if (ao != nullptr) { - for (typename std::vector::size_type i = 0; i < size; i++) { - ao->Set(i, T2::Box(value[i])); - } - } -} - -template -static void PacMapGetArray(const sptr &ao, std::vector &array) -{ - auto func = [&](AAFwk::IInterface *object) { - if (object != nullptr) { - T3 *value = T3::Query(object); - if (value != nullptr) { - array.push_back(T2::Unbox(value)); - } - } - }; - AAFwk::Array::ForEach(ao.GetRefPtr(), func); -} - -PacMapNodeTypeArray::PacMapNodeTypeArray(const PacMapNodeTypeArray &other) : PacMapNode(other) -{ - InnerDeepCopy(&other); -} - -PacMapNodeTypeArray &PacMapNodeTypeArray::operator=(const PacMapNodeTypeArray &other) -{ - if (this != &other) { - value_ = other.value_; - } - return *this; -} - -/** - * @brief Adds some short values to current object. - * @param value Added list of data. - */ -void PacMapNodeTypeArray::PutShortValueArray(const std::vector &value) -{ - PacMapSetArray(AAFwk::g_IID_IShort, value, value_); -} - -/** - * @brief Adds some int values to current object. - * @param value Added list of data. - */ -void PacMapNodeTypeArray::PutIntegerValueArray(const std::vector &value) -{ - PacMapSetArray(AAFwk::g_IID_IInteger, value, value_); -} - -/** - * @brief Adds some long values to current object. - * @param value Added list of data. - */ -void PacMapNodeTypeArray::PutLongValueArray(const std::vector &value) -{ - PacMapSetArray(AAFwk::g_IID_ILong, value, value_); -} - -/** - * @brief Adds some boolean values to current object. - * @param value Added list of data. - */ -void PacMapNodeTypeArray::PutBooleanValueArray(const std::vector &value) -{ - PacMapSetArray(AAFwk::g_IID_IBoolean, value, value_); -} - -/** - * @brief Adds some char values to current object. - * @param value Added list of data. - */ -void PacMapNodeTypeArray::PutCharValueArray(const std::vector &value) -{ - PacMapSetArray(AAFwk::g_IID_IByte, value, value_); -} - -/** - * @brief Adds some byte values to current object. - * @param value Added list of data. - */ -void PacMapNodeTypeArray::PutByteValueArray(const std::vector &value) -{ - PacMapSetArray(AAFwk::g_IID_IByte, value, value_); -} - -/** - * @brief Adds some float values to current object. - * @param value Added list of data. - */ -void PacMapNodeTypeArray::PutFloatValueArray(const std::vector &value) -{ - PacMapSetArray(AAFwk::g_IID_IFloat, value, value_); -} - -/** - * @brief Adds some double values to current object. - * @param value Added list of data. - */ -void PacMapNodeTypeArray::PutDoubleValueArray(const std::vector &value) -{ - PacMapSetArray(AAFwk::g_IID_IDouble, value, value_); -} - -/** - * @brief Adds some string {std::string} values to current object. - * @param value Added list of data. - */ -void PacMapNodeTypeArray::PutStringValueArray(const std::vector &value) -{ - PacMapSetArray(AAFwk::g_IID_IString, value, value_); -} - -/** - * @brief Obtains some short values. - * @param value Save the returned short values. - */ -void PacMapNodeTypeArray::GetShortValueArray(std::vector &value) -{ - PacMapGetArray(value_, value); -} - -/** - * @brief Obtains some int values. - * @param value Save the returned int values. - */ -void PacMapNodeTypeArray::GetIntegerValueArray(std::vector &value) -{ - PacMapGetArray(value_, value); -} - -/** - * @brief Obtains some long values. - * @param value Save the returned long values. - */ -void PacMapNodeTypeArray::GetLongValueArray(std::vector &value) -{ - PacMapGetArray(value_, value); -} - -/** - * @brief Obtains some boolean values. - * @param value Save the returned boolean values. - */ -void PacMapNodeTypeArray::GetBooleanValueArray(std::vector &value) -{ - PacMapGetArray(value_, value); -} - -/** - * @brief Obtains some char values. - * @param value Save the returned char values. - */ -void PacMapNodeTypeArray::GetCharValueArray(std::vector &value) -{ - PacMapGetArray(value_, value); -} - -/** - * @brief Obtains some byte values. - * @param value Save the returned byte values. - */ -void PacMapNodeTypeArray::GetByteValueArray(std::vector &value) -{ - PacMapGetArray(value_, value); -} - -/** - * @brief Obtains some float values. - * @param value Save the returned float values. - */ -void PacMapNodeTypeArray::GetFloatValueArray(std::vector &value) -{ - PacMapGetArray(value_, value); -} - -/** - * @brief Obtains some double values. - * @param value Save the returned double values. - */ -void PacMapNodeTypeArray::GetDoubleValueArray(std::vector &value) -{ - PacMapGetArray(value_, value); -} - -/** - * @brief Obtains some std::string values. - * @param value Save the returned std::string values. - */ -void PacMapNodeTypeArray::GetStringValueArray(std::vector &value) -{ - PacMapGetArray(value_, value); -} - -/** - * @brief Indicates whether some other object is "equal to" this one. - * @param other The object with which to compare. - * @return true if this object is the same as the obj argument; false otherwise. - */ -bool PacMapNodeTypeArray::Equals(const PacMapNode *other) -{ - if (other == nullptr) { - return false; - } - - PacMapNode *pnode = const_cast(other); - PacMapNodeTypeArray *other_ = static_cast(pnode); - if (other_ == nullptr) { - return false; - } - - if (value_.GetRefPtr() == other_->value_.GetRefPtr()) { - return true; - } - - if (value_.GetRefPtr() == nullptr || other_->value_.GetRefPtr() == nullptr) { - return false; - } - - EQUALS_ARRAY_DATA(Short, short, other_); - EQUALS_ARRAY_DATA(Integer, int, other_); - EQUALS_ARRAY_DATA(Long, long, other_); - EQUALS_ARRAY_DATA(Char, char, other_); - EQUALS_ARRAY_DATA(Byte, AAFwk::byte, other_); - EQUALS_ARRAY_DATA(Boolean, bool, other_); - EQUALS_ARRAY_DATA(Float, float, other_); - EQUALS_ARRAY_DATA(Double, double, other_); - EQUALS_ARRAY_DATA(String, std::string, other_); - - return false; -} - -/** - * @brief Copy the data of the specified object to the current object with deepcopy - * @param other The original object that stores the data. - */ -void PacMapNodeTypeArray::DeepCopy(const PacMapNode *other) -{ - PacMapNodeTypeArray *array_object = (PacMapNodeTypeArray *)other; - InnerDeepCopy(array_object); -} - -void PacMapNodeTypeArray::InnerDeepCopy(const PacMapNodeTypeArray *other) -{ - if (other == nullptr) { - return; - } - - PacMapNodeTypeArray *pother = const_cast(other); - if (AAFwk::Array::IsStringArray(pother->value_)) { - INNER_DEEP_COPY(String, std::string, pother); - } else if (AAFwk::Array::IsBooleanArray(pother->value_)) { - INNER_DEEP_COPY(Boolean, bool, pother); - } else if (AAFwk::Array::IsByteArray(pother->value_)) { - INNER_DEEP_COPY(Byte, AAFwk::byte, pother); - } else if (AAFwk::Array::IsShortArray(pother->value_)) { - INNER_DEEP_COPY(Short, short, pother); - } else if (AAFwk::Array::IsIntegerArray(pother->value_)) { - INNER_DEEP_COPY(Integer, int, pother); - } else if (AAFwk::Array::IsLongArray(pother->value_)) { - INNER_DEEP_COPY(Long, long, pother); - } else if (AAFwk::Array::IsFloatArray(pother->value_)) { - INNER_DEEP_COPY(Float, float, pother); - } else if (AAFwk::Array::IsDoubleArray(pother->value_)) { - INNER_DEEP_COPY(Double, double, pother); - } else { - return; - } -} - -/** - * @brief Whether the stored data is of short type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeArray::IsShort(void) -{ - IS_STORED_ARRAY_DATA_TYPE(Short, value_); -} - -/** - * @brief Whether the stored data is of integer type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeArray::IsInteger(void) -{ - IS_STORED_ARRAY_DATA_TYPE(Integer, value_); -} - -/** - * @brief Whether the stored data is of long type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeArray::IsLong(void) -{ - IS_STORED_ARRAY_DATA_TYPE(Long, value_); -} - -/** - * @brief Whether the stored data is of char type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeArray::IsChar(void) -{ - return IsByte(); -} - -/** - * @brief Whether the stored data is of byte type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeArray::IsByte(void) -{ - IS_STORED_ARRAY_DATA_TYPE(Byte, value_); -} - -/** - * @brief Whether the stored data is of boolean type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeArray::IsBoolean(void) -{ - IS_STORED_ARRAY_DATA_TYPE(Boolean, value_); -} - -/** - * @brief Whether the stored data is of float type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeArray::IsFloat(void) -{ - IS_STORED_ARRAY_DATA_TYPE(Float, value_); -} - -/** - * @brief Whether the stored data is of double type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeArray::IsDouble(void) -{ - IS_STORED_ARRAY_DATA_TYPE(Double, value_); -} - -/** - * @brief Whether the stored data is of string type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeArray::IsString(void) -{ - IS_STORED_ARRAY_DATA_TYPE(String, value_); -} - -bool PacMapNodeTypeArray::MarshallingArrayString(Parcel &parcel) const -{ - std::vector array; - auto func = [&](AAFwk::IInterface *object) { - if (AAFwk::IString::Query(object) != nullptr) { - std::string s = AAFwk::String::Unbox(AAFwk::IString::Query(object)); - array.push_back(Str8ToStr16(s)); - } - }; - AAFwk::Array::ForEach(value_, func); - - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int32, parcel, PACMAP_DATA_ARRAY_STRING); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(String16Vector, parcel, array); - return true; -} - -bool PacMapNodeTypeArray::MarshallingArrayBoolean(Parcel &parcel) const -{ - std::vector array; - PacMapGetArray(value_, array); - - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int32, parcel, PACMAP_DATA_ARRAY_BOOLEAN); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int8Vector, parcel, array); - return true; -} - -bool PacMapNodeTypeArray::MarshallingArrayByte(Parcel &parcel) const -{ - std::vector array; - PacMapGetArray(value_, array); - - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int32, parcel, PACMAP_DATA_ARRAY_BYTE); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int8Vector, parcel, array); - return true; -} - -bool PacMapNodeTypeArray::MarshallingArrayShort(Parcel &parcel) const -{ - std::vector array; - PacMapGetArray(value_, array); - - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int32, parcel, PACMAP_DATA_ARRAY_SHORT); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int16Vector, parcel, array); - return true; -} - -bool PacMapNodeTypeArray::MarshallingArrayInteger(Parcel &parcel) const -{ - std::vector array; - PacMapGetArray(value_, array); - - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int32, parcel, PACMAP_DATA_ARRAY_INTEGER); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int32Vector, parcel, array); - return true; -} - -bool PacMapNodeTypeArray::MarshallingArrayLong(Parcel &parcel) const -{ - std::vector array; - PacMapGetArray(value_, array); - return WriteLongVector(parcel, array); -} - -bool PacMapNodeTypeArray::MarshallingArrayFloat(Parcel &parcel) const -{ - std::vector array; - PacMapGetArray(value_, array); - - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int32, parcel, PACMAP_DATA_ARRAY_FLOAT); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(FloatVector, parcel, array); - return true; -} - -bool PacMapNodeTypeArray::MarshallingArrayDouble(Parcel &parcel) const -{ - std::vector array; - PacMapGetArray(value_, array); - - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int32, parcel, PACMAP_DATA_ARRAY_DOUBLE); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(DoubleVector, parcel, array); - return true; -} - -/** - * @brief Marshals this Sequenceable object to a Parcel. - * @param key Indicates the key in String format. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Marshals success returns true, otherwise returns false. - */ -bool PacMapNodeTypeArray::Marshalling(const std::string &key, Parcel &parcel) const -{ - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(String16, parcel, Str8ToStr16(key)); - - if (AAFwk::Array::IsStringArray(value_)) { - return MarshallingArrayString(parcel); - } else if (AAFwk::Array::IsBooleanArray(value_)) { - return MarshallingArrayBoolean(parcel); - } else if (AAFwk::Array::IsByteArray(value_)) { - return MarshallingArrayByte(parcel); - } else if (AAFwk::Array::IsShortArray(value_)) { - return MarshallingArrayShort(parcel); - } else if (AAFwk::Array::IsIntegerArray(value_)) { - return MarshallingArrayInteger(parcel); - } else if (AAFwk::Array::IsLongArray(value_)) { - return MarshallingArrayLong(parcel); - } else if (AAFwk::Array::IsFloatArray(value_)) { - return MarshallingArrayFloat(parcel); - } else if (AAFwk::Array::IsDoubleArray(value_)) { - return MarshallingArrayDouble(parcel); - } else { - return false; - } -} - -bool PacMapNodeTypeArray::UnmarshallingArrayShort(Parcel &parcel) -{ - std::vector value; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int16Vector, parcel, &value); - PutShortValueArray(value); - return true; -} - -bool PacMapNodeTypeArray::UnmarshallingArrayInteger(Parcel &parcel) -{ - std::vector value; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int32Vector, parcel, &value); - PutIntegerValueArray(value); - return true; -} - -bool PacMapNodeTypeArray::UnmarshallingArrayLong(Parcel &parcel) -{ - std::vector value; - if (!ReadLongVector(parcel, value)) { - return false; - } - PutLongValueArray(value); - return true; -} - -bool PacMapNodeTypeArray::UnmarshallingArrayByte(Parcel &parcel) -{ - std::vector value; - std::vector byteValue; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int8Vector, parcel, &value); - - for (int i = 0; i < (int)value.size(); i++) { - byteValue.push_back(value[i]); - } - PutByteValueArray(byteValue); - return true; -} - -bool PacMapNodeTypeArray::UnmarshallingArrayBoolean(Parcel &parcel) -{ - std::vector value; - std::vector boolValue; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int8Vector, parcel, &value); - - for (int i = 0; i < (int)value.size(); i++) { - boolValue.push_back((value[i] == 0) ? false : true); - } - PutBooleanValueArray(boolValue); - return true; -} - -bool PacMapNodeTypeArray::UnmarshallingArrayFloat(Parcel &parcel) -{ - std::vector value; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(FloatVector, parcel, &value); - PutFloatValueArray(value); - return true; -} - -bool PacMapNodeTypeArray::UnmarshallingArrayDouble(Parcel &parcel) -{ - std::vector value; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(DoubleVector, parcel, &value); - PutDoubleValueArray(value); - return true; -} - -bool PacMapNodeTypeArray::UnmarshallingArrayString(Parcel &parcel) -{ - std::vector value; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(String16Vector, parcel, &value); - - std::vector::size_type size = value.size(); - value_ = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_IString); - if (value_ != nullptr) { - for (std::vector::size_type i = 0; i < size; i++) { - value_->Set(i, AAFwk::String::Box(Str16ToStr8(value[i]))); - } - return true; - } else { - return false; - } -} - -/** - * @brief Unmarshals this Sequenceable object from a Parcel. - * @param dataType Indicates the type of data stored. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Unmarshals success returns true, otherwise returns false. - */ -bool PacMapNodeTypeArray::Unmarshalling(int32_t dataType, Parcel &parcel) -{ - switch (dataType) { - case PACMAP_DATA_ARRAY_SHORT: - return UnmarshallingArrayShort(parcel); - case PACMAP_DATA_ARRAY_INTEGER: - return UnmarshallingArrayInteger(parcel); - case PACMAP_DATA_ARRAY_LONG: - return UnmarshallingArrayLong(parcel); - case PACMAP_DATA_ARRAY_CHAR: - [[clang::fallthrough]]; - case PACMAP_DATA_ARRAY_BYTE: - return UnmarshallingArrayByte(parcel); - case PACMAP_DATA_ARRAY_BOOLEAN: - return UnmarshallingArrayBoolean(parcel); - case PACMAP_DATA_ARRAY_FLOAT: - return UnmarshallingArrayFloat(parcel); - case PACMAP_DATA_ARRAY_DOUBLE: - return UnmarshallingArrayDouble(parcel); - case PACMAP_DATA_ARRAY_STRING: - return UnmarshallingArrayString(parcel); - default: - return false; - } - return true; -} - -bool PacMapNodeTypeArray::WriteLongVector(Parcel &parcel, const std::vector &value) const -{ - if (value.size() > INT_MAX) { - return false; - } - - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int32, parcel, PACMAP_DATA_ARRAY_LONG); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int32, parcel, value.size()); - for (int i = 0; i < (int)value.size(); i++) { - long value_ = value[i]; - if (!parcel.WriteBuffer((void *)&value_, sizeof(long))) { - return false; - } - } - return true; -} - -bool PacMapNodeTypeArray::ReadLongVector(Parcel &parcel, std::vector &value) -{ - int count = 0; - value.clear(); - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int32, parcel, count); - - long *pvalue_ = nullptr; - for (auto i = 0; i < count; i++) { - const uint8_t *pdata = parcel.ReadBuffer(sizeof(long)); - if (pdata != nullptr) { - pvalue_ = (long *)pdata; - value.push_back(*pvalue_); - } else { - return false; - } - } - return true; -} -} // namespace AppExecFwk -} // namespace OHOS diff --git a/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_base.cpp b/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_base.cpp deleted file mode 100755 index 179fc7442e0..00000000000 --- a/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_base.cpp +++ /dev/null @@ -1,586 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ohos/aafwk/base/pac_map_node_base.h" -#include -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -#define EQUALS_BASE_DATA(id, right) \ - do { \ - if (Is##id() && right->Is##id()) { \ - return Get##id##Value() == right->Get##id##Value(); \ - } \ - } while (0) - -#define READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(type, parcel, data) \ - do { \ - if (!(parcel).Read##type(data)) { \ - return false; \ - } \ - } while (0) - -#define WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(type, parcel, data) \ - do { \ - if (!(parcel).Write##type(data)) { \ - return false; \ - } \ - } while (0) - -template -static T1 PacMapGetBaseValue(sptr &object, T1 defaultValue) -{ - T2 *pv = T2::Query(object); - if (pv != nullptr) { - return T3::Unbox(pv); - } else { - return defaultValue; - } -} - -PacMapNodeTypeBase::PacMapNodeTypeBase(const PacMapNodeTypeBase &other) : PacMapNode(other) -{ - InnerDeepCopy(&other); -} - -PacMapNodeTypeBase &PacMapNodeTypeBase::operator=(const PacMapNodeTypeBase &other) -{ - if (this != &other) { - value_ = other.value_; - } - return *this; -} - -/** - * @brief Adds a short value to current object. - * @param value Added data. - */ -void PacMapNodeTypeBase::PutShortValue(short value) -{ - value_ = AAFwk::Short::Box(value); -} - -/** - * @brief Adds a int value to current object. - * @param value Added data. - */ -void PacMapNodeTypeBase::PutIntValue(int value) -{ - value_ = AAFwk::Integer::Box(value); -} - -/** - * @brief Adds a long value to current object. - * @param value Added data. - */ -void PacMapNodeTypeBase::PutLongValue(long value) -{ - value_ = AAFwk::Long::Box(value); -} - -/** - * @brief Adds a boolean value to current object. - * @param value Added data. - */ -void PacMapNodeTypeBase::PutBooleanValue(bool value) -{ - value_ = AAFwk::Boolean::Box(value); -} - -/** - * @brief Adds a char value to current object. - * @param value Added data. - */ -void PacMapNodeTypeBase::PutCharValue(char value) -{ - value_ = AAFwk::Byte::Box(value); -} - -/** - * @brief Adds a byte value to current object. - * @param value Added data. - */ -void PacMapNodeTypeBase::PutByteValue(AAFwk::byte value) -{ - value_ = AAFwk::Byte::Box(value); -} - -/** - * @brief Adds a float value to current object. - * @param value Added data. - */ -void PacMapNodeTypeBase::PutFloatValue(float value) -{ - value_ = AAFwk::Float::Box(value); -} - -/** - * @brief Adds a double value to current object. - * @param value Added data. - */ -void PacMapNodeTypeBase::PutDoubleValue(double value) -{ - value_ = AAFwk::Double::Box(value); -} - -/** - * @brief Adds a string {std::string} value to current object. - * @param value Added data. - */ -void PacMapNodeTypeBase::PutStringValue(const std::string &value) -{ - value_ = AAFwk::String::Box(value); -} - -/** - * @brief Obtains the short value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the short value, otherwise return the @a defaultValue. - */ -short PacMapNodeTypeBase::GetShortValue(short defaultValue) -{ - return PacMapGetBaseValue(value_, defaultValue); -} - -/** - * @brief Obtains the int value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the int value, otherwise return the @a defaultValue. - */ -int PacMapNodeTypeBase::GetIntegerValue(int defaultValue) -{ - return PacMapGetBaseValue(value_, defaultValue); -} - -/** - * @brief Obtains the long value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the long value, otherwise return the @a defaultValue. - */ -long PacMapNodeTypeBase::GetLongValue(long defaultValue) -{ - return PacMapGetBaseValue(value_, defaultValue); -} - -/** - * @brief Obtains the boolean value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the boolean value, otherwise return the @a defaultValue. - */ -bool PacMapNodeTypeBase::GetBooleanValue(bool defaultValue) -{ - return PacMapGetBaseValue(value_, defaultValue); -} - -/** - * @brief Obtains the char value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the char value, otherwise return the @a defaultValue. - */ -char PacMapNodeTypeBase::GetCharValue(char defaultValue) -{ - return PacMapGetBaseValue(value_, defaultValue); -} - -/** - * @brief Obtains the byte value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the byte value, otherwise return the @a defaultValue. - */ -AAFwk::byte PacMapNodeTypeBase::GetByteValue(AAFwk::byte defaultValue) -{ - return PacMapGetBaseValue(value_, defaultValue); -} - -/** - * @brief Obtains the float value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the float value, otherwise return the @a defaultValue. - */ -float PacMapNodeTypeBase::GetFloatValue(float defaultValue) -{ - return PacMapGetBaseValue(value_, defaultValue); -} - -/** - * @brief Obtains the double value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the double value, otherwise return the @a defaultValue. - */ -double PacMapNodeTypeBase::GetDoubleValue(double defaultValue) -{ - return PacMapGetBaseValue(value_, defaultValue); -} - -/** - * @brief Obtains the string {std::string} value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the std::string value, otherwise return the @a defaultValue. - */ -std::string PacMapNodeTypeBase::GetStringValue(const std::string &defaultValue) -{ - return PacMapGetBaseValue(value_, defaultValue); -} - -/** - * @brief Indicates whether some other object is "equal to" this one. - * @param other The object with which to compare. - * @return true if this object is the same as the obj argument; false otherwise. - */ -bool PacMapNodeTypeBase::Equals(const PacMapNode *other) -{ - if (other == nullptr) { - return false; - } - - PacMapNode *pnode = const_cast(other); - PacMapNodeTypeBase *other_ = static_cast(pnode); - if (other_ == nullptr) { - return false; - } - - if (value_.GetRefPtr() == other_->value_.GetRefPtr()) { - return true; - } - - if (value_.GetRefPtr() == nullptr || other_->value_.GetRefPtr() == nullptr) { - return false; - } - - EQUALS_BASE_DATA(Short, other_); - EQUALS_BASE_DATA(Integer, other_); - EQUALS_BASE_DATA(Long, other_); - EQUALS_BASE_DATA(Byte, other_); - EQUALS_BASE_DATA(Char, other_); - EQUALS_BASE_DATA(Boolean, other_); - EQUALS_BASE_DATA(Float, other_); - EQUALS_BASE_DATA(Double, other_); - EQUALS_BASE_DATA(String, other_); - - return false; -} - -/** - * @brief Copy the data of the specified object to the current object with deepcopy - * @param other The original object that stores the data. - */ -void PacMapNodeTypeBase::DeepCopy(const PacMapNode *other) -{ - PacMapNodeTypeBase *base_object = (PacMapNodeTypeBase *)other; - InnerDeepCopy(base_object); -} - -void PacMapNodeTypeBase::InnerDeepCopy(const PacMapNodeTypeBase *other) -{ - PacMapNodeTypeBase *other_ = const_cast(other); - - if (AAFwk::IString::Query(other_->value_) != nullptr) { - std::string value = AAFwk::String::Unbox(AAFwk::IString::Query(other_->value_)); - PutStringValue(value); - } else if (AAFwk::IBoolean::Query(other_->value_) != nullptr) { - bool value = AAFwk::Boolean::Unbox(AAFwk::IBoolean::Query(other_->value_)); - PutBooleanValue(value); - } else if (AAFwk::IByte::Query(other_->value_) != nullptr) { - AAFwk::byte value = AAFwk::Byte::Unbox(AAFwk::IByte::Query(other_->value_)); - PutByteValue(value); - } else if (AAFwk::IShort::Query(other_->value_) != nullptr) { - short value = AAFwk::Short::Unbox(AAFwk::IShort::Query(other_->value_)); - PutShortValue(value); - } else if (AAFwk::IInteger::Query(other_->value_) != nullptr) { - int value = AAFwk::Integer::Unbox(AAFwk::IInteger::Query(other_->value_)); - PutIntValue(value); - } else if (AAFwk::ILong::Query(other_->value_) != nullptr) { - long value = AAFwk::Long::Unbox(AAFwk::ILong::Query(other_->value_)); - PutLongValue(value); - } else if (AAFwk::IFloat::Query(other_->value_) != nullptr) { - float value = AAFwk::Float::Unbox(AAFwk::IFloat::Query(other_->value_)); - PutFloatValue(value); - } else if (AAFwk::IDouble::Query(other_->value_) != nullptr) { - double value = AAFwk::Double::Unbox(AAFwk::IDouble::Query(other_->value_)); - PutDoubleValue(value); - } -} - -/** - * @brief Whether the stored data is of short type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeBase::IsShort(void) -{ - if (value_.GetRefPtr() != nullptr) { - return AAFwk::IShort::Query(value_) != nullptr; - } - return false; -} - -/** - * @brief Whether the stored data is of integer type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeBase::IsInteger(void) -{ - if (value_.GetRefPtr() != nullptr) { - return AAFwk::IInteger::Query(value_) != nullptr; - } - return false; -} - -/** - * @brief Whether the stored data is of long type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeBase::IsLong(void) -{ - if (value_.GetRefPtr() != nullptr) { - return AAFwk::ILong::Query(value_) != nullptr; - } - return false; -} - -/** - * @brief Whether the stored data is of char type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeBase::IsChar(void) -{ - return IsByte(); -} - -/** - * @brief Whether the stored data is of byte type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeBase::IsByte(void) -{ - if (value_.GetRefPtr() != nullptr) { - return AAFwk::IByte::Query(value_) != nullptr; - } - return false; -} - -/** - * @brief Whether the stored data is of boolean type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeBase::IsBoolean(void) -{ - if (value_.GetRefPtr() != nullptr) { - return AAFwk::IBoolean::Query(value_) != nullptr; - } - return false; -} - -/** - * @brief Whether the stored data is of float type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeBase::IsFloat(void) -{ - if (value_.GetRefPtr() != nullptr) { - return AAFwk::IFloat::Query(value_) != nullptr; - } - return false; -} - -/** - * @brief Whether the stored data is of double type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeBase::IsDouble(void) -{ - if (value_.GetRefPtr() != nullptr) { - return AAFwk::IDouble::Query(value_) != nullptr; - } - return false; -} - -/** - * @brief Whether the stored data is of string type. - * @return If yes return true, otherwise return false. - */ -bool PacMapNodeTypeBase::IsString(void) -{ - if (value_.GetRefPtr() != nullptr) { - return AAFwk::IString::Query(value_) != nullptr; - } - return false; -} - -/** - * @brief Marshals this Sequenceable object to a Parcel. - * @param key Indicates the key in String format. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Marshals success returns true, otherwise returns false. - */ -bool PacMapNodeTypeBase::Marshalling(const std::string &key, Parcel &parcel) const -{ - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(String16, parcel, Str8ToStr16(key)); - - if (AAFwk::IShort::Query(value_) != nullptr) { - short value = AAFwk::Short::Unbox(AAFwk::IShort::Query(value_)); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int32, parcel, PACMAP_DATA_SHORT); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Uint16, parcel, value); - } else if (AAFwk::IInteger::Query(value_) != nullptr) { - int value = AAFwk::Integer::Unbox(AAFwk::IInteger::Query(value_)); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int32, parcel, PACMAP_DATA_INTEGER); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int32, parcel, value); - } else if (AAFwk::ILong::Query(value_) != nullptr) { - long value = AAFwk::Long::Unbox(AAFwk::ILong::Query(value_)); - if (!WriteLong(parcel, value)) { - return false; - } - } else if (AAFwk::IFloat::Query(value_) != nullptr) { - float value = AAFwk::Float::Unbox(AAFwk::IFloat::Query(value_)); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int32, parcel, PACMAP_DATA_FLOAT); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Float, parcel, value); - } else if (AAFwk::IDouble::Query(value_) != nullptr) { - double value = AAFwk::Double::Unbox(AAFwk::IDouble::Query(value_)); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int32, parcel, PACMAP_DATA_DOUBLE); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Double, parcel, value); - } else if (AAFwk::IString::Query(value_) != nullptr) { - std::string value = AAFwk::String::Unbox(AAFwk::IString::Query(value_)); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int32, parcel, PACMAP_DATA_STRING); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(String16, parcel, Str8ToStr16(value)); - } else if (AAFwk::IBoolean::Query(value_) != nullptr) { - bool value = AAFwk::Boolean::Unbox(AAFwk::IBoolean::Query(value_)); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int32, parcel, PACMAP_DATA_BOOLEAN); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int8, parcel, value); - } else if (AAFwk::IByte::Query(value_) != nullptr) { - AAFwk::byte value = AAFwk::Byte::Unbox(AAFwk::IByte::Query(value_)); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int32, parcel, PACMAP_DATA_BYTE); - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int8, parcel, value); - } - return true; -} - -bool PacMapNodeTypeBase::ReadFromParcelShort(Parcel &parcel) -{ - short value; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int16, parcel, value); - value_ = AAFwk::Short::Box(value); - return true; -} - -bool PacMapNodeTypeBase::ReadFromParcelInt(Parcel &parcel) -{ - int value; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int32, parcel, value); - value_ = AAFwk::Integer::Box(value); - return true; -} - -bool PacMapNodeTypeBase::ReadFromParcelLong(Parcel &parcel) -{ - long value; - if (ReadLong(parcel, value)) { - value_ = AAFwk::Long::Box(value); - return true; - } else { - return false; - } -} - -bool PacMapNodeTypeBase::ReadFromParcelByte(Parcel &parcel) -{ - int8_t value; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int8, parcel, value); - value_ = AAFwk::Byte::Box(value); - return true; -} - -bool PacMapNodeTypeBase::ReadFromParcelBool(Parcel &parcel) -{ - int8_t value; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int8, parcel, value); - value_ = AAFwk::Boolean::Box(value); - return true; -} - -bool PacMapNodeTypeBase::ReadFromParcelFloat(Parcel &parcel) -{ - float value; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Float, parcel, value); - value_ = AAFwk::Float::Box(value); - return true; -} - -bool PacMapNodeTypeBase::ReadFromParcelDouble(Parcel &parcel) -{ - double value; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Double, parcel, value); - value_ = AAFwk::Double::Box(value); - return true; -} - -bool PacMapNodeTypeBase::ReadFromParcelString(Parcel &parcel) -{ - std::u16string value; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(String16, parcel, value); - value_ = AAFwk::String::Box(Str16ToStr8(value)); - return true; -} - -/** - * @brief Unmarshals this Sequenceable object from a Parcel. - * @param dataType Indicates the type of data stored. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Unmarshals success returns true, otherwise returns false. - */ -bool PacMapNodeTypeBase::Unmarshalling(int32_t dataType, Parcel &parcel) -{ - switch (dataType) { - case PACMAP_DATA_SHORT: - return ReadFromParcelShort(parcel); - case PACMAP_DATA_INTEGER: - return ReadFromParcelInt(parcel); - case PACMAP_DATA_LONG: - return ReadFromParcelLong(parcel); - case PACMAP_DATA_CHAR: - return ReadFromParcelByte(parcel); - case PACMAP_DATA_BYTE: - return ReadFromParcelByte(parcel); - case PACMAP_DATA_BOOLEAN: - return ReadFromParcelBool(parcel); - case PACMAP_DATA_FLOAT: - return ReadFromParcelFloat(parcel); - case PACMAP_DATA_DOUBLE: - return ReadFromParcelDouble(parcel); - case PACMAP_DATA_STRING: - return ReadFromParcelString(parcel); - default: - break; - } - return false; -} - -bool PacMapNodeTypeBase::WriteLong(Parcel &parcel, long value) const -{ - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL_BASE(Int32, parcel, PACMAP_DATA_LONG); - return parcel.WriteBuffer((void *)&value, sizeof(long)); -} - -bool PacMapNodeTypeBase::ReadLong(Parcel &parcel, long &value) -{ - const uint8_t *pdata = parcel.ReadBuffer(sizeof(long)); - if (pdata == nullptr) { - return false; - } - - value = *((long *)pdata); - return true; -} -} // namespace AppExecFwk -} // namespace OHOS diff --git a/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_user_object.cpp b/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_user_object.cpp deleted file mode 100755 index eae831ac3f8..00000000000 --- a/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_user_object.cpp +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ohos/aafwk/base/pac_map_node_user_object.h" -#include -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -PacMapUserObjectLoader &PacMapUserObjectLoader::GetInstance(void) -{ - static PacMapUserObjectLoader gPacMapUserObjectLoader; - return gPacMapUserObjectLoader; -} - -/** - * @brief Registered user-defined serialization class. - * @param objectName The name of the custom class. - * @param createFun Function object that creates an instance of a custom class. - */ -void PacMapUserObjectLoader::RegisterUserObject(const std::string &objectName, const CreateUserMapObject &createFun) -{ - register_class_list_.emplace(objectName, createFun); -} - -/** - * @brief Represents obtaining an instance of an object of a registered serialization class. - * @param className The name of the custom class. - * - * @return Returns an instance of the object, or nullptr on failure. - */ -TUserMapObject *PacMapUserObjectLoader::GetUserObjectByName(const std::string &className) -{ - auto iter = register_class_list_.find(className); - if (iter != register_class_list_.end()) { - return iter->second(); - } else { - return nullptr; - } -} - -PacMapNodeTypeObject::PacMapNodeTypeObject(const PacMapNodeTypeObject &other) : PacMapNode(other) -{ - InnerDeepCopy(&other); -} - -PacMapNodeTypeObject &PacMapNodeTypeObject::operator=(const PacMapNodeTypeObject &other) -{ - if (this != &other) { - object_value_ = other.object_value_; - } - return *this; -} - -/** - * @brief Adds a object to current object. The object must be a subclass of TUserMapObject - * @param value Added object. A smart pointer to a subclass of TUserMapObject. - */ -void PacMapNodeTypeObject::PutObject(const std::shared_ptr &object) -{ - object_value_ = object; -} - -/** - * @brief Obtains the object value. - * @return Returns the smart pointer to subclass of TUserMapObject. - */ -std::shared_ptr PacMapNodeTypeObject::GetObject(void) -{ - return object_value_; -} - -/** - * @brief Indicates whether some other object is "equal to" this one. - * @param other The object with which to compare. - * @return true if this object is the same as the obj argument; false otherwise. - */ -bool PacMapNodeTypeObject::Equals(const PacMapNode *other) -{ - if (other == nullptr) { - return false; - } - - PacMapNode *pnode = const_cast(other); - PacMapNodeTypeObject *other_ = static_cast(pnode); - if (other_ == nullptr) { - return false; - } - - if (object_value_.get() == other_->object_value_.get()) { - return true; - } - - if (object_value_.get() == nullptr || other_->object_value_.get() == nullptr) { - return false; - } - - return object_value_->Equals(other_->object_value_.get()); -} - -/** - * @brief Copy the data of the specified object to the current object with deepcopy - * @param other The original object that stores the data. - */ -void PacMapNodeTypeObject::DeepCopy(const PacMapNode *other) -{ - PacMapNodeTypeObject *object_object = (PacMapNodeTypeObject *)other; - if (object_object != nullptr) { - InnerDeepCopy(object_object); - } -} - -void PacMapNodeTypeObject::InnerDeepCopy(const PacMapNodeTypeObject *other) -{ - if (other == nullptr || other->object_value_ == nullptr) { - return; - } - - TUserMapObject *userObject = - PacMapUserObjectLoader::GetInstance().GetUserObjectByName(other->object_value_.get()->GetClassName()); - if (userObject == nullptr) { - return; - } - - std::shared_ptr user_object(userObject); - user_object->DeepCopy(other->object_value_.get()); - object_value_ = user_object; -} - -/** - * @brief Marshals this Sequenceable object to a Parcel. - * @param key Indicates the key in String format. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Marshals success returns true, otherwise returns false. - */ -bool PacMapNodeTypeObject::Marshalling(const std::string &key, Parcel &parcel) const -{ - if (object_value_ == nullptr) { - return false; - } - - if (!parcel.WriteString16(Str8ToStr16(key))) { - return false; - } - if (!parcel.WriteInt32(PACMAP_DATA_OBJECT)) { - return false; - } - if (!parcel.WriteString16(Str8ToStr16(object_value_->GetClassName()))) { - return false; - } - - return object_value_->Marshalling(parcel); -} - -/** - * @brief Unmarshals this Sequenceable object from a Parcel. - * @param dataType Indicates the type of data stored. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Unmarshals success returns true, otherwise returns false. - */ -bool PacMapNodeTypeObject::Unmarshalling(int32_t dataType, Parcel &parcel) -{ - std::u16string u16ClassName; - std::string className; - // obtains name of class - if (!parcel.ReadString16(u16ClassName)) { - return false; - } - className = Str16ToStr8(u16ClassName); - - std::shared_ptr user_object(PacMapUserObjectLoader::GetInstance().GetUserObjectByName(className)); - if (user_object == nullptr) { - return false; - } - - if (user_object->Unmarshalling(parcel)) { - object_value_ = user_object; - return true; - } - return false; -} -} // namespace AppExecFwk -} // namespace OHOS diff --git a/frameworks/kits/base/cpp/src/ohos/aafwk/base/user_object_wrapper.cpp b/frameworks/kits/base/cpp/src/ohos/aafwk/base/user_object_wrapper.cpp new file mode 100755 index 00000000000..6dd5a591404 --- /dev/null +++ b/frameworks/kits/base/cpp/src/ohos/aafwk/base/user_object_wrapper.cpp @@ -0,0 +1,131 @@ +/* + * 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 "ohos/aafwk/base/user_object_wrapper.h" +#include "ohos/aafwk/base/user_object_base.h" + +namespace OHOS { +namespace AAFwk { +namespace { +const std::string SPLIT = "#"; +}; +IINTERFACE_IMPL_1(UserObject, Object, IUserObject); + +ErrCode UserObject::GetValue(std::shared_ptr &value) +{ + value = value_; + return ERR_OK; +} +bool UserObject::Equals(IObject &other) +{ + if (value_ == nullptr) { + return false; + } + + UserObject *otherObj = static_cast(IUserObject::Query(&other)); + if (value_->GetClassName() == otherObj->value_->GetClassName()) { + return otherObj != nullptr && otherObj->value_->Equals(value_); + } + return false; +} + +std::string UserObject::ToString() +{ + if (value_ == nullptr) { + return std::string(""); + } + return value_->GetClassName() + SPLIT + value_->ToString(); +} + +sptr UserObject::Box(const std::shared_ptr &value) +{ + if (value != nullptr) { + sptr object = new (std::nothrow) UserObject(value); + return object; + } else { + return nullptr; + } +} + +std::shared_ptr UserObject::Unbox(IUserObject *object) +{ + std::shared_ptr value = nullptr; + if (object == nullptr) { + return nullptr; + } + + object->GetValue(value); + return value; +} + +sptr UserObject::Parse(const std::string &str) +{ + std::size_t len = str.length(); + if (len < 1) { + return nullptr; + } + std::size_t splitPos = str.find(SPLIT); + if (splitPos == std::string::npos) { + return nullptr; + } + std::string className = str.substr(0, splitPos); + std::string content = str.substr(className.length() + 1, len - 1); + if (className.length() + SPLIT.length() + content.length() != len) { + return nullptr; + } + + UserObjectBase *userObjectBase = + static_cast(UserObjectBaseLoader::GetInstance().GetUserObjectByName(className)); + if (userObjectBase != nullptr) { + userObjectBase->Parse(content); + sptr ret = new UserObject(std::shared_ptr(userObjectBase)); + return ret; + } + return nullptr; +} + +UserObjectBaseLoader &UserObjectBaseLoader::GetInstance(void) +{ + static UserObjectBaseLoader gUserObjectBaseLoader; + return gUserObjectBaseLoader; +} + +/** + * @brief Registered user-defined serialization class. + * @param objectName The name of the custom class. + * @param createFun Function object that creates an instance of a custom class. + */ +void UserObjectBaseLoader::RegisterUserObject(const std::string &objectName, const CreateUserObjectBase &createFun) +{ + register_class_list_.emplace(objectName, createFun); +} + +/** + * @brief Represents obtaining an instance of an object of a registered serialization class. + * @param className The name of the custom class. + * + * @return Returns an instance of the object, or nullptr on failure. + */ +UserObjectBase *UserObjectBaseLoader::GetUserObjectByName(const std::string &className) +{ + auto iter = register_class_list_.find(className); + if (iter != register_class_list_.end()) { + return iter->second(); + } else { + return nullptr; + } +} + +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/content/cpp/src/ohos/aafwk/content/pac_map.cpp b/frameworks/kits/content/cpp/src/ohos/aafwk/content/pac_map.cpp index 51409dea88d..4f1e5e6d887 100755 --- a/frameworks/kits/content/cpp/src/ohos/aafwk/content/pac_map.cpp +++ b/frameworks/kits/content/cpp/src/ohos/aafwk/content/pac_map.cpp @@ -14,49 +14,176 @@ */ #include "pac_map.h" +#include +#include +#include +#include +#include +#include +#include #include "parcel_macro.h" #include "string_ex.h" +#include "ohos/aafwk/base/array_wrapper.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/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/string_wrapper.h" +#include "ohos/aafwk/base/zchar_wrapper.h" +#include "ohos/aafwk/base/user_object_base.h" +#include "ohos/aafwk/base/user_object_wrapper.h" + +using IUserObject = OHOS::AAFwk::IUserObject; +using InterfaceID = OHOS::AAFwk::InterfaceID; +using Short = OHOS::AAFwk::Short; +using Integer = OHOS::AAFwk::Integer; +using Long = OHOS::AAFwk::Long; +using Boolean = OHOS::AAFwk::Boolean; +using Char = OHOS::AAFwk::Char; +using Byte = OHOS::AAFwk::Byte; +using Float = OHOS::AAFwk::Float; +using Double = OHOS::AAFwk::Double; +using String = OHOS::AAFwk::String; namespace OHOS { namespace AppExecFwk { -#define PAC_MAP_ADD_BASE(id, key, value, mapList) \ - RemoveDataNode(key); \ - std::shared_ptr pnode = std::make_shared(); \ - pnode->Put##id##Value(value); \ - mapList.emplace(key, pnode); - -#define PAC_MAP_ADD_ARRAY(id, key, value, mapList) \ - RemoveDataNode(key); \ - std::shared_ptr pnode = std::make_shared(); \ - pnode->Put##id##ValueArray(value); \ - mapList.emplace(key, pnode); - -#define GET_PAC_MAP_BASE(id, mapList, key, defaultValue) \ - auto it = mapList.find(key); \ - if (it != mapList.end()) { \ - PacMapNodeTypeBase *pBase = static_cast(it->second.get()); \ - if (pBase != nullptr) { \ - return pBase->Get##id##Value(defaultValue); \ - } \ - } \ - return defaultValue; +namespace { +const int FLOAT_PRECISION = 7; +const int DOUBLE_PRECISION = 17; +const std::regex NUMBER_REGEX("^[-+]?([0-9]+)([.]([0-9]+))?$"); +}; // namespace + +#define PAC_MAP_PUT_VALUE(id, iid, key, value, mapList) \ + RemoveData(mapList, key); \ + sptr val = id::Box(value); \ + mapList.emplace(key, val); + +#define PAC_MAP_PUT_FLOAT_VALUE(id, iid, key, value, mapList) \ + RemoveData(mapList, key); \ + sptr val = id::Box(value); \ + mapList.emplace(key, val); + +#define PAC_MAP_GET_VALUE(id, key, value, mapList, defaultValue) \ + auto it = dataList_.find(key); \ + if (it != dataList_.end()) { \ + if (id::Query(it->second.GetRefPtr()) != nullptr) { \ + sptr idValue = id::Query(it->second.GetRefPtr()); \ + value retVal = 0; \ + idValue->GetValue(retVal); \ + return retVal; \ + } \ + return defaultValue; \ + } + +#define PAC_MAP_GET_STRING_VALUE(id, key, value, mapList, defaultValue) \ + auto it = dataList_.find(key); \ + if (it != dataList_.end()) { \ + if (id::Query(it->second.GetRefPtr()) != nullptr) { \ + sptr idValue = id::Query(it->second.GetRefPtr()); \ + std::string retVal; \ + idValue->GetString(retVal); \ + return retVal; \ + } \ + return defaultValue; \ + } -#define GET_PAC_MAP_ARRAY(id, mapList, key, value) \ - auto it = mapList.find(key); \ - if (it != mapList.end()) { \ - PacMapNodeTypeArray *pArray = static_cast(it->second.get()); \ - if (pArray != nullptr) { \ - pArray->Get##id##ValueArray(value); \ - } \ +#define PAC_MAP_ADD_ARRAY(id, key, value, mapList) \ + RemoveData(mapList, key); \ + std::size_t size = value.size(); \ + sptr ao = new Array(size, g_IID_##I##id); \ + for (std::size_t i = 0; i < size; i++) { \ + ao->Set(i, id::Box(value[i])); \ + } \ + mapList.emplace(key, sptr(static_cast(ao.GetRefPtr()))); + +#define GET_PAC_MAP_ARRAY(id, mapList, key, value) \ + auto it = mapList.find(key); \ + if (it != mapList.end()) { \ + if (IArray::Query(it->second.GetRefPtr()) != nullptr) { \ + if (Array::Is##id##Array(IArray::Query(it->second.GetRefPtr()))) { \ + auto func = [&](IInterface *object) { \ + if (I##id::Query(object) != nullptr) { \ + value.push_back(id::Unbox(I##id::Query(object))); \ + } \ + }; \ + Array::ForEach(IArray::Query(it->second.GetRefPtr()), func); \ + } \ + } \ } +#define GET_BASE_DATA_VALUE(id, it, value, json, type) \ + I##id *data = I##id::Query(it->second.GetRefPtr()); \ + value val = 0; \ + data->GetValue(val); \ + json["data"] = val; \ + json["type"] = type; + +#define GET_BASE_FlOAT_DATA_VALUE(iid, it, value, json, type) \ + iid *data = iid::Query(it->second.GetRefPtr()); \ + value val = 0; \ + data->GetValue(val); \ + char buffer[BUFFER_LENGTH] = {0}; \ + int ret = sprintf_s(buffer, sizeof(buffer), "%.6f", val); \ + if (ret == -1) { \ + return false; \ + } \ + json["data"] = std::string(buffer); \ + json["type"] = type; + +#define GET_BASE_FLOAT_DOUBLE_DATA_VALUE(iid, id, it, value, precision, json, type) \ + iid *data = iid::Query(it->second); \ + if (data != nullptr) { \ + value val = id::Unbox(data); \ + json["data"] = RawTypeToString(val, precision); \ + json["type"] = type; \ + } + +#define GET_BASE_STRING_DATA_VALUE(id, it, value, json, type) \ + I##id *data = I##id::Query(it->second.GetRefPtr()); \ + value val; \ + data->GetString(val); \ + json["data"] = val; \ + json["type"] = type; + +#define GET_BASE_LONG_DATA_VALUE(id, it, value, json, type) \ + I##id *data = I##id::Query(it->second.GetRefPtr()); \ + value val = 0; \ + data->GetValue(val); \ + json["data"] = std::to_string(val); \ + json["type"] = type; + +#define PAC_MAP_GET_ARRAY_VAL(idInterface, id, ao, array) \ + if (ao == nullptr) { \ + return false; \ + } \ + if (IArray::Query(it->second.GetRefPtr()) != nullptr) { \ + auto func = [&](AAFwk::IInterface *object) { \ + if (object != nullptr) { \ + idInterface *value = idInterface::Query(object); \ + if (value != nullptr) { \ + array.emplace_back(id::Unbox(value)); \ + } \ + } \ + }; \ + Array::ForEach(IArray::Query(it->second.GetRefPtr()), func); \ + } + +using namespace OHOS::AAFwk; +IINTERFACE_IMPL_1(PacMap, Object, IPacMap); /** * @brief A replication structure with deep copy. */ PacMap::PacMap(const PacMap &other) { - data_list_.clear(); - DeepCopyData(data_list_, other.data_list_); + std::lock_guard mLock(mapLock_); + dataList_.clear(); + std::string str = MapListToString(other.dataList_); + StringToMapList(str, dataList_); } PacMap::~PacMap() @@ -70,7 +197,9 @@ PacMap::~PacMap() PacMap &PacMap::operator=(const PacMap &other) { if (&other != this) { - ShallowCopyData(data_list_, other.data_list_); + dataList_.clear(); + std::string str = MapListToString(other.dataList_); + StringToMapList(str, dataList_); } return *this; } @@ -81,7 +210,7 @@ PacMap &PacMap::operator=(const PacMap &other) void PacMap::Clear(void) { std::lock_guard mLock(mapLock_); - data_list_.clear(); + dataList_.clear(); } /** @@ -93,7 +222,8 @@ PacMap PacMap::Clone(void) { std::lock_guard mLock(mapLock_); PacMap pac_map; - ShallowCopyData(pac_map.data_list_, data_list_); + std::string currentString = MapListToString(dataList_); + StringToMapList(currentString, pac_map.dataList_); return pac_map; } @@ -106,10 +236,18 @@ PacMap PacMap::DeepCopy(void) { std::lock_guard mLock(mapLock_); PacMap pac_map; - DeepCopyData(pac_map.data_list_, data_list_); + std::string str = MapListToString(dataList_); + StringToMapList(str, pac_map.dataList_); return pac_map; } +void PacMap::DeepCopy(PacMap &other) +{ + std::lock_guard mLock(mapLock_); + dataList_.clear(); + StringToMapList(MapListToString(other.dataList_), dataList_); +} + /** * @brief Adds a short value matching a specified key. * @param key A specified key. @@ -118,9 +256,12 @@ PacMap PacMap::DeepCopy(void) void PacMap::PutShortValue(const std::string &key, short value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_BASE(Short, key, value, data_list_); + InnerPutShortValue(dataList_, key, value); +} +void PacMap::InnerPutShortValue(PacMapList &mapList, const std::string &key, short value) +{ + PAC_MAP_PUT_VALUE(Short, IShort, key, value, mapList) } - /** * @brief Adds a integer value matching a specified key. * @param key A specified key. @@ -129,9 +270,12 @@ void PacMap::PutShortValue(const std::string &key, short value) void PacMap::PutIntValue(const std::string &key, int value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_BASE(Int, key, value, data_list_); + InnerPutIntValue(dataList_, key, value); +} +void PacMap::InnerPutIntValue(PacMapList &mapList, const std::string &key, int value) +{ + PAC_MAP_PUT_VALUE(Integer, IInteger, key, value, mapList) } - /** * @brief Adds a long value matching a specified key. * @param key A specified key. @@ -140,9 +284,12 @@ void PacMap::PutIntValue(const std::string &key, int value) void PacMap::PutLongValue(const std::string &key, long value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_BASE(Long, key, value, data_list_); + InnerPutLongValue(dataList_, key, value); +} +void PacMap::InnerPutLongValue(PacMapList &mapList, const std::string &key, long value) +{ + PAC_MAP_PUT_VALUE(Long, ILong, key, value, mapList) } - /** * @brief Adds a boolean value matching a specified key. * @param key A specified key. @@ -151,9 +298,12 @@ void PacMap::PutLongValue(const std::string &key, long value) void PacMap::PutBooleanValue(const std::string &key, bool value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_BASE(Boolean, key, value, data_list_); + InnerPutBooleanValue(dataList_, key, value); +} +void PacMap::InnerPutBooleanValue(PacMapList &mapList, const std::string &key, bool value) +{ + PAC_MAP_PUT_VALUE(Boolean, IBoolean, key, value, mapList) } - /** * @brief Adds a char value matching a specified key. * @param key A specified key. @@ -162,7 +312,11 @@ void PacMap::PutBooleanValue(const std::string &key, bool value) void PacMap::PutCharValue(const std::string &key, char value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_BASE(Char, key, value, data_list_); + InnerPutCharValue(dataList_, key, value); +} +void PacMap::InnerPutCharValue(PacMapList &mapList, const std::string &key, char value) +{ + PAC_MAP_PUT_VALUE(Char, IChar, key, value, mapList) } /** @@ -173,9 +327,12 @@ void PacMap::PutCharValue(const std::string &key, char value) void PacMap::PutByteValue(const std::string &key, AAFwk::byte value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_BASE(Byte, key, value, data_list_); + InnerPutByteValue(dataList_, key, value); +} +void PacMap::InnerPutByteValue(PacMapList &mapList, const std::string &key, AAFwk::byte value) +{ + PAC_MAP_PUT_VALUE(Byte, IByte, key, value, mapList) } - /** * @brief Adds a float value matching a specified key. * @param key A specified key. @@ -184,7 +341,11 @@ void PacMap::PutByteValue(const std::string &key, AAFwk::byte value) void PacMap::PutFloatValue(const std::string &key, float value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_BASE(Float, key, value, data_list_); + InnerPutFloatValue(dataList_, key, value); +} +void PacMap::InnerPutFloatValue(PacMapList &mapList, const std::string &key, float value) +{ + PAC_MAP_PUT_VALUE(Float, IFloat, key, value, mapList) } /** @@ -195,9 +356,12 @@ void PacMap::PutFloatValue(const std::string &key, float value) void PacMap::PutDoubleValue(const std::string &key, double value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_BASE(Double, key, value, data_list_); + InnerPutDoubleValue(dataList_, key, value); +} +void PacMap::InnerPutDoubleValue(PacMapList &mapList, const std::string &key, double value) +{ + PAC_MAP_PUT_VALUE(Double, IDouble, key, value, mapList) } - /** * @brief Adds a string {std::string} value matching a specified key. * @param key A specified key. @@ -206,23 +370,55 @@ void PacMap::PutDoubleValue(const std::string &key, double value) void PacMap::PutStringValue(const std::string &key, const std::string &value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_BASE(String, key, value, data_list_); + InnerPutStringValue(dataList_, key, value); +} +void PacMap::InnerPutStringValue(PacMapList &mapList, const std::string &key, const std::string &value) +{ + PAC_MAP_PUT_VALUE(String, IString, key, value, mapList); } /** - * @brief Adds an object value matching a specified key. The object must be a subclass of TUserMapObject. + * @brief Adds an object value matching a specified key. The object must be a subclass of UserObjectBase. * @param key A specified key. * @param value A smart pointer to the object that matches the specified key. */ -void PacMap::PutObject(const std::string &key, const std::shared_ptr &value) +void PacMap::PutObject(const std::string &key, const std::shared_ptr &value) { + if (value == nullptr) { + return; + } std::lock_guard mLock(mapLock_); - RemoveDataNode(key); - std::shared_ptr pnode = std::make_shared(); - pnode->PutObject(value); - data_list_.emplace(key, pnode); + InnerPutObject(dataList_, key, value); +} +void PacMap::InnerPutObject(PacMapList &mapList, const std::string &key, const std::shared_ptr &value) +{ + RemoveData(mapList, key); + sptr valObject = OHOS::AAFwk::UserObject::Box(value); + if (valObject == nullptr) { + return; + } + mapList.emplace(key, valObject); +} +/** + * @brief Adds an PacMap value matching a specified key. + * @param key A specified key. + * @param value The value that matches the specified key. + */ +bool PacMap::PutPacMap(const std::string &key, const PacMap &value) +{ + std::lock_guard mLock(mapLock_); + return InnerPutPacMap(dataList_, key, const_cast(value)); +} +bool PacMap::InnerPutPacMap(PacMapList &mapList, const std::string &key, PacMap &value) +{ + RemoveData(mapList, key); + sptr pacMap = new (std::nothrow) PacMap(value); + if (pacMap != nullptr) { + mapList.emplace(key, pacMap); + return true; + } + return false; } - /** * @brief Adds some short values matching a specified key. * @param key A specified key. @@ -231,9 +427,12 @@ void PacMap::PutObject(const std::string &key, const std::shared_ptr &value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_ARRAY(Short, key, value, data_list_); + InnerPutShortValueArray(dataList_, key, value); +} +void PacMap::InnerPutShortValueArray(PacMapList &mapList, const std::string &key, const std::vector &value) +{ + PAC_MAP_ADD_ARRAY(Short, key, value, mapList) } - /** * @brief Adds some integer values matching a specified key. * @param key A specified key. @@ -242,9 +441,12 @@ void PacMap::PutShortValueArray(const std::string &key, const std::vector void PacMap::PutIntValueArray(const std::string &key, const std::vector &value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_ARRAY(Integer, key, value, data_list_); + InnerPutIntValueArray(dataList_, key, value); +} +void PacMap::InnerPutIntValueArray(PacMapList &mapList, const std::string &key, const std::vector &value) +{ + PAC_MAP_ADD_ARRAY(Integer, key, value, mapList) } - /** * @brief Adds some long values matching a specified key. * @param key A specified key. @@ -253,9 +455,12 @@ void PacMap::PutIntValueArray(const std::string &key, const std::vector &va void PacMap::PutLongValueArray(const std::string &key, const std::vector &value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_ARRAY(Long, key, value, data_list_); + InnerPutLongValueArray(dataList_, key, value); +} +void PacMap::InnerPutLongValueArray(PacMapList &mapList, const std::string &key, const std::vector &value) +{ + PAC_MAP_ADD_ARRAY(Long, key, value, mapList) } - /** * @brief Adds some boolean values matching a specified key. * @param key A specified key. @@ -264,9 +469,12 @@ void PacMap::PutLongValueArray(const std::string &key, const std::vector & void PacMap::PutBooleanValueArray(const std::string &key, const std::vector &value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_ARRAY(Boolean, key, value, data_list_); + InnerPutBooleanValueArray(dataList_, key, value); +} +void PacMap::InnerPutBooleanValueArray(PacMapList &mapList, const std::string &key, const std::vector &value) +{ + PAC_MAP_ADD_ARRAY(Boolean, key, value, mapList) } - /** * @brief Adds some char values matching a specified key. * @param key A specified key. @@ -275,9 +483,12 @@ void PacMap::PutBooleanValueArray(const std::string &key, const std::vector &value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_ARRAY(Char, key, value, data_list_); + InnerPutCharValueArray(dataList_, key, value); +} +void PacMap::InnerPutCharValueArray(PacMapList &mapList, const std::string &key, const std::vector &value) +{ + PAC_MAP_ADD_ARRAY(Char, key, value, mapList) } - /** * @brief Adds some byte values matching a specified key. * @param key A specified key. @@ -286,9 +497,12 @@ void PacMap::PutCharValueArray(const std::string &key, const std::vector & void PacMap::PutByteValueArray(const std::string &key, const std::vector &value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_ARRAY(Byte, key, value, data_list_); + InnerPutByteValueArray(dataList_, key, value); +} +void PacMap::InnerPutByteValueArray(PacMapList &mapList, const std::string &key, const std::vector &value) +{ + PAC_MAP_ADD_ARRAY(Byte, key, value, mapList) } - /** * @brief Adds some float values matching a specified key. * @param key A specified key. @@ -297,9 +511,12 @@ void PacMap::PutByteValueArray(const std::string &key, const std::vector &value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_ARRAY(Float, key, value, data_list_); + InnerPutFloatValueArray(dataList_, key, value); +} +void PacMap::InnerPutFloatValueArray(PacMapList &mapList, const std::string &key, const std::vector &value) +{ + PAC_MAP_ADD_ARRAY(Float, key, value, mapList) } - /** * @brief Adds some double values matching a specified key. * @param key A specified key. @@ -308,9 +525,12 @@ void PacMap::PutFloatValueArray(const std::string &key, const std::vector void PacMap::PutDoubleValueArray(const std::string &key, const std::vector &value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_ARRAY(Double, key, value, data_list_); + InnerPutDoubleValueArray(dataList_, key, value); +} +void PacMap::InnerPutDoubleValueArray(PacMapList &mapList, const std::string &key, const std::vector &value) +{ + PAC_MAP_ADD_ARRAY(Double, key, value, mapList) } - /** * @brief Adds some string {std::string} values matching a specified key. * @param key A specified key. @@ -319,19 +539,23 @@ void PacMap::PutDoubleValueArray(const std::string &key, const std::vector &value) { std::lock_guard mLock(mapLock_); - PAC_MAP_ADD_ARRAY(String, key, value, data_list_); + InnerPutStringValueArray(dataList_, key, value); +} +void PacMap::InnerPutStringValueArray( + PacMapList &mapList, const std::string &key, const std::vector &value) +{ + PAC_MAP_ADD_ARRAY(String, key, value, mapList) } - /** * @brief Inserts all key-value pairs of a map object into the built-in data object. * Duplicate key values will be replaced. * @param mapData Store a list of key-value pairs. */ -void PacMap::PutAll(const std::map &mapData) +void PacMap::PutAll(std::map &mapData) { std::lock_guard mLock(mapLock_); - data_list_.clear(); - DeepCopyData(data_list_, mapData); + dataList_.clear(); + StringToMapList(MapListToString(mapData), dataList_); } /** @@ -341,8 +565,8 @@ void PacMap::PutAll(const std::map &mapData) void PacMap::PutAll(PacMap &pacMap) { std::lock_guard mLock(mapLock_); - data_list_.clear(); - DeepCopyData(data_list_, pacMap.data_list_); + dataList_.clear(); + StringToMapList(MapListToString(pacMap.dataList_), dataList_); } /** @@ -354,7 +578,8 @@ void PacMap::PutAll(PacMap &pacMap) int PacMap::GetIntValue(const std::string &key, int defaultValue) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_BASE(Integer, data_list_, key, defaultValue); + PAC_MAP_GET_VALUE(IInteger, key, int, dataList_, defaultValue) + return defaultValue; } /** @@ -366,7 +591,8 @@ int PacMap::GetIntValue(const std::string &key, int defaultValue) short PacMap::GetShortValue(const std::string &key, short defaultValue) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_BASE(Short, data_list_, key, defaultValue); + PAC_MAP_GET_VALUE(IShort, key, short, dataList_, defaultValue) + return defaultValue; } /** @@ -378,7 +604,8 @@ short PacMap::GetShortValue(const std::string &key, short defaultValue) bool PacMap::GetBooleanValue(const std::string &key, bool defaultValue) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_BASE(Boolean, data_list_, key, defaultValue); + PAC_MAP_GET_VALUE(IBoolean, key, bool, dataList_, defaultValue) + return defaultValue; } /** @@ -390,7 +617,8 @@ bool PacMap::GetBooleanValue(const std::string &key, bool defaultValue) long PacMap::GetLongValue(const std::string &key, long defaultValue) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_BASE(Long, data_list_, key, defaultValue); + PAC_MAP_GET_VALUE(ILong, key, long, dataList_, defaultValue) + return defaultValue; } /** @@ -402,7 +630,8 @@ long PacMap::GetLongValue(const std::string &key, long defaultValue) char PacMap::GetCharValue(const std::string &key, char defaultValue) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_BASE(Char, data_list_, key, defaultValue); + PAC_MAP_GET_VALUE(IChar, key, zchar, dataList_, defaultValue) + return defaultValue; } /** @@ -414,7 +643,8 @@ char PacMap::GetCharValue(const std::string &key, char defaultValue) AAFwk::byte PacMap::GetByteValue(const std::string &key, AAFwk::byte defaultValue) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_BASE(Byte, data_list_, key, defaultValue); + PAC_MAP_GET_VALUE(IByte, key, byte, dataList_, defaultValue) + return defaultValue; } /** @@ -426,7 +656,8 @@ AAFwk::byte PacMap::GetByteValue(const std::string &key, AAFwk::byte defaultValu float PacMap::GetFloatValue(const std::string &key, float defaultValue) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_BASE(Float, data_list_, key, defaultValue); + PAC_MAP_GET_VALUE(IFloat, key, float, dataList_, defaultValue) + return defaultValue; } /** @@ -438,7 +669,8 @@ float PacMap::GetFloatValue(const std::string &key, float defaultValue) double PacMap::GetDoubleValue(const std::string &key, double defaultValue) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_BASE(Double, data_list_, key, defaultValue); + PAC_MAP_GET_VALUE(IDouble, key, double, dataList_, defaultValue) + return defaultValue; } /** @@ -450,7 +682,8 @@ double PacMap::GetDoubleValue(const std::string &key, double defaultValue) std::string PacMap::GetStringValue(const std::string &key, const std::string &defaultValue) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_BASE(String, data_list_, key, defaultValue); + PAC_MAP_GET_STRING_VALUE(IString, key, std::string, dataList_, defaultValue) + return defaultValue; } /** @@ -461,7 +694,7 @@ std::string PacMap::GetStringValue(const std::string &key, const std::string &de void PacMap::GetIntValueArray(const std::string &key, std::vector &value) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_ARRAY(Integer, data_list_, key, value); + GET_PAC_MAP_ARRAY(Integer, dataList_, key, value) } /** @@ -472,9 +705,8 @@ void PacMap::GetIntValueArray(const std::string &key, std::vector &value) void PacMap::GetShortValueArray(const std::string &key, std::vector &value) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_ARRAY(Short, data_list_, key, value); + GET_PAC_MAP_ARRAY(Short, dataList_, key, value) } - /** * @brief Obtains some boolean values matching a specified key. * @param key A specified key. @@ -483,7 +715,7 @@ void PacMap::GetShortValueArray(const std::string &key, std::vector &valu void PacMap::GetBooleanValueArray(const std::string &key, std::vector &value) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_ARRAY(Boolean, data_list_, key, value); + GET_PAC_MAP_ARRAY(Boolean, dataList_, key, value) } /** @@ -494,7 +726,7 @@ void PacMap::GetBooleanValueArray(const std::string &key, std::vector &val void PacMap::GetLongValueArray(const std::string &key, std::vector &value) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_ARRAY(Long, data_list_, key, value); + GET_PAC_MAP_ARRAY(Long, dataList_, key, value) } /** @@ -505,7 +737,7 @@ void PacMap::GetLongValueArray(const std::string &key, std::vector &value) void PacMap::GetCharValueArray(const std::string &key, std::vector &value) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_ARRAY(Char, data_list_, key, value); + GET_PAC_MAP_ARRAY(Char, dataList_, key, value) } /** @@ -516,7 +748,7 @@ void PacMap::GetCharValueArray(const std::string &key, std::vector &value) void PacMap::GetByteValueArray(const std::string &key, std::vector &value) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_ARRAY(Byte, data_list_, key, value); + GET_PAC_MAP_ARRAY(Byte, dataList_, key, value) } /** @@ -527,7 +759,7 @@ void PacMap::GetByteValueArray(const std::string &key, std::vector void PacMap::GetFloatValueArray(const std::string &key, std::vector &value) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_ARRAY(Float, data_list_, key, value); + GET_PAC_MAP_ARRAY(Float, dataList_, key, value) } /** @@ -538,7 +770,7 @@ void PacMap::GetFloatValueArray(const std::string &key, std::vector &valu void PacMap::GetDoubleValueArray(const std::string &key, std::vector &value) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_ARRAY(Double, data_list_, key, value); + GET_PAC_MAP_ARRAY(Double, dataList_, key, value) } /** @@ -549,7 +781,7 @@ void PacMap::GetDoubleValueArray(const std::string &key, std::vector &va void PacMap::GetStringValueArray(const std::string &key, std::vector &value) { std::lock_guard mLock(mapLock_); - GET_PAC_MAP_ARRAY(String, data_list_, key, value); + GET_PAC_MAP_ARRAY(String, dataList_, key, value) } /** @@ -557,20 +789,39 @@ void PacMap::GetStringValueArray(const std::string &key, std::vector PacMap::GetObject(const std::string &key) +std::shared_ptr PacMap::GetObject(const std::string &key) { std::lock_guard mLock(mapLock_); - auto it = data_list_.find(key); - if (it == data_list_.end()) { + auto it = dataList_.find(key); + if (it == dataList_.end()) { return nullptr; } - PacMapNodeTypeObject *pObject = static_cast(it->second.get()); - if (pObject == nullptr) { - return nullptr; + if (it->second != nullptr) { + if (IUserObject::Query(it->second.GetRefPtr()) != nullptr) { + return UserObject::Unbox(static_cast(it->second.GetRefPtr())); + } } - return pObject->GetObject(); + return nullptr; +} + +/** + * @brief Obtains the PacMap matching a specified key. + * @param key A specified key. + * @return Returns PacMap that matches the key. + */ +PacMap PacMap::GetPacMap(const std::string &key) +{ + std::lock_guard mLock(mapLock_); + PacMap pacmap; + auto it = dataList_.find(key); + if (it != dataList_.end()) { + if (IPacMap::Query(it->second.GetRefPtr()) != nullptr) { + pacmap.DeepCopy(*static_cast(IPacMap::Query(it->second.GetRefPtr()))); + } + } + return pacmap; } /** @@ -578,75 +829,169 @@ std::shared_ptr PacMap::GetObject(const std::string &key) * @return Returns all data in current PacMap. There is no dependency between the returned data and * the original data. */ -std::map PacMap::GetAll(void) +std::map PacMap::GetAll(void) { std::lock_guard mLock(mapLock_); PacMapList tmpMapList; - ShallowCopyData(tmpMapList, this->data_list_); - return tmpMapList; -} + StringToMapList(MapListToString(dataList_), tmpMapList); -void PacMap::DeepCopyData(PacMapList &desPacMapList, const PacMapList &srcPacMapList) -{ - for (auto it = srcPacMapList.begin(); it != srcPacMapList.end(); it++) { - if (it->second->IsBase()) { - std::shared_ptr pac_node = std::make_shared(); - pac_node->DeepCopy(it->second.get()); - desPacMapList.emplace(it->first, pac_node); - } else if (it->second->IsArray()) { - std::shared_ptr pac_node = std::make_shared(); - pac_node->DeepCopy(it->second.get()); - desPacMapList.emplace(it->first, pac_node); - } else if (it->second->IsObject()) { - std::shared_ptr pac_node = std::make_shared(); - pac_node->DeepCopy(it->second.get()); - desPacMapList.emplace(it->first, pac_node); - } - } + return tmpMapList; } -void PacMap::ShallowCopyData(PacMapList &desPacMapList, const PacMapList &srcPacMapList) +void PacMap::ShallowCopyData(PacMapList &desPacMap, const PacMapList &srcPacMap) { - desPacMapList.clear(); - for (auto it = srcPacMapList.begin(); it != srcPacMapList.end(); it++) { - desPacMapList.emplace(it->first, it->second); + desPacMap.clear(); + for (auto it = srcPacMap.begin(); it != srcPacMap.end(); it++) { + desPacMap.emplace(it->first, it->second); } } -void PacMap::RemoveDataNode(const std::string &key) +void PacMap::RemoveData(PacMapList &pacMapList, const std::string &key) { - auto it = data_list_.find(key); - if (it != data_list_.end()) { - data_list_.erase(it); + auto it = pacMapList.find(key); + if (it != pacMapList.end()) { + pacMapList.erase(it); } } bool PacMap::EqualPacMapData(const PacMapList &leftPacMapList, const PacMapList &rightPacMapList) { + if (leftPacMapList.size() != rightPacMapList.size()) { + return false; + } + for (auto right = rightPacMapList.begin(); right != rightPacMapList.end(); right++) { auto left = leftPacMapList.find(right->first); if (left == leftPacMapList.end()) { return false; } + if (left->second.GetRefPtr() == right->second.GetRefPtr()) { + continue; + } + + // PacMap Object + if (IPacMap::Query(right->second.GetRefPtr()) != nullptr) { + auto leftMapIt = leftPacMapList.find(right->first); + if (leftMapIt == leftPacMapList.end()) { + return false; + } + if (IPacMap::Query(leftMapIt->second.GetRefPtr()) == nullptr) { + return false; + } - if (left->second.get() == right->second.get()) { + PacMap *rightMap = static_cast(IPacMap::Query(right->second.GetRefPtr())); + PacMap *leftMap = static_cast(IPacMap::Query(leftMapIt->second.GetRefPtr())); + if (!EqualPacMapData(leftMap->dataList_, rightMap->dataList_)) { + return false; + } continue; } - if (left->second->GetMapNodeTypType() != right->second->GetMapNodeTypType()) { + if (!Object::Equals(*(right->second.GetRefPtr()), *(left->second.GetRefPtr()))) { return false; } + } + return true; +} - if (left->second->Equals(right->second.get())) { - continue; - } else { +template +static void GetArrayData( + AAFwk::IInterface *interface, std::vector &array, std::function IsArrayfunc) +{ + if (interface == nullptr) { + return; + } + if (IsArrayfunc(IArray::Query(interface))) { + auto func = [&](IInterface *object) { array.push_back(id::Unbox(iid::Query(object))); }; + Array::ForEach(IArray::Query(interface), func); + } +} + +template +static bool CompareTwoArrayData( + AAFwk::IInterface *one_interface, AAFwk::IInterface *two_interface, std::function IsArrayfunc) +{ + typename std::vector array; + GetArrayData(IArray::Query(one_interface), array, IsArrayfunc); + + if (!IsArrayfunc(IArray::Query(two_interface))) { + return false; + } + typename std::vector otherArray; + GetArrayData(IArray::Query(two_interface), otherArray, IsArrayfunc); + if (array.size() != 0 && otherArray.size() != 0 && array.size() != otherArray.size()) { + return false; + } + for (std::size_t i = 0; i < array.size(); i++) { + auto it = std::find(otherArray.begin(), otherArray.end(), array[i]); + if (it == array.end()) { return false; } } return true; } +bool PacMap::CompareArrayData(AAFwk::IInterface *one_interface, AAFwk::IInterface *two_interface) +{ + if (IArray::Query(one_interface) != nullptr && IArray::Query(two_interface) != nullptr) { + IArray *array_one = IArray::Query(one_interface); + IArray *array_two = IArray::Query(two_interface); + long size1 = 0; + array_one->GetLength(size1); + long size2 = 0; + array_two->GetLength(size2); + if (size1 != 0 && size2 != 0 && size1 != size2) { + return false; + } + if (AAFwk::Array::IsBooleanArray(IArray::Query(one_interface))) { + if (!CompareTwoArrayData( + one_interface, two_interface, AAFwk::Array::IsBooleanArray)) { + return false; + } + } else if (AAFwk::Array::IsCharArray(AAFwk::IArray::Query(one_interface))) { + return false; + } else if (AAFwk::Array::IsByteArray(IArray::Query(one_interface))) { + if (!CompareTwoArrayData( + one_interface, two_interface, AAFwk::Array::IsByteArray)) { + return false; + } + } else if (AAFwk::Array::IsShortArray(IArray::Query(one_interface))) { + if (!CompareTwoArrayData( + one_interface, two_interface, AAFwk::Array::IsShortArray)) { + return false; + } + } else if (AAFwk::Array::IsIntegerArray(IArray::Query(one_interface))) { + if (!CompareTwoArrayData( + one_interface, two_interface, AAFwk::Array::IsIntegerArray)) { + return false; + } + } else if (AAFwk::Array::IsLongArray(IArray::Query(one_interface))) { + if (!CompareTwoArrayData( + one_interface, two_interface, AAFwk::Array::IsLongArray)) { + return false; + } + } else if (AAFwk::Array::IsFloatArray(IArray::Query(one_interface))) { + if (!CompareTwoArrayData( + one_interface, two_interface, AAFwk::Array::IsFloatArray)) { + return false; + } + } else if (AAFwk::Array::IsDoubleArray(IArray::Query(one_interface))) { + if (!CompareTwoArrayData( + one_interface, two_interface, AAFwk::Array::IsDoubleArray)) { + return false; + } + } else if (AAFwk::Array::IsStringArray(IArray::Query(one_interface))) { + if (!CompareTwoArrayData( + one_interface, two_interface, AAFwk::Array::IsStringArray)) { + return false; + } + } else { + return false; + } + } + return true; +} /** * @brief Indicates whether some other object is "equal to" this one. * @param pacMap The object with which to compare. @@ -663,11 +1008,11 @@ bool PacMap::Equals(const PacMap *pacMap) return true; } - if (data_list_.size() != pacMap->data_list_.size()) { + if (dataList_.size() != pacMap->dataList_.size()) { return false; } - if (!EqualPacMapData(data_list_, pacMap->data_list_)) { + if (!EqualPacMapData(dataList_, pacMap->dataList_)) { return false; } @@ -685,7 +1030,7 @@ bool PacMap::Equals(const PacMap &pacMap) */ bool PacMap::IsEmpty(void) const { - return data_list_.empty(); + return dataList_.empty(); } /** @@ -694,7 +1039,7 @@ bool PacMap::IsEmpty(void) const */ int PacMap::GetSize(void) const { - return data_list_.size(); + return dataList_.size(); } /** @@ -705,7 +1050,7 @@ const std::set PacMap::GetKeys(void) std::lock_guard mLock(mapLock_); std::set keys; - for (auto it = data_list_.begin(); it != data_list_.end(); it++) { + for (auto it = dataList_.begin(); it != dataList_.end(); it++) { keys.emplace(it->first); } return keys; @@ -719,7 +1064,7 @@ const std::set PacMap::GetKeys(void) bool PacMap::HasKey(const std::string &key) { std::lock_guard mLock(mapLock_); - return (data_list_.find(key) != data_list_.end()); + return (dataList_.find(key) != dataList_.end()); } /** @@ -729,160 +1074,665 @@ bool PacMap::HasKey(const std::string &key) void PacMap::Remove(const std::string &key) { std::lock_guard mLock(mapLock_); - auto it = data_list_.find(key); - if (it != data_list_.end()) { - data_list_.erase(it); + auto it = dataList_.find(key); + if (it != dataList_.end()) { + dataList_.erase(it); } } -bool PacMap::WriteBaseToParcel( - const std::string &key, const std::shared_ptr &nodeData, Parcel &parcel) const +bool PacMap::ReadFromParcel(Parcel &parcel) { - PacMapNodeTypeBase *node_base = static_cast(nodeData.get()); - if (node_base == nullptr) { - return false; + std::string value = parcel.ReadString(); + if (!value.empty()) { + return StringToMapList(value, dataList_); + } else { + return true; } - return node_base->Marshalling(key, parcel); } -bool PacMap::WriteArrayToParcel( - const std::string &key, const std::shared_ptr &nodeData, Parcel &parcel) const +/** + * @brief Marshals this Sequenceable object to a Parcel. + * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Marshals success returns true, otherwise returns false. + */ +bool PacMap::Marshalling(Parcel &parcel) const { - PacMapNodeTypeArray *node_array = static_cast(nodeData.get()); - if (node_array == nullptr) { + if (!parcel.WriteString("PACMAP")) { return false; } - return node_array->Marshalling(key, parcel); + std::string str = MapListToString(dataList_); + return parcel.WriteString(str); } -bool PacMap::WriteObjectToParcel( - const std::string &key, const std::shared_ptr &nodeData, Parcel &parcel) const +/** + * @brief Unmarshals this S`nceable object from a Parcel. + * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Unmarshals success returns a smart pointer to PacMap, otherwise returns nullptr. + */ +PacMap *PacMap::Unmarshalling(Parcel &parcel) { - PacMapNodeTypeObject *node_object = static_cast(nodeData.get()); - if (node_object == nullptr) { + std::string value = parcel.ReadString(); + if (value != "PACMAP") { + return nullptr; + } + PacMap *pPacMap = new (std::nothrow) PacMap(); + if (pPacMap != nullptr && !pPacMap->ReadFromParcel(parcel)) { + delete pPacMap; + return nullptr; + } + return pPacMap; +} + +/** + * @brief Object serialization to string. + * @return Returns the serialized string. + */ +std::string PacMap::ToString() +{ + std::lock_guard mLock(mapLock_); + return MapListToString(dataList_); +} + +std::string PacMap::MapListToString(const PacMapList &mapList) const +{ + Json::Value root; + Json::Value dataObject; + + ToJson(mapList, dataObject); + root["pacmap"] = dataObject; + + std::ostringstream os; + Json::StreamWriterBuilder builder; + builder.settings_["indentation"] = ""; + std::unique_ptr jsonWriter(builder.newStreamWriter()); + if (jsonWriter != nullptr) { + jsonWriter->write(root, &os); + return os.str(); + } else { + return std::string(""); + } +} + +bool PacMap::ToJson(const PacMapList &mapList, Json::Value &dataObject) const +{ + bool isOK = false; + for (auto it = mapList.begin(); it != mapList.end(); it++) { + Json::Value item; + isOK = false; + if (IPacMap::Query(it->second.GetRefPtr()) != nullptr) { + PacMap *pacmap = static_cast(IPacMap::Query(it->second.GetRefPtr())); + if (pacmap != nullptr) { + Json::Value item2; + isOK = pacmap->ToJson(pacmap->dataList_, item2); + if (isOK) { + item["type"] = PACMAP_DATA_PACMAP; + item["data"] = item2; + } + } + } else { + isOK = GetBaseJsonValue(it, item); + } + if (isOK) { + dataObject[it->first] = item; + } else { + return false; + } + } + return true; +} +template +static std::string RawTypeToString(const RawType value, unsigned int precisionAfterPoint) +{ + std::ostringstream out; + out.precision(std::numeric_limits::digits10); + out << value; + + std::string res = out.str(); + auto pos = res.find('.'); + if (pos == std::string::npos) + return res; + + auto splitLen = pos + 1 + precisionAfterPoint; + if (res.size() <= splitLen) + return res; + + return res.substr(0, splitLen); +} + +bool PacMap::GetBaseJsonValue(PacMapList::const_iterator &it, Json::Value &json) const +{ + // base data : long =>string + if (IShort::Query(it->second.GetRefPtr()) != nullptr) { + GET_BASE_DATA_VALUE(Short, it, short, json, PACMAP_DATA_SHORT) + } else if (IInteger::Query(it->second.GetRefPtr()) != nullptr) { + GET_BASE_DATA_VALUE(Integer, it, int, json, PACMAP_DATA_INTEGER) + } else if (ILong::Query(it->second.GetRefPtr()) != nullptr) { + // long:string + GET_BASE_LONG_DATA_VALUE(Long, it, long, json, PACMAP_DATA_LONG) + } else if (IChar::Query(it->second.GetRefPtr()) != nullptr) { + GET_BASE_DATA_VALUE(Char, it, zchar, json, PACMAP_DATA_CHAR) + } else if (IByte::Query(it->second.GetRefPtr()) != nullptr) { + GET_BASE_DATA_VALUE(Byte, it, byte, json, PACMAP_DATA_BYTE) + } else if (IBoolean::Query(it->second.GetRefPtr()) != nullptr) { + GET_BASE_DATA_VALUE(Boolean, it, bool, json, PACMAP_DATA_BOOLEAN) + } else if (IFloat::Query(it->second.GetRefPtr()) != nullptr) { + // base long:string + GET_BASE_FLOAT_DOUBLE_DATA_VALUE(IFloat, Float, it, float, FLOAT_PRECISION, json, PACMAP_DATA_FLOAT) + } else if (IDouble::Query(it->second.GetRefPtr()) != nullptr) { + // base :double to string + GET_BASE_FLOAT_DOUBLE_DATA_VALUE(IDouble, Double, it, double, DOUBLE_PRECISION, json, PACMAP_DATA_DOUBLE) + } else if (IString::Query(it->second.GetRefPtr()) != nullptr) { + GET_BASE_STRING_DATA_VALUE(String, it, std::string, json, PACMAP_DATA_STRING) + } else if (IArray::Query(it->second.GetRefPtr()) != nullptr) { + // array data + return GetArrayJsonValue(it, json); + } else if (IUserObject::Query(it->second.GetRefPtr()) != nullptr) { + // Object data [UserObject--data:UserObjectBase] + return GetUserObjectJsonValue(it, json); + } else { return false; } - return node_object->Marshalling(key, parcel); + return true; } -bool PacMap::ReadBaseFromParcel(const std::string &key, int32_t dataType, Parcel &parcel) +// Base data: short +bool PacMap::ToJsonArrayShort(std::vector &array, Json::Value &item, int type) const { - std::shared_ptr pnode = std::make_shared(); - if (pnode->Unmarshalling(dataType, parcel)) { - data_list_.emplace(key, pnode); + if (array.size() > 0) { + for (size_t i = 0; i < array.size(); i++) { + item["data"].append(array[i]); + } + item["type"] = type; return true; } return false; } - -bool PacMap::ReadArrayFromParcel(const std::string &key, int32_t dataType, Parcel &parcel) +// Base data: Integer +bool PacMap::ToJsonArrayInt(std::vector &array, Json::Value &item, int type) const { - std::shared_ptr pnode = std::make_shared(); - if (pnode->Unmarshalling(dataType, parcel)) { - data_list_.emplace(key, pnode); + if (array.size() > 0) { + for (size_t i = 0; i < array.size(); i++) { + item["data"].append(array[i]); + } + item["type"] = type; + return true; + } + return false; +} +// Base data: long:sting +bool PacMap::ToJsonArrayLong(std::vector &array, Json::Value &item, int type) const +{ + if (array.size() > 0) { + for (size_t i = 0; i < array.size(); i++) { + item["data"].append(std::to_string(array[i])); + } + item["type"] = type; return true; } return false; } -bool PacMap::ReadObjectFromParcel(const std::string &key, int32_t dataType, Parcel &parcel) +// Base data: byte +bool PacMap::ToJsonArrayByte(std::vector &array, Json::Value &item, int type) const +{ + if (array.size() > 0) { + for (size_t i = 0; i < array.size(); i++) { + item["data"].append(array[i]); + } + item["type"] = type; + return true; + } + return false; +} +// Base data: bool +bool PacMap::ToJsonArrayBoolean(std::vector &array, Json::Value &item, int type) const +{ + if (array.size() > 0) { + for (size_t i = 0; i < array.size(); i++) { + item["data"].append((int)array[i]); + } + item["type"] = type; + return true; + } + return false; +} +// Base data: Float to string +bool PacMap::ToJsonArrayFloat(std::vector &array, Json::Value &item, int type) const +{ + if (array.size() > 0) { + for (size_t i = 0; i < array.size(); i++) { + item["data"].append(RawTypeToString(array[i], FLOAT_PRECISION)); + } + item["type"] = type; + return true; + } + return false; +} +// Base data: Double to string +bool PacMap::ToJsonArrayDouble(std::vector &array, Json::Value &item, int type) const { - std::shared_ptr pnode = std::make_shared(); - if (pnode->Unmarshalling(dataType, parcel)) { - data_list_.emplace(key, pnode); + if (array.size() > 0) { + for (size_t i = 0; i < array.size(); i++) { + item["data"].append(RawTypeToString(array[i], DOUBLE_PRECISION)); + } + item["type"] = type; + return true; + } + return false; +} +// Base data: string +bool PacMap::ToJsonArrayString(std::vector &array, Json::Value &item, int type) const +{ + if (array.size() > 0) { + for (size_t i = 0; i < array.size(); i++) { + item["data"].append(array[i]); + } + item["type"] = type; return true; } return false; } -bool PacMap::ReadFromParcel(Parcel &parcel) +bool PacMap::GetArrayJsonValue(PacMapList::const_iterator &it, Json::Value &json) const +{ + if (IArray::Query(it->second.GetRefPtr()) == nullptr) { + return false; + } + IArray *array = static_cast(it->second.GetRefPtr()); + if (array == nullptr) { + return false; + } + if (Array::IsShortArray(array)) { + std::vector array; + PAC_MAP_GET_ARRAY_VAL(AAFwk::IShort, AAFwk::Short, it->second.GetRefPtr(), array) + return ToJsonArrayShort(array, json, PACMAP_DATA_ARRAY_SHORT); + } else if (Array::IsIntegerArray(array)) { + std::vector array; + PAC_MAP_GET_ARRAY_VAL(AAFwk::IInteger, AAFwk::Integer, it->second.GetRefPtr(), array) + return ToJsonArrayInt(array, json, PACMAP_DATA_ARRAY_INTEGER); + } else if (Array::IsLongArray(array)) { + std::vector array; + PAC_MAP_GET_ARRAY_VAL(AAFwk::ILong, AAFwk::Long, it->second.GetRefPtr(), array); + return ToJsonArrayLong(array, json, PACMAP_DATA_ARRAY_LONG); + } else if (Array::IsCharArray(array)) { + return false; + } else if (Array::IsByteArray(array)) { + std::vector array; + PAC_MAP_GET_ARRAY_VAL(AAFwk::IByte, AAFwk::Byte, it->second.GetRefPtr(), array); + return ToJsonArrayByte(array, json, PACMAP_DATA_ARRAY_BYTE); + } else if (Array::IsBooleanArray(array)) { + std::vector array; + PAC_MAP_GET_ARRAY_VAL(AAFwk::IBoolean, AAFwk::Boolean, it->second.GetRefPtr(), array); + return ToJsonArrayBoolean(array, json, PACMAP_DATA_ARRAY_BOOLEAN); + } else if (Array::IsFloatArray(array)) { + std::vector array; + PAC_MAP_GET_ARRAY_VAL(AAFwk::IFloat, AAFwk::Float, it->second.GetRefPtr(), array); + return ToJsonArrayFloat(array, json, PACMAP_DATA_ARRAY_FLOAT); + } else if (Array::IsDoubleArray(array)) { + std::vector array; + PAC_MAP_GET_ARRAY_VAL(AAFwk::IDouble, AAFwk::Double, it->second.GetRefPtr(), array); + return ToJsonArrayDouble(array, json, PACMAP_DATA_ARRAY_DOUBLE); + } else if (Array::IsStringArray(array)) { + std::vector array; + PAC_MAP_GET_ARRAY_VAL(AAFwk::IString, AAFwk::String, it->second.GetRefPtr(), array); + return ToJsonArrayString(array, json, PACMAP_DATA_ARRAY_STRING); + } else { + return false; + } + return true; +} +bool PacMap::GetUserObjectJsonValue(PacMapList::const_iterator &it, Json::Value &json) const { - int32_t size; - int32_t data_type; - uint32_t udata_type; + std::shared_ptr myObjectBase = UserObject::Unbox(IUserObject::Query(it->second.GetRefPtr())); + if (myObjectBase == nullptr) { + return false; + } - // read element count - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, size); + std::string userObjectString = myObjectBase->ToString(); + Json::Value objectData; - for (int32_t i = 0; i < size; i++) { - std::string key; - data_type = 0; + json["type"] = PACMAP_DATA_USEROBJECT; + json["class"] = myObjectBase->GetClassName(); + json["data"] = userObjectString; + return true; +} - // read key - key = Str16ToStr8(parcel.ReadString16()); - if (key == "") { - continue; - } +/** + * @brief Restore pacmap from the string. + * @return Return true if successful, otherwise false. + */ +bool PacMap::FromString(const std::string &str) +{ + std::lock_guard mLock(mapLock_); + dataList_.clear(); + return StringToMapList(str, dataList_); +} - // read type of data - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, data_type); +bool PacMap::StringToMapList(const std::string &str, PacMapList &mapList) +{ + if (str.empty()) { + return false; + } - // read data - udata_type = data_type; - if ((udata_type & 0x000000FF) == udata_type) { - if (!ReadBaseFromParcel(key, data_type, parcel)) { - return false; - } - } else if ((udata_type & 0x0000FF00) == udata_type) { - if (!ReadArrayFromParcel(key, data_type, parcel)) { - return false; - } - } else if ((udata_type & 0x00FF0000) == udata_type) { - if (!ReadObjectFromParcel(key, data_type, parcel)) { - return false; - } + JSONCPP_STRING err; + Json::Value root; + + const int rawJsonLength = static_cast(str.length()); + Json::CharReaderBuilder builder; + Json::CharReader *reader(builder.newCharReader()); + if (!reader->parse(str.c_str(), str.c_str() + rawJsonLength, &root, &err)) { + return false; + } + delete reader; + reader = nullptr; + + if (!root.isMember("pacmap")) { + return false; + } + + Json::Value dataObject = root["pacmap"]; + if (dataObject.isNull()) { + return true; + } + return ParseJson(dataObject, mapList); +} + +bool PacMap::ParseJson(Json::Value &data, PacMapList &mapList) +{ + Json::Value::Members keyList = data.getMemberNames(); + if (keyList.size() == 0) { + return false; + } + Json::Value item; + for (size_t i = 0; i < keyList.size(); i++) { + item = data[keyList[i]]; + if (!item.isNull()) { + ParseJsonItem(mapList, keyList[i], item); } } return true; } +bool PacMap::ParseJsonItem(PacMapList &mapList, const std::string &key, Json::Value &item) +{ + // base data, object data, arry data + switch (item["type"].asInt()) { + case PACMAP_DATA_SHORT: + InnerPutShortValue(mapList, key, item["data"].asInt()); + break; + case PACMAP_DATA_INTEGER: + InnerPutIntValue(mapList, key, item["data"].asInt()); + break; + case PACMAP_DATA_LONG: + InnerPutLongValue(mapList, key, std::atol(item["data"].asString().c_str())); + break; + case PACMAP_DATA_CHAR: + InnerPutCharValue(mapList, key, item["data"].asInt()); + break; + case PACMAP_DATA_BYTE: + InnerPutByteValue(mapList, key, item["data"].asInt()); + break; + case PACMAP_DATA_BOOLEAN: + InnerPutBooleanValue(mapList, key, item["data"].asBool()); + break; + case PACMAP_DATA_FLOAT: + InnerPutFloatValue(mapList, key, std::atof(item["data"].asString().c_str())); + break; + case PACMAP_DATA_DOUBLE: + InnerPutDoubleValue(mapList, key, std::atof(item["data"].asString().c_str())); + break; + case PACMAP_DATA_STRING: + InnerPutStringValue(mapList, key, item["data"].asString()); + break; + case PACMAP_DATA_USEROBJECT: + InnerPutObjectValue(mapList, key, item); + break; + case PACMAP_DATA_PACMAP: + InnerPutPacMapValue(mapList, key, item); + break; + default: + return ParseJsonItemArray(mapList, key, item); + } + return true; +} + +bool PacMap::ParseJsonItemArray(PacMapList &mapList, const std::string &key, Json::Value &item) +{ + switch (item["type"].asInt()) { + case PACMAP_DATA_ARRAY_SHORT: + return ParseJsonItemArrayShort(mapList, key, item); + case PACMAP_DATA_ARRAY_INTEGER: + return ParseJsonItemArrayInteger(mapList, key, item); + case PACMAP_DATA_ARRAY_LONG: + return ParseJsonItemArrayLong(mapList, key, item); + case PACMAP_DATA_ARRAY_CHAR: + return ParseJsonItemArrayChar(mapList, key, item); + case PACMAP_DATA_ARRAY_BYTE: + return ParseJsonItemArrayByte(mapList, key, item); + case PACMAP_DATA_ARRAY_BOOLEAN: + return ParseJsonItemArrayBoolean(mapList, key, item); + case PACMAP_DATA_ARRAY_FLOAT: + return ParseJsonItemArrayFloat(mapList, key, item); + case PACMAP_DATA_ARRAY_DOUBLE: + return ParseJsonItemArrayDouble(mapList, key, item); + case PACMAP_DATA_ARRAY_STRING: + return ParseJsonItemArrayString(mapList, key, item); + default: + return false; + } +} + +bool PacMap::ParseJsonItemArrayShort(PacMapList &mapList, const std::string &key, Json::Value &item) +{ + Json::Value arrayValue = item["data"]; + if (arrayValue.isNull()) { + return true; + } + + std::vector shortList; + for (size_t i = 0; i < arrayValue.size(); i++) { + shortList.push_back(arrayValue[i].asInt()); + } + InnerPutShortValueArray(mapList, key, shortList); + return true; +} + +bool PacMap::ParseJsonItemArrayInteger(PacMapList &mapList, const std::string &key, Json::Value &item) +{ + Json::Value arrayValue = item["data"]; + if (arrayValue.isNull()) { + return true; + } + + std::vector intList; + for (size_t i = 0; i < arrayValue.size(); i++) { + intList.push_back(arrayValue[i].asInt()); + } + InnerPutIntValueArray(mapList, key, intList); + return true; +} /** - * @brief Marshals this Sequenceable object to a Parcel. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Marshals success returns true, otherwise returns false. + * @brief Determine whether the string content is a numeric string + * @param str indicates stirng. + * @return bool */ -bool PacMap::Marshalling(Parcel &parcel) const +bool PacMap::IsNumber(const std::string &str) +{ + return std::regex_match(str, NUMBER_REGEX); +} + +bool PacMap::ParseJsonItemArrayLong(PacMapList &mapList, const std::string &key, Json::Value &item) { - // write element count - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, data_list_.size()); + Json::Value arrayValue = item["data"]; - if (IsEmpty()) { + if (arrayValue.isNull()) { return true; } - for (auto it = data_list_.begin(); it != data_list_.end(); it++) { - if (it->second->IsBase()) { - if (!WriteBaseToParcel(it->first, it->second, parcel)) { - return false; - } - } else if (it->second->IsArray()) { - if (!WriteArrayToParcel(it->first, it->second, parcel)) { - return false; - } - } else if (it->second->IsObject()) { - if (!WriteObjectToParcel(it->first, it->second, parcel)) { - return false; - } + std::vector longList; + for (size_t i = 0; i < arrayValue.size(); i++) { + if (!IsNumber(arrayValue[i].asString())) { + return false; } + long longVal = std::atol(arrayValue[i].asString().c_str()); + longList.push_back(longVal); + } + InnerPutLongValueArray(mapList, key, longList); + return true; +} + +bool PacMap::ParseJsonItemArrayChar(PacMapList &mapList, const std::string &key, Json::Value &item) +{ + Json::Value arrayValue = item["data"]; + if (arrayValue.isNull()) { + return true; } + std::vector charList; + for (size_t i = 0; i < arrayValue.size(); i++) { + charList.push_back(arrayValue[i].asInt()); + } + InnerPutCharValueArray(mapList, key, charList); return true; } -/** - * @brief Unmarshals this Sequenceable object from a Parcel. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Unmarshals success returns a smart pointer to PacMap, otherwise returns nullptr. - */ -PacMap *PacMap::Unmarshalling(Parcel &parcel) +bool PacMap::ParseJsonItemArrayByte(PacMapList &mapList, const std::string &key, Json::Value &item) { - PacMap *pPacMap = new (std::nothrow) PacMap(); - if (pPacMap != nullptr && !pPacMap->ReadFromParcel(parcel)) { - delete pPacMap; - return nullptr; + Json::Value arrayValue = item["data"]; + if (arrayValue.isNull()) { + return true; } - return pPacMap; + + std::vector byteList; + for (size_t i = 0; i < arrayValue.size(); i++) { + byteList.push_back(arrayValue[i].asInt()); + } + InnerPutByteValueArray(mapList, key, byteList); + return true; +} + +bool PacMap::ParseJsonItemArrayBoolean(PacMapList &mapList, const std::string &key, Json::Value &item) +{ + Json::Value arrayValue = item["data"]; + if (arrayValue.isNull()) { + return true; + } + + std::vector boolList; + for (size_t i = 0; i < arrayValue.size(); i++) { + boolList.push_back(arrayValue[i].asBool()); + } + InnerPutBooleanValueArray(mapList, key, boolList); + return true; +} + +bool PacMap::ParseJsonItemArrayFloat(PacMapList &mapList, const std::string &key, Json::Value &item) +{ + Json::Value arrayValue = item["data"]; + if (arrayValue.isNull()) { + return true; + } + std::vector floatList; + for (size_t i = 0; i < arrayValue.size(); i++) { + floatList.push_back(std::atof(arrayValue[i].asString().c_str())); + } + InnerPutFloatValueArray(mapList, key, floatList); + return true; +} + +bool PacMap::ParseJsonItemArrayDouble(PacMapList &mapList, const std::string &key, Json::Value &item) +{ + Json::Value arrayValue = item["data"]; + if (arrayValue.isNull()) { + return true; + } + + std::vector doubleList; + for (size_t i = 0; i < arrayValue.size(); i++) { + doubleList.push_back(std::atof(arrayValue[i].asString().c_str())); + } + InnerPutDoubleValueArray(mapList, key, doubleList); + return true; +} + +bool PacMap::ParseJsonItemArrayString(PacMapList &mapList, const std::string &key, Json::Value &item) +{ + Json::Value arrayValue = item["data"]; + if (arrayValue.isNull()) { + return true; + } + + std::vector stringList; + for (size_t i = 0; i < arrayValue.size(); i++) { + stringList.push_back(arrayValue[i].asString()); + } + InnerPutStringValueArray(mapList, key, stringList); + return true; } + +bool PacMap::InnerPutObjectValue(PacMapList &mapList, const std::string &key, Json::Value &item) +{ + std::string className = item["class"].asString(); + if (className.empty()) { + return false; + } + + UserObjectBase *userObjectIns = UserObjectBaseLoader::GetInstance().GetUserObjectByName(className); + if (userObjectIns == nullptr) { + return false; + } + + std::string userObjectString = item["data"].asString(); + if (!userObjectString.empty()) { + userObjectIns->Parse(userObjectString); + } + + std::shared_ptr userObject(userObjectIns); + InnerPutObject(mapList, key, userObject); + return true; +} + +bool PacMap::InnerPutPacMapValue(PacMapList &mapList, const std::string &key, Json::Value &item) +{ + Json::Value value = item["data"]; + + if (value.isNull()) { + return false; + } + PacMap *p = new (std::nothrow) PacMap(); + if (p == nullptr) { + return false; + } + sptr sp = p; + if (p->ParseJson(value, p->dataList_)) { + mapList.emplace(key, sp); + return true; + } + + return false; +} + +bool PacMap::Equals(IObject &other) +{ + PacMap *otherObj = static_cast(IPacMap::Query(&other)); + if (otherObj == nullptr) { + return false; + } + + return Equals(otherObj); +} + +sptr PacMap::Parse(const std::string &str) +{ + PacMap *pacmap = new (std::nothrow) PacMap(); + if (pacmap != nullptr) { + pacmap->StringToMapList(str, pacmap->dataList_); + } + sptr ret = pacmap; + + return ret; +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp index cf72743e482..fc35a719669 100755 --- a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp +++ b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp @@ -48,7 +48,7 @@ const std::string Want::FLAG_HOME_INTENT_FROM_SYSTEM("flag.home.intent.from.syst const std::string Want::OCT_EQUALSTO("075"); // '=' const std::string Want::OCT_SEMICOLON("073"); // ';' const std::string Want::MIME_TYPE("mime-type"); -const std::string Want::WANT_HEADER("#Want;"); +const std::string Want::WANT_HEADER("#Intent;"); /** * @description:Default construcotr of Want class, which is used to initialzie flags and URI. @@ -1159,18 +1159,14 @@ Want *Want::ParseUri(const std::string &uri) if (uri.length() <= 0) { return nullptr; } - std::string head = WANT_HEADER; std::string end = ";end"; - if (uri.find(head) != 0) { return nullptr; } - if (uri.rfind(end) != (uri.length() - end.length())) { return nullptr; } - bool ret = true; std::string content; std::size_t pos; @@ -1180,11 +1176,17 @@ Want *Want::ParseUri(const std::string &uri) if (want == nullptr) { return nullptr; } - + Want *baseWant = want; + bool inPicker = false; pos = uri.find_first_of(";", begin); do { if (pos != std::string::npos) { content = uri.substr(begin, pos - begin); + if (content.compare("PICK") == 0) { + want = new (std::nothrow) Want(); + inPicker = true; + continue; + } ret = ParseUriInternal(content, element, *want); if (!ret) { break; @@ -1198,14 +1200,18 @@ Want *Want::ParseUri(const std::string &uri) break; } } while (true); - + if (inPicker) { + if (baseWant->GetBundle().empty()) { + // baseWant->SetPicker(want); + } + want = baseWant; + } if (ret) { want->SetElement(element); } else { delete want; want = nullptr; } - return want; } @@ -1294,6 +1300,18 @@ std::string Want::WantToUri(Want &want) std::string Want::ToUri() const { std::string uriString = WANT_HEADER; + ToUriStringInner(uriString); + + if (picker_ != nullptr) { + uriString.append("PICK;"); + picker_->ToUriStringInner(uriString); + } + uriString += "end"; + + return uriString; +} +void Want::ToUriStringInner(std::string &uriString) const +{ if (operation_.GetAction().length() > 0) { uriString += "action=" + Encode(operation_.GetAction()) + ";"; } @@ -1305,6 +1323,15 @@ std::string Want::ToUri() const uriString += "entity=" + Encode(entity) + ";"; } } + if (operation_.GetDeviceId().length() > 0) { + uriString += "device=" + Encode(operation_.GetDeviceId()) + ";"; + } + if (operation_.GetBundleName().length() > 0) { + uriString += "bundle=" + Encode(operation_.GetBundleName()) + ";"; + } + if (operation_.GetAbilityName().length() > 0) { + uriString += "ability=" + Encode(operation_.GetAbilityName()) + ";"; + } if (operation_.GetFlags() != 0) { uriString += "flag="; char buf[HEX_STRING_BUF_LEN]{0}; @@ -1315,14 +1342,10 @@ std::string Want::ToUri() const uriString += ";"; } } - if (operation_.GetDeviceId().length() > 0) { - uriString += "device=" + Encode(operation_.GetDeviceId()) + ";"; - } - if (operation_.GetBundleName().length() > 0) { - uriString += "bundle=" + Encode(operation_.GetBundleName()) + ";"; - } - if (operation_.GetAbilityName().length() > 0) { - uriString += "ability=" + Encode(operation_.GetAbilityName()) + ";"; + if (!operation_.GetBundleName().empty()) { + uriString.append("package="); + uriString.append(Encode(operation_.GetBundleName())); + uriString.append(";"); } auto params = parameters_.GetParams(); auto iter = params.cbegin(); @@ -1352,12 +1375,7 @@ std::string Want::ToUri() const uriString += "." + Encode(iter->first) + "=" + Encode(Object::ToString(*(o.GetRefPtr()))) + ";"; iter++; } - - uriString += "end"; - - return uriString; } - /** * @description: Formats a specified URI. * This method uses the Uri.getLowerCaseScheme() method to format a URI and then saves @@ -1688,6 +1706,8 @@ bool Want::ParseUriInternal(const std::string &content, ElementName &element, Wa element.SetBundleName(value); } else if (prop == "ability") { element.SetAbilityName(value); + } else if (prop == "package") { + want.SetBundle(Decode(value)); } else if (prop.length() > TYPE_TAG_SIZE) { std::string key = prop.substr(TYPE_TAG_SIZE); if (!Want::CheckAndSetParameters(want, key, prop, value)) { diff --git a/frameworks/kits/content/cpp/test/BUILD.gn b/frameworks/kits/content/cpp/test/BUILD.gn index eef0ff06d6a..d0883d273b3 100755 --- a/frameworks/kits/content/cpp/test/BUILD.gn +++ b/frameworks/kits/content/cpp/test/BUILD.gn @@ -306,11 +306,7 @@ ohos_unittest("want_params_wrapper_test") { ohos_unittest("want_test") { module_out_path = module_output_path - sources = [ - "../src/ohos/aafwk/content/want.cpp", - "../src/ohos/aafwk/content/want_params.cpp", - "unittest/common/want_test.cpp", - ] + sources = [ "unittest/common/want_test.cpp" ] configs = [ ":module_private_config", diff --git a/frameworks/kits/content/cpp/test/unittest/common/want_params_wrapper_test.cpp b/frameworks/kits/content/cpp/test/unittest/common/want_params_wrapper_test.cpp index 14c364c11dd..c64ec237f10 100755 --- a/frameworks/kits/content/cpp/test/unittest/common/want_params_wrapper_test.cpp +++ b/frameworks/kits/content/cpp/test/unittest/common/want_params_wrapper_test.cpp @@ -152,7 +152,7 @@ HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_0600, Function | MediumTes { auto wantParamsPtr = WantParamWrapper::Box({}); - ASSERT_NE(wantParamsPtr, nullptr); + EXPECT_NE(wantParamsPtr, nullptr); WantParams wantParams; ErrCode result = wantParamsPtr->GetValue(wantParams); diff --git a/frameworks/kits/content/cpp/test/unittest/common/want_test.cpp b/frameworks/kits/content/cpp/test/unittest/common/want_test.cpp index 948899dde41..fa3eb07f180 100755 --- a/frameworks/kits/content/cpp/test/unittest/common/want_test.cpp +++ b/frameworks/kits/content/cpp/test/unittest/common/want_test.cpp @@ -113,7 +113,7 @@ void WantBaseTest::SetUp(void) void WantBaseTest::TearDown(void) {} -const std::string WantBaseTest::URI_STRING_HEAD("#Want;"); +const std::string WantBaseTest::URI_STRING_HEAD("#Intent;"); const std::string WantBaseTest::URI_STRING_END(";end"); /** @@ -126,7 +126,7 @@ HWTEST_F(WantBaseTest, AaExecFwk_Want_Type_0100, Function | MediumTest | Level1) if (want_ != nullptr) { std::string description = "liuuy"; want_->SetType(description); - EXPECT_EQ(description, want_->GetType()); + EXPECT_STREQ(description.c_str(), want_->GetType().c_str()); } } @@ -140,7 +140,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_Action_0100, Function | MediumTest | Level1) if (want_ != nullptr) { std::string actiondescription = "liuuy"; want_->SetAction(actiondescription); - EXPECT_EQ(actiondescription, want_->GetAction()); + EXPECT_STREQ(actiondescription.c_str(), want_->GetAction().c_str()); } } @@ -154,7 +154,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_Bundle_0100, Function | MediumTest | Level1) if (want_ != nullptr) { std::string bundleName = "liuuy"; want_->SetBundle(bundleName); - EXPECT_EQ(bundleName, want_->GetBundle()); + EXPECT_STREQ(bundleName.c_str(), want_->GetBundle().c_str()); } } @@ -1131,10 +1131,6 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_0100, Function | MediumTest | L HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_0200, Function | MediumTest | Level1) { std::string search; - std::size_t pos = 0; - std::size_t length = 0; - std::size_t result = 0; - std::size_t head = 0; std::string action = Want::ACTION_PLAY; std::string entity = Want::ENTITY_VIDEO; @@ -1152,73 +1148,6 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_0200, Function | MediumTest | L wantOrigin.SetElement(element); std::string uri = wantOrigin.ToUri(); - - search = WantBaseTest::URI_STRING_HEAD; - result = uri.find(search, pos); - EXPECT_EQ(result, pos); - if (result != std::string::npos) { - head = result + search.length(); - } - length += head; - - search = std::string("action=") + action + std::string(";"); - result = uri.find(search); - EXPECT_NE(result, std::string::npos); - EXPECT_GE(result, head); - if (result != std::string::npos) { - length += search.length(); - } - - search = std::string("entity=") + entity + std::string(";"); - result = uri.find(search); - EXPECT_NE(result, std::string::npos); - EXPECT_GE(result, head); - if (result != std::string::npos) { - length += search.length(); - } - - search = std::string("flag=") + flagStr + std::string(";"); - result = uri.find(search); - EXPECT_NE(result, std::string::npos); - EXPECT_GE(result, head); - if (result != std::string::npos) { - length += search.length(); - } - - search = std::string("device=") + device + std::string(";"); - result = uri.find(search); - EXPECT_NE(result, std::string::npos); - EXPECT_GE(result, head); - if (result != std::string::npos) { - length += search.length(); - } - - search = std::string("bundle=") + bundle + std::string(";"); - result = uri.find(search); - EXPECT_NE(result, std::string::npos); - EXPECT_GE(result, head); - if (result != std::string::npos) { - length += search.length(); - } - - search = std::string("ability=") + ability + std::string(";"); - result = uri.find(search); - EXPECT_NE(result, std::string::npos); - EXPECT_GE(result, head); - if (result != std::string::npos) { - length += search.length(); - } - - search = WantBaseTest::URI_STRING_END; - result = uri.find(search); - EXPECT_NE(result, std::string::npos); - EXPECT_GE(result, head); - if (result != std::string::npos) { - length += search.length() - 1; - } - - EXPECT_EQ(uri.length(), length); - Want *wantNew = Want::ParseUri(uri); EXPECT_NE(wantNew, nullptr); @@ -1233,6 +1162,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_0200, Function | MediumTest | L EXPECT_EQ(wantNew->GetFlags(), flag); delete wantNew; + wantNew = nullptr; } } @@ -1594,7 +1524,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_0700, Function | MediumTest | L HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_0800, Function | MediumTest | Level1) { std::string empty; - std::string uri = "#Want;action=;entity=;device=;bundle=;ability=;flag=;end"; + std::string uri = "#Intent;action=;entity=;device=;bundle=;ability=;flag=;end"; EXPECT_NE(static_cast(uri.length()), 0); Want *want = Want::ParseUri(uri); @@ -1621,7 +1551,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_0800, Function | MediumTest | L HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_0900, Function | MediumTest | Level1) { std::string empty; - std::string uri = "#Want;action=want.action.VIEW;flag=\"123\";end"; + std::string uri = "#Intent;action=want.action.VIEW;flag=\"123\";end"; EXPECT_NE(static_cast(uri.length()), 0); Want *want = Want::ParseUri(uri); @@ -1635,7 +1565,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_0900, Function | MediumTest | L /** * @tc.number: AaFwk_Want_ParseUri_ToUri_1000 * @tc.name: ParseUri and ToUri - * @tc.desc: Verify the function when head is not "#Want". + * @tc.desc: Verify the function when head is not "#Intent". */ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1000, Function | MediumTest | Level1) { @@ -1659,7 +1589,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1000, Function | MediumTest | L HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1100, Function | MediumTest | Level1) { std::string empty; - std::string uri = "#Want;flag=;end"; + std::string uri = "#Intent;flag=;end"; EXPECT_NE(static_cast(uri.length()), 0); Want *want = Want::ParseUri(uri); @@ -1680,7 +1610,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1200, Function | MediumTest | L { std::string empty; unsigned int flag = 0X12345678; - std::string uri = "#Want;flag=0X12345678;end"; + std::string uri = "#Intent;flag=0X12345678;end"; EXPECT_NE(static_cast(uri.length()), 0); Want *want = Want::ParseUri(uri); @@ -1737,7 +1667,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1300, Function | MediumTest | L */ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1400, Function | MediumTest | Level1) { - std::string uri = "#Want;action;end"; + std::string uri = "#Intent;action;end"; Want *want = Want::ParseUri(uri); EXPECT_EQ(want, nullptr); if (want != nullptr) { @@ -1745,7 +1675,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1400, Function | MediumTest | L want = nullptr; } - uri = "#Want;entity;end"; + uri = "#Intent;entity;end"; want = Want::ParseUri(uri); EXPECT_EQ(want, nullptr); if (want != nullptr) { @@ -1753,7 +1683,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1400, Function | MediumTest | L want = nullptr; } - uri = "#Want;device;end"; + uri = "#Intent;device;end"; want = Want::ParseUri(uri); EXPECT_EQ(want, nullptr); if (want != nullptr) { @@ -1761,7 +1691,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1400, Function | MediumTest | L want = nullptr; } - uri = "#Want;bundle;end"; + uri = "#Intent;bundle;end"; want = Want::ParseUri(uri); EXPECT_EQ(want, nullptr); if (want != nullptr) { @@ -1769,7 +1699,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1400, Function | MediumTest | L want = nullptr; } - uri = "#Want;ability;end"; + uri = "#Intent;ability;end"; want = Want::ParseUri(uri); EXPECT_EQ(want, nullptr); if (want != nullptr) { @@ -1777,7 +1707,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1400, Function | MediumTest | L want = nullptr; } - uri = "#Want;flag;end"; + uri = "#Intent;flag;end"; want = Want::ParseUri(uri); EXPECT_EQ(want, nullptr); if (want != nullptr) { @@ -1785,7 +1715,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1400, Function | MediumTest | L want = nullptr; } - uri = "#Want;param;end"; + uri = "#Intent;param;end"; want = Want::ParseUri(uri); EXPECT_EQ(want, nullptr); if (want != nullptr) { @@ -1793,7 +1723,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1400, Function | MediumTest | L want = nullptr; } - uri = "#Want;=;end"; + uri = "#Intent;=;end"; want = Want::ParseUri(uri); EXPECT_NE(want, nullptr); if (want != nullptr) { @@ -1801,7 +1731,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1400, Function | MediumTest | L want = nullptr; } - uri = "#Want;abc=;end"; + uri = "#Intent;abc=;end"; want = Want::ParseUri(uri); EXPECT_NE(want, nullptr); if (want != nullptr) { @@ -1809,7 +1739,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1400, Function | MediumTest | L want = nullptr; } - uri = "#Want;=abc;end"; + uri = "#Intent;=abc;end"; want = Want::ParseUri(uri); EXPECT_NE(want, nullptr); if (want != nullptr) { @@ -1817,7 +1747,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1400, Function | MediumTest | L want = nullptr; } - uri = "#Want;xxxx=yyy;end"; + uri = "#Intent;xxxx=yyy;end"; want = Want::ParseUri(uri); EXPECT_NE(want, nullptr); if (want != nullptr) { @@ -1825,7 +1755,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_ParseUri_ToUri_1400, Function | MediumTest | L want = nullptr; } - uri = "#Want;;;;;;end"; + uri = "#Intent;;;;;;end"; want = Want::ParseUri(uri); EXPECT_NE(want, nullptr); if (want != nullptr) { @@ -3882,7 +3812,7 @@ HWTEST_F(WantBaseTest, AaFwk_Want_HasParameter_0100, Function | MediumTest | Lev */ HWTEST_F(WantBaseTest, AaFwk_Want_HasParameter_0200, Function | MediumTest | Level1) { - std::string key = std::to_string(Array::SIGNATURE) + ".#Want;key=3{\"\\b\\\";end"; + std::string key = std::to_string(Array::SIGNATURE) + ".#Intent;key=3{\"\\b\\\";end"; std::vector arrayValue = {'.', '=', ';'}; std::shared_ptr p1 = std::make_shared(); if (p1 == nullptr) { diff --git a/frameworks/kits/test/BUILD.gn b/frameworks/kits/test/BUILD.gn index d8aa70497a0..ae4868271da 100755 --- a/frameworks/kits/test/BUILD.gn +++ b/frameworks/kits/test/BUILD.gn @@ -38,6 +38,7 @@ config("module_private_config") { "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include", "//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility", "//foundation/aafwk/standard/services/abilitymgr/include", + "//third_party/jsoncpp/include", ] } @@ -50,6 +51,7 @@ ohos_moduletest("ability_moduletest") { "//foundation/aafwk/standard/frameworks/kits/test/mock/AMS/mock_ability_manager_service.cpp", "//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility/demo_ability_test.cpp", "//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility/mock_lifecycle_observer.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/aafwk_dummy_configuration.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_connect_callback_stub.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_proxy.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_stub.cpp", @@ -61,11 +63,13 @@ ohos_moduletest("ability_moduletest") { "//foundation/aafwk/standard/services/abilitymgr/src/image_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/lifecycle_state_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/mission_description_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/mission_option.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/mission_record_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/mission_snapshot_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/mission_stack_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/sender_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/stack_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/stack_setting.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/want_sender_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/wants_info.cpp", "moduletest/cpp/abilitytest/ability_test.cpp", @@ -90,6 +94,7 @@ ohos_moduletest("ability_moduletest") { "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] @@ -108,6 +113,7 @@ ohos_moduletest("ability_conetxt_test") { "//foundation/aafwk/standard/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.cpp", "//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility/demo_ability_test.cpp", "//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility/mock_lifecycle_observer.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/aafwk_dummy_configuration.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_connect_callback_stub.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_proxy.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_stub.cpp", @@ -143,6 +149,7 @@ ohos_moduletest("ability_conetxt_test") { "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] @@ -163,6 +170,7 @@ ohos_moduletest("data_ability_operation_moduletest") { "//foundation/aafwk/standard/frameworks/kits/test/mock/AMS/mock_ability_manager_service.cpp", "//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility/demo_ability_test.cpp", "//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility/mock_lifecycle_observer.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/aafwk_dummy_configuration.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_connect_callback_stub.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_proxy.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_stub.cpp", @@ -204,6 +212,7 @@ ohos_moduletest("data_ability_operation_moduletest") { "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] @@ -213,6 +222,46 @@ ohos_moduletest("data_ability_operation_moduletest") { ] } +ohos_moduletest("data_ability_helper_module_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility", + "//foundation/aafwk/standard/frameworks/kits/test/mock/DemoObServer", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include", + "//foundation/aafwk/standard/services/dataobsmgr/include", + "//foundation/aafwk/standard/interfaces/innerkits/dataobs_manager/include", + "//foundation/distributedschedule/samgr/services/samgr/native/include", + "//foundation/communication/ipc/interfaces/innerkits/libdbinder/include", + ] + + sources = [ "//foundation/aafwk/standard/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_helper_module_test.cpp" ] + + configs = [ + ":module_private_config", + "//foundation/aafwk/standard/interfaces/innerkits/want:want_public_config", + "//foundation/aafwk/standard/frameworks/kits/ability/native:ability_config", + ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + ################################################################################ group("moduletest") { testonly = true @@ -223,6 +272,7 @@ group("moduletest") { deps += [ ":ability_conetxt_test", ":ability_moduletest", + ":data_ability_helper_module_test", ":data_ability_operation_moduletest", ] } diff --git a/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h b/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h index 286c4445cc2..1d1f45d272a 100644 --- a/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h +++ b/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h @@ -78,6 +78,18 @@ public: MOCK_METHOD2(RegisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(UnregisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); + MOCK_METHOD4(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode)); + MOCK_METHOD1(MoveMissionToFloatingStack, int(const MissionOption &missionOption)); + MOCK_METHOD1(MoveMissionToSplitScreenStack, int(const MissionOption &missionOption)); + MOCK_METHOD2( + ChangeFocusAbility, int(const sptr &lostFocusToken, const sptr &getFocusToken)); + MOCK_METHOD1(MinimizeMultiWindow, int(int missionId)); + MOCK_METHOD1(MaximizeMultiWindow, int(int missionId)); + MOCK_METHOD1(GetFloatingMissions, int(std::vector &list)); + MOCK_METHOD1(CloseMultiWindow, int(int missionId)); + MOCK_METHOD1(SetMissionStackSetting, int(const StackSetting &stackSetting)); + MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id)); int MoveMissionToEnd(const sptr &token, const bool nonFirst) override; bool IsFirstInMission(const sptr &token) override; @@ -111,6 +123,11 @@ public: return 0; } + int UpdateConfiguration(const DummyConfiguration &config) + { + return 0; + } + AbilityLifeCycleState curstate_ = AbilityLifeCycleState::ABILITY_STATE_INITIAL; sptr abilityScheduler_; // kit interface used to schedule ability life Want want_; diff --git a/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.h b/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.h index 9db181de247..7fea6a0c2db 100644 --- a/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.h +++ b/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.h @@ -74,6 +74,18 @@ public: MOCK_METHOD2(RegisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(UnregisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); + MOCK_METHOD4(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode)); + MOCK_METHOD1(MoveMissionToFloatingStack, int(const MissionOption &missionOption)); + MOCK_METHOD1(MoveMissionToSplitScreenStack, int(const MissionOption &missionOption)); + MOCK_METHOD2( + ChangeFocusAbility, int(const sptr &lostFocusToken, const sptr &getFocusToken)); + MOCK_METHOD1(MinimizeMultiWindow, int(int missionId)); + MOCK_METHOD1(MaximizeMultiWindow, int(int missionId)); + MOCK_METHOD1(GetFloatingMissions, int(std::vector &list)); + MOCK_METHOD1(CloseMultiWindow, int(int missionId)); + MOCK_METHOD1(SetMissionStackSetting, int(const StackSetting &stackSetting)); + MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id)); int MoveMissionToEnd(const sptr &token, const bool nonFirst) override; bool IsFirstInMission(const sptr &token) override; @@ -101,6 +113,10 @@ public: { return 0; } + int UpdateConfiguration(const DummyConfiguration &config) + { + return 0; + } sptr AcquireDataAbility( const Uri &uri, bool tryBind, const sptr &callerToken) override diff --git a/frameworks/kits/test/mock/DemoAbility/mock_ability_test.h b/frameworks/kits/test/mock/DemoAbility/mock_ability_test.h new file mode 100644 index 00000000000..e5c102a2843 --- /dev/null +++ b/frameworks/kits/test/mock/DemoAbility/mock_ability_test.h @@ -0,0 +1,109 @@ +/* + * 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 MOCK_ABILITY_TEST_H +#define MOCK_ABILITY_TEST_H + +#include "gmock/gmock.h" + +#include "ability.h" +#include "ability_loader.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { + +class MockAbilityTest : public Ability { +public: + + int Insert(const Uri &uri, const ValuesBucket &value) + { + GTEST_LOG_(INFO) << "MockAbilityTest::Insert called"; + return 20; + } + int Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) + { + GTEST_LOG_(INFO) << "MockAbilityTest::Update called"; + return 33; + } + + std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) + { + std::vector result; + result.push_back("Type1"); + result.push_back("Type2"); + result.push_back("Type3"); + return result; + } + + int OpenFile(const Uri &uri, const std::string &mode) + { + int fd; + GTEST_LOG_(INFO) << "MockAbilityTest::OpenFile called"; + FILE *fd1 = fopen("/test/te.txt", "r"); + fd = fileno(fd1); + + return fd; + } + + int OpenRawFile(const Uri &uri, const std::string &mode) + { + GTEST_LOG_(INFO) << "MockAbilityTest::OpenRawFile called"; + + return 122; + } + + int BatchInsert(const Uri &uri, const std::vector &values) + { + GTEST_LOG_(INFO) << "MockAbilityTest::BatchInsert called"; + return 115; + } + + bool Reload(const Uri &uri, const PacMap &extras) + { + GTEST_LOG_(INFO) << "MockAbilityTest::Reload called"; + return true; + } + + int Delete(const Uri &uri, const DataAbilityPredicates &predicates) + { + GTEST_LOG_(INFO) << "MockAbilityTest::Delete called"; + return 234; + } + + std::string GetType(const Uri &uri) + { + GTEST_LOG_(INFO) << "MockAbilityTest::GetType called"; + std::string type("Type1"); + return type; + } + + Uri NormalizeUri(const Uri &uri) + { + GTEST_LOG_(INFO) << "MockAbilityTest::NormalizeUri called"; + return uri; + } + + Uri DenormalizeUri(const Uri &uri) + { + GTEST_LOG_(INFO) << "MockAbilityTest::DenormalizeUri called"; + return uri; + } + +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // MOCK_ABILITY_TEST_H \ No newline at end of file diff --git a/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node.cpp b/frameworks/kits/test/mock/DemoObServer/mock_ability_hancle_for_data_observer.h similarity index 64% rename from frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node.cpp rename to frameworks/kits/test/mock/DemoObServer/mock_ability_hancle_for_data_observer.h index cde2688ccd4..7c00c904308 100644 --- a/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node.cpp +++ b/frameworks/kits/test/mock/DemoObServer/mock_ability_hancle_for_data_observer.h @@ -12,25 +12,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef MOCK_ABILIT_HANCLDE_FOR_DATA_OBSERVER_H +#define MOCK_ABILIT_HANCLDE_FOR_DATA_OBSERVER_H -#include "ohos/aafwk/base/pac_map_node.h" +#include + +#include "gtest/gtest.h" + +#include "event_handler.h" namespace OHOS { namespace AppExecFwk { -/** - * @brief A constructor data. - */ -PacMapNode::PacMapNode(const PacMapNode &other) -{ - data_type_ = other.data_type_; -} -PacMapNode &PacMapNode::operator=(const PacMapNode &other) +bool EventHandler::SendEvent(InnerEvent::Pointer &event, int64_t delayTime, Priority priority) { - if (this != &other) { - data_type_ = other.data_type_; - } - return *this; + auto callback = event->GetTaskCallback(); + callback(); + return true; } + } // namespace AppExecFwk } // namespace OHOS + +#endif // MOCK_ABILIT_HANCLDE_FOR_DATA_OBSERVER_H \ No newline at end of file diff --git a/frameworks/kits/test/mock/DemoObServer/mock_ability_manager_client.h b/frameworks/kits/test/mock/DemoObServer/mock_ability_manager_client.h new file mode 100644 index 00000000000..46ed31af3bd --- /dev/null +++ b/frameworks/kits/test/mock/DemoObServer/mock_ability_manager_client.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MOCK_ABILITY_MANAGER_CLIENT_H +#define MOCK_ABILITY_MANAGER_CLIENT_H + +#include +#include + +#include "gtest/gtest.h" + +#include "ability_manager_client.h" +#include "ability_scheduler_proxy.h" + +#include +#include + +#include "mock_ability_thread_for_data_observer.h" + +namespace OHOS { +namespace AAFwk { + +class DemoAbilityManagerClientData { +public: + DemoAbilityManagerClientData(){}; + virtual ~DemoAbilityManagerClientData(){}; + + std::map> data; +}; + +static DemoAbilityManagerClientData demoAbilityMgrClientData; + +sptr AAFwk::AbilityManagerClient::AcquireDataAbility( + const Uri &uri, bool tryBind, const sptr &callerToken) +{ + sptr retval = nullptr; + auto iter = demoAbilityMgrClientData.data.find(uri.ToString()); + if (iter == demoAbilityMgrClientData.data.end()) { + GTEST_LOG_(INFO) << "mock_ability_manager_client:find data is null called"; + sptr abilityThread = AppExecFwk::MockCreateAbilityThread(); + sptr remoteProxy(new (std::nothrow) AAFwk::AbilitySchedulerProxy(abilityThread)); + demoAbilityMgrClientData.data.emplace(uri.ToString(), remoteProxy); + + retval = remoteProxy; + + if(retval == nullptr) + { + GTEST_LOG_(INFO) << "mock_ability_thread_for_data_observer:mock result retval is nullptr called"; + } + } else { + retval = iter->second; + GTEST_LOG_(INFO) << "mock_ability_manager_client:find data is not null called"; + } + + return retval; +} + +ErrCode AbilityManagerClient::ReleaseDataAbility( + sptr dataAbilityScheduler, const sptr &callerToken) +{ + return ERR_OK; +} + + + +} // namespace AAFwk +} // namespace OHOS + +#endif // MOCK_ABILITY_MANAGER_CLIENT_H diff --git a/frameworks/kits/test/mock/DemoObServer/mock_ability_thread_for_data_observer.h b/frameworks/kits/test/mock/DemoObServer/mock_ability_thread_for_data_observer.h new file mode 100644 index 00000000000..9c172586303 --- /dev/null +++ b/frameworks/kits/test/mock/DemoObServer/mock_ability_thread_for_data_observer.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MOCK_ABILITY_THREAD_FOR_DATA_OBSERVER_H +#define MOCK_ABILITY_THREAD_FOR_DATA_OBSERVER_H + +#include +#include + +#include "gtest/gtest.h" + +#include "mock_ability_test.h" +#include "ohos_application.h" +#include "ability_thread.h" +#include "event_runner.h" +#include "ability_info.h" +#include "ability_local_record.h" +#include // +namespace OHOS { +namespace AppExecFwk { + +sptr MockCreateAbilityThread() +{ + sptr abilitythread(new (std::nothrow) AppExecFwk::AbilityThread()); + if(abilitythread == nullptr) + { + GTEST_LOG_(INFO) << "mock_ability_thread_for_data_observer:mock abilityhreadptr is nullptr called"; + } + + std::shared_ptr application = std::make_shared(); + if(application == nullptr) + { + GTEST_LOG_(INFO) << "mock_ability_thread_for_data_observer:mock applicationptr is nullptr called"; + } + + std::shared_ptr info = std::make_shared(); + if(info == nullptr) + { + GTEST_LOG_(INFO) << "mock_ability_thread_for_data_observer:mock AbilityInfo::info is nullptr called"; + } + + info->name = std::string("MockAbilityTest"); + info->type = AbilityType::DATA; + info->isNativeAbility = true; + std::cout << "info->name : " << (*info).name <type : " << (*info).type. < token = sptr(new AbilityThread()); + + std::shared_ptr abilityRecord = std::make_shared(info, token); + std::shared_ptr mainRunner = EventRunner::Create(info->name); + + abilitythread->Attach(application, abilityRecord, mainRunner); + + return abilitythread; +} + +} // namespace AppExecFwk +} // namespace OHOS +#endif // MOCK_ABILITY_THREAD_FOR_DATA_OBSERVER_H \ No newline at end of file diff --git a/frameworks/kits/test/moduletest/cpp/abilitytest/ability_test.cpp b/frameworks/kits/test/moduletest/cpp/abilitytest/ability_test.cpp index 1eb7a02f513..c0cfad0fdf7 100755 --- a/frameworks/kits/test/moduletest/cpp/abilitytest/ability_test.cpp +++ b/frameworks/kits/test/moduletest/cpp/abilitytest/ability_test.cpp @@ -864,665 +864,6 @@ HWTEST_F(AbilityTerminateTest, AaFwk_WMS_window_test_0200, Function | MediumTest GTEST_LOG_(INFO) << "AaFwk_WMS_window_test_002 TerminateAbility"; } -/** - * @tc.number: AaFwk_DataAbility_GetFileTypes_0100 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the file types in the dataability. - - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_GetFileTypes_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_GetFileTypes_0100"; - - std::shared_ptr application = std::make_shared(); - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->type = AppExecFwk::AbilityType::DATA; - abilityInfo->name = "DemoAbility"; - std::shared_ptr abilityRecord = - std::make_shared(abilityInfo, abilityToken); - - AbilityThread::AbilityThreadMain(application, abilityRecord); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::string mimeTypeFilter("mimeTypeFiltertest"); - std::vector result = helper->GetFileTypes(uri2, mimeTypeFilter); - - int count = result.size(); - EXPECT_EQ(count, 3); - - std::vector list; - list.push_back("Type1"); - list.push_back("Type2"); - list.push_back("Type3"); - - for (int i = 0; i < count; i++) { - EXPECT_STREQ(result.at(i).c_str(), list.at(i).c_str()); - } - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_GetFileTypes_0100"; -} - -/** - * @tc.number: AaFwk_DataAbility_GetFileTypes_0200 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the file types in the dataability failed without abilityimpl. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_GetFileTypes_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_GetFileTypes_0200"; - - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - sptr thread = sptr(new AbilityThread()); - EXPECT_NE(thread, nullptr); - if (thread != nullptr) { - AbilityManagerClient::GetInstance()->AttachAbilityThread(thread, abilityToken); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = - std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::string mimeTypeFilter("mimeTypeFiltertest"); - std::vector result = helper->GetFileTypes(uri2, mimeTypeFilter); - - int count = result.size(); - EXPECT_EQ(count, 0); - } - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_GetFileTypes_0200"; -} - -/** - * @tc.number: AaFwk_DataAbility_OpenFile_0100 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the fd in the dataability. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_OpenFile_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_OpenFile_0100"; - - std::shared_ptr application = std::make_shared(); - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->type = AppExecFwk::AbilityType::DATA; - abilityInfo->name = "DemoAbility"; - std::shared_ptr abilityRecord = - std::make_shared(abilityInfo, abilityToken); - - AbilityThread::AbilityThreadMain(application, abilityRecord); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::string mode("modetest"); - int fd = helper->OpenFile(uri2, mode); - - EXPECT_EQ(fd, 123); - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_OpenFile_0100"; -} - -/** - * @tc.number: AaFwk_DataAbility_OpenFile_0200 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the fd in the dataability failed without abilityimpl. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_OpenFile_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_OpenFile_0200"; - - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - sptr thread = sptr(new AbilityThread()); - EXPECT_NE(thread, nullptr); - if (thread != nullptr) { - AbilityManagerClient::GetInstance()->AttachAbilityThread(thread, abilityToken); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = - std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::string mode("modetest"); - int fd = helper->OpenFile(uri2, mode); - - EXPECT_EQ(fd, -1); - } - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_OpenFile_0200"; -} - -/** - * @tc.number: AaFwk_DataAbility_OpenRawFile_0100 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the fd in the dataability. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_OpenRawFile_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_OpenRawFile_0100"; - - std::shared_ptr application = std::make_shared(); - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->type = AppExecFwk::AbilityType::DATA; - abilityInfo->name = "DemoAbility"; - std::shared_ptr abilityRecord = - std::make_shared(abilityInfo, abilityToken); - - AbilityThread::AbilityThreadMain(application, abilityRecord); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::string mode("modetest"); - int fd = helper->OpenRawFile(uri2, mode); - - EXPECT_EQ(fd, 567); - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_OpenRawFile_0100"; -} - -/** - * @tc.number: AaFwk_DataAbility_OpenRawFile_0200 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the fd in the dataability failed without abilityimpl. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_OpenRawFile_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_OpenRawFile_0200"; - - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - sptr thread = sptr(new AbilityThread()); - EXPECT_NE(thread, nullptr); - if (thread != nullptr) { - AbilityManagerClient::GetInstance()->AttachAbilityThread(thread, abilityToken); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = - std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::string mode("modetest"); - int fd = helper->OpenRawFile(uri2, mode); - - EXPECT_EQ(fd, -1); - } - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_OpenRawFile_0200"; -} - -/** - * @tc.number: AaFwk_DataAbility_BatchInsert_0100 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the ret in the dataability. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_BatchInsert_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_BatchInsert_001"; - - std::shared_ptr application = std::make_shared(); - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->type = AppExecFwk::AbilityType::DATA; - abilityInfo->name = "DemoAbility"; - std::shared_ptr abilityRecord = - std::make_shared(abilityInfo, abilityToken); - - AbilityThread::AbilityThreadMain(application, abilityRecord); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::vector values; - int fd = helper->BatchInsert(uri2, values); - - EXPECT_EQ(fd, 789); - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_BatchInsert_001"; -} - -/** - * @tc.number: AaFwk_DataAbility_BatchInsert_0200 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the ret in the dataability failed without abilityimpl. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_BatchInsert_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_BatchInsert_0200"; - - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - sptr thread = sptr(new AbilityThread()); - EXPECT_NE(thread, nullptr); - if (thread != nullptr) { - AbilityManagerClient::GetInstance()->AttachAbilityThread(thread, abilityToken); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = - std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::vector values; - int fd = helper->BatchInsert(uri2, values); - - EXPECT_EQ(fd, -1); - } - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_BatchInsert_0200"; -} - -/** - * @tc.number: AaFwk_DataAbility_Reload_0100 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the ret in the dataability. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_Reload_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Reload_0100"; - - std::shared_ptr application = std::make_shared(); - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->type = AppExecFwk::AbilityType::DATA; - abilityInfo->name = "DemoAbility"; - std::shared_ptr abilityRecord = - std::make_shared(abilityInfo, abilityToken); - - AbilityThread::AbilityThreadMain(application, abilityRecord); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - PacMap extras; - int fd = helper->Reload(uri2, extras); - - EXPECT_EQ(fd, true); - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Reload_0100"; -} - -/** - * @tc.number: AaFwk_DataAbility_Reload_0200 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the ret in the dataability failed without abilityimpl. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_Reload_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Reload_002"; - - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - sptr thread = sptr(new AbilityThread()); - EXPECT_NE(thread, nullptr); - if (thread != nullptr) { - AbilityManagerClient::GetInstance()->AttachAbilityThread(thread, abilityToken); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = - std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - PacMap extras; - int fd = helper->Reload(uri2, extras); - - EXPECT_EQ(fd, false); - } - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Reload_002"; -} - -/** - * @tc.number: AaFwk_DataAbility_Update_0100 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the number of data records updated in the dataability. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_Update_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Update_0100"; - - std::shared_ptr application = std::make_shared(); - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->type = AppExecFwk::AbilityType::DATA; - abilityInfo->name = "DemoAbility"; - std::shared_ptr abilityRecord = - std::make_shared(abilityInfo, abilityToken); - - AbilityThread::AbilityThreadMain(application, abilityRecord); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - ValuesBucket val("valtest"); - DataAbilityPredicates predicates("predicatestest"); - int index = helper->Update(uri2, val, predicates); - - EXPECT_EQ(index, 456); - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Update_0100"; -} - -/** - * @tc.number: AaFwk_DataAbility_Update_0200 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the number of data records updated in the dataability failed without abilityimpl. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_Update_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Update_0200"; - - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - sptr thread = sptr(new AbilityThread()); - EXPECT_NE(thread, nullptr); - if (thread != nullptr) { - AbilityManagerClient::GetInstance()->AttachAbilityThread(thread, abilityToken); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = - std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - ValuesBucket val("valtest"); - DataAbilityPredicates predicates("predicatestest"); - int index = helper->Update(uri2, val, predicates); - - EXPECT_EQ(index, -1); - } - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Update_0200"; -} - -/** - * @tc.number: AaFwk_DataAbility_Delete_0100 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the number of data records deleted in the dataability. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_Delete_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Delete_0100"; - - std::shared_ptr application = std::make_shared(); - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->type = AppExecFwk::AbilityType::DATA; - abilityInfo->name = "DemoAbility"; - std::shared_ptr abilityRecord = - std::make_shared(abilityInfo, abilityToken); - - AbilityThread::AbilityThreadMain(application, abilityRecord); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - DataAbilityPredicates predicates("predicatestest"); - int index = helper->Delete(uri2, predicates); - - EXPECT_EQ(index, 234); - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Delete_0100"; -} - -/** - * @tc.number: AaFwk_DataAbility_Delete_0200 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the number of data records deleted in the dataability failed without abilityimpl. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_Delete_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Delete_0200"; - - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - sptr thread = sptr(new AbilityThread()); - EXPECT_NE(thread, nullptr); - if (thread != nullptr) { - AbilityManagerClient::GetInstance()->AttachAbilityThread(thread, abilityToken); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = - std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - DataAbilityPredicates predicates("predicatestest"); - int index = helper->Delete(uri2, predicates); - - EXPECT_EQ(index, -1); - } - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Delete_0200"; -} - -/** - * @tc.number: AaFwk_DataAbility_Insert_0100 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the index of the newly inserted data record in the dataability. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_Insert_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Insert_0100"; - - std::shared_ptr application = std::make_shared(); - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->type = AppExecFwk::AbilityType::DATA; - abilityInfo->name = "DemoAbility"; - std::shared_ptr abilityRecord = - std::make_shared(abilityInfo, abilityToken); - - AbilityThread::AbilityThreadMain(application, abilityRecord); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - ValuesBucket val("valtest"); - int index = helper->Insert(uri2, val); - - EXPECT_EQ(index, 345); - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Insert_0100"; -} - -/** - * @tc.number: AaFwk_DataAbility_Insert_0200 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the index of the newly inserted data record in the dataability failed without abilityimpl. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_Insert_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Insert_0200"; - - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - sptr thread = sptr(new AbilityThread()); - EXPECT_NE(thread, nullptr); - if (thread != nullptr) { - AbilityManagerClient::GetInstance()->AttachAbilityThread(thread, abilityToken); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = - std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - ValuesBucket val("valtest"); - int index = helper->Insert(uri2, val); - EXPECT_EQ(index, -1); - } - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_Insert_0200"; -} - -/** - * @tc.number: AaFwk_DataAbility_GetType_0100 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the type string set in the dataability. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_GetType_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_GetType_0100"; - - std::shared_ptr application = std::make_shared(); - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->type = AppExecFwk::AbilityType::DATA; - abilityInfo->name = "DemoAbility"; - std::shared_ptr abilityRecord = - std::make_shared(abilityInfo, abilityToken); - - AbilityThread::AbilityThreadMain(application, abilityRecord); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::string type = helper->GetType(uri2); - - EXPECT_STREQ(type.c_str(), "Type1"); - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_GetType_0100"; -} - -/** - * @tc.number: AaFwk_DataAbility_GetType_0200 - * @tc.name: DataAbilityHelper - * @tc.desc: Get the type string set in the dataability failed without abilityimpl. - */ -HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_GetType_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataAbility_GetType_0200"; - - sptr abilityToken = sptr(new AbilityThread()); - EXPECT_NE(abilityToken, nullptr); - if (abilityToken != nullptr) { - sptr thread = sptr(new AbilityThread()); - EXPECT_NE(thread, nullptr); - if (thread != nullptr) { - AbilityManagerClient::GetInstance()->AttachAbilityThread(thread, abilityToken); - - std::shared_ptr context = std::make_shared(); - std::shared_ptr uri = - std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); - std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); - - EXPECT_NE(helper, nullptr); - if (helper != nullptr) { - Uri uri2("dataability://com.example.myapplication5.DataAbilityTest"); - std::string type = helper->GetType(uri2); - - EXPECT_STREQ(type.c_str(), ""); - } - } - } - GTEST_LOG_(INFO) << "AaFwk_DataAbility_GetType_0200"; -} - /** * @tc.number: AaFwk_DataAbility_Launch_0100 * @tc.name: DataAbilityHelper diff --git a/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_helper_module_test.cpp b/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_helper_module_test.cpp new file mode 100644 index 00000000000..01057cdb228 --- /dev/null +++ b/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_helper_module_test.cpp @@ -0,0 +1,653 @@ +/* + * 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 "gtest/gtest.h" +#include "mock_ability_test.h" +#include "mock_ability_manager_client.h" +#include "mock_ability_thread_for_data_observer.h" +#include "context.h" +#include "ability_context.h" +#include "data_ability_helper.h" + +namespace OHOS { +namespace AppExecFwk { + +using namespace testing::ext; +REGISTER_AA(MockAbilityTest) +/* + * Parameters: + * Action + * Entity + * Flag + * ElementName + */ +class DataAbilityHelperTest : public testing::Test { +public: + DataAbilityHelperTest(){}; + virtual ~DataAbilityHelperTest(){}; + + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + +public: +}; + +void DataAbilityHelperTest::SetUpTestCase(void) +{} + +void DataAbilityHelperTest::TearDownTestCase(void) +{} + +void DataAbilityHelperTest::SetUp(void) +{} + +void DataAbilityHelperTest::TearDown(void) +{} + +/** + * @tc.number: AaFwk_DataAbilityHelper_Insert_Test_0100 + * @tc.name: DataAbilityHelper + * @tc.desc: Insert with DataAbilityHelper which created with uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Insert_Test_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_Test_0100 start"; + + sptr thread = nullptr; + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + ValuesBucket val("22"); + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + + int value = dataAbilityHelper->Insert(urivalue, val); + + EXPECT_EQ(value, 20); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_Test_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_Insert_Test_0200 + * @tc.name: DataAbilityHelper + * @tc.desc: Insert with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Insert_Test_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_Test_0200 start"; + + sptr thread = nullptr; + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + ValuesBucket val("20"); + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + + int value = dataAbilityHelper->Insert(urivalue, val); + + EXPECT_EQ(value, 20); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_Test_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_Update_Test_0100 + * @tc.name: DataAbilityHelper + * @tc.desc: Update with DataAbilityHelper which created with uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Update_Test_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Update_Test_0100 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + + ValuesBucket val("22"); + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + DataAbilityPredicates predicates("33"); + int value = dataAbilityHelper->Update(urivalue, val, predicates); + EXPECT_EQ(value, 33); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Update_Test_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_Update_Test_0200 + * @tc.name: DataAbilityHelper + * @tc.desc: Update with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Update_Test_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_Test_0200 start"; + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + + ValuesBucket val("22"); + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + DataAbilityPredicates predicates("33"); + int value = dataAbilityHelper->Update(urivalue, val, predicates); + EXPECT_EQ(value, 33); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_Test_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_GetFileTypes_Test_0100 + * @tc.name: DataAbilityHelper + * @tc.desc: GetFileTypes with DataAbilityHelper which created with uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetFileTypes_Test_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_Test_0100 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + + std::string mimeTypeFilter("mimeTypeFiltertest"); + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::vector result = dataAbilityHelper->GetFileTypes(urivalue, mimeTypeFilter); + + std::vector list; + list.push_back("Type1"); + list.push_back("Type2"); + list.push_back("Type3"); + + for (int i = 0; i < result.size(); i++) { + EXPECT_STREQ(result.at(i).c_str(), list.at(i).c_str()); + } + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_Test_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_GetFileTypes_Test_0200 + * @tc.name: DataAbilityHelper + * @tc.desc: GetFileTypes with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetFileTypes_Test_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_Test_0200 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::string mimeTypeFilter("mimeTypeFiltertest"); + std::vector result = dataAbilityHelper->GetFileTypes(urivalue, mimeTypeFilter); + + std::vector list; + list.push_back("Type1"); + list.push_back("Type2"); + list.push_back("Type3"); + + for (unsigned int i = 0; i < result.size(); i++) { + EXPECT_STREQ(result.at(i).c_str(), list.at(i).c_str()); + } + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_Test_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_OpenFile_Test_0100 + * @tc.name: DataAbilityHelper + * @tc.desc: Openfile with DataAbilityHelper which created with uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenFile_Test_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_Test_0100 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10?test/te.txt"); + std::string mode("r"); + int fd = dataAbilityHelper->OpenFile(urivalue, mode); + std::string result = "123456"; + FILE *file = fdopen(fd, "r"); + char str[7]; + if (!feof(file)) { + fgets(str, 7, file); + } + string stringstr(str); + EXPECT_STREQ(stringstr.c_str(), result.c_str()); + + fclose(file); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_Test_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_OpenFile_Test_0200 + * @tc.name: DataAbilityHelper Insert + * @tc.desc: Openfile with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenFile_Test_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_Test_0200 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10?test/te.txt"); + std::string mode("r"); + int fd = dataAbilityHelper->OpenFile(urivalue, mode); + + std::string result = "123456"; + FILE *file = fdopen(fd, "r"); + char str[7]; + if (!feof(file)) { + fgets(str, 7, file); + } + string stringstr(str); + EXPECT_STREQ(stringstr.c_str(), result.c_str()); + + fclose(file); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_Test_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_OpenRawFile_Test_0100 + * @tc.name: DataAbilityHelper + * @tc.desc: OpenRawFile with DataAbilityHelper which created with uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenRawFile_Test_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_Test_0100 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::string mode("modetest"); + int fd = dataAbilityHelper->OpenRawFile(urivalue, mode); + + EXPECT_EQ(fd, 122); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_Test_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_OpenRawFile_Test_0200 + * @tc.name: DataAbilityHelper Insert + * @tc.desc: OpenRawFile with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenRawFile_Test_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_Test_0200 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::string mode("modetest"); + int fd = dataAbilityHelper->OpenRawFile(urivalue, mode); + + EXPECT_EQ(fd, 122); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_Test_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_BatchInsert_Test_0100 + * @tc.name: DataAbilityHelper + * @tc.desc: BatchInsert with DataAbilityHelper which created with uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_BatchInsert_Test_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_Test_0100 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::vector values; + int fd = dataAbilityHelper->BatchInsert(urivalue, values); + + EXPECT_EQ(fd, 115); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_Test_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_BatchInsert_Test_0200 + * @tc.name: DataAbilityHelper Insert + * @tc.desc: BatchInsert with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_BatchInsert_Test_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_Test_0200 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::vector values; + int fd = dataAbilityHelper->BatchInsert(urivalue, values); + + EXPECT_EQ(fd, 115); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_Test_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_Reload_Test_0100 + * @tc.name: DataAbilityHelper + * @tc.desc: Reload with DataAbilityHelper which created with uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Reload_Test_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_Test_0100 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + PacMap extras; + int fd = dataAbilityHelper->Reload(urivalue, extras); + + EXPECT_EQ(fd, true); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_Test_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_Reload_Test_0200 + * @tc.name: DataAbilityHelper + * @tc.desc: Reload with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Reload_Test_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_Test_0200 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + PacMap extras; + int fd = dataAbilityHelper->Reload(urivalue, extras); + + EXPECT_EQ(fd, true); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_Test_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_Delete_Test_0100 + * @tc.name: DataAbilityHelper + * @tc.desc: Delete with DataAbilityHelper which created with uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Delete_Test_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_Test_0100 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + DataAbilityPredicates predicates("predicatestest"); + int index = dataAbilityHelper->Delete(urivalue, predicates); + + EXPECT_EQ(index, 234); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_Test_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_Delete_Test_0200 + * @tc.name: DataAbilityHelper + * @tc.desc: Delete with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Delete_Test_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_Test_0200 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + DataAbilityPredicates predicates("predicatestest"); + int index = dataAbilityHelper->Delete(urivalue, predicates); + + EXPECT_EQ(index, 234); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_Test_0200 end"; +} +/** + * @tc.number: AaFwk_DataAbilityHelper_Query_Test_0100 + * @tc.name: DataAbilityHelper + * @tc.desc: Query with DataAbilityHelper which created with uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Query_Test_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_Test_0100 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + + std::vector columns; + columns.push_back("string1"); + columns.push_back("string2"); + columns.push_back("string3"); + DataAbilityPredicates predicates; + + EXPECT_NE(nullptr, dataAbilityHelper->Query(urivalue, columns, predicates)); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_Test_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_Query_Test_0200 + * @tc.name: DataAbilityHelper Insert + * @tc.desc: Query with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Query_Test_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_Test_0200 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + + std::vector columns; + columns.push_back("string1"); + columns.push_back("string2"); + columns.push_back("string3"); + DataAbilityPredicates predicates; + + EXPECT_NE(nullptr, dataAbilityHelper->Query(urivalue, columns, predicates)); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_Test_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_GetType_Test_0100 + * @tc.name: DataAbilityHelper + * @tc.desc: Gettype with DataAbilityHelper which created with uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetType_Test_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_Test_0100 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::string type = dataAbilityHelper->GetType(urivalue); + + EXPECT_STREQ(type.c_str(), "Type1"); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_Test_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_GetType_Test_0200 + * @tc.name: DataAbilityHelper + * @tc.desc: GetType with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetType_Test_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_Test_0200 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::string type = dataAbilityHelper->GetType(urivalue); + + EXPECT_STREQ(type.c_str(), "Type1"); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_Test_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_NormalizeUri_Test_0100 + * @tc.name: DataAbilityHelper NormalizeUri + * @tc.desc: NormalizeUri with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_NormalizeUri_Test_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_NormalizeUri_Test_0100 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + Uri type(""); + type = dataAbilityHelper->NormalizeUri(urivalue); + + EXPECT_STREQ(type.ToString().c_str(), urivalue.ToString().c_str()); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_NormalizeUri_Test_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_NormalizeUri_Test_0200 + * @tc.name: DataAbilityHelper NormalizeUri + * @tc.desc: NormalizeUri with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_NormalizeUri_Test_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_NormalizeUri_Test_0200 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + Uri type(""); + type = dataAbilityHelper->NormalizeUri(urivalue); + + EXPECT_STREQ(type.ToString().c_str(), urivalue.ToString().c_str()); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_NormalizeUri_Test_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_DenormalizeUri_Test_0100 + * @tc.name: DataAbilityHelper + * @tc.desc: DenormalizeUri with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_DenormalizeUri_Test_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_DenormalizeUri_Test_0100 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context, uri); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + Uri type(""); + type = dataAbilityHelper->DenormalizeUri(urivalue); + + EXPECT_STREQ(type.ToString().c_str(), urivalue.ToString().c_str()); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_DenormalizeUri_Test_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityHelper_DenormalizeUri_Test_0200 + * @tc.name: DataAbilityHelper DenormalizeUri + * @tc.desc: DenormalizeUri with DataAbilityHelper which created without uri. + */ +HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_DenormalizeUri_Test_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_DenormalizeUri_Test_0200 start"; + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = + std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); + std::shared_ptr dataAbilityHelper = DataAbilityHelper::Creator(context); + + Uri urivalue("dataability://device_id/com.domainname.dataability.persondata/person/10"); + Uri type(""); + type = dataAbilityHelper->DenormalizeUri(urivalue); + + EXPECT_STREQ(type.ToString().c_str(), urivalue.ToString().c_str()); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_DenormalizeUri_Test_0200 end"; +} + + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/BUILD.gn b/frameworks/kits/tools/BUILD.gn new file mode 100644 index 00000000000..d1c98ba2d66 --- /dev/null +++ b/frameworks/kits/tools/BUILD.gn @@ -0,0 +1,23 @@ +# +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +group("tool_ability") { + deps = [ + "simulateEntryAbility:simulate_entry_ability_native", + "simulateFeatureAbility:simulate_feature_ability_native", + "verifyAbility/verifyActAbility:verify_act_ability_native", + "verifyAbility/verifyIOAbility:verify_io_ability_native", + ] +} diff --git a/frameworks/kits/tools/simulateEntryAbility/BUILD.gn b/frameworks/kits/tools/simulateEntryAbility/BUILD.gn new file mode 100644 index 00000000000..7acfba4b23e --- /dev/null +++ b/frameworks/kits/tools/simulateEntryAbility/BUILD.gn @@ -0,0 +1,64 @@ +# +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = + "//foundation/aafwk/standard/frameworks/kits/tools/simulateEntryAbility" +config("simulate_entry_ability_config") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/appexecfwk/standard/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", + ] + + defines = [ + "APP_LOG_TAG = \"simulateEntryAbility\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("simulate_entry_ability_native") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/simulate_entry_ability_fir.cpp", + "${SUBDEMOSYSTEM_DIR}/src/simulate_entry_ability_sed.cpp", + ] + configs = [ ":simulate_entry_ability_config" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "abilitydemo" +} diff --git a/frameworks/kits/tools/simulateEntryAbility/config.json b/frameworks/kits/tools/simulateEntryAbility/config.json new file mode 100644 index 00000000000..f661f86e843 --- /dev/null +++ b/frameworks/kits/tools/simulateEntryAbility/config.json @@ -0,0 +1,49 @@ +{ + "app":{ + "bundleName": "com.ix.simulate.entry", + "vendor": "neusoft", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.SimulateEntryAbilityFir.src", + "name":"SimulateEntryAbilityFir", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "SimulateEntryAbilityFir", + "icon": "$media:snowball", + "label": "SimulateEntryAbilityFir Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "SimulateEntryAbilitySed", + "icon": "$media:snowflakes", + "label": "SimulateEntryAbilitySed Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/frameworks/kits/tools/simulateEntryAbility/include/simulate_entry_ability_fir.h b/frameworks/kits/tools/simulateEntryAbility/include/simulate_entry_ability_fir.h new file mode 100644 index 00000000000..a03e745aabb --- /dev/null +++ b/frameworks/kits/tools/simulateEntryAbility/include/simulate_entry_ability_fir.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 _SIMULATE_ENTRY_ABILITY_FIR_ +#define _SIMULATE_ENTRY_ABILITY_FIR_ +#include "ability_loader.h" +namespace OHOS { +namespace AppExecFwk { +class SimulateEntryAbilityFir : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_SIMULATE_ENTRY_ABILITY_FIR_ \ No newline at end of file diff --git a/frameworks/kits/tools/simulateEntryAbility/include/simulate_entry_ability_sed.h b/frameworks/kits/tools/simulateEntryAbility/include/simulate_entry_ability_sed.h new file mode 100644 index 00000000000..db0555ac587 --- /dev/null +++ b/frameworks/kits/tools/simulateEntryAbility/include/simulate_entry_ability_sed.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 _SIMULATE_ENTRY_ABILITY_SED_ +#define _SIMULATE_ENTRY_ABILITY_SED_ +#include "ability_loader.h" +namespace OHOS { +namespace AppExecFwk { +class SimulateEntryAbilitySed : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_SIMULATE_ENTRY_ABILITY_SED_ \ No newline at end of file diff --git a/frameworks/kits/tools/simulateEntryAbility/src/simulate_entry_ability_fir.cpp b/frameworks/kits/tools/simulateEntryAbility/src/simulate_entry_ability_fir.cpp new file mode 100644 index 00000000000..3de27f9bb33 --- /dev/null +++ b/frameworks/kits/tools/simulateEntryAbility/src/simulate_entry_ability_fir.cpp @@ -0,0 +1,47 @@ +/* + * 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 "simulate_entry_ability_fir.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void SimulateEntryAbilityFir::OnStart(const Want &want) +{ + APP_LOGI("SimulateEntryAbilityFir::onStart"); + Ability::OnStart(want); +} +void SimulateEntryAbilityFir::OnStop() +{ + APP_LOGI("SimulateEntryAbilityFir::onStop"); + Ability::OnStop(); +} +void SimulateEntryAbilityFir::OnActive() +{ + APP_LOGI("SimulateEntryAbilityFir::OnActive"); + Ability::OnActive(); +} +void SimulateEntryAbilityFir::OnInactive() +{ + APP_LOGI("SimulateEntryAbilityFir::OnInactive"); + Ability::OnInactive(); +} +void SimulateEntryAbilityFir::OnBackground() +{ + APP_LOGI("SimulateEntryAbilityFir::OnBackground"); + Ability::OnBackground(); +} +REGISTER_AA(SimulateEntryAbilityFir) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/simulateEntryAbility/src/simulate_entry_ability_sed.cpp b/frameworks/kits/tools/simulateEntryAbility/src/simulate_entry_ability_sed.cpp new file mode 100644 index 00000000000..1d72531c6d9 --- /dev/null +++ b/frameworks/kits/tools/simulateEntryAbility/src/simulate_entry_ability_sed.cpp @@ -0,0 +1,47 @@ +/* + * 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 "simulate_entry_ability_sed.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void SimulateEntryAbilitySed::OnStart(const Want &want) +{ + APP_LOGI("SimulateEntryAbilitySed::onStart"); + Ability::OnStart(want); +} +void SimulateEntryAbilitySed::OnStop() +{ + APP_LOGI("SimulateEntryAbilitySed::onStop"); + Ability::OnStop(); +} +void SimulateEntryAbilitySed::OnActive() +{ + APP_LOGI("SimulateEntryAbilitySed::OnActive"); + Ability::OnActive(); +} +void SimulateEntryAbilitySed::OnInactive() +{ + APP_LOGI("SimulateEntryAbilitySed::OnInactive"); + Ability::OnInactive(); +} +void SimulateEntryAbilitySed::OnBackground() +{ + APP_LOGI("SimulateEntryAbilitySed::OnBackground"); + Ability::OnBackground(); +} +REGISTER_AA(SimulateEntryAbilitySed) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/simulateFeatureAbility/BUILD.gn b/frameworks/kits/tools/simulateFeatureAbility/BUILD.gn new file mode 100644 index 00000000000..f90f92e012a --- /dev/null +++ b/frameworks/kits/tools/simulateFeatureAbility/BUILD.gn @@ -0,0 +1,63 @@ +# +# 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") +SUBDEMOSYSTEM_DIR = + "//foundation/aafwk/standard/frameworks/kits/tools/simulateFeatureAbility" +config("simulate_feature_ability_config") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//foundation/appexecfwk/standard/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + defines = [ + "APP_LOG_TAG = \"simulateFeatureAbility\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("simulate_feature_ability_native") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/simulate_feature_ability_fir.cpp", + "${SUBDEMOSYSTEM_DIR}/src/simulate_feature_ability_sed.cpp", + ] + configs = [ ":simulate_feature_ability_config" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "abilitydemo" +} diff --git a/frameworks/kits/tools/simulateFeatureAbility/config.json b/frameworks/kits/tools/simulateFeatureAbility/config.json new file mode 100644 index 00000000000..4bfe85829bc --- /dev/null +++ b/frameworks/kits/tools/simulateFeatureAbility/config.json @@ -0,0 +1,49 @@ +{ + "app":{ + "bundleName": "com.ix.simulate.feature", + "vendor": "neusoft", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.SimulateFeatureAbilityFir.src", + "name":"SimulateFeatureAbilityFir", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "SimulateFeatureAbilityFir", + "icon": "$media:snowball", + "label": "SimulateFeatureAbilityFir Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "SimulateFeatureAbilitySed", + "icon": "$media:snowflakes", + "label": "SimulateFeatureAbilitySed Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/frameworks/kits/tools/simulateFeatureAbility/include/simulate_feature_ability_fir.h b/frameworks/kits/tools/simulateFeatureAbility/include/simulate_feature_ability_fir.h new file mode 100644 index 00000000000..2dfa6e52801 --- /dev/null +++ b/frameworks/kits/tools/simulateFeatureAbility/include/simulate_feature_ability_fir.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 _SIMULATE_FEATURE_ABILITY_FIR_ +#define _SIMULATE_FEATURE_ABILITY_FIR_ +#include "ability_loader.h" +namespace OHOS { +namespace AppExecFwk { +class SimulateFeatureAbilityFir : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_SIMULATE_FEATURE_ABILITY_FIR_ \ No newline at end of file diff --git a/frameworks/kits/tools/simulateFeatureAbility/include/simulate_feature_ability_sed.h b/frameworks/kits/tools/simulateFeatureAbility/include/simulate_feature_ability_sed.h new file mode 100644 index 00000000000..44a740fb235 --- /dev/null +++ b/frameworks/kits/tools/simulateFeatureAbility/include/simulate_feature_ability_sed.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 _SIMULATE_FEATURE_ABILITY_SED_ +#define _SIMULATE_FEATURE_ABILITY_SED_ +#include "ability_loader.h" +namespace OHOS { +namespace AppExecFwk { +class SimulateFeatureAbilitySed : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_SIMULATE_FEATURE_ABILITY_SED_ \ No newline at end of file diff --git a/frameworks/kits/tools/simulateFeatureAbility/src/simulate_feature_ability_fir.cpp b/frameworks/kits/tools/simulateFeatureAbility/src/simulate_feature_ability_fir.cpp new file mode 100644 index 00000000000..37c832b9312 --- /dev/null +++ b/frameworks/kits/tools/simulateFeatureAbility/src/simulate_feature_ability_fir.cpp @@ -0,0 +1,47 @@ +/* + * 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 "simulate_feature_ability_fir.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void SimulateFeatureAbilityFir::OnStart(const Want &want) +{ + APP_LOGI("SimulateFeatureAbilityFir::onStart"); + Ability::OnStart(want); +} +void SimulateFeatureAbilityFir::OnStop() +{ + APP_LOGI("SimulateFeatureAbilityFir::onStop"); + Ability::OnStop(); +} +void SimulateFeatureAbilityFir::OnActive() +{ + APP_LOGI("SimulateFeatureAbilityFir::OnActive"); + Ability::OnActive(); +} +void SimulateFeatureAbilityFir::OnInactive() +{ + APP_LOGI("SimulateFeatureAbilityFir::OnInactive"); + Ability::OnInactive(); +} +void SimulateFeatureAbilityFir::OnBackground() +{ + APP_LOGI("SimulateFeatureAbilityFir::OnBackground"); + Ability::OnBackground(); +} +REGISTER_AA(SimulateFeatureAbilityFir) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/simulateFeatureAbility/src/simulate_feature_ability_sed.cpp b/frameworks/kits/tools/simulateFeatureAbility/src/simulate_feature_ability_sed.cpp new file mode 100644 index 00000000000..ec1ceda4dad --- /dev/null +++ b/frameworks/kits/tools/simulateFeatureAbility/src/simulate_feature_ability_sed.cpp @@ -0,0 +1,47 @@ +/* + * 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 "simulate_feature_ability_sed.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void SimulateFeatureAbilitySed::OnStart(const Want &want) +{ + APP_LOGI("SimulateFeatureAbilitySed::onStart"); + Ability::OnStart(want); +} +void SimulateFeatureAbilitySed::OnStop() +{ + APP_LOGI("SimulateFeatureAbilitySed::onStop"); + Ability::OnStop(); +} +void SimulateFeatureAbilitySed::OnActive() +{ + APP_LOGI("SimulateFeatureAbilitySed::OnActive"); + Ability::OnActive(); +} +void SimulateFeatureAbilitySed::OnInactive() +{ + APP_LOGI("SimulateFeatureAbilitySed::OnInactive"); + Ability::OnInactive(); +} +void SimulateFeatureAbilitySed::OnBackground() +{ + APP_LOGI("SimulateFeatureAbilitySed::OnBackground"); + Ability::OnBackground(); +} +REGISTER_AA(SimulateFeatureAbilitySed) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/BUILD.gn b/frameworks/kits/tools/verifyAbility/verifyActAbility/BUILD.gn new file mode 100644 index 00000000000..d0995bdd3d5 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/BUILD.gn @@ -0,0 +1,76 @@ +# +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import("//build/ohos.gni") +SUBDEMOSYSTEM_DIR = "//foundation/aafwk/standard/frameworks/kits/tools/verifyAbility/verifyActAbility" +config("verify_act_ability_config") { + visibility = [ ":*" ] + include_dirs = [ "${SUBDEMOSYSTEM_DIR}/include" ] + defines = [ + "APP_LOG_TAG = \"verifyActAbility\"", + "LOG_DOMAIN = 0xD002200", + ] +} +config("verify_act_ability_public_config") { + visibility = [ ":*" ] + include_dirs = [ + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/event/common/cesfwk/innerkits/include", + "//foundation/event/common/cesfwk/kits/native/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/tools/bm/include", + "//third_party/jsoncpp/include", + ] +} +ohos_shared_library("verify_act_ability_native") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/verify_act_data_first_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_eighth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_fifth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_first_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_fourth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_ninth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_second_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_seventh_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_sixth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_tenth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_third_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_service_first_ability.cpp", + "//foundation/appexecfwk/standard/tools/bm/src/status_receiver_impl.cpp", + ] + configs = [ ":verify_act_ability_config" ] + public_configs = [ ":verify_act_ability_public_config" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//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/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "abilitydemo" +} diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/config.json b/frameworks/kits/tools/verifyAbility/verifyActAbility/config.json new file mode 100644 index 00000000000..f21a55f1a09 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/config.json @@ -0,0 +1,141 @@ +{ + "app":{ + "bundleName": "com.ix.verify.act", + "vendor": "neusoft", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.VerifyActAbility.src", + "name":"VerifyActFirstAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "VerifyActFirstAbility", + "icon": "$media:snowball", + "label": "VerifyActFirstAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyActSecondAbility", + "icon": "$media:snowflakes", + "label": "VerifyActSecondAbility Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyActThirdAbility", + "icon": "$media:snowflakes", + "label": "VerifyActThirdAbility Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyActFourthAbility", + "icon": "$media:snowflakes", + "label": "VerifyActFourthAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyActFifthAbility", + "icon": "$media:snowflakes", + "label": "VerifyActFifthAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyActSixthAbility", + "icon": "$media:snowflakes", + "label": "VerifyActSixthAbility Ability", + "launchType": "singleton", + "configChanges": ["locale","layout"], + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyActSeventhAbility", + "icon": "$media:snowflakes", + "label": "VerifyActSeventhAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyActEighthAbility", + "icon": "$media:snowflakes", + "label": "VerifyActEighthAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyActNinthAbility", + "icon": "$media:snowflakes", + "label": "VerifyActNinthAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyActTenthAbility", + "icon": "$media:snowflakes", + "label": "VerifyActTenthAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyServiceFirstAbility", + "icon": "$media:snowflakes", + "label": "VerifyServiceFirstAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + }, + { + "name": "VerifyActDataFirstAbility", + "icon": "$media:snowball", + "label": "Data Firs Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "data", + "uri": "dataability://com.ix.VerifyActFirstDataAbility", + "visible": true + }] + } +} \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_data_first_ability.h b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_data_first_ability.h new file mode 100644 index 00000000000..d9c0de52b7d --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_data_first_ability.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 _MAIN_DATA_ABILITY_H_ +#define _MAIN_DATA_ABILITY_H_ +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "ability.h" +#include "matching_skills.h" +#include "common_event_subscribe_info.h" +#include "common_event_subscriber.h" +#include "common_event.h" +#include "common_event_data.h" +#include "iremote_object.h" +#include "common_event_publish_info.h" + +namespace OHOS { +namespace AppExecFwk { +class VerifyActDataFirstAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual int Insert(const Uri &uri, const ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) override; + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + virtual int OpenFile(const Uri &uri, const std::string &mode) override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_MAIN_ABILITY_H_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_eighth_ability.h b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_eighth_ability.h new file mode 100644 index 00000000000..dad04d18125 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_eighth_ability.h @@ -0,0 +1,38 @@ +/* + * 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 _VERIFY_ACT_EIGHTH_ABILITY_ +#define _VERIFY_ACT_EIGHTH_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyActEighthAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +class SubscriberEighth : public EventFwk::CommonEventSubscriber { +public: + SubscriberEighth(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_ACT_EIGHTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_fifth_ability.h b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_fifth_ability.h new file mode 100644 index 00000000000..0f0af202c5f --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_fifth_ability.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _VERIFY_ACT_FIFTH_ABILITY_ +#define _VERIFY_ACT_FIFTH_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +#include "ability_lifecycle_observer_interface.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +namespace { +const int INSERT = 0; //"Test Insert()" +const int DELETE = 1; //"Test Delete()" +const int UPDATE = 2; //"Test Update()" +const int QUERY = 3; //"Test Query()" +const int GETFILETYPES = 4; //"Test GetFileType()" +const int OPENFILE = 5; //"Test openfile()" +} // namespace +class CommentDataAbilityTest : public EventFwk::CommonEventSubscriber { +public: + CommentDataAbilityTest(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + std::weak_ptr DataAbility_; +}; +class VerifyActFifthAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + std::shared_ptr subscriberDataAbility = nullptr; +}; +class VerifyFifthLifecycleObserver : public ILifecycleObserver { +public: + VerifyFifthLifecycleObserver() = default; + virtual ~VerifyFifthLifecycleObserver() = default; + void OnActive() override; + void OnBackground() override; + void OnForeground(const Want &want) override; + void OnInactive() override; + void OnStart(const Want &want) override; + void OnStop() override; + void OnStateChanged(LifeCycle::Event event, const Want &want) override; + void OnStateChanged(LifeCycle::Event event) override; +}; +class SubscriberFifth : public EventFwk::CommonEventSubscriber { +public: + SubscriberFifth(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + std::shared_ptr lifeCycle = nullptr; + std::shared_ptr observer = nullptr; + Want want; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_ACT_FIFTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_first_ability.h b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_first_ability.h new file mode 100644 index 00000000000..d469f48b5fb --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_first_ability.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 _VERIFY_ACT_FIRST_ABILITY_ +#define _VERIFY_ACT_FIRST_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +#include "app_log_wrapper.h" +#include "common_event_manager.h" +#include "ability_connect_callback_stub.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int CONNECT_SERVICE_ABILITY = 0; +const int DISCONNECT_SERVICE_ABILITY = 1; +const int START_SERVICE_ABILITY = 2; +const int STOP_SERVICE_ABILITY = 3; +} // namespace +class VerifyActFirstAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +class VerifyIOAbilityLifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + VerifyIOAbilityLifecycleCallbacks() = default; + virtual ~VerifyIOAbilityLifecycleCallbacks() = default; + + virtual void OnAbilityStart(const std::shared_ptr &ability); + virtual void OnAbilityInactive(const std::shared_ptr &ability); + virtual void OnAbilityBackground(const std::shared_ptr &ability); + virtual void OnAbilityForeground(const std::shared_ptr &ability); + virtual void OnAbilityActive(const std::shared_ptr &ability); + virtual void OnAbilityStop(const std::shared_ptr &ability); + virtual void OnAbilitySaveState(const PacMap &outState); +}; + +class AbilityContextStartAbilityTest : public EventFwk::CommonEventSubscriber { +public: + AbilityContextStartAbilityTest(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); +}; +class ConnectServiceAbilityTest : public EventFwk::CommonEventSubscriber { +public: + ConnectServiceAbilityTest( + const EventFwk::CommonEventSubscribeInfo &sp, std::shared_ptr abilityContext, sptr conne) + : EventFwk::CommonEventSubscriber(sp) + { + abilityContext_ = abilityContext; + conne_ = conne; + }; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + std::shared_ptr abilityContext_ = nullptr; + sptr conne_ = nullptr; +}; +class AbilityConnectionActFirst : public AAFwk::AbilityConnectionStub { +public: + AbilityConnectionActFirst(){}; + virtual ~AbilityConnectionActFirst(){}; + virtual void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + static int onAbilityConnectDoneCount; + static int onAbilityDisconnectDoneCount; + static int test; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_ACT_FIRST_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_fourth_ability.h b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_fourth_ability.h new file mode 100644 index 00000000000..8d64ef9ba0e --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_fourth_ability.h @@ -0,0 +1,47 @@ +/* + * 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 _VERIFY_ACT_FOURTH_ABILITY_ +#define _VERIFY_ACT_FOURTH_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int START_ABILITY_FOR_RESULT = 0; //"Test StartAbilityForResult()" +const int START_ABILITY = 1; //"Test StartAbility()" +const int DUMP = 2; //"Test Dump()" +} // namespace +class VerifyActFourthAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnAbilityResult(int requestCode, int resultCode, const Want &resultData) override; +}; + +class CommentAbilityTest : public EventFwk::CommonEventSubscriber { +public: + CommentAbilityTest(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + std::shared_ptr ability_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_ACT_FOURTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_ninth_ability.h b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_ninth_ability.h new file mode 100644 index 00000000000..6e3501c16b6 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_ninth_ability.h @@ -0,0 +1,53 @@ +/* + * 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 _VERIFY_ACT_NINTH_ABILITY_ +#define _VERIFY_ACT_NINTH_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { +//using namespace OHOS::EventFwk; +namespace { +const int ABORT_COMMON_EVENT = 0; +const int GET_CLEAR_ABORT_COMMON_EVENT = 1; +const int SET_CODE_DATA = 2; +const int SET_CODE_AND_DATA = 3; +const int ASYNC_ABORT_COMMON_EVENT = 4; +const int ASYNC_GET_CLEAR_ABORT_COMMON_EVENT = 5; +const int UN_SUBSCRIBE_COMMON_EVENT = 6; +const int ASYNC_SET_CODE_DATA = 7; +} // namespace +class VerifyActNinthAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +class SubscriberNinth : public EventFwk::CommonEventSubscriber, std::enable_shared_from_this { +public: + SubscriberNinth(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + +private: + static void AsyncProcess(const std::shared_ptr &result, int code); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_ACT_NINTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_second_ability.h b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_second_ability.h new file mode 100644 index 00000000000..81a512264c0 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_second_ability.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _VERIFY_ACT_SECOND_ABILITY_ +#define _VERIFY_ACT_SECOND_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyActSecondAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; + +class TerminateAbilityTest : public EventFwk::CommonEventSubscriber { +public: + TerminateAbilityTest(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + std::shared_ptr ability_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_ACT_SECOND_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_seventh_ability.h b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_seventh_ability.h new file mode 100644 index 00000000000..13d3f39ae04 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_seventh_ability.h @@ -0,0 +1,37 @@ +/* + * 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 _VERIFY_ACT_SEVENTH_ABILITY_ +#define _VERIFY_ACT_SEVENTH_ABILITY_ +#include "ability_loader.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyActSeventhAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +class SubscriberSeventh : public EventFwk::CommonEventSubscriber { +public: + SubscriberSeventh(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_ACT_SEVENTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_sixth_ability.h b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_sixth_ability.h new file mode 100644 index 00000000000..f5c53083a94 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_sixth_ability.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 _VERIFY_ACT_SIXTH_ABILITY_ +#define _VERIFY_ACT_SIXTH_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyActSixthAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_ACT_SIXTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_tenth_ability.h b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_tenth_ability.h new file mode 100644 index 00000000000..5aebf2fa802 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_tenth_ability.h @@ -0,0 +1,38 @@ +/* + * 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 _VERIFY_ACT_TENTH_ABILITY_ +#define _VERIFY_ACT_TENTH_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyActTenthAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +class SubscriberTen : public EventFwk::CommonEventSubscriber { +public: + SubscriberTen(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_ACT_TENTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_third_ability.h b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_third_ability.h new file mode 100644 index 00000000000..c95f113ff40 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_act_third_ability.h @@ -0,0 +1,43 @@ +/* + * 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 _VERIFY_ACT_THITRD_ABILITY_ +#define _VERIFY_ACT_THITRD_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +namespace { +const int INSTALL = 0; //"Install()" +const int UNINSTALL = 1; //"Uninstall()" +} // namespace +class VerifyActThirdAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +class HapManageDemo : public EventFwk::CommonEventSubscriber { +public: + HapManageDemo(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + sptr HapManagePtr = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_ACT_THITRD_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_service_first_ability.h b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_service_first_ability.h new file mode 100644 index 00000000000..0eb73f3a6f9 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/include/verify_service_first_ability.h @@ -0,0 +1,37 @@ +/* + * 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 _VERIFY_SERVICE_FIRST_ABILITY_ +#define _VERIFY_SERVICE_FIRST_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyServiceFirstAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_SERVICE_FIRST_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_data_first_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_data_first_ability.cpp new file mode 100644 index 00000000000..97f8b7aa2d9 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_data_first_ability.cpp @@ -0,0 +1,63 @@ +/* + * 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 "verify_act_data_first_ability.h" +#include "app_log_wrapper.h" +#include "common_event_manager.h" +#include "unistd.h" +#include +namespace OHOS { +namespace AppExecFwk { +#define RETURN_DEFAULT 1 +void VerifyActDataFirstAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} + +int VerifyActDataFirstAbility::Insert(const Uri &uri, const ValuesBucket &value) +{ + return RETURN_DEFAULT; +} + +int VerifyActDataFirstAbility::Delete(const Uri &uri, const DataAbilityPredicates &predicates) +{ + return RETURN_DEFAULT; +} + +int VerifyActDataFirstAbility::Update( + const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) +{ + return RETURN_DEFAULT; +} + +std::shared_ptr VerifyActDataFirstAbility::Query( + const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) +{ + return nullptr; +} + +std::vector VerifyActDataFirstAbility::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + std::vector value; + return value; +} + +int VerifyActDataFirstAbility::OpenFile(const Uri &uri, const std::string &mode) +{ + return RETURN_DEFAULT; +} +REGISTER_AA(VerifyActDataFirstAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_eighth_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_eighth_ability.cpp new file mode 100644 index 00000000000..f02ee38d5a6 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_eighth_ability.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 "verify_act_eighth_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void SubscriberEighth::OnReceiveEvent(const EventFwk::CommonEventData &data) +{} +void VerifyActEighthAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyActEighthAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyActEighthAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyActEighthAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyActEighthAbility::OnBackground() +{ + Ability::OnBackground(); +} +REGISTER_AA(VerifyActEighthAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_fifth_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_fifth_ability.cpp new file mode 100644 index 00000000000..3bd8100b9ff --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_fifth_ability.cpp @@ -0,0 +1,74 @@ +/* + * 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 "verify_act_fifth_ability.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +void VerifyFifthLifecycleObserver::OnActive() +{} + +void VerifyFifthLifecycleObserver::OnBackground() +{} + +void VerifyFifthLifecycleObserver::OnForeground(const Want &want) +{} + +void VerifyFifthLifecycleObserver::OnInactive() +{} + +void VerifyFifthLifecycleObserver::OnStart(const Want &want) +{} + +void VerifyFifthLifecycleObserver::OnStop() +{} + +void VerifyFifthLifecycleObserver::OnStateChanged(LifeCycle::Event event, const Want &want) +{} + +void VerifyFifthLifecycleObserver::OnStateChanged(LifeCycle::Event event) +{} +void VerifyActFifthAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyActFifthAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyActFifthAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyActFifthAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyActFifthAbility::OnBackground() +{ + Ability::OnBackground(); +} +void VerifyActFifthAbility::OnForeground(const Want &want) +{ + Ability::OnForeground(want); +} +void CommentDataAbilityTest::OnReceiveEvent(const EventFwk::CommonEventData &data) +{} +void SubscriberFifth::OnReceiveEvent(const EventFwk::CommonEventData &data) +{} +REGISTER_AA(VerifyActFifthAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_first_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_first_ability.cpp new file mode 100644 index 00000000000..f915d28cccb --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_first_ability.cpp @@ -0,0 +1,75 @@ +/* + * 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 "verify_act_first_ability.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +void AbilityConnectionActFirst::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{} + +void AbilityConnectionActFirst::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{} +void VerifyIOAbilityLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{} +void VerifyIOAbilityLifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{} + +void VerifyActFirstAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyActFirstAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyActFirstAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyActFirstAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyActFirstAbility::OnBackground() +{ + Ability::OnBackground(); +} + +void AbilityContextStartAbilityTest::OnReceiveEvent(const EventFwk::CommonEventData &data) +{} + +void ConnectServiceAbilityTest::OnReceiveEvent(const EventFwk::CommonEventData &data) +{} +REGISTER_AA(VerifyActFirstAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_fourth_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_fourth_ability.cpp new file mode 100644 index 00000000000..ac101449e06 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_fourth_ability.cpp @@ -0,0 +1,48 @@ +/* + * 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 "verify_act_fourth_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void VerifyActFourthAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyActFourthAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyActFourthAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyActFourthAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyActFourthAbility::OnBackground() +{ + Ability::OnBackground(); +} + +void VerifyActFourthAbility::OnAbilityResult(int requestCode, int resultCode, const Want &resultData) +{} + +void CommentAbilityTest::OnReceiveEvent(const EventFwk::CommonEventData &data) +{} +REGISTER_AA(VerifyActFourthAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_ninth_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_ninth_ability.cpp new file mode 100644 index 00000000000..3ab5fec457e --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_ninth_ability.cpp @@ -0,0 +1,48 @@ +/* + * 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 "verify_act_ninth_ability.h" +#include "app_log_wrapper.h" +#include +namespace OHOS { +namespace AppExecFwk { +void SubscriberNinth::OnReceiveEvent(const EventFwk::CommonEventData &data) +{} +void SubscriberNinth::AsyncProcess(const std::shared_ptr &result, int code) +{} + +void VerifyActNinthAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyActNinthAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyActNinthAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyActNinthAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyActNinthAbility::OnBackground() +{ + Ability::OnBackground(); +} +REGISTER_AA(VerifyActNinthAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_second_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_second_ability.cpp new file mode 100644 index 00000000000..83cf71c0a97 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_second_ability.cpp @@ -0,0 +1,45 @@ +/* + * 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 "verify_act_second_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void VerifyActSecondAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyActSecondAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyActSecondAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyActSecondAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyActSecondAbility::OnBackground() +{ + Ability::OnBackground(); +} + +void TerminateAbilityTest ::OnReceiveEvent(const EventFwk::CommonEventData &data) +{} +REGISTER_AA(VerifyActSecondAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_seventh_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_seventh_ability.cpp new file mode 100644 index 00000000000..c61fe398804 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_seventh_ability.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 "verify_act_seventh_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void SubscriberSeventh::OnReceiveEvent(const EventFwk::CommonEventData &data) +{} +void VerifyActSeventhAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyActSeventhAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyActSeventhAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyActSeventhAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyActSeventhAbility::OnBackground() +{ + Ability::OnBackground(); +} +REGISTER_AA(VerifyActSeventhAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_sixth_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_sixth_ability.cpp new file mode 100644 index 00000000000..7a77faa987d --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_sixth_ability.cpp @@ -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. + */ + +#include "verify_act_sixth_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void VerifyActSixthAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyActSixthAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyActSixthAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyActSixthAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyActSixthAbility::OnBackground() +{ + Ability::OnBackground(); +} +REGISTER_AA(VerifyActSixthAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_tenth_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_tenth_ability.cpp new file mode 100644 index 00000000000..bc1a3679a09 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_tenth_ability.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 "verify_act_tenth_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void SubscriberTen::OnReceiveEvent(const EventFwk::CommonEventData &data) +{} +void VerifyActTenthAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyActTenthAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyActTenthAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyActTenthAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyActTenthAbility::OnBackground() +{ + Ability::OnBackground(); +} +REGISTER_AA(VerifyActTenthAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_third_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_third_ability.cpp new file mode 100644 index 00000000000..edf7010bb71 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_act_third_ability.cpp @@ -0,0 +1,48 @@ +/* + * 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 "verify_act_third_ability.h" +#include "app_log_wrapper.h" +#include "bundle_installer_proxy.h" +#include "status_receiver_impl.h" + +namespace OHOS { +namespace AppExecFwk { +void VerifyActThirdAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyActThirdAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyActThirdAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyActThirdAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyActThirdAbility::OnBackground() +{ + Ability::OnBackground(); +} +void HapManageDemo::OnReceiveEvent(const EventFwk::CommonEventData &data) +{} + +REGISTER_AA(VerifyActThirdAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_service_first_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_service_first_ability.cpp new file mode 100644 index 00000000000..6e42066d0a1 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyActAbility/src/verify_service_first_ability.cpp @@ -0,0 +1,63 @@ +/* + * 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 "verify_service_first_ability.h" +#include "app_log_wrapper.h" +#include "bundle_installer_proxy.h" +#include "status_receiver_impl.h" + +namespace OHOS { +namespace AppExecFwk { +void VerifyServiceFirstAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyServiceFirstAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyServiceFirstAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyServiceFirstAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyServiceFirstAbility::OnBackground() +{ + Ability::OnBackground(); +} +void VerifyServiceFirstAbility::OnForeground(const Want &want) +{ + Ability::OnForeground(want); +} + +void VerifyServiceFirstAbility::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + Ability::OnCommand(want, restart, startId); +} +sptr VerifyServiceFirstAbility::OnConnect(const Want &want) +{ + Ability::OnConnect(want); + return Ability::GetToken(); +} +void VerifyServiceFirstAbility::OnDisconnect(const Want &want) +{ + Ability::OnDisconnect(want); +} +REGISTER_AA(VerifyServiceFirstAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/BUILD.gn b/frameworks/kits/tools/verifyAbility/verifyIOAbility/BUILD.gn new file mode 100644 index 00000000000..9daf31867e8 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/BUILD.gn @@ -0,0 +1,70 @@ +# +# 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") +SUBDEMOSYSTEM_DIR = "//foundation/aafwk/standard/frameworks/kits/tools/verifyAbility/verifyIOAbility" +config("verify_io_ability_config") { + visibility = [ ":*" ] + include_dirs = [ "${SUBDEMOSYSTEM_DIR}/include" ] + defines = [ + "APP_LOG_TAG = \"verifyIoAbility\"", + "LOG_DOMAIN = 0xD002200", + ] +} +config("verify_io_ability_public_config") { + visibility = [ ":*" ] + include_dirs = [ + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/event/common/cesfwk/innerkits/include", + "//foundation/event/common/cesfwk/kits/native/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//third_party/jsoncpp/include", + ] +} +ohos_shared_library("verify_io_ability_native") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/verify_io_eighth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_io_fifth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_io_first_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_io_fourth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_io_ninth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_io_second_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_io_seventh_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_io_sixth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_io_tenth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_io_third_ability.cpp", + ] + configs = [ ":verify_io_ability_config" ] + public_configs = [ ":verify_io_ability_public_config" ] + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "abilitydemo" +} diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/config.json b/frameworks/kits/tools/verifyAbility/verifyIOAbility/config.json new file mode 100644 index 00000000000..f0858e40051 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/config.json @@ -0,0 +1,121 @@ +{ + "app":{ + "bundleName": "com.ix.verify.io", + "vendor": "neusoft", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.VerifyIOAbility.src", + "name":"VerifyIoFirstAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "VerifyIoFirstAbility", + "icon": "$media:snowball", + "label": "VerifyIoFirstAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyIoSecondAbility", + "icon": "$media:snowflakes", + "label": "VerifyIoSecondAbility Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyIoThirdAbility", + "icon": "$media:snowflakes", + "label": "VerifyIoThirdAbility Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyIoFourthAbility", + "icon": "$media:snowflakes", + "label": "VerifyIoFourthAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyIoFifthAbility", + "icon": "$media:snowflakes", + "label": "VerifyIoFifthAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyIoSixthAbility", + "icon": "$media:snowflakes", + "label": "VerifyIoSixthAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyIoSeventhAbility", + "icon": "$media:snowflakes", + "label": "VerifyIoSeventhAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyIoEighthAbility", + "icon": "$media:snowflakes", + "label": "VerifyIoEighthAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyIoNinthAbility", + "icon": "$media:snowflakes", + "label": "VerifyIoNinthAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "VerifyIoTenthAbility", + "icon": "$media:snowflakes", + "label": "VerifyIoTenthAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_eighth_ability.h b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_eighth_ability.h new file mode 100644 index 00000000000..e1e2ba9fae6 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_eighth_ability.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 _VERIFY_IO_EIGHTH_ABILITY_ +#define _VERIFY_IO_EIGHTH_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyIoEighthAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_IO_EIGHTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_fifth_ability.h b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_fifth_ability.h new file mode 100644 index 00000000000..1defd57f426 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_fifth_ability.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 _VERIFY_IO_FIFTH_ABILITY_ +#define _VERIFY_IO_FIFTH_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyIoFifthAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_IO_FIFTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_first_ability.h b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_first_ability.h new file mode 100644 index 00000000000..e101f37ca42 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_first_ability.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 _VERIFY_IO_FIRST_ABILITY_ +#define _VERIFY_IO_FIRST_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyIoFirstAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_IO_FIRST_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_fourth_ability.h b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_fourth_ability.h new file mode 100644 index 00000000000..71522fa3555 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_fourth_ability.h @@ -0,0 +1,41 @@ +/* + * 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 _VERIFY_IO_FOURTH_ABILITY_ +#define _VERIFY_IO_FOURTH_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyIoFourthAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; +}; + +class SubAbilityTestTerminate : public EventFwk::CommonEventSubscriber, public Ability { +public: + SubAbilityTestTerminate(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + VerifyIoFourthAbility *m_s = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_IO_FOURTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_ninth_ability.h b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_ninth_ability.h new file mode 100644 index 00000000000..f89038f3e54 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_ninth_ability.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 _VERIFY_IO_NINTH_ABILITY_ +#define _VERIFY_IO_NINTH_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyIoNinthAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_IO_NINTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_second_ability.h b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_second_ability.h new file mode 100644 index 00000000000..009c58c353f --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_second_ability.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 _VERIFY_IO_SECOND_ABILITY_ +#define _VERIFY_IO_SECOND_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyIoSecondAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_IO_SECOND_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_seventh_ability.h b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_seventh_ability.h new file mode 100644 index 00000000000..90efb5af3fb --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_seventh_ability.h @@ -0,0 +1,38 @@ +/* + * 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 _VERIFY_IO_SEVENTH_ABILITY_ +#define _VERIFY_IO_SEVENTH_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyIoSeventhAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + +private: + OHOS::Parcel parcelForCommonEventData_; + OHOS::Parcel parcelForCommonEventSubscribeInfo_; + OHOS::Parcel parcelForCommonEventPublishInfo_; + OHOS::Parcel parcelForMatchingSkills_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_IO_SEVENTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_sixth_ability.h b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_sixth_ability.h new file mode 100644 index 00000000000..23d8f25f1e8 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_sixth_ability.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 _VERIFY_IO_SIXTH_ABILITY_ +#define _VERIFY_IO_SIXTH_ABILITY_ +#include "ability_loader.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyIoSixthAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_IO_SIXTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_tenth_ability.h b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_tenth_ability.h new file mode 100644 index 00000000000..b276cd4a166 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_tenth_ability.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 _VERIFY_IO_TENTH_ABILITY_ +#define _VERIFY_IO_TENTH_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyIoTenAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_IO_TENTH_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_third_ability.h b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_third_ability.h new file mode 100644 index 00000000000..2dfac82154a --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/include/verify_io_third_ability.h @@ -0,0 +1,43 @@ +/* + * 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 _VERIFY_IO_THITRD_ABILITY_ +#define _VERIFY_IO_THITRD_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +namespace OHOS { +namespace AppExecFwk { +class VerifyIoThirdAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +class CleanCacheCallbackDerived : public ICleanCacheCallback { +public: + void OnCleanCacheFinished(bool succeeded); + sptr AsObject(); +}; +class BundleStatusCallbackDerived : public IBundleStatusCallback { +public: + void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, + const std::string &bundleName); + sptr AsObject(); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_IO_THITRD_ABILITY_ \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_eighth_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_eighth_ability.cpp new file mode 100644 index 00000000000..cf7233fbd6c --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_eighth_ability.cpp @@ -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. + */ + +#include "verify_io_eighth_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void VerifyIoEighthAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyIoEighthAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyIoEighthAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyIoEighthAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyIoEighthAbility::OnBackground() +{ + Ability::OnBackground(); +} +REGISTER_AA(VerifyIoEighthAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_fifth_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_fifth_ability.cpp new file mode 100644 index 00000000000..0041f0373f5 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_fifth_ability.cpp @@ -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. + */ + +#include "verify_io_fifth_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void VerifyIoFifthAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyIoFifthAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyIoFifthAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyIoFifthAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyIoFifthAbility::OnBackground() +{ + Ability::OnBackground(); +} +REGISTER_AA(VerifyIoFifthAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_first_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_first_ability.cpp new file mode 100644 index 00000000000..6b0247a653d --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_first_ability.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 "verify_io_first_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { + +void VerifyIoFirstAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyIoFirstAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyIoFirstAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyIoFirstAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyIoFirstAbility::OnBackground() +{ + Ability::OnBackground(); +} + +REGISTER_AA(VerifyIoFirstAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/ability/abilityresult.d.ts b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_fourth_ability.cpp similarity index 45% rename from interfaces/kits/js/ability/abilityresult.d.ts rename to frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_fourth_ability.cpp index f1c5907cfb6..7a796cf8d8b 100644 --- a/interfaces/kits/js/ability/abilityresult.d.ts +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_fourth_ability.cpp @@ -1,49 +1,50 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Want } from './want'; - -export interface AbilityResult { - /** - * Indicates result code for startAbilityResult. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap aafwk - */ - resultCode: number; - - /** - * Indicates the data returned after the ability is started. You can define the data returned. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap aafwk - */ - want?: Want; -} - -export interface StartAbilityResult extends AbilityResult { - /** - * Indicates the Want containing information about the target ability to start. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap aafwk - */ - requestCode: number; -} \ No newline at end of file +/* + * 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 "verify_io_fourth_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void VerifyIoFourthAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyIoFourthAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyIoFourthAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyIoFourthAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyIoFourthAbility::OnBackground() +{ + Ability::OnBackground(); +} +void VerifyIoFourthAbility::OnForeground(const Want &want) +{ + Ability::OnForeground(want); +} + +void SubAbilityTestTerminate ::OnReceiveEvent(const EventFwk::CommonEventData &data) +{} + +REGISTER_AA(VerifyIoFourthAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_ninth_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_ninth_ability.cpp new file mode 100644 index 00000000000..cc78b99010e --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_ninth_ability.cpp @@ -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. + */ + +#include "verify_io_ninth_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void VerifyIoNinthAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyIoNinthAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyIoNinthAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyIoNinthAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyIoNinthAbility::OnBackground() +{ + Ability::OnBackground(); +} +REGISTER_AA(VerifyIoNinthAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_second_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_second_ability.cpp new file mode 100644 index 00000000000..cf226c7eed4 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_second_ability.cpp @@ -0,0 +1,43 @@ +/* + * 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 "verify_io_second_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void VerifyIoSecondAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyIoSecondAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyIoSecondAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyIoSecondAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyIoSecondAbility::OnBackground() +{ + Ability::OnBackground(); +} + +REGISTER_AA(VerifyIoSecondAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_seventh_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_seventh_ability.cpp new file mode 100644 index 00000000000..5d0d3c91812 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_seventh_ability.cpp @@ -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. + */ + +#include "verify_io_seventh_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void VerifyIoSeventhAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyIoSeventhAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyIoSeventhAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyIoSeventhAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyIoSeventhAbility::OnBackground() +{ + Ability::OnBackground(); +} +REGISTER_AA(VerifyIoSeventhAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_sixth_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_sixth_ability.cpp new file mode 100644 index 00000000000..2256331c142 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_sixth_ability.cpp @@ -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. + */ + +#include "verify_io_sixth_ability.h" +#include "app_log_wrapper.h" +#include "skills.h" +namespace OHOS { +namespace AppExecFwk { +using IAbilityConnection = OHOS::AAFwk::IAbilityConnection; +using Skills = OHOS::AAFwk::Skills; +using PatternsMatcher = OHOS::AAFwk::PatternsMatcher; +using MatchType = OHOS::AAFwk::MatchType; +using WantParams = OHOS::AAFwk::WantParams; +void VerifyIoSixthAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyIoSixthAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyIoSixthAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyIoSixthAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyIoSixthAbility::OnBackground() +{ + Ability::OnBackground(); +} + +REGISTER_AA(VerifyIoSixthAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_tenth_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_tenth_ability.cpp new file mode 100644 index 00000000000..6d62ea6ddf1 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_tenth_ability.cpp @@ -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. + */ + +#include "verify_io_tenth_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void VerifyIoTenAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyIoTenAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyIoTenAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyIoTenAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyIoTenAbility::OnBackground() +{ + Ability::OnBackground(); +} +REGISTER_AA(VerifyIoTenAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_third_ability.cpp b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_third_ability.cpp new file mode 100644 index 00000000000..80e72321b24 --- /dev/null +++ b/frameworks/kits/tools/verifyAbility/verifyIOAbility/src/verify_io_third_ability.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 "verify_io_third_ability.h" +#include "app_log_wrapper.h" +namespace OHOS { +namespace AppExecFwk { +void VerifyIoThirdAbility::OnStart(const Want &want) +{ + Ability::OnStart(want); +} +void VerifyIoThirdAbility::OnStop() +{ + Ability::OnStop(); +} +void VerifyIoThirdAbility::OnActive() +{ + Ability::OnActive(); +} +void VerifyIoThirdAbility::OnInactive() +{ + Ability::OnInactive(); +} +void VerifyIoThirdAbility::OnBackground() +{ + Ability::OnBackground(); +} + +REGISTER_AA(VerifyIoThirdAbility) +void CleanCacheCallbackDerived::OnCleanCacheFinished(bool succeeded) +{} +void BundleStatusCallbackDerived::OnBundleStateChanged( + const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, const std::string &bundleName) +{} +sptr CleanCacheCallbackDerived::AsObject() +{ + return nullptr; +} +sptr BundleStatusCallbackDerived::AsObject() +{ + return nullptr; +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/ability_manager/BUILD.gn b/interfaces/innerkits/ability_manager/BUILD.gn old mode 100644 new mode 100755 index dfeddb31bbe..d76a6790b51 --- a/interfaces/innerkits/ability_manager/BUILD.gn +++ b/interfaces/innerkits/ability_manager/BUILD.gn @@ -18,6 +18,7 @@ config("ability_manager_public_config") { visibility = [ ":*" ] include_dirs = [ "include/", + "//third_party/jsoncpp/include", "${innerkits_path}/want/include", "//utils/native/base/include", "//utils/system/safwk/native/include", @@ -36,6 +37,7 @@ config("ability_manager_public_config") { ohos_shared_library("ability_manager") { sources = [ + "${services_path}/abilitymgr/src/aafwk_dummy_configuration.cpp", "${services_path}/abilitymgr/src/ability_connect_callback_stub.cpp", "${services_path}/abilitymgr/src/ability_manager_client.cpp", "${services_path}/abilitymgr/src/ability_manager_proxy.cpp", @@ -44,15 +46,18 @@ ohos_shared_library("ability_manager") { "${services_path}/abilitymgr/src/ability_record_info.cpp", "${services_path}/abilitymgr/src/ability_scheduler_proxy.cpp", "${services_path}/abilitymgr/src/ability_scheduler_stub.cpp", + "${services_path}/abilitymgr/src/ability_start_setting.cpp", "${services_path}/abilitymgr/src/caller_info.cpp", "${services_path}/abilitymgr/src/image_info.cpp", "${services_path}/abilitymgr/src/lifecycle_state_info.cpp", "${services_path}/abilitymgr/src/mission_description_info.cpp", + "${services_path}/abilitymgr/src/mission_option.cpp", "${services_path}/abilitymgr/src/mission_record_info.cpp", "${services_path}/abilitymgr/src/mission_snapshot_info.cpp", "${services_path}/abilitymgr/src/mission_stack_info.cpp", "${services_path}/abilitymgr/src/sender_info.cpp", "${services_path}/abilitymgr/src/stack_info.cpp", + "${services_path}/abilitymgr/src/stack_setting.cpp", "${services_path}/abilitymgr/src/want_sender_info.cpp", "${services_path}/abilitymgr/src/wants_info.cpp", "//foundation/aafwk/standard/frameworks/kits/ability/native/src/task_handler.cpp", @@ -72,6 +77,7 @@ ohos_shared_library("ability_manager") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/interfaces/innerkits/ability_manager/ability_manager_headers.gni b/interfaces/innerkits/ability_manager/ability_manager_headers.gni index d6a305e895d..23efb8011db 100644 --- a/interfaces/innerkits/ability_manager/ability_manager_headers.gni +++ b/interfaces/innerkits/ability_manager/ability_manager_headers.gni @@ -29,6 +29,11 @@ ability_manager_headers = { "want_sender_info.h", "want_sender_interface.h", "want_receiver_interface.h", + "aafwk_dummy_configuration.h", + "ability_window_configuration.h", + "ability_start_setting.h", + "mission_option.h", + "stack_setting.h", ] header_base = "interfaces/innerkits/ability_manager/include" } diff --git a/interfaces/innerkits/ability_manager/include/aafwk_dummy_configuration.h b/interfaces/innerkits/ability_manager/include/aafwk_dummy_configuration.h new file mode 100644 index 00000000000..405dda501d0 --- /dev/null +++ b/interfaces/innerkits/ability_manager/include/aafwk_dummy_configuration.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_INTERFACES_INNERKITS_CONFIGURATION_H +#define OHOS_AAFWK_INTERFACES_INNERKITS_CONFIGURATION_H + +#include + +#include "nocopyable.h" +#include "parcel.h" + +namespace OHOS { +namespace AAFwk { + +class DummyConfiguration : public Parcelable { +public: + DummyConfiguration() = default; + explicit DummyConfiguration(const std::string &name); + virtual ~DummyConfiguration() = default; + + /** + * @brief Obtains the name of the Configuration. + * + * @return Returns the Configuration name. + */ + inline const std::string &GetName() const + { + return testInfostr_; + } + + unsigned int Differ(const std::shared_ptr config) const; + + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static DummyConfiguration *Unmarshalling(Parcel &parcel); + +private: + std::string testInfostr_; +}; + +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_INTERFACES_INNERKITS_CONFIGURATION_H \ No newline at end of file diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_client.h b/interfaces/innerkits/ability_manager/include/ability_manager_client.h index f5955a07581..05ee7d2eff8 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_client.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_client.h @@ -96,7 +96,7 @@ public: * @param requestCode Ability request code. * @return Returns ERR_OK on success, others on failure. */ - ErrCode StartAbility(const Want &want, int requestCode = -1); + ErrCode StartAbility(const Want &want, int requestCode = DEFAULT_INVAL_VALUE); /** * StartAbility with want, send want to ability manager service. @@ -106,7 +106,19 @@ public: * @param requestCode Ability request code. * @return Returns ERR_OK on success, others on failure. */ - ErrCode StartAbility(const Want &want, const sptr &callerToken, int requestCode = -1); + ErrCode StartAbility( + const Want &want, const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE); + + /** + * Starts a new ability with specific start settings. + * + * @param want Indicates the ability to start. + * @param requestCode the resultCode of the ability to start. + * @param abilityStartSetting Indicates the setting ability used to start. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE); /** * TerminateAbility with want, return want from ability manager service. @@ -324,6 +336,8 @@ public: */ int GetMissionLockModeState(); + int UpdateConfiguration(const DummyConfiguration &config); + sptr GetWantSender(const WantSenderInfo &wantSenderInfo, const sptr &callerToken); ErrCode SendWantSender(const sptr &target, const SenderInfo &senderInfo); @@ -346,6 +360,63 @@ public: ErrCode GetPendingRequestWant(const sptr &target, std::shared_ptr &want); + /** + * Moving mission to the specified stack by mission option(Enter floating window mode). + * @param missionOption, target mission option + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode MoveMissionToFloatingStack(const MissionOption &missionOption); + + /** + * Moving mission to the specified stack by mission option(Enter floating window mode). + * @param missionOption, target mission option + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode MoveMissionToSplitScreenStack(const MissionOption &missionOption); + + /** + * minimize multiwindow by mission id. + * @param missionId, the id of target mission + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode MinimizeMultiWindow(int missionId); + + /** + * maximize multiwindow by mission id. + * @param missionId, the id of target mission + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode MaximizeMultiWindow(int missionId); + + /** + * Change the focus of ability in the mission stack. + * @param lostToken, the token of lost focus ability + * @param getToken, the token of get focus ability + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode ChangeFocusAbility(const sptr &lostFocusToken, const sptr &getFocusToken); + + /** + * get missions info of floating mission stack. + * @param list, mission info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetFloatingMissions(std::vector &list); + + /** + * close multiwindow by mission id. + * @param missionId, the id of target mission. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode CloseMultiWindow(int missionId); + + /** + * set special mission stack default settings. + * @param stackSetting, mission stack default settings. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode SetMissionStackSetting(const StackSetting &stackSetting); + private: static std::mutex mutex_; static std::shared_ptr instance_; diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_errors.h b/interfaces/innerkits/ability_manager/include/ability_manager_errors.h index 90e10ab1b1f..e829b47593e 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_errors.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_errors.h @@ -209,6 +209,73 @@ enum { * Result(2097193) for system is lock mission state. */ LOCK_MISSION_STATE_DENY_REQUEST, + /** + * Result(2097190) for move mission to stack: out of size of moving mission. + */ + MOVE_MISSION_TO_STACK_OUT_OF_SIZE, + /** + * Result(2097191) for move mission to stack: moving missions are not same window mode. + */ + MOVE_MISSION_TO_STACK_NOT_SAME_WIN_MODE, + /** + * Result(2097192) for move mission to stack: moving mission is not exist. + */ + MOVE_MISSION_TO_STACK_NOT_EXIST_MISSION, + /** + * Result(2097193) for move mission to stack: target mission or ability can't support multi window display. + */ + MOVE_MISSION_TO_STACK_NOT_SUPPORT_MULTI_WIN, + /** + * Result(2097194) for move mission to stack: target mission stack size is overflow. + */ + MOVE_MISSION_TO_STACK_TARGET_STACK_OVERFLOW, + /** + * Result(2097195) for move mission to stack: already in moving state, request is denied. + */ + MOVE_MISSION_TO_STACK_MOVING_DENIED, + /** + * Result(2097196) for minimize multi window failed. + */ + MINIMIZE_MULTI_WINDOW_FAILED, + /** + * Result(2097197) for maximize multiwindow: target mission is not exist in multiwindow stack. + */ + MAXIMIZE_MULTIWINDOW_NOT_EXIST, + /** + * Result(2097198) for maximize multi window failed. + */ + MAXIMIZE_MULTIWINDOW_FAILED, + /** + * Result(2097199) for change focus ability failed. + */ + CHANGE_FOCUS_ABILITY_FAILED, + /** + * Result(2097200) for get floating stack failed + */ + GET_FLOATING_STACK_FAILED, + /** + * Result(2097201) for close mutli window failed + */ + CLOSE_MULTI_WINDOW_FAILED, + /** + * Result(2097202) for start ability by setting failed + */ + START_ABILITY_SETTING_FAILED, + /** + * Result(2097203) for start ability by setting ,the ability not support multiwindow. + */ + START_ABILITY_SETTING_NOT_SUPPORT_MULTI_WIN, + + /** + * Result(2097194) for no found abilityrecord by caller + */ + NO_FOUND_ABILITY_BY_CALLER, + + /** + * Result(2097195) for ability visible attribute is false. + */ + ABILITY_VISIBLE_FALSE_DENY_REQUEST, + }; enum { diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h index 17930e108b3..92040bdee45 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h @@ -23,19 +23,24 @@ #include "ability_connect_callback_interface.h" #include "ability_scheduler_interface.h" +#include "ability_start_setting.h" #include "mission_snapshot_info.h" #include "ability_mission_info.h" +#include "mission_option.h" #include "stack_info.h" +#include "stack_setting.h" #include "uri.h" #include "want.h" #include "want_sender_info.h" #include "sender_info.h" #include "want_sender_interface.h" #include "want_receiver_interface.h" +#include "aafwk_dummy_configuration.h" namespace OHOS { namespace AAFwk { const std::string ABILITY_MANAGER_SERVICE_NAME = "AbilityManagerService"; +const int DEFAULT_INVAL_VALUE = -1; /** * @class IAbilityManager * IAbilityManager interface is used to access ability manager services. @@ -51,7 +56,7 @@ public: * @param requestCode, Ability request code. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, int requestCode = -1) = 0; + virtual int StartAbility(const Want &want, int requestCode = DEFAULT_INVAL_VALUE) = 0; /** * StartAbility with want, send want to ability manager service. @@ -61,7 +66,19 @@ public: * @param requestCode, Ability request code. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, const sptr &callerToken, int requestCode = -1) = 0; + virtual int StartAbility( + const Want &want, const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) = 0; + + /** + * Starts a new ability with specific start settings. + * + * @param want Indicates the ability to start. + * @param requestCode the resultCode of the ability to start. + * @param abilityStartSetting Indicates the setting ability used to start. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) = 0; /** * TerminateAbility, terminate the special ability. @@ -286,6 +303,64 @@ public: */ virtual int UninstallApp(const std::string &bundleName) = 0; + /** + * Moving mission to the specified stack by mission option(Enter floating window mode). + * @param missionOption, target mission option + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MoveMissionToFloatingStack(const MissionOption &missionOption) = 0; + + /** + * Moving mission to the specified stack by mission option(Enter floating window mode). + * @param missionOption, target mission option + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MoveMissionToSplitScreenStack(const MissionOption &missionOption) = 0; + + /** + * Change the focus of ability in the mission stack. + * @param lostToken, the token of lost focus ability + * @param getToken, the token of get focus ability + * @return Returns ERR_OK on success, others on failure. + */ + virtual int ChangeFocusAbility( + const sptr &lostFocusToken, const sptr &getFocusToken) = 0; + + /** + * minimize multiwindow by mission id. + * @param missionId, the id of target mission + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MinimizeMultiWindow(int missionId) = 0; + + /** + * maximize multiwindow by mission id. + * @param missionId, the id of target mission + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MaximizeMultiWindow(int missionId) = 0; + + /** + * get missions info of floating mission stack. + * @param list, mission info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int GetFloatingMissions(std::vector &list) = 0; + + /** + * close multiwindow by mission id. + * @param missionId, the id of target mission. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CloseMultiWindow(int missionId) = 0; + + /** + * set special mission stack default settings. + * @param stackSetting, mission stack default settings. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetMissionStackSetting(const StackSetting &stackSetting) = 0; + /** Checks whether this ability is the first ability in a mission. * @param lostToken, the token of ability * @return Returns true is first in Mission. @@ -347,6 +422,14 @@ public: */ virtual int GetMissionLockModeState() = 0; + /** + * Updates the configuration by modifying the configuration. + * + * @param config Indicates the new configuration + * @return Returns ERR_OK on success, others on failure. + */ + virtual int UpdateConfiguration(const DummyConfiguration &config) = 0; + virtual sptr GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) = 0; @@ -429,6 +512,30 @@ public: // ipc id for terminate ability by callerToken and request code (19) TERMINATE_ABILITY_BY_CALLER, + // ipc id for move mission to floating stack (20) + MOVE_MISSION_TO_FLOATING_STACK, + + // ipc id for move mission to floating stack (21) + MOVE_MISSION_TO_SPLITSCREEN_STACK, + + // ipc id for change focus ability (22) + CHANGE_FOCUS_ABILITY, + + // ipc id for Minimize MultiWindow (23) + MINIMIZE_MULTI_WINDOW, + + // ipc id for Maximize MultiWindow (24) + MAXIMIZE_MULTI_WINDOW, + + // ipc id for get floating missions (25) + GET_FLOATING_MISSIONS, + + // ipc id for get floating missions (26) + CLOSE_MULTI_WINDOW, + + // ipc id for set mission stack setting (27) + SET_STACK_SETTING, + // ipc id for isfirstinmission app (28) IS_FIRST_IN_MISSION, @@ -456,6 +563,9 @@ public: // ipc id for get mission lock mode state (36) GET_MISSION_LOCK_MODE_STATE, + // ipc id for update configuration (37) + UPDATE_CONFIGURATION, + // ipc id 1001-2000 for DMS // ipc id for starting ability (1001) START_ABILITY = 1001, @@ -494,6 +604,9 @@ public: GET_PENDING_REQUEST_WANT, + // ipc id for starting ability by settings(1006) + START_ABILITY_FOR_SETTINGS, + // ipc id 2001-3000 for tools // ipc id for dumping state (2001) DUMP_STATE = 2001, diff --git a/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h b/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h index 989987c7021..cdb491d7224 100644 --- a/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h +++ b/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h @@ -21,6 +21,7 @@ #include "dummy_values_bucket.h" #include "dummy_data_ability_predicates.h" #include "dummy_result_set.h" +#include "aafwk_dummy_configuration.h" #include "lifecycle_state_info.h" #include "pac_map.h" #include "want.h" @@ -84,6 +85,11 @@ public: */ virtual void ScheduleRestoreAbilityState(const PacMap &inState) = 0; + /* + * ScheduleUpdateConfiguration, scheduling update configuration. + */ + virtual void ScheduleUpdateConfiguration(const DummyConfiguration &config) = 0; + /** * @brief Obtains the MIME types of files supported. * @@ -196,6 +202,48 @@ public: */ virtual int BatchInsert(const Uri &uri, const std::vector &values) = 0; + /** + * @brief notify multi window mode changed. + * + * @param winModeKey Indicates ability Window display mode. + * @param flag Indicates this ability has been enter this mode. + */ + virtual void NotifyMultiWinModeChanged(int32_t winModeKey, bool flag) = 0; + + /** + * @brief notify this ability is top active ability. + * + * @param flag true: Indicates this ability is top active ability + */ + virtual void NotifyTopActiveAbilityChanged(bool flag) = 0; + + /** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the + * context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to + * any method that is called on the Data ability must require normalization verification and denormalization. The + * default implementation of this method returns null, indicating that this Data ability does not support URI + * normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ + virtual Uri NormalizeUri(const Uri &uri) = 0; + + /** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed + * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found + * in the current environment. + */ + virtual Uri DenormalizeUri(const Uri &uri) = 0; + enum { // ipc id for scheduling ability to a state of life cycle SCHEDULE_ABILITY_TRANSACTION = 0, @@ -248,8 +296,19 @@ public: // ipc id for scheduling BatchInsert​ SCHEDULE_BATCHINSERT, - // ipc id for display unlock message - DISPLAY_UNLOCK_MISSION_MESSAGE + // ipc id for scheduling multi window changed + MULTI_WIN_CHANGED, + + // ipc id for scheduling update configuration + SCHEDULE_UPDATE_CONFIGURATION, + + // ipc id for notify this ability is top active + TOP_ACTIVE_ABILITY_CHANGED, + // ipc id for scheduling NormalizeUri + SCHEDULE_NORMALIZEURI, + + // ipc id for scheduling DenormalizeUri + SCHEDULE_DENORMALIZEURI, }; }; } // namespace AAFwk diff --git a/interfaces/innerkits/ability_manager/include/ability_start_setting.h b/interfaces/innerkits/ability_manager/include/ability_start_setting.h new file mode 100644 index 00000000000..56ed2a09a71 --- /dev/null +++ b/interfaces/innerkits/ability_manager/include/ability_start_setting.h @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_ABILITY_START_SETTING_H +#define OHOS_AAFWK_ABILITY_START_SETTING_H + +#include +#include +#include +#include +#include "parcel.h" + +namespace OHOS { +namespace AAFwk { + +class AbilityStartSetting final : public Parcelable, public std::enable_shared_from_this { +public: + static const std::string BOUNDS_KEY; + static const std::string WINDOW_DISPLAY_ID_KEY; + static const std::string WINDOW_MODE_KEY; + + /** + * @brief Construct copy function. + * @param other indicates instance of abilitystartsetting object + * @return none. + */ + AbilityStartSetting(const AbilityStartSetting &other); + /** + * @brief Overload assignment operation. + * @param other indicates instance of abilitystartsetting object. + * @return Returns current instance of abilitystartsetting object. + */ + AbilityStartSetting &operator=(const AbilityStartSetting &other); + + virtual ~AbilityStartSetting() = default; + + /** + * @brief Obtains the names of all the attributes that have been added to this AbilityStartSetting object. + * + * @return Returns the set of attribute names included in this AbilityStartSetting object. + */ + std::set GetPropertiesKey(); + + /** + * @brief Obtains the names of all the attributes that have been added to this AbilityStartSetting object. + * + * @return Returns the set of attribute names included in this AbilityStartSetting object. + */ + static std::shared_ptr GetEmptySetting(); + + /** + * @brief Checks whether this AbilityStartSetting object is empty. + * + * @return Returns true if this AbilityStartSetting object is empty and animatorOption is null; returns false + * otherwise. + */ + bool IsEmpty(); + /** + * @brief Sets the names of all the attributes of the AbilityStartSetting object. + * + * @param key Indicates the name of the key. + * @param value The window display mode of the values. + */ + void AddProperty(const std::string &key, const std::string &value); + + /** + * @brief Gets the name of the attributes of the AbilityStartSetting object. + * + * @param key Indicates the name of the key. + * @return Returns value Indicates the value of the attributes of the AbilityStartSetting object + */ + std::string GetProperty(const std::string &key); + + /* + * @brief Write the data of AbilityStartSetting to the file stream + * @param parcel indicates write the data of AbilityStartSetting to the file stream through parcel + * @return bool + */ + bool Marshalling(Parcel &parcel) const; + + /** + * @brief Reading file stream through parcel to generate AbilityStartSetting instance + * @param parcel indicates reading file stream through parcel to generate AbilityStartSetting instance + * @return AbilityStartSetting shared_ptr + */ + static AbilityStartSetting *Unmarshalling(Parcel &parcel); + +protected: + AbilityStartSetting() = default; + friend std::shared_ptr AbilityStartSettingCreator(); + +private: + std::map abilityStarKey_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_ABILITY_START_SETTING_H diff --git a/interfaces/innerkits/ability_manager/include/ability_window_configuration.h b/interfaces/innerkits/ability_manager/include/ability_window_configuration.h new file mode 100644 index 00000000000..9075e3ece44 --- /dev/null +++ b/interfaces/innerkits/ability_manager/include/ability_window_configuration.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_AAFWK_ABILITY_WINDOW_CONFIGURATION_H +#define OHOS_AAFWK_ABILITY_WINDOW_CONFIGURATION_H + +namespace OHOS { +namespace AAFwk { +enum AbilityWindowConfiguration { + /** + * Indicates that the Page ability is in an undefined window display mode. + */ + MULTI_WINDOW_DISPLAY_UNDEFINED = 0, + /** + * Indicates that the Page ability is in the fullscreen display mode. + */ + MULTI_WINDOW_DISPLAY_FULLSCREEN = 1, + /** + * Indicates that the Page ability is displayed in the primary window when it is in split-screen mode. + * The primary window, which triggers the split-screen mode, refers to the top window in the + * top/bottom split-screen mode or the left window in the left/right screen mode. + */ + MULTI_WINDOW_DISPLAY_PRIMARY = 100, + /** + * Indicates that the Page ability is displayed in the secondary window when it is in split-screen mode. + * The secondary window refers to the bottom window in the top/bottom split-screen mode or + * the right window in the left/right screen mode. + */ + MULTI_WINDOW_DISPLAY_SECONDARY = 101, + /** + * Indicates that the Page ability is in floating window display mode. + */ + MULTI_WINDOW_DISPLAY_FLOATING = 102 +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_ABILITY_WINDOW_CONFIGURATION_H \ No newline at end of file diff --git a/interfaces/innerkits/ability_manager/include/lifecycle_state_info.h b/interfaces/innerkits/ability_manager/include/lifecycle_state_info.h index 17c96d16e26..858410bf59a 100644 --- a/interfaces/innerkits/ability_manager/include/lifecycle_state_info.h +++ b/interfaces/innerkits/ability_manager/include/lifecycle_state_info.h @@ -19,6 +19,7 @@ #include #include "parcel.h" +#include "ability_start_setting.h" #include "caller_info.h" namespace OHOS { @@ -45,6 +46,7 @@ struct LifeCycleStateInfo : public Parcelable { int missionId = -1; int stackId = -1; CallerInfo caller; + std::shared_ptr setting = nullptr; bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; diff --git a/interfaces/innerkits/ability_manager/include/mission_option.h b/interfaces/innerkits/ability_manager/include/mission_option.h new file mode 100644 index 00000000000..ca294b28197 --- /dev/null +++ b/interfaces/innerkits/ability_manager/include/mission_option.h @@ -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. + */ + +#ifndef OHOS_AAFWK_MISSION_OPTION_H +#define OHOS_AAFWK_MISSION_OPTION_H + +#include "ability_window_configuration.h" +#include "parcel.h" + +#include + +namespace OHOS { +namespace AAFwk { +const int32_t DISPLAY_DEFAULT_ID = 0; +const int32_t MISSION_INVAL_VALUE = -1; +const int32_t DEFAULT_USER_ID = 0; +/** + * @class MissionOption + * MissionOption contains option information for mission which one needs to be moved. + */ +class MissionOption final : public Parcelable { +public: + MissionOption() = default; + virtual ~MissionOption() = default; + + bool IsSameWindowMode(const AbilityWindowConfiguration &key) const; + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static MissionOption *Unmarshalling(Parcel &parcel); + + int32_t userId = DEFAULT_USER_ID; // stack 's user id ,default value is 0 + int32_t missionId = MISSION_INVAL_VALUE; // mission record id + // multi window mode key , default in an undefined + AbilityWindowConfiguration winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED; + int32_t displayKey = DISPLAY_DEFAULT_ID; // display screen device id + + void AddProperty(const std::string &key, const std::string &value); + void GetProperty(const std::string &key, std::string &value); + +private: + std::map properties_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_MISSION_OPTION_H \ No newline at end of file diff --git a/interfaces/innerkits/ability_manager/include/stack_setting.h b/interfaces/innerkits/ability_manager/include/stack_setting.h new file mode 100644 index 00000000000..4e7da3f1592 --- /dev/null +++ b/interfaces/innerkits/ability_manager/include/stack_setting.h @@ -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. + */ + +#ifndef OHOS_AAFWK_STACK_SETTING_H +#define OHOS_AAFWK_STACK_SETTING_H + +#include "ability_window_configuration.h" +#include "parcel.h" + +#include + +namespace OHOS { +namespace AAFwk { +enum STACK_ID { + LAUNCHER_MISSION_STACK_ID = 0, + DEFAULT_MISSION_STACK_ID, + SPLIT_SCREEN_MISSION_STACK_ID, + FLOATING_MISSION_STACK_ID +}; +/** + * @struct StackSetting + * StackSetting contains default setting for mission stack. + */ +struct StackSetting final : public Parcelable { + + int32_t userId = 0; // stack 's user id ,default value is 0 + // multi window mode key , default in an undefined + STACK_ID stackId = DEFAULT_MISSION_STACK_ID; + int32_t maxHoldMission = -1; // default unlimited. + bool isSyncVisual = false; // default don'r support synchronous visualization when multiwindow + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static StackSetting *Unmarshalling(Parcel &parcel); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_STACK_SETTING_H \ No newline at end of file diff --git a/interfaces/innerkits/base/BUILD.gn b/interfaces/innerkits/base/BUILD.gn old mode 100644 new mode 100755 index e5b4809c6b9..071b0770b7a --- a/interfaces/innerkits/base/BUILD.gn +++ b/interfaces/innerkits/base/BUILD.gn @@ -24,6 +24,8 @@ config("base_public_config") { "//foundation/aafwk/standard/interfaces/innerkits/base/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", "//foundation/appexecfwk/standard/common/log/include", + "//third_party/jsoncpp/include", + "//utils/native/base/include", ] } @@ -41,17 +43,17 @@ ohos_shared_library("base") { "${baseImpl}/float_wrapper.cpp", "${baseImpl}/int_wrapper.cpp", "${baseImpl}/long_wrapper.cpp", - "${baseImpl}/pac_map_node.cpp", - "${baseImpl}/pac_map_node_array.cpp", - "${baseImpl}/pac_map_node_base.cpp", - "${baseImpl}/pac_map_node_user_object.cpp", "${baseImpl}/short_wrapper.cpp", "${baseImpl}/string_wrapper.cpp", + "${baseImpl}/user_object_wrapper.cpp", "${baseImpl}/zchar_wrapper.cpp", ] configs = [ ":base_config" ] public_configs = [ ":base_public_config" ] - deps = [ "//utils/native/base:utils" ] + deps = [ + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] subsystem_name = "aafwk" part_name = "aafwk_standard" diff --git a/interfaces/innerkits/base/include/ohos/aafwk/base/base_interfaces.h b/interfaces/innerkits/base/include/ohos/aafwk/base/base_interfaces.h old mode 100644 new mode 100755 index 6a82d185ee2..d0f31baf5db --- a/interfaces/innerkits/base/include/ohos/aafwk/base/base_interfaces.h +++ b/interfaces/innerkits/base/include/ohos/aafwk/base/base_interfaces.h @@ -14,11 +14,12 @@ */ #ifndef OHOS_AAFWK_BASE_IINTERFACE_H #define OHOS_AAFWK_BASE_IINTERFACE_H - +#include #include #include "base_def.h" #include "refbase.h" +#include "user_object_base.h" namespace OHOS { namespace AAFwk { @@ -180,6 +181,33 @@ INTERFACE(IArray, 875b9da6 - 9913 - 4370 - 8847 - e1961be6e560) virtual ErrCode Set(long index, /* [in] */ IInterface *value) = 0; /* [in] */ }; + +INTERFACE(IPacMap, f92066fd - fd0c - 401b - a3f6 - 626da3bac9d5) +{ + inline static IPacMap *Query(IInterface * object) + { + if (object == nullptr) { + return nullptr; + } + return static_cast(object->Query(g_IID_IPacMap)); + } + + virtual bool FromString(const std::string &str) = 0; +}; + +INTERFACE(IUserObject, 4edb325d - 8532 - 4af7 - b42e - 82f4f29dfdea) +{ + inline static IUserObject *Query(IInterface * object) + { + if (object == nullptr) { + return nullptr; + } + return static_cast(object->Query(g_IID_IUserObject)); + } + + virtual ErrCode GetValue(std::shared_ptr & value) = 0; /* [out] */ +}; + } // namespace AAFwk } // namespace OHOS #endif // OHOS_AAFWK_BASE_IINTERFACE_H diff --git a/interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node.h b/interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node.h deleted file mode 100644 index 4ce92f5981a..00000000000 --- a/interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node.h +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_AppExecFwk_PAC_MAP_NODE_H -#define OHOS_AppExecFwk_PAC_MAP_NODE_H - -#include "parcel.h" - -namespace OHOS { -namespace AppExecFwk { -// base: 0x00000001 ~ 0x000000FF -// array: 0x00000100 ~ 0x0000FF00 -// boject: 0x00010000 ~ 0x00FF0000 -#define PACMAP_DATA_SHORT 0x00000001 -#define PACMAP_DATA_INTEGER 0x00000002 -#define PACMAP_DATA_LONG 0x00000003 -#define PACMAP_DATA_CHAR 0x00000004 -#define PACMAP_DATA_BYTE 0x00000005 -#define PACMAP_DATA_BOOLEAN 0x00000007 -#define PACMAP_DATA_FLOAT 0x00000008 -#define PACMAP_DATA_DOUBLE 0x00000009 -#define PACMAP_DATA_STRING 0x0000000A -#define PACMAP_DATA_ARRAY_SHORT 0x00000100 -#define PACMAP_DATA_ARRAY_INTEGER 0x00000200 -#define PACMAP_DATA_ARRAY_LONG 0x00000300 -#define PACMAP_DATA_ARRAY_CHAR 0x00000400 -#define PACMAP_DATA_ARRAY_BYTE 0x00000500 -#define PACMAP_DATA_ARRAY_BOOLEAN 0x00000600 -#define PACMAP_DATA_ARRAY_FLOAT 0x00000700 -#define PACMAP_DATA_ARRAY_DOUBLE 0x00000800 -#define PACMAP_DATA_ARRAY_STRING 0x00000900 -#define PACMAP_DATA_OBJECT 0x00010000 - -typedef enum { - DT_PACMAP_BASE = 0, /* Basic data types */ - DT_PACMAP_ARRAY, /* Basic aray of data types */ - DT_PACMAP_OBJECT /* custum object */ -} PacMapNodeType; - -class PacMapNode { -public: - /** - * @brief A constructor data. - * @param data_type Rough data types, it is an enumerated type, see {@PacMapNodeType}. - */ - PacMapNode(PacMapNodeType data_type) : data_type_(data_type) - {} - virtual ~PacMapNode() = default; - PacMapNode() = default; - - /** - * @brief A constructor data. - */ - PacMapNode(const PacMapNode &other); - - PacMapNode &operator=(const PacMapNode &other); - - inline bool IsBase(void) const - { - return data_type_ == DT_PACMAP_BASE; - } - inline bool IsArray(void) const - { - return data_type_ == DT_PACMAP_ARRAY; - } - inline bool IsObject(void) const - { - return data_type_ == DT_PACMAP_OBJECT; - } - inline PacMapNodeType GetMapNodeTypType(void) - { - return data_type_; - } - - /** - * @brief Indicates whether some other object is "equal to" this one. - * @param other The object with which to compare. - * @return Resturns true if this object is the same as the obj argument; false otherwise. - */ - virtual bool Equals(const PacMapNode *other) = 0; - - /** - * @brief Copy the data of the specified object to the current object with deepcopy - * @param other The original object that stores the data. - */ - virtual void DeepCopy(const PacMapNode *other) = 0; - - /** - * @brief Marshals this Sequenceable object to a Parcel. - * @param key Indicates the key in String format. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Marshals success returns true, otherwise returns false. - */ - virtual bool Marshalling(const std::string &key, Parcel &parcel) const = 0; - - /** - * @brief Unmarshals this Sequenceable object from a Parcel. - * @param dataType Indicates the type of data stored. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Unmarshals success returns true, otherwise returns false. - */ - virtual bool Unmarshalling(int32_t dataType, Parcel &parcel) = 0; - -protected: - PacMapNodeType data_type_; -}; -} // namespace AppExecFwk -} // namespace OHOS - -#endif diff --git a/interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node_array.h b/interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node_array.h deleted file mode 100644 index 77a83465edb..00000000000 --- a/interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node_array.h +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_AppExecFwk_PAC_MAP_NODE_ARRAY_H -#define OHOS_AppExecFwk_PAC_MAP_NODE_ARRAY_H - -#include "parcel.h" -#include "base_types.h" -#include "array_wrapper.h" -#include "bool_wrapper.h" -#include "zchar_wrapper.h" -#include "byte_wrapper.h" -#include "double_wrapper.h" -#include "float_wrapper.h" -#include "int_wrapper.h" -#include "long_wrapper.h" -#include "short_wrapper.h" -#include "string_wrapper.h" - -#include "pac_map_node.h" - -namespace OHOS { -namespace AppExecFwk { -class PacMapNodeTypeArray : public PacMapNode { -public: - PacMapNodeTypeArray() : PacMapNode(DT_PACMAP_ARRAY), value_(nullptr) - {} - virtual ~PacMapNodeTypeArray() = default; - - PacMapNodeTypeArray(const PacMapNodeTypeArray &other); - PacMapNodeTypeArray &operator=(const PacMapNodeTypeArray &other); - - /** - * @brief Adds some short values to current object. - * @param value Added list of data. - */ - void PutShortValueArray(const std::vector &value); - - /** - * @brief Adds some int values to current object. - * @param value Added list of data. - */ - void PutIntegerValueArray(const std::vector &value); - - /** - * @brief Adds some long values to current object. - * @param value Added list of data. - */ - void PutLongValueArray(const std::vector &value); - - /** - * @brief Adds some boolean values to current object. - * @param value Added list of data. - */ - void PutBooleanValueArray(const std::vector &value); - - /** - * @brief Adds some char values to current object. - * @param value Added list of data. - */ - void PutCharValueArray(const std::vector &value); - - /** - * @brief Adds some byte values to current object. - * @param value Added list of data. - */ - void PutByteValueArray(const std::vector &value); - - /** - * @brief Adds some float values to current object. - * @param value Added list of data. - */ - void PutFloatValueArray(const std::vector &value); - - /** - * @brief Adds some double values to current object. - * @param value Added list of data. - */ - void PutDoubleValueArray(const std::vector &value); - - /** - * @brief Adds some string {std::string} values to current object. - * @param value Added list of data. - */ - void PutStringValueArray(const std::vector &value); - - /** - * @brief Obtains some short values. - * @param value Save the returned short values. - */ - void GetShortValueArray(std::vector &value); - - /** - * @brief Obtains some int values. - * @param value Save the returned int values. - */ - void GetIntegerValueArray(std::vector &value); - - /** - * @brief Obtains some long values. - * @param value Save the returned long values. - */ - void GetLongValueArray(std::vector &value); - - /** - * @brief Obtains some boolean values. - * @param value Save the returned boolean values. - */ - void GetBooleanValueArray(std::vector &value); - - /** - * @brief Obtains some char values. - * @param value Save the returned char values. - */ - void GetCharValueArray(std::vector &value); - - /** - * @brief Obtains some byte values. - * @param value Save the returned byte values. - */ - void GetByteValueArray(std::vector &value); - - /** - * @brief Obtains some float values. - * @param value Save the returned float values. - */ - void GetFloatValueArray(std::vector &value); - - /** - * @brief Obtains some double values. - * @param value Save the returned double values. - */ - void GetDoubleValueArray(std::vector &value); - - /** - * @brief Obtains some std::string values. - * @param value Save the returned std::string values. - */ - void GetStringValueArray(std::vector &value); - - /** - * @brief Indicates whether some other object is "equal to" this one. - * @param other The object with which to compare. - * @return true if this object is the same as the obj argument; false otherwise. - */ - virtual bool Equals(const PacMapNode *other) override; - - /** - * @brief Copy the data of the specified object to the current object with deepcopy - * @param other The original object that stores the data. - */ - virtual void DeepCopy(const PacMapNode *other) override; - - /** - * @brief Whether the stored data is of short type. - * @return If yes return true, otherwise return false. - */ - bool IsShort(void); - - /** - * @brief Whether the stored data is of integer type. - * @return If yes return true, otherwise return false. - */ - bool IsInteger(void); - - /** - * @brief Whether the stored data is of long type. - * @return If yes return true, otherwise return false. - */ - bool IsLong(void); - - /** - * @brief Whether the stored data is of char type. - * @return If yes return true, otherwise return false. - */ - bool IsChar(void); - - /** - * @brief Whether the stored data is of byte type. - * @return If yes return true, otherwise return false. - */ - bool IsByte(void); - - /** - * @brief Whether the stored data is of boolean type. - * @return If yes return true, otherwise return false. - */ - bool IsBoolean(void); - - /** - * @brief Whether the stored data is of float type. - * @return If yes return true, otherwise return false. - */ - bool IsFloat(void); - - /** - * @brief Whether the stored data is of double type. - * @return If yes return true, otherwise return false. - */ - bool IsDouble(void); - - /** - * @brief Whether the stored data is of string type. - * @return If yes return true, otherwise return false. - */ - bool IsString(void); - - /** - * @brief Marshals this Sequenceable object to a Parcel. - * @param key Indicates the key in String format. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Marshals success returns true, otherwise returns false. - */ - virtual bool Marshalling(const std::string &key, Parcel &parcel) const override; - - /** - * @brief Unmarshals this Sequenceable object from a Parcel. - * @param dataType Indicates the type of data stored. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Unmarshals success returns true, otherwise returns false. - */ - virtual bool Unmarshalling(int32_t dataType, Parcel &parcel) override; - -private: - sptr value_; - - void InnerDeepCopy(const PacMapNodeTypeArray *other); - bool WriteLongVector(Parcel &parcel, const std::vector &value) const; - bool ReadLongVector(Parcel &parcel, std::vector &value); - - bool MarshallingArrayString(Parcel &parcel) const; - bool MarshallingArrayBoolean(Parcel &parcel) const; - bool MarshallingArrayByte(Parcel &parcel) const; - bool MarshallingArrayShort(Parcel &parcel) const; - bool MarshallingArrayInteger(Parcel &parcel) const; - bool MarshallingArrayLong(Parcel &parcel) const; - bool MarshallingArrayFloat(Parcel &parcel) const; - bool MarshallingArrayDouble(Parcel &parcel) const; - - bool UnmarshallingArrayShort(Parcel &parcel); - bool UnmarshallingArrayInteger(Parcel &parcel); - bool UnmarshallingArrayLong(Parcel &parcel); - bool UnmarshallingArrayByte(Parcel &parcel); - bool UnmarshallingArrayBoolean(Parcel &parcel); - bool UnmarshallingArrayFloat(Parcel &parcel); - bool UnmarshallingArrayDouble(Parcel &parcel); - bool UnmarshallingArrayString(Parcel &parcel); -}; -} // namespace AppExecFwk -} // namespace OHOS - -#endif diff --git a/interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node_base.h b/interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node_base.h deleted file mode 100755 index 755204d3019..00000000000 --- a/interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node_base.h +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_AppExecFwk_PAC_MAP_NODE_BASE_H -#define OHOS_AppExecFwk_PAC_MAP_NODE_BASE_H - -#include "parcel.h" -#include "base_types.h" -#include "bool_wrapper.h" -#include "zchar_wrapper.h" -#include "byte_wrapper.h" -#include "double_wrapper.h" -#include "float_wrapper.h" -#include "int_wrapper.h" -#include "long_wrapper.h" -#include "short_wrapper.h" -#include "string_wrapper.h" - -#include "pac_map_node.h" - -namespace OHOS { -namespace AppExecFwk { -class PacMapNodeTypeBase : public PacMapNode { -public: - PacMapNodeTypeBase() : PacMapNode(DT_PACMAP_BASE), value_(nullptr) - {} - virtual ~PacMapNodeTypeBase() = default; - - PacMapNodeTypeBase(const PacMapNodeTypeBase &other); - PacMapNodeTypeBase &operator=(const PacMapNodeTypeBase &other); - - /** - * @brief Adds a short value to current object. - * @param value Added data. - */ - void PutShortValue(short value); - - /** - * @brief Adds a int value to current object. - * @param value Added data. - */ - void PutIntValue(int value); - - /** - * @brief Adds a long value to current object. - * @param value Added data. - */ - void PutLongValue(long value); - - /** - * @brief Adds a boolean value to current object. - * @param value Added data. - */ - void PutBooleanValue(bool value); - - /** - * @brief Adds a char value to current object. - * @param value Added data. - */ - void PutCharValue(char value); - - /** - * @brief Adds a byte value to current object. - * @param value Added data. - */ - void PutByteValue(AAFwk::byte value); - - /** - * @brief Adds a float value to current object. - * @param value Added data. - */ - void PutFloatValue(float value); - - /** - * @brief Adds a double value to current object. - * @param value Added data. - */ - void PutDoubleValue(double value); - - /** - * @brief Adds a string {std::string} value to current object. - * @param value Added data. - */ - void PutStringValue(const std::string &value); - - /** - * @brief Obtains the short value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the short value, otherwise return the @a defaultValue. - */ - short GetShortValue(short defaultValue = 0); - - /** - * @brief Obtains the int value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the int value, otherwise return the @a defaultValue. - */ - int GetIntegerValue(int defaultValue = 0); - - /** - * @brief Obtains the long value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the long value, otherwise return the @a defaultValue. - */ - long GetLongValue(long defaultValue = 0); - - /** - * @brief Obtains the boolean value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the boolean value, otherwise return the @a defaultValue. - */ - bool GetBooleanValue(bool defaultValue = false); - - /** - * @brief Obtains the char value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the char value, otherwise return the @a defaultValue. - */ - char GetCharValue(char defaultValue = 0x00); - - /** - * @brief Obtains the byte value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the byte value, otherwise return the @a defaultValue. - */ - AAFwk::byte GetByteValue(AAFwk::byte defaultValue = 0x00); - - /** - * @brief Obtains the float value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the float value, otherwise return the @a defaultValue. - */ - float GetFloatValue(float defaultValue = 0.0f); - - /** - * @brief Obtains the double value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the double value, otherwise return the @a defaultValue. - */ - double GetDoubleValue(double defaultValue = 0.0); - - /** - * @brief Obtains the string {std::string} value. - * @param defaultValue The return value when the function fails. - * @return If the match is successful, return the std::string value, otherwise return the @a defaultValue. - */ - std::string GetStringValue(const std::string &defaultValue = ""); - - /** - * @brief Whether the stored data is of short type. - * @return If yes return true, otherwise return false. - */ - bool IsShort(void); - - /** - * @brief Whether the stored data is of integer type. - * @return If yes return true, otherwise return false. - */ - bool IsInteger(void); - - /** - * @brief Whether the stored data is of long type. - * @return If yes return true, otherwise return false. - */ - bool IsLong(void); - - /** - * @brief Whether the stored data is of char type. - * @return If yes return true, otherwise return false. - */ - bool IsChar(void); - - /** - * @brief Whether the stored data is of byte type. - * @return If yes return true, otherwise return false. - */ - bool IsByte(void); - - /** - * @brief Whether the stored data is of boolean type. - * @return If yes return true, otherwise return false. - */ - bool IsBoolean(void); - - /** - * @brief Whether the stored data is of float type. - * @return If yes return true, otherwise return false. - */ - bool IsFloat(void); - - /** - * @brief Whether the stored data is of double type. - * @return If yes return true, otherwise return false. - */ - bool IsDouble(void); - - /** - * @brief Whether the stored data is of string type. - * @return If yes return true, otherwise return false. - */ - bool IsString(void); - - /** - * @brief Indicates whether some other object is "equal to" this one. - * @param other The object with which to compare. - * @return true if this object is the same as the obj argument; false otherwise. - */ - virtual bool Equals(const PacMapNode *other) override; - - /** - * @brief Copy the data of the specified object to the current object with deepcopy - * @param other The original object that stores the data. - */ - virtual void DeepCopy(const PacMapNode *other) override; - - /** - * @brief Marshals this Sequenceable object to a Parcel. - * @param key Indicates the key in String format. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Marshals success returns true, otherwise returns false. - */ - virtual bool Marshalling(const std::string &key, Parcel &parcel) const override; - - /** - * @brief Unmarshals this Sequenceable object from a Parcel. - * @param dataType Indicates the type of data stored. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Unmarshals success returns true, otherwise returns false. - */ - virtual bool Unmarshalling(int32_t dataType, Parcel &parcel) override; - -private: - sptr value_; - - void InnerDeepCopy(const PacMapNodeTypeBase *other); - bool WriteLong(Parcel &parcel, long value) const; - bool ReadLong(Parcel &parcel, long &value); - - bool ReadFromParcelShort(Parcel &parcel); - bool ReadFromParcelInt(Parcel &parcel); - bool ReadFromParcelLong(Parcel &parcel); - bool ReadFromParcelByte(Parcel &parcel); - bool ReadFromParcelBool(Parcel &parcel); - bool ReadFromParcelFloat(Parcel &parcel); - bool ReadFromParcelString(Parcel &parcel); - bool ReadFromParcelDouble(Parcel &parcel); -}; -} // namespace AppExecFwk -} // namespace OHOS - -#endif diff --git a/interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node_user_object.h b/interfaces/innerkits/base/include/ohos/aafwk/base/user_object_base.h similarity index 36% rename from interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node_user_object.h rename to interfaces/innerkits/base/include/ohos/aafwk/base/user_object_base.h index 3beb314cece..e6ff75505a2 100755 --- a/interfaces/innerkits/base/include/ohos/aafwk/base/pac_map_node_user_object.h +++ b/interfaces/innerkits/base/include/ohos/aafwk/base/user_object_base.h @@ -12,26 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef OHOS_AppExecFwk_PAC_MAP_NODE_USER_OBJECT_H -#define OHOS_AppExecFwk_PAC_MAP_NODE_USER_OBJECT_H - -#include -#include +#ifndef OHOS_APPEXECFWK_USER_OBJECT_BASE_H +#define OHOS_APPEXECFWK_USER_OBJECT_BASE_H #include #include "parcel.h" -#include "pac_map_node.h" - +#include "string_ex.h" namespace OHOS { -namespace AppExecFwk { -/** - * Tusermapobject is used as the base class for object deserialization - */ -class TUserMapObject : public Parcelable { +namespace AAFwk { +class UserObjectBase : public Parcelable { public: - TUserMapObject(const std::string &className) : class_name_(className) + UserObjectBase(const std::string &className) : class_name_(className) {} - virtual ~TUserMapObject() = default; + virtual ~UserObjectBase() = default; inline void SetClassName(const std::string &className) { @@ -41,127 +33,99 @@ public: { return class_name_; } + /** + * @brief The current object parameter is converted to a string + * @param none + * @return returns string of current object parameter + */ + virtual std::string ToString() const = 0; + + /** + * @brief The current object parameter is converted to a string + * @param none + * @return returns string of current object parameter + */ + virtual void Parse(const std::string &str) = 0; + + /** + * @brief Copy the data of the specified object to the current object with deepcopy + */ + virtual void DeepCopy(std::shared_ptr &other) = 0; /** * @brief Indicates whether some other object is "equal to" this one. * @param other The object with which to compare. * @return true if this object is the same as the obj argument; false otherwise. */ - virtual bool Equals(const TUserMapObject *other) = 0; + virtual bool Equals(std::shared_ptr &other) = 0; /** - * @brief Copy the data of the specified object to the current object with deepcopy + * @brief Writes a parcelable object to the given parcel. + * @param parcel indicates Parcel object + * @return Returns true being written on success or false if any error occur. */ - virtual void DeepCopy(const TUserMapObject *other) = 0; - + virtual bool Marshalling(Parcel &parcel) const + { + std::string tostring = ToString(); + return parcel.WriteString16(Str8ToStr16(tostring)); + } /** - * @brief Unmarshals this Sequenceable object from a Parcel. - * - * @return Unmarshals success returns true, otherwise returns false. + * @brief Read a parcelable object to the given parcel. + * @param parcel indicates Parcel object + * @return Returns true being read on success or false if any error occur. */ - virtual bool Unmarshalling(Parcel &parcel) = 0; + virtual bool Unmarshalling(Parcel &parcel) + { + std::string tostring = Str16ToStr8(parcel.ReadString16()); + Parse(tostring); + return true; + } protected: std::string class_name_; }; -using CreateUserMapObject = std::function; - -class PacMapUserObjectLoader { +using CreateUserObjectBase = std::function; +class UserObjectBaseLoader { public: - static PacMapUserObjectLoader &GetInstance(void); - ~PacMapUserObjectLoader() = default; + static UserObjectBaseLoader &GetInstance(void); + ~UserObjectBaseLoader() = default; /** * @brief Registered user-defined serialization class. * @param objectName The name of the custom class. * @param createFun Function object that creates an instance of a custom class. */ - void RegisterUserObject(const std::string &objectName, const CreateUserMapObject &createFun); + void RegisterUserObject(const std::string &objectName, const CreateUserObjectBase &createFun); /** * @brief Represents obtaining an instance of an object of a registered serialization class. - * @param className The name of the custom class. + * @param className The name of the custom class {UserObjectBase subClass}. * * @return Returns an instance of the object, or nullptr on failure. */ - TUserMapObject *GetUserObjectByName(const std::string &className); + UserObjectBase *GetUserObjectByName(const std::string &className); private: - std::unordered_map register_class_list_; - PacMapUserObjectLoader() = default; - PacMapUserObjectLoader(const PacMapUserObjectLoader &) = delete; - PacMapUserObjectLoader &operator=(const PacMapUserObjectLoader &) = delete; - PacMapUserObjectLoader(PacMapUserObjectLoader &&) = delete; - PacMapUserObjectLoader &operator=(PacMapUserObjectLoader &&) = delete; + std::unordered_map register_class_list_; + UserObjectBaseLoader() = default; + UserObjectBaseLoader(const UserObjectBaseLoader &) = delete; + UserObjectBaseLoader &operator=(const UserObjectBaseLoader &) = delete; + UserObjectBaseLoader(UserObjectBaseLoader &&) = delete; + UserObjectBaseLoader &operator=(UserObjectBaseLoader &&) = delete; }; /** - * @brief Register the object's deserialization class, which must be a child TUserMapObject. + * @brief Register the object's deserialization class, which must be a child UserObjectBase. * * @param className The name of class. */ -#define REGISTER_USER_MAP_OBJECT(className) \ +#define REGISTER_USER_OBJECT_BASE(className) \ static __attribute__((constructor)) void RegisterUserMapObject_##className() \ { \ - PacMapUserObjectLoader::GetInstance().RegisterUserObject( \ - #className, []() -> TUserMapObject * { return new (std::nothrow) className; }); \ + UserObjectBaseLoader::GetInstance().RegisterUserObject( \ + #className, []() -> UserObjectBase * { return new (std::nothrow) className; }); \ } -class PacMapNodeTypeObject : public PacMapNode { -public: - PacMapNodeTypeObject() : PacMapNode(DT_PACMAP_OBJECT), object_value_(nullptr) - {} - virtual ~PacMapNodeTypeObject() = default; - - PacMapNodeTypeObject(const PacMapNodeTypeObject &other); - PacMapNodeTypeObject &operator=(const PacMapNodeTypeObject &other); - - /** - * @brief Adds a object to current object. The object must be a subclass of TUserMapObject - * @param object Added object. A smart pointer to a subclass of TUserMapObject. - */ - void PutObject(const std::shared_ptr &object); - - /** - * @brief Obtains the object value. - * @return Returns the smart pointer to subclass of TUserMapObject. - */ - std::shared_ptr GetObject(void); - - /** - * @brief Indicates whether some other object is "equal to" this one. - * @param other The object with which to compare. - * @return true if this object is the same as the obj argument; false otherwise. - */ - virtual bool Equals(const PacMapNode *other) override; - - /** - * @brief Copy the data of the specified object to the current object with deepcopy - * @param other The original object that stores the data. - */ - virtual void DeepCopy(const PacMapNode *other) override; - - /** - * @brief Marshals this Sequenceable object to a Parcel. - * @param key Indicates the key in String format. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Marshals success returns true, otherwise returns false. - */ - virtual bool Marshalling(const std::string &key, Parcel &parcel) const override; - - /** - * @brief Unmarshals this Sequenceable object from a Parcel. - * @param dataType Indicates the type of data stored. - * @param parcel Indicates the Parcel object into which the Sequenceable object has been marshaled. - * @return Unmarshals success returns true, otherwise returns false. - */ - virtual bool Unmarshalling(int32_t dataType, Parcel &parcel) override; - -private: - std::shared_ptr object_value_; - void InnerDeepCopy(const PacMapNodeTypeObject *other); -}; -} // namespace AppExecFwk +} // namespace AAFwk } // namespace OHOS - -#endif +#endif // OHOS_APPEXECFWK_USER_OBJECT_BASE_H diff --git a/interfaces/innerkits/base/include/ohos/aafwk/base/user_object_wrapper.h b/interfaces/innerkits/base/include/ohos/aafwk/base/user_object_wrapper.h new file mode 100755 index 00000000000..0ea0a8c22dd --- /dev/null +++ b/interfaces/innerkits/base/include/ohos/aafwk/base/user_object_wrapper.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_AAFWK_USER_OBJECT_WRAPPER_H +#define OHOS_AAFWK_USER_OBJECT_WRAPPER_H +#include +#include +#include "ohos/aafwk/base/base_object.h" +#include "refbase.h" +#include "ohos/aafwk/base/user_object_base.h" + +namespace OHOS { +namespace AAFwk { + +class UserObject final : public Object, public IUserObject { +public: + inline UserObject(const std::shared_ptr &value) : value_(value) + {} + + virtual ~UserObject() = default; + + IINTERFACE_DECL(); + + ErrCode GetValue(std::shared_ptr &value) override; /* [out] */ + + bool Equals(IObject &other) override; /* [in] */ + + std::string ToString() override; + + static sptr Box(const std::shared_ptr &value); /* [in] */ + + static std::shared_ptr Unbox(IUserObject *object); /* [in] */ + + static sptr Parse(const std::string &str); /* [in] */ + +public: + static constexpr char SIGNATURE = 'O'; + +private: + std::shared_ptr value_ = nullptr; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_USER_OBJECT_WRAPPER_H diff --git a/interfaces/innerkits/want/BUILD.gn b/interfaces/innerkits/want/BUILD.gn index 6637357cb53..57928d23cf0 100755 --- a/interfaces/innerkits/want/BUILD.gn +++ b/interfaces/innerkits/want/BUILD.gn @@ -37,6 +37,7 @@ config("want_public_config") { "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", "//foundation/aafwk/standard/frameworks/kits/content/cpp/src", + "//third_party/jsoncpp/include", ] } @@ -63,6 +64,7 @@ ohos_shared_library("want") { #"//foundation/distributeddatamgr/distributeddatamgr:build_module", "//foundation/distributedschedule/samgr/interfaces/innerkits/lsamgr:lsamgr", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/interfaces/innerkits/want/include/ohos/aafwk/content/pac_map.h b/interfaces/innerkits/want/include/ohos/aafwk/content/pac_map.h old mode 100644 new mode 100755 index 6379c4fa707..b7fa4539069 --- a/interfaces/innerkits/want/include/ohos/aafwk/content/pac_map.h +++ b/interfaces/innerkits/want/include/ohos/aafwk/content/pac_map.h @@ -23,22 +23,53 @@ #include #include #include - +#include "securec.h" +#include "json/json.h" #include "parcel.h" -#include "ohos/aafwk/base/pac_map_node.h" -#include "ohos/aafwk/base/pac_map_node_base.h" -#include "ohos/aafwk/base/pac_map_node_array.h" -#include "ohos/aafwk/base/pac_map_node_user_object.h" +#include "ohos/aafwk/base/base_def.h" +#include "ohos/aafwk/base/base_object.h" +#include "ohos/aafwk/base/base_interfaces.h" + +// json key define +// base: 0x00000001 ~ 0x000000FF +// array: 0x00000100 ~ 0x0000FF00 +// boject: 0x00010000 ~ 0x00FF0000 +#define PACMAP_DATA_NONE 0x00 +// base data +#define PACMAP_DATA_SHORT 0x00000001 +#define PACMAP_DATA_INTEGER 0x00000002 +#define PACMAP_DATA_LONG 0x00000003 +#define PACMAP_DATA_CHAR 0x00000004 +#define PACMAP_DATA_BYTE 0x00000005 +#define PACMAP_DATA_BOOLEAN 0x00000007 +#define PACMAP_DATA_FLOAT 0x00000008 +#define PACMAP_DATA_DOUBLE 0x00000009 +#define PACMAP_DATA_STRING 0x0000000A +// array data +#define PACMAP_DATA_ARRAY_SHORT 0x00000100 +#define PACMAP_DATA_ARRAY_INTEGER 0x00000200 +#define PACMAP_DATA_ARRAY_LONG 0x00000300 +#define PACMAP_DATA_ARRAY_CHAR 0x00000400 +#define PACMAP_DATA_ARRAY_BYTE 0x00000500 +#define PACMAP_DATA_ARRAY_BOOLEAN 0x00000600 +#define PACMAP_DATA_ARRAY_FLOAT 0x00000700 +#define PACMAP_DATA_ARRAY_DOUBLE 0x00000800 +#define PACMAP_DATA_ARRAY_STRING 0x00000900 +// object data +#define PACMAP_DATA_USEROBJECT 0x00010000 +#define PACMAP_DATA_PACMAP 0x00020000 namespace OHOS { namespace AppExecFwk { namespace PacMapObject { -using Object = std::shared_ptr; -} // namespace PacMapObject +using INTERFACE = sptr; +}; // namespace PacMapObject -using PacMapList = std::map; +using namespace AAFwk; +using UserObjectBase = AAFwk::UserObjectBase; +using PacMapList = std::map; -class PacMap : public Parcelable { +class PacMap final : public Parcelable, public Object, public IPacMap { public: /** * @brief Default constructor used to create a PacMap instance, in which the Map object has no key-value pair. @@ -52,6 +83,8 @@ public: ~PacMap(); + IINTERFACE_DECL(); + /** * @brief A overload operation with shallow copy. */ @@ -74,6 +107,7 @@ public: * @param pacMap Returns the constructed object. */ PacMap DeepCopy(void); + void DeepCopy(PacMap &other); /** * @brief Adds a short value matching a specified key. @@ -139,11 +173,18 @@ public: void PutStringValue(const std::string &key, const std::string &value); /** - * @brief Adds an object value matching a specified key. The object must be a subclass of TUserMapObject. + * @brief Adds an object value matching a specified key. The object must be a subclass of UserObjectBase. * @param key A specified key. * @param value A smart pointer to the object that matches the specified key. */ - void PutObject(const std::string &key, const std::shared_ptr &value); + void PutObject(const std::string &key, const std::shared_ptr &value); + + /** + * @brief Adds an PacMap value matching a specified key. + * @param key A specified key. + * @param value The value that matches the specified key. + */ + bool PutPacMap(const std::string &key, const PacMap &value); /** * @brief Adds some short values matching a specified key. @@ -213,7 +254,7 @@ public: * Duplicate key values will be replaced. * @param mapData Store a list of key-value pairs. */ - void PutAll(const std::map &mapData); + void PutAll(std::map &mapData); /** * @brief Saves the data in a PacMap object to the current object. Duplicate key values will be replaced. @@ -361,14 +402,21 @@ public: * @param key A specified key. * @return Returns the smart pointer to object that matches the key. */ - std::shared_ptr GetObject(const std::string &key); + std::shared_ptr GetObject(const std::string &key); + + /** + * @brief Obtains the PacMap matching a specified key. + * @param key A specified key. + * @return Returns PacMap that matches the key. + */ + PacMap GetPacMap(const std::string &key); /** * @brief Obtains all the data that has been stored with shallow copy. * @return Returns all data in current PacMap. There is no dependency between the returned data and * the original data. */ - std::map GetAll(void); + std::map GetAll(void); /** * @brief Indicates whether some other object is "equal to" this one. @@ -422,21 +470,93 @@ public: */ static PacMap *Unmarshalling(Parcel &parcel); + /** + * @brief Save pacmap to string. + * @return Returns the string. + */ + virtual std::string ToString() override; + + /** + * @brief Restore pacmap from the string. + * @return Return true if successful, otherwise false. + */ + virtual bool FromString(const std::string &str) override; + + ErrCode GetValue(PacMap &value); + + virtual bool Equals(IObject &other) override; + + static sptr Parse(const std::string &str); + + static constexpr char SIGNATURE = 'P'; + private: - PacMapList data_list_; + PacMapList dataList_; std::mutex mapLock_; - - void DeepCopyData(PacMapList &desPacMapList, const PacMapList &srcPacMapList); - void ShallowCopyData(PacMapList &desPacMapList, const PacMapList &srcPacMapList); - void RemoveDataNode(const std::string &key); + bool GetBaseJsonValue(PacMapList::const_iterator &it, Json::Value &json) const; + bool GetArrayJsonValue(PacMapList::const_iterator &it, Json::Value &json) const; + bool GetUserObjectJsonValue(PacMapList::const_iterator &it, Json::Value &json) const; + void ShallowCopyData(PacMapList &desPacMap, const PacMapList &srcPacMap); + void RemoveData(PacMapList &srcPacMap, const std::string &key); bool EqualPacMapData(const PacMapList &leftPacMapList, const PacMapList &rightPacMapList); - bool WriteBaseToParcel(const std::string &key, const std::shared_ptr &nodeData, Parcel &parcel) const; - bool WriteArrayToParcel(const std::string &key, const std::shared_ptr &nodeData, Parcel &parcel) const; - bool WriteObjectToParcel(const std::string &key, const std::shared_ptr &nodeData, Parcel &parcel) const; bool ReadFromParcel(Parcel &parcel); - bool ReadBaseFromParcel(const std::string &key, int32_t dataType, Parcel &parcel); - bool ReadArrayFromParcel(const std::string &key, int32_t dataType, Parcel &parcel); - bool ReadObjectFromParcel(const std::string &key, int32_t dataType, Parcel &parcel); + + bool ParseJson(Json::Value &data, PacMapList &mapList); + bool ParseJsonItem(PacMapList &mapList, const std::string &key, Json::Value &item); + bool ParseJsonItemArray(PacMapList &mapList, const std::string &key, Json::Value &item); + bool ParseJsonItemArrayShort(PacMapList &mapList, const std::string &key, Json::Value &item); + bool ParseJsonItemArrayInteger(PacMapList &mapList, const std::string &key, Json::Value &item); + bool ParseJsonItemArrayLong(PacMapList &mapList, const std::string &key, Json::Value &item); + bool ParseJsonItemArrayChar(PacMapList &mapList, const std::string &key, Json::Value &item); + bool ParseJsonItemArrayByte(PacMapList &mapList, const std::string &key, Json::Value &item); + bool ParseJsonItemArrayBoolean(PacMapList &mapList, const std::string &key, Json::Value &item); + bool ParseJsonItemArrayFloat(PacMapList &mapList, const std::string &key, Json::Value &item); + bool ParseJsonItemArrayDouble(PacMapList &mapList, const std::string &key, Json::Value &item); + bool ParseJsonItemArrayString(PacMapList &mapList, const std::string &key, Json::Value &item); + + bool InnerPutObjectValue(PacMapList &mapList, const std::string &key, Json::Value &item); + bool InnerPutPacMapValue(PacMapList &mapList, const std::string &key, Json::Value &item); + + bool ToJson(const PacMapList &mapList, Json::Value &dataObject) const; + + // bool EqualsInterface(AAFwk::IInterface *one_interface, AAFwk::IInterface *two_interface); + std::string MapListToString(const PacMapList &mapList) const; + bool StringToMapList(const std::string &str, PacMapList &mapList); + + void InnerPutShortValue(PacMapList &mapList, const std::string &key, short value); + void InnerPutIntValue(PacMapList &mapList, const std::string &key, int value); + void InnerPutLongValue(PacMapList &mapList, const std::string &key, long value); + void InnerPutBooleanValue(PacMapList &mapList, const std::string &key, bool value); + void InnerPutCharValue(PacMapList &mapList, const std::string &key, char value); + void InnerPutByteValue(PacMapList &mapList, const std::string &key, AAFwk::byte value); + void InnerPutFloatValue(PacMapList &mapList, const std::string &key, float value); + void InnerPutDoubleValue(PacMapList &mapList, const std::string &key, double value); + void InnerPutStringValue(PacMapList &mapList, const std::string &key, const std::string &value); + void InnerPutObject(PacMapList &mapList, const std::string &key, const std::shared_ptr &value); + bool InnerPutPacMap(PacMapList &mapList, const std::string &key, PacMap &value); + + void InnerPutShortValueArray(PacMapList &mapList, const std::string &key, const std::vector &value); + void InnerPutIntValueArray(PacMapList &mapList, const std::string &key, const std::vector &value); + void InnerPutLongValueArray(PacMapList &mapList, const std::string &key, const std::vector &value); + void InnerPutBooleanValueArray(PacMapList &mapList, const std::string &key, const std::vector &value); + void InnerPutCharValueArray(PacMapList &mapList, const std::string &key, const std::vector &value); + void InnerPutByteValueArray(PacMapList &mapList, const std::string &key, const std::vector &value); + void InnerPutFloatValueArray(PacMapList &mapList, const std::string &key, const std::vector &value); + void InnerPutDoubleValueArray(PacMapList &mapList, const std::string &key, const std::vector &value); + void InnerPutStringValueArray(PacMapList &mapList, const std::string &key, const std::vector &value); + + // char data:none + bool ToJsonArrayShort(std::vector &array, Json::Value &item, int type) const; + bool ToJsonArrayInt(std::vector &array, Json::Value &item, int type) const; + bool ToJsonArrayLong(std::vector &array, Json::Value &item, int type) const; + bool ToJsonArrayByte(std::vector &array, Json::Value &item, int type) const; + bool ToJsonArrayBoolean(std::vector &array, Json::Value &item, int type) const; + bool ToJsonArrayFloat(std::vector &array, Json::Value &item, int type) const; + bool ToJsonArrayDouble(std::vector &array, Json::Value &item, int type) const; + bool ToJsonArrayString(std::vector &array, Json::Value &item, int type) const; + + bool IsNumber(const std::string &str); + bool CompareArrayData(AAFwk::IInterface *one_interface, AAFwk::IInterface *two_interface); }; } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/want/include/ohos/aafwk/content/want.h b/interfaces/innerkits/want/include/ohos/aafwk/content/want.h index e62364b6927..15acb6da4c3 100755 --- a/interfaces/innerkits/want/include/ohos/aafwk/content/want.h +++ b/interfaces/innerkits/want/include/ohos/aafwk/content/want.h @@ -790,6 +790,7 @@ private: bool ReadFromParcel(Parcel &parcel); static bool CheckAndSetParameters(Want &want, const std::string &key, std::string &prop, const std::string &value); Uri GetLowerCaseScheme(const Uri &uri); + void ToUriStringInner(std::string &uriString) const; }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/kits/js/@ohos.ability.featureability.d.ts b/interfaces/kits/js/@ohos.ability.featureAbility.d.ts similarity index 48% rename from interfaces/kits/js/@ohos.ability.featureability.d.ts rename to interfaces/kits/js/@ohos.ability.featureAbility.d.ts index 1672c635aa0..2ca32e6290f 100755 --- a/interfaces/kits/js/@ohos.ability.featureability.d.ts +++ b/interfaces/kits/js/@ohos.ability.featureAbility.d.ts @@ -12,88 +12,111 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { AsyncCallback } from './.basic'; -import { Context } from './app/context'; +import { AsyncCallback } from './basic'; import { Want } from './ability/want'; -import { StartAbilityParameter, StartAbilityForResultParameter } from './ability/startabilityparameter'; -import { AbilityResult, StartAbilityResult } from './ability/abilityresult'; +import { StartAbilityParameter } from './ability/startAbilityParameter'; +import { AbilityResult } from './ability/abilityResult'; +import { Context } from './app/context'; +import { ConnectOptions } from './ability/connectOptions'; /** * A Feature Ability represents an ability with a UI and is designed to interact with users. * @name featureAbility - * @since 3 + * @since 6 * @sysCap AAFwk * @devices phone, tablet * @permission N/A */ declare namespace featureAbility { /** - * Checks whether the main window of this ability has window focus. + * Obtain the want sended from the source ability. * @devices phone, tablet - * @since 3 + * @since 6 * @sysCap AAFwk - * @param - - * @return Returns true if this ability currently has window focus; returns false otherwise. + * @return - */ - function hasWindowFocus(): Promise; - function hasWindowFocus(callback: AsyncCallback): void; + function getWant(callback: AsyncCallback): void; + function getWant(): Promise; /** - * Destroys the current ability. + * Starts a new ability. * @devices phone, tablet - * @since 3 + * @since 6 * @sysCap AAFwk - * @param - + * @param parameter Indicates the ability to start. * @return - */ - function terminateAbility(): Promise; - function terminateAbility(callback: AsyncCallback): void; + function startAbility(parameter: StartAbilityParameter, callback: AsyncCallback): void; + function startAbility(parameter: StartAbilityParameter): Promise; /** - * Obtain the want sended from the source ability. + * Obtains the application context. + * + * @return Returns the application context. + * @since 6 + */ + function getContext(): Context; + + /** + * Starts an ability and returns the execution result when the ability is destroyed. * @devices phone, tablet - * @since 3 + * @since 7 * @sysCap AAFwk * @param parameter Indicates the ability to start. * @return - */ - function getWant(callback: AsyncCallback): void; - function getWant(): Promise; + function startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback): void; + function startAbilityForResult(parameter: StartAbilityParameter): Promise; /** - * Starts a new ability. + * Sets the result code and data to be returned by this Page ability to the caller + * and destroys this Page ability. * @devices phone, tablet - * @since 3 + * @since 7 * @sysCap AAFwk - * @param parameter Indicates the ability to start. + * @param parameter Indicates the result to return. * @return - */ - function startAbility(parameter: StartAbilityParameter, callback: AsyncCallback): void; - function startAbility(parameter: StartAbilityParameter): Promise; + function terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback): void; + function terminateSelfWithResult(parameter: AbilityResult): Promise; /** - * Starts a new ability, onAbilityResult will be called after this new ability is terminated. + * Destroys this Page ability. * @devices phone, tablet - * @since 3 + * @since 7 * @sysCap AAFwk - * @param parameter Indicates the ability to start. * @return - */ - function startAbilityForResult(parameter: StartAbilityForResultParameter, - resultCallback: AsyncCallback, callback: AsyncCallback): void; - function startAbilityForResult(parameter: StartAbilityForResultParameter, - resultCallback: AsyncCallback): Promise; + function terminateSelf(callback: AsyncCallback): void; /** - * Sets the result code and data to be returned by this Feature ability to the caller. + * Checks whether the main window of this ability has window focus. * @devices phone, tablet - * @since 3 + * @since 7 * @sysCap AAFwk - * @param AbilityResult Indicates the result code returned after the ability is destroyed. - * You can define the result code to identify an error. - * @return - */ - function finishWithResult(result: AbilityResult, callback: AsyncCallback): void; - function finishWithResult(result: AbilityResult): Promise; + function hasWindowFocus(callback: AsyncCallback): void; + function hasWindowFocus(): Promise; + + /** + * Connects an ability to a Service ability. + * @devices phone, tablet + * @since 7 + * @sysCap AAFwk + * @param request Indicates the Service ability to connect. + * @param options Indicates the callback object when the Service ability is connected. + * @return Returns true if the connection is successful; returns false otherwise. + */ + function connectAbility(request: Want, options:ConnectOptions): number; + + /** + * Disconnects an ability from a Service ability. + * @devices phone, tablet + * @since 7 + * @sysCap AAFwk + * @param connection Indicates the Service ability to disconnect. + */ + function disconnectAbility(connection: number, callback:AsyncCallback): void; + function disconnectAbility(connection: number): Promise; } export default featureAbility; \ No newline at end of file diff --git a/interfaces/kits/js/app/runningprocessinfo.d.ts b/interfaces/kits/js/@ohos.ability.particleAbility.d.ts old mode 100755 new mode 100644 similarity index 32% rename from interfaces/kits/js/app/runningprocessinfo.d.ts rename to interfaces/kits/js/@ohos.ability.particleAbility.d.ts index aae749e1b6b..53e4f039fcd --- a/interfaces/kits/js/app/runningprocessinfo.d.ts +++ b/interfaces/kits/js/@ohos.ability.particleAbility.d.ts @@ -1,95 +1,62 @@ -/* - * 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 abilityManager from './../@ohos.app.abilitymanager'; -/** - * @name This class saves process information about an application - * @since 3 - * @SysCap appexecfwk - * @import import app from '@system.app' - * @permission N/A - * @devices phone, tablet - */ - export interface RunningProcessInfo { - /** - * The id of the current process - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - */ - pid: number; - - /** - * The name of the current process - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - */ - processName: string; - - /** - * The list of packaget in the current process - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - */ - pkgList: Array; - - /** - * The uid of the current process - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - */ - uid: number; - - /** - * the memory level of the current process - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - */ - lastMemoryLevel: number; - - /** - * the weight of the current process - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - */ - weight: number; - - /** - * the ReasonCode of weight for the current process - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - */ - weightReasonCode: abilityManager.WeightReasonCode; -} \ No newline at end of file +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AsyncCallback } from './basic'; +import { StartAbilityParameter } from './ability/startAbilityParameter'; +import { Want } from './ability/want'; +import { ConnectOptions } from './ability/connectOptions'; + +/** + * A Particle Ability represents an ability with service. + * @name particleAbility + * @since 6 + * @sysCap AAFwk + * @devices phone, tablet + * @permission N/A + */ +declare namespace particleAbility { + + /** + * Service ability uses this method to start a specific ability. + * @devices phone, tablet + * @since 6 + * @sysCap AAFwk + * @param parameter Indicates the ability to start. + * @return - + */ + function startAbility(parameter: StartAbilityParameter, callback: AsyncCallback): void; + function startAbility(parameter: StartAbilityParameter): Promise; + + /** + * Connects an ability to a Service ability. + * @devices phone, tablet + * @since 7 + * @sysCap AAFwk + * @param request Indicates the Service ability to connect. + * @param options Indicates the callback object when the Service ability is connected. + * @return Returns true if the connection is successful; returns false otherwise. + */ + function connectAbility(request: Want, options:ConnectOptions): number; + + /** + * Disconnects an ability from a Service ability. + * @devices phone, tablet + * @since 7 + * @sysCap AAFwk + * @param connection Indicates the Service ability to disconnect. + */ + function disconnectAbility(connection: number, callback:AsyncCallback): void; + function disconnectAbility(connection: number): Promise; +} +export default particleAbility; diff --git a/interfaces/kits/js/@ohos.ability.wantConstant.d.ts b/interfaces/kits/js/@ohos.ability.wantConstant.d.ts new file mode 100644 index 00000000000..e05916b8cff --- /dev/null +++ b/interfaces/kits/js/@ohos.ability.wantConstant.d.ts @@ -0,0 +1,341 @@ +/* + * 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. + */ + +/** + * the constant for action and entity in the want + * @name wantConstant + * @since 6 + * @sysCap aafwk + * @devices phone, tablet + * @permission N/A + */ + declare namespace wantConstant { + /** + * the constant for action of the want + * @name Action + * @since 6 + * @sysCap aafwk + * @devices phone, tablet + * @permission N/A + */ + export enum Action { + /** + * Indicates the action of backing home. + * + * @since 1 + */ + ACTION_HOME = "ohos.want.action.home", + + /** + * Indicates the action of starting a Page ability that displays a keypad. + * + * @since 6 + */ + ACTION_DIAL = "ohos.want.action.dial", + + /** + * Indicates the action of starting a Page ability for search. + * + * @since 6 + */ + ACTION_SEARCH = "ohos.want.action.search", + + /** + * Indicates the action of starting a Page ability that provides wireless network settings, for example, + * Wi-Fi options. + * + * @since 6 + */ + ACTION_WIRELESS_SETTINGS = "ohos.settings.wireless", + + /** + * Indicates the action of starting a Page ability that manages installed applications. + * + * @since 6 + */ + ACTION_MANAGE_APPLICATIONS_SETTINGS = "ohos.settings.manage.applications", + + /** + * Indicates the action of starting a Page ability that displays details of a specified application. + * + *

You must specify the application bundle name in the {@code package} attribute of the {@code Intent} + * containing this action. + * + * @since 6 + */ + ACTION_APPLICATION_DETAILS_SETTINGS = "ohos.settings.application.details", + + /** + * Indicates the action of starting a Page ability for setting an alarm clock. + * + * @since 6 + */ + ACTION_SET_ALARM = "ohos.want.action.setAlarm", + + /** + * Indicates the action of starting a Page ability that displays all alarm + * clocks. + * + * @since 6 + */ + ACTION_SHOW_ALARMS = "ohos.want.action.showAlarms", + + /** + * Indicates the action of starting a Page ability for snoozing an alarm clock. + * + * @since 6 + */ + ACTION_SNOOZE_ALARM = "ohos.want.action.snoozeAlarm", + + /** + * Indicates the action of starting a Page ability for deleting an alarm clock. + * + * @since 6 + */ + ACTION_DISMISS_ALARM = "ohos.want.action.dismissAlarm", + + /** + * Indicates the action of starting a Page ability for dismissing a timer. + * + * @since 6 + */ + ACTION_DISMISS_TIMER = "ohos.want.action.dismissTimer", + + /** + * Indicates the action of starting a Page ability for sending a sms. + * + * @since 6 + */ + ACTION_SEND_SMS = "ohos.want.action.sendSms", + + /** + * Indicates the action of starting a Page ability for opening contacts or pictures. + * + * @since 6 + */ + ACTION_CHOOSE = "ohos.want.action.choose", + + /** + * Indicates the action of showing the application selection dialog box. + * + * @since 6 + */ + ACTION_SELECT = "ohos.want.action.select", + + /** + * Indicates the action of sending a single data record. + * + * @since 6 + */ + ACTION_SEND_DATA = "ohos.want.action.sendData", + + /** + * Indicates the action of sending multiple data records. + * + * @since 6 + */ + ACTION_SEND_MULTIPLE_DATA = "ohos.want.action.sendMultipleData", + + /** + * Indicates the action of requesting the media scanner to scan files and adding the files to the media library. + * + * @since 6 + */ + ACTION_SCAN_MEDIA_FILE = "ohos.want.action.scanMediaFile", + + /** + * Indicates the action of viewing data. + * + * @since 6 + */ + ACTION_VIEW_DATA = "ohos.want.action.viewData", + + /** + * Indicates the action of editing data. + * + * @since 6 + */ + ACTION_EDIT_DATA = "ohos.want.action.editData", + + /** + * Indicates the choices you will show with {@link #ACTION_PICKER}. + * + * @since 6 + */ + INTENT_PARAMS_INTENT = "ability.want.params.INTENT", + + /** + * Indicates the CharSequence dialog title when used with a {@link #ACTION_PICKER}. + * + * @since 6 + */ + INTENT_PARAMS_TITLE = "ability.want.params.TITLE", + + /** + * Indicates the action of select file. + * + * @since 7 + */ + ACTION_FILE_SELECT = "ohos.action.fileSelect", + + /** + * Indicates the URI holding a stream of data associated with the Intent when used with a {@link #ACTION_SEND_DATA}. + * + * @since 7 + */ + PARAMS_STREAM = "ability.params.stream", + } + + /** + * the constant for Entity of the want + * @name Action + * @since 6 + * @sysCap aafwk + * @devices phone, tablet + * @permission N/A + */ + export enum Entity { + /** + * Indicates the default entity, which is used if the entity is not specified. + * + * @since 6 + */ + ENTITY_DEFAULT = "entity.system.default", + + /** + * Indicates the home screen entity. + * + * @since 6 + */ + ENTITY_HOME = "entity.system.home", + + /** + * Indicates the voice interaction entity. + * + * @since 6 + */ + ENTITY_VOICE = "entity.system.voice", + + /** + * Indicates the browser category. + * + * @since 6 + */ + ENTITY_BROWSABLE = "entity.system.browsable", + + /** + * Indicates the video category. + */ + ENTITY_VIDEO = "entity.system.video" + } + + export enum Flags { + /** + * Indicates the grant to perform read operations on the URI. + * + * @hide + */ + FLAG_AUTH_READ_URI_PERMISSION = 0x00000001, + + /** + * Indicates the grant to perform write operations on the URI. + * + * @hide + */ + FLAG_AUTH_WRITE_URI_PERMISSION = 0x00000002, + + /** + * Returns the result to the source ability. + */ + FLAG_ABILITY_FORWARD_RESULT = 0x00000004, + + /** + * Determines whether an ability on the local device can be migrated to a remote device. + */ + FLAG_ABILITY_CONTINUATION = 0x00000008, + + /** + * Specifies whether a component does not belong to OHOS. + */ + FLAG_NOT_OHOS_COMPONENT = 0x00000010, + + /** + * Specifies whether an ability is started. + */ + FLAG_ABILITY_FORM_ENABLED = 0x00000020, + + /** + * Indicates the grant for possible persisting on the URI. + * + * @hide + */ + FLAG_AUTH_PERSISTABLE_URI_PERMISSION = 0x00000040, + + /** + * Returns the result to the source ability slice. + * + * @hide + */ + FLAG_AUTH_PREFIX_URI_PERMISSION = 0x00000080, + + /** + * Supports multi-device startup in the distributed scheduling system. + */ + FLAG_ABILITYSLICE_MULTI_DEVICE = 0x00000100, + + /** + * Indicates that an ability using the Service template is started regardless of whether the host application has + * been started. + */ + FLAG_START_FOREGROUND_ABILITY = 0x00000200, + + /** + * Indicates the continuation is reversible. + * + * @hide + */ + FLAG_ABILITY_CONTINUATION_REVERSIBLE = 0x00000400, + + /** + * Install the specified ability if it's not installed. + */ + FLAG_INSTALL_ON_DEMAND = 0x00000800, + + /** + * Install the specifiedi ability with background mode if it's not installed. + */ + FLAG_INSTALL_WITH_BACKGROUND_MODE = 0x80000000, + + /** + * Indicates the operation of clearing other missions. This flag can be set for the {@code Intent} passed to + * {@link ohos.app.Context#startAbility} and must be used together with {@link FLAG_ABILITY_NEW_MISSION}. + */ + FLAG_ABILITY_CLEAR_MISSION = 0x00008000, + + /** + * Indicates the operation of creating a task on the historical mission stack. + */ + FLAG_ABILITY_NEW_MISSION = 0x10000000, + + /** + * Indicates that the existing instance of the ability to start will be reused if it is already at the top of + * the mission stack. Otherwise, a new ability instance will be created. + * + */ + FLAG_ABILITY_MISSION_TOP = 0x20000000 + } +} + +export default wantConstant; \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.ability.wantconstant.d.ts b/interfaces/kits/js/@ohos.ability.wantconstant.d.ts deleted file mode 100644 index 467cad638fe..00000000000 --- a/interfaces/kits/js/@ohos.ability.wantconstant.d.ts +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"), - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * the constant for action and entity in the want - * @name wantConstant - * @since 3 - * @sysCap aafwk - * @devices phone, tablet - * @permission N/A - */ -declare namespace wantConstant { - /** - * the constant for action of the want - * @name Action - * @since 3 - * @sysCap aafwk - * @devices phone, tablet - * @permission N/A - */ - export enum Action { - /** - * Indicates the action of backing home. - * - * @since 1 - */ - ACTION_HOME = "action.system.home", - - /** - * Indicates the action of playing a media item. - * - * @since 1 - */ - ACTION_PLAY = "action.system.play", - - /** - * Indicates the action of installing a bundle. - * - * @since 1 - */ - ACTION_BUNDLE_ADD = "action.bundle.add", - - /** - * Indicates the action of uninstalling a bundle. - * - * @since 1 - */ - ACTION_BUNDLE_REMOVE = "action.bundle.remove", - - /** - * Indicates the action of updating a bundle. - * - * @since 1 - */ - ACTION_BUNDLE_UPDATE = "action.bundle.update", - - /** - * Indicates the action of booking a taxi. - * - * @since 1 - */ - ACTION_ORDER_TAXI = "ability.intent.ORDER_TAXI", - - /** - * Indicates the action of querying driving bans. - * - * @since 1 - */ - ACTION_QUERY_TRAFFIC_RESTRICTION = "ability.intent.QUERY_TRAFFIC_RESTRICTION", - - /** - * Indicates the action of querying routes. - * - * @since 1 - */ - ACTION_PLAN_ROUTE = "ability.intent.PLAN_ROUTE", - - /** - * Indicates the action of booking a flight. - * - * @since 1 - */ - ACTION_BOOK_FLIGHT = "ability.intent.BOOK_FLIGHT", - - /** - * Indicates the action of booking a train ticket. - * - * @since 1 - */ - ACTION_BOOK_TRAIN_TICKET = "ability.intent.BOOK_TRAIN_TICKET", - - /** - * Indicates the action of booking a hotel. - * - * @since 1 - */ - ACTION_BOOK_HOTEL = "ability.intent.BOOK_HOTEL", - - /** - * Indicates the action of querying a travel guide. - * - * @since 1 - */ - ACTION_QUERY_TRAVELLING_GUIDELINE = "ability.intent.QUERY_TRAVELLING_GUIDELINE", - - /** - * Indicates the action of querying nearby places. - * - * @since 1 - */ - ACTION_QUERY_POI_INFO = "ability.intent.QUERY_POI_INFO", - - /** - * Indicates the action of querying horoscope. - * - * @since 1 - */ - ACTION_QUERY_CONSTELLATION_FORTUNE = "ability.intent.QUERY_CONSTELLATION_FORTUNE", - - /** - * Indicates the action of querying the Chinese Almanac calendar. - * - * @since 1 - */ - ACTION_QUERY_ALMANC = "ability.intent.QUERY_ALMANC", - - /** - * Indicates the action of querying weather. - * - * @since 1 - */ - ACTION_QUERY_WEATHER = "ability.intent.QUERY_WEATHER", - - /** - * Indicates the action of querying the encyclopedia. - * - * @since 1 - */ - ACTION_QUERY_ENCYCLOPEDIA = "ability.intent.QUERY_ENCYCLOPEDIA", - - /** - * Indicates the action of searching for a recipe. - * - * @since 1 - */ - ACTION_QUERY_RECIPE = "ability.intent.QUERY_RECIPE", - - /** - * Indicates the action of ordering take-out food. - * - * @since 1 - */ - ACTION_BUY_TAKEOUT = "ability.intent.BUY_TAKEOUT", - - /** - * Indicates the action of translating text. - * - * @since 1 - */ - ACTION_TRANSLATE_TEXT = "ability.intent.TRANSLATE_TEXT", - - /** - * Indicates the action of shopping. - * - * @since 1 - */ - ACTION_BUY = "ability.intent.BUY", - - /** - * Indicates the action of tracking shipment status. - * - * @since 1 - */ - ACTION_QUERY_LOGISTICS_INFO = "ability.intent.QUERY_LOGISTICS_INFO", - - /** - * Indicates the action of shipping a bundle. - * - * @since 1 - */ - ACTION_SEND_LOGISTICS = "ability.intent.SEND_LOGISTICS", - - /** - * Indicates the action of querying sports teams and game schedule. - * - * @since 1 - */ - ACTION_QUERY_SPORTS_INFO = "ability.intent.QUERY_SPORTS_INFO", - - /** - * Indicates the action of browsing news. - * - * @since 1 - */ - ACTION_QUERY_NEWS = "ability.intent.QUERY_NEWS", - - /** - * Indicates the action of reading jokes. - * - * @since 1 - */ - ACTION_QUERY_JOKE = "ability.intent.QUERY_JOKE", - - /** - * Indicates the action of watching video clips. - * - * @since 1 - */ - ACTION_WATCH_VIDEO_CLIPS = "ability.intent.WATCH_VIDEO_CLIPS", - - /** - * Indicates the action of querying stock market quotes. - * - * @since 1 - */ - ACTION_QUERY_STOCK_INFO = "ability.intent.QUERY_STOCK_INFO", - - /** - * Indicates that the locale has changed. - * - * @since 1 - */ - ACTION_LOCALE_CHANGED = "ability.intent.LOCALE_CHANGED" - } - - /** - * the constant for Entity of the want - * @name Action - * @since 3 - * @sysCap aafwk - * @devices phone, tablet - * @permission N/A - */ - export enum Entity { - /** - * Indicates the home screen category. - * - * @since 1 - */ - ENTITY_HOME = "entity.system.home", - - /** - * Indicates the video category. - * - * @since 1 - */ - ENTITY_VIDEO = "entity.system.video" - } -} - -export default wantConstant; \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.app.abilityManager.d.ts b/interfaces/kits/js/@ohos.app.abilityManager.d.ts new file mode 100644 index 00000000000..f9393afbaf2 --- /dev/null +++ b/interfaces/kits/js/@ohos.app.abilityManager.d.ts @@ -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. + */ + +import { AsyncCallback } from './basic'; +import { AbilityMissionInfo } from './app/abilityMissionInfo'; +import { ActiveProcessInfo } from './app/activeProcessInfo'; + +/** + * This module provides the capability to manage abilities and obtaining system task information. + * + * @since 7 + * @SysCap SystemCapability.Appexecfwk + * @devices phone, tablet, tv, wearable + * @import import abilityManager from '@ohos.app.abilityManager' + * @permission N/A + */ +declare namespace abilityManager { + + enum ProcessErrCode { + NO_ERROR = 0, + CRASHED, + NO_RESPONSE, + } + + + /** + * Get information about running processes + * @since 7 + * @SysCap SystemCapability.Appexecfwk + * @devices phone, tablet, tv, wearable + * @return a list of ActiveProcessInfo records describing each process. + * @permission ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION + * @systemapi hide this for inner system use + */ + function getActiveProcessInfos(): Promise>; + function getActiveProcessInfos(callback: AsyncCallback>): void; + + /** + * Get information about the running ability missions + * @since 7 + * @SysCap SystemCapability.Appexecfwk + * @devices phone, tablet, tv, wearable + * @param upperLimit The maximum number of mission infos to return in the array. + * @return an array of AbilityMissionInfo records describing each active mission. + * @permission ohos.permission.ACCESS_MISSIONS + * @systemapi hide this for inner system use + */ + function getActiveAbilityMissionInfos(upperLimit: number): Promise>; + function getActiveAbilityMissionInfos(upperLimit: number, callback: AsyncCallback>): void; + + /** + * Get information about recently run missions + * @since 7 + * @SysCap SystemCapability.Appexecfwk + * @devices phone, tablet, tv, wearable + * @param upperLimit The maximum number of previous mission infos to return in the array. + * @return an array of AbilityMissionInfo records describing each of the previous mission. + * @permission ohos.permission.ACCESS_MISSIONS_EXTRA + * @systemapi hide this for inner system use + */ + function getPreviousAbilityMissionInfos(upperLimit: number): Promise>; + function getPreviousAbilityMissionInfos(upperLimit: number, callback: AsyncCallback>): void; + + /** + * Delete the specified missions + * @since 7 + * @SysCap SystemCapability.Appexecfwk + * @devices phone, tablet, tv, wearable + * @param missionIds An array of missions, representing the missions that need to be deleted. + * @permission ohos.permission.DELETE_MISSIONS + * @systemapi hide this for inner system use + */ + function deleteMissions(missionIds: Array): Promise; + function deleteMissions(missionIds: Array, callback: AsyncCallback): void; + +} + +export default abilityManager; diff --git a/interfaces/kits/js/@ohos.app.abilitymanager.d.ts b/interfaces/kits/js/@ohos.app.abilitymanager.d.ts deleted file mode 100644 index 62d3db42382..00000000000 --- a/interfaces/kits/js/@ohos.app.abilitymanager.d.ts +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { AbilityMissionInfo } from './app/abilitymissioninfo'; -import { RunningProcessInfo } from './app/runningprocessinfo'; -import { AsyncCallback } from './.basic'; - -/** - * Obtains running process and memory information about an application. - * @name abilityManager - * @since 3 - * @sysCap appexecfwk - * @devices phone, tablet - * @permission N/A - */ -declare namespace abilityManager { - - export enum WeightReasonCode { - REASON_UNKNOWN = 0, - WEIGHT_FOREGROUND = 100, - WEIGHT_FOREGROUND_SERVICE = 125, - WEIGHT_VISIBLE = 200, - WEIGHT_PERCEPTIBLE = 230, - WEIGHT_SERVICE = 300, - WEIGHT_TOP_SLEEPING = 325, - WEIGHT_CANT_SAVE_STATE = 350, - WEIGHT_CACHED = 400, - WEIGHT_GONE = 1000, - } - /** - * Obtains information about application processes that are running on the device. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @returns Returns a list of running processes. - */ - function getAllRunningProcesses(): Promise>; - - /** - * Obtains information about the application process running on the device through callback. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @param callback Specified callback method. - */ - function getAllRunningProcesses(callback: AsyncCallback>): void; - - /** - * Queries information about the running Ability Mission. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @returns Returns the AbilityMissionInfos. - */ - function queryRunningAbilityMissionInfos(maxNum: number): Promise>; - - /** - * Queries information about the running Ability Mission through callback. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @param callback Specified callback method. - */ - function queryRunningAbilityMissionInfos(maxNum: number, callback: AsyncCallback>): void; - - /** - * Queries information about the recent Ability Mission. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @returns Returns the AbilityMissionInfos. - */ - function queryRecentAbilityMissionInfos(maxNum: number, flag: number): Promise>; - - /** - * Queries information about the recent Ability Mission. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @param callback Specified callback method. - */ - function queryRecentAbilityMissionInfos(maxNum: number, flag: number, callback: AsyncCallback>): void; - - /** - * Remove the mission associated with the given mission ID. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @param missionId Indicates the mission ID - * @returns Returns 0 for success, return non-0 for failure. - */ - function removeMission(missionId: number): Promise; - - /** - * Remove the mission associated with the given mission ID. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @param missionId Indicates the mission ID - * @param callback Specified callback method - */ - function removeMission(missionId: number, callback: AsyncCallback): void; - - /** - * Remove the missions associated with the given array of the mission ID. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @param missionIds Indicates the array of the mission ID - * @returns Returns 0 for success, return non-0 for failure. - */ - function removeMissions(missionIds: Array): Promise; - - /** - * Remove the missions associated with the given array of the mission ID. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @param missionIds Indicates the array of the mission ID - * @param callback Specified callback method - */ - function removeMissions(missionIds: Array, callback: AsyncCallback): void; - - /** - * Removes all the recent missions - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @returns Returns 0 for success, return non-0 for failure. - */ - function clearMissions(): Promise; - - /** - * Removes all the recent missions - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @param callback Specified callback method. - */ - function clearMissions(callback: AsyncCallback): void; - - /** - * Ask that the mission associated with a given mission ID be moved to the - * front of the stack. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @param missionId Indicates the mission ID - * @returns Returns 0 for success, return non-0 for failure. - */ - function moveMissionToTop(missionId: number): Promise; - - /** - * Ask that the mission associated with a given mission ID be moved to the - * front of the stack. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @param missionId Indicates the mission ID - * @param callback Specified callback method. - */ - function moveMissionToTop(missionId: number, callback: AsyncCallback): void; - - /** - * Kills all background processes associated with a specified bundle. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @param bundleName Indicates the bundle name - * @returns Returns 0 for success, return non-0 for failure. - */ - function killProcessesByBundleName(bundleName: string): Promise; - - /** - * Kills all background processes associated with a specified bundle through callback. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - * @param bundleName Indicates the bundle name - * @param callback Specified callback method - */ - function killProcessesByBundleName(bundleName: string, callback: AsyncCallback): void; -} -export default abilityManager; \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.bundle.d.ts b/interfaces/kits/js/@ohos.bundle.d.ts index 537a609d62b..08c015fea98 100644 --- a/interfaces/kits/js/@ohos.bundle.d.ts +++ b/interfaces/kits/js/@ohos.bundle.d.ts @@ -1,345 +1,235 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { AsyncCallback } from './.basic'; -import { ApplicationInfo } from './bundle/applicationinfo'; -import { BundleInfo } from './bundle/bundleinfo'; -import { AbilityInfo } from './bundle/abilityinfo'; -import { Want } from './ability/want'; -import { BundleInstaller } from './bundle/bundleinstaller'; -import permission from './@ohos.security.permission'; - -/** - * @name BundleFlag - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ -export declare interface BundleFlag { - getBundleDefault: boolean; - getBundleWithAbilities: boolean; - getAbilityInfoWithPermission: boolean; - getAbilityInfoWithApplication: boolean; - getApplicationInfoWithPermission: boolean; - getBundleWithRequestedPermission: boolean; - getAllApplicationInfo: boolean; -} - -export declare interface QueryParameter { - flags?: number; - userId?: string; -} - -/** - * bundle. - * @name bundle - * @since 3 - * @sysCap appexecfwk - * @devices phone, tablet - * @permission N/A - */ -declare namespace bundle { - export enum ModuleUpdateFlag { - FLAG_MODULE_UPGRADE_CHECK = 0, - FLAG_MODULE_UPGRADE_INSTALL = 1, - FLAG_MODULE_UPGRADE_INSTALL_WITH_CONFIG_WINDOWS = 2, - } - - export enum FormType { - JAVA = 0, - JS = 1, - } - - export enum ColorMode { - AUTO_MODE = -1, - DARK_MODE = 0, - LIGHT_MODE = 1, - } - - export enum GrantStatus { - PERMISSION_DENIED = -1, - PERMISSION_GRANTED = 0, - } - - export enum ModuleRemoveFlag { - FLAG_MODULE_NOT_USED_BY_FORM = 0, - FLAG_MODULE_USED_BY_FORM = 1, - FLAG_MODULE_NOT_USED_BY_SHORTCUT = 2, - FLAG_MODULE_USED_BY_SHORTCUT = 3, - } - - export enum SignatureCompareResult { - SIGNATURE_MATCHED = 0, - SIGNATURE_NOT_MATCHED = 1, - SIGNATURE_UNKNOWN_BUNDLE = 2, - } - - export enum ShortcutExistence { - SHORTCUT_EXISTENCE_EXISTS = 0, - SHORTCUT_EXISTENCE_NOT_EXISTS = 1, - SHORTCUT_EXISTENCE_UNKNOW = 2, - } - - export enum QueryShortCutFlag { - QUERY_SHORTCUT_HOME = 0, - } - - /** - * @name AbilityType - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ - export enum AbilityType { - UNKNOWN, - PAGE, - SERVICE, - DATA, - } - - /** - * @name AbilitySubType - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ - export enum AbilitySubType { - UNSPECIFIED = 0, - CA = 1, - } - - /** - * @name DisplayOrientation - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ - export enum DisplayOrientation { - UNSPECIFIED, - LANDSCAPE, - PORTRAIT, - FOLLOWRECENT, - } - - /** - * @name LaunchMode - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ - export enum LaunchMode { - SINGLETON = 0, - STANDARD = 1, - } - - export enum InstallErrorCode{ - SUCCESS = 0, - STATUS_INSTALL_FAILURE = 1, - STATUS_INSTALL_FAILURE_ABORTED = 2, - STATUS_INSTALL_FAILURE_INVALID = 3, - STATUS_INSTALL_FAILURE_CONFLICT = 4, - STATUS_INSTALL_FAILURE_STORAGE = 5, - STATUS_INSTALL_FAILURE_INCOMPATIBLE = 6, - STATUS_UNINSTALL_FAILURE = 7, - STATUS_UNINSTALL_FAILURE_BLOCKED = 8, - STATUS_UNINSTALL_FAILURE_ABORTED = 9, - STATUS_UNINSTALL_FAILURE_CONFLICT = 10, - STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT = 0x0B, - STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED = 0x0C, - STATUS_ABILITY_NOT_FOUND = 0x40, - STATUS_BMS_SERVICE_ERROR = 0x41 - } - - /** - * Obtains BundleInfo based on a given bundle name. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param bundleName Indicates the bundle name. - * @param callback Specified callback method. - */ - function getBundleInfo(bundleName: string, flags: number, callback: AsyncCallback) : void; - - /** - * Obtains BundleInfo based on a given bundle name. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param bundleName Indicates the bundle name. - * @return BundleInfo. - */ - function getBundleInfo(bundleName: string, flags: number) : Promise; - - /** - * Obtains Bundle installer to install or uninstall hap. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @return BundleInstaller. - */ - function getBundleInstaller(callback: AsyncCallback): void; - - /** - * Obtains Bundle installer to install or uninstall hap. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @return BundleInstaller. - */ - function getBundleInstaller(): Promise; - - /** - * Obtains the ApplicationInfo based on a given application name. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param bundleName Indicates the application name. - * @param callback Specified callback method. - */ - function getApplicationInfo(bundleName: string, flags: number, userId: number, callback: AsyncCallback) : void; - - /** - * Obtains the ApplicationInfo based on a given application name. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param bundleName Indicates the application name. - * @return ApplicationInfo. - */ - function getApplicationInfo(bundleName: string, flags: number, userId: number) : Promise; - - /** - * Query the AbilityInfo by the given Want. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param want Indicates the Want for the ability to be queried. - * @param callback Specified callback method. - */ - function queryAbilityByWant(want: Want, params: QueryParameter, callback: AsyncCallback>): void; - - /** - * Query the AbilityInfo by the given Want. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param want Indicates the Want for the ability to be queried. - * @return AbilityInfo. - */ - function queryAbilityByWant(want: Want, params: QueryParameter): Promise; - - /** - * Obtains BundleInfo of all bundles available in the system. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param callback Specified callback method. - */ - function getBundleInfos(flags: BundleFlag, callback: AsyncCallback>) : void; - - /** - * Obtains BundleInfo of all bundles available in the system. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @return Array of BundleInfo. - */ - function getBundleInfos(flags: BundleFlag) : Promise>; - - /** - * Obtains information about all installed applications. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param callback Specified callback method. - */ - function getApplicationInfos(flags: number, userId: number, callback: AsyncCallback>) : void; - - /** - * Obtains information about all installed applications. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param NA - * @return Array of ApplicationInfo. - */ - function getApplicationInfos(flags: number, userId: number) : Promise>; - - /** - * Obtains information about a bundle contained in a HAP. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param hapFilePath Indicates the path of the HAP. - * @param callback Specified callback method. - */ - function getBundleArchiveInfo(hapFilePath: string, flags: number, callback: AsyncCallback) : void; - - /** - * Obtains information about a bundle contained in a HAP. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param hapFilePath Indicates the path of the HAP. - * @return BundleInfo. - */ - function getBundleArchiveInfo(hapFilePath: string, flags: number) : Promise; - - /** - * Obtains detailed information about a specified permission. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param permissionName Indicates the name of the permission. - * @param callback Specified callback method. - */ - function getPermissionDef(permissionName: string, callback: AsyncCallback) : void; - /** - * Obtains detailed information about a specified permission. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param permissionName Indicates the name of the permission. - * @return PermissionDef. - */ - function getPermissionDef(permissionName: string) : Promise; -} - -export default bundle; \ No newline at end of file +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AsyncCallback } from './basic'; +import { ApplicationInfo } from './bundle/applicationInfo'; +import { BundleInfo } from './bundle/bundleInfo'; +import { AbilityInfo } from './bundle/abilityInfo'; +import { Want } from './ability/want'; +import { BundleInstaller } from './bundle/bundleInstaller'; +import { ElementName } from './bundle/elementName'; +import { ShortcutInfo } from './bundle/shortcutInfo'; +import { ModuleUsageRecord } from './bundle/moduleUsageRecord'; +import permission from './@ohos.security.permission'; + +/** + * @name BundleFlag + * @since 3 + * @SysCap BMS + * @import NA + * @permission NA + * @devices phone, tablet + */ +type PermissionEvent = 'permissionChange' | 'anyPermissionChange'; + +/** + * bundle. + * @name bundle + * @since 3 + * @sysCap appexecfwk + * @devices phone, tablet + * @permission N/A + */ +declare namespace bundle { + + enum BundleFlag { + GET_BUNDLE_DEFAULT = 0x00000000, + GET_BUNDLE_WITH_ABILITIES = 0x00000001, + GET_APPLICATION_INFO_WITH_PERMISSION = 0x00000008, + } + + export enum GrantStatus { + PERMISSION_DENIED = -1, + PERMISSION_GRANTED = 0, + } + + /** + * @name AbilityType + * @since 3 + * @SysCap BMS + * @import NA + * @permission NA + * @devices phone, tablet + */ + export enum AbilityType { + UNKNOWN, + PAGE, + SERVICE, + DATA, + } + + /** + * @name AbilitySubType + * @since 3 + * @SysCap BMS + * @import NA + * @permission NA + * @devices phone, tablet + */ + export enum AbilitySubType { + UNSPECIFIED = 0, + CA = 1, + } + + /** + * @name DisplayOrientation + * @since 3 + * @SysCap BMS + * @import NA + * @permission NA + * @devices phone, tablet + */ + export enum DisplayOrientation { + UNSPECIFIED, + LANDSCAPE, + PORTRAIT, + FOLLOWRECENT, + } + + /** + * @name LaunchMode + * @since 3 + * @SysCap BMS + * @import NA + * @permission NA + * @devices phone, tablet + */ + export enum LaunchMode { + SINGLETON = 0, + STANDARD = 1, + } + + export enum InstallErrorCode{ + SUCCESS = 0, + STATUS_INSTALL_FAILURE = 1, + STATUS_INSTALL_FAILURE_ABORTED = 2, + STATUS_INSTALL_FAILURE_INVALID = 3, + STATUS_INSTALL_FAILURE_CONFLICT = 4, + STATUS_INSTALL_FAILURE_STORAGE = 5, + STATUS_INSTALL_FAILURE_INCOMPATIBLE = 6, + STATUS_UNINSTALL_FAILURE = 7, + STATUS_UNINSTALL_FAILURE_BLOCKED = 8, + STATUS_UNINSTALL_FAILURE_ABORTED = 9, + STATUS_UNINSTALL_FAILURE_CONFLICT = 10, + STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT = 0x0B, + STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED = 0x0C, + STATUS_ABILITY_NOT_FOUND = 0x40, + STATUS_BMS_SERVICE_ERROR = 0x41 + } + + /** + * Obtains BundleInfo based on a given bundle name. + * + * @devices phone, tablet + * @since 3 + * @SysCap BMS + * @param bundleName Indicates the bundle name. + * @param callback Specified callback method. + */ + function getBundleInfo(bundleName: string, bundelFlags: number, callback: AsyncCallback): void; + + /** + * Obtains Bundle installer to install or uninstall hap. + * + * @devices phone, tablet + * @since 3 + * @SysCap BMS + * @return BundleInstaller. + */ + function getBundleInstaller(callback: AsyncCallback): void; + function getBundleInstaller(): Promise; + + /** + * Obtains the ApplicationInfo based on a given application name. + * + * @devices phone, tablet + * @since 3 + * @SysCap BMS + * @param bundleName Indicates the application name. + * @param callback Specified callback method. + */ + function getApplicationInfo(bundleName: string, bundelFlags: number, userId: number, callback: AsyncCallback) : void; + function getApplicationInfo(bundleName: string, bundelFlags: number, userId?: number) : Promise; + + function checkPermission(bundleName: string, permission: string, callback: AsyncCallback): void; + function checkPermission(bundleName: string, permission: string): Promise; + + /** + * Obtains BundleInfo of all bundles available in the system. + * + * @devices phone, tablet + * @since 3 + * @SysCap BMS + * @param callback Specified callback method. + */ + function getBundleInfos(bundelFlag: BundleFlag, callback: AsyncCallback>) : void; + function getBundleInfos(bundelFlag: BundleFlag) : Promise>; + + // void registerAllPermissionsChanged(IRemoteObject callback) throws RemoteException; + function on(type: PermissionEvent, callback: AsyncCallback): void; + function on(type: PermissionEvent, uids: Array, callback: AsyncCallback): void; + + // void unregisterPermissionsChanged(IRemoteObject callback) throws RemoteException; + function off(type: PermissionEvent, callback: AsyncCallback):void; + function off(type: PermissionEvent, uids: Array, callback: AsyncCallback): void; + + /** + * Obtains information about all installed applications. + * + * @devices phone, tablet + * @since 3 + * @SysCap BMS + * @param callback Specified callback method. + */ + function getApplicationInfos(bundelFlags: number, userId: number, callback: AsyncCallback>) : void; + function getApplicationInfos(bundelFlags: number, callback: AsyncCallback>) : void; + function getApplicationInfos(bundelFlags: number, userId?: number) : Promise>; + + /** + * Obtains information about a bundle contained in a HAP. + * + * @devices phone, tablet + * @since 3 + * @SysCap BMS + * @param hapFilePath Indicates the path of the HAP. + * @param callback Specified callback method. + */ + function getBundleArchiveInfo(hapFilePath: string, bundelFlags: number, callback: AsyncCallback) : void + function getBundleArchiveInfo(hapFilePath: string, bundelFlags: number) : Promise; + + // List getShortcutInfos(String bundleName) throws RemoteException; + function getShortcutInfos(bundleName: string, callback: AsyncCallback>): void; + function getShortcutInfos(bundleName: string): Promise>; + + /** + * Obtains detailed information about a specified permission. + * + * @devices phone, tablet + * @since 3 + * @SysCap BMS + * @param permissionName Indicates the name of the permission. + * @param callback Specified callback method. + */ + function getPermissionDef(permissionName: string, callback: AsyncCallback) : void; + function getPermissionDef(permissionName: string) : Promise; + + function getHomeShortcutInfos(callback: AsyncCallback>): void; + function getHomeShortcutInfos(): Promise; + + // List getModuleUsageRecords(int maxNum) throws RemoteException, IllegalArgumentException; + function getModuleUsageRecords(maxNum: number, callback: AsyncCallback>): void; + function getModuleUsageRecords(maxNum: number): Promise>; +} + +export default bundle; diff --git a/interfaces/kits/js/app/processinfo.d.ts b/interfaces/kits/js/ability/abilityResult.d.ts similarity index 60% rename from interfaces/kits/js/app/processinfo.d.ts rename to interfaces/kits/js/ability/abilityResult.d.ts index f249df8e46d..834f9b505de 100644 --- a/interfaces/kits/js/app/processinfo.d.ts +++ b/interfaces/kits/js/ability/abilityResult.d.ts @@ -12,33 +12,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { Want } from './want'; -/** - * @name This class saves process information about an application - * @since 3 - * @SysCap appexecfwk - * @import import app from '@system.app' - * @permission N/A - * @devices phone, tablet - */ -export interface ProcessInfo { +export interface AbilityResult { /** - * The id of the current process - * + * Indicates the result code returned after the ability is destroyed. You can define the result + * code to identify an error. * @default - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk + * @since 7 + * @sysCap AAFwk */ - pid: number; + resultCode: number; /** - * The name of the current process - * + * Indicates the data returned after the ability is destroyed. You can define the data returned. + * This parameter can be null. * @default - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk + * @since 7 + * @sysCap AAFwk */ - processName: string; + want?: Want; } \ No newline at end of file diff --git a/interfaces/kits/js/ability/connectOptions.d.ts b/interfaces/kits/js/ability/connectOptions.d.ts new file mode 100644 index 00000000000..9247001a4d2 --- /dev/null +++ b/interfaces/kits/js/ability/connectOptions.d.ts @@ -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. + */ +import rpc from './../@ohos.rpc'; +import { ElementName } from '../bundle/elementName'; + +/** + * Provides callback methods that are called when a remote ability using the Service template is connected or + * disconnected. + * + *

You must override the methods of this interface to implement your processing logic for the connection and + * disconnection of an ability using the Service template (Service ability for short).

+ * + * @Syscap {@link SystemCapability.Aafwk#ABILITY} + * @since 1 + */ +declare interface ConnectOptions { + onConnect: (elementName: ElementName, iRemoteObject: IRemoteObject) => void; + onDisconnect: (elementName: ElementName) => void; + onFailed: (code: number) => void; +} \ No newline at end of file diff --git a/interfaces/kits/js/ability/startabilityparameter.d.ts b/interfaces/kits/js/ability/startAbilityParameter.d.ts similarity index 81% rename from interfaces/kits/js/ability/startabilityparameter.d.ts rename to interfaces/kits/js/ability/startAbilityParameter.d.ts index 0fef0182221..3e449112768 100644 --- a/interfaces/kits/js/ability/startabilityparameter.d.ts +++ b/interfaces/kits/js/ability/startAbilityParameter.d.ts @@ -13,6 +13,7 @@ * limitations under the License. */ import { Want } from './want'; +import { TaskSyncAnimationOptions } from './taskSyncAnimator' export interface StartAbilityParameter { /** @@ -34,16 +35,14 @@ export interface StartAbilityParameter { * @SysCap aafwk */ abilityStartSetting?: {[key: string]: any}; -} -export interface StartAbilityForResultParameter extends StartAbilityParameter { /** - * Indicates the Want containing information about the target ability to start. + * Indicates the special start setting used in starting ability with TaskSyncAnimation. * * @default - * @devices phone, tablet - * @since 3 + * @since 8 * @SysCap aafwk */ - requestCode: number; + taskSyncAnimationOptions?: TaskSyncAnimationOptions; } \ No newline at end of file diff --git a/interfaces/kits/js/ability/want.d.ts b/interfaces/kits/js/ability/want.d.ts index fbbd63b92b6..90a6b23ddd5 100644 --- a/interfaces/kits/js/ability/want.d.ts +++ b/interfaces/kits/js/ability/want.d.ts @@ -13,70 +13,20 @@ * limitations under the License. */ -/** - * @name WantOptions - * @since 3 - * @SysCap AAFwk - * @import - * @permission N/A - * @devices phone, tablet - */ -export declare interface WantOptions { - // indicates the grant to perform read operations on the URI - authReadUriPermission: boolean; - - // indicates the grant to perform write operations on the URI - authWriteUriPermission: boolean; - - // support forward intent result to origin ability - abilityForwardResult: boolean; - - // used for marking the ability start-up is triggered by continuation - abilityContinuation: boolean; - - // specifies whether a component does not belong to ohos - notOhosComponent: boolean; - - // specifies whether an ability is started - abilityFormEnabled: boolean; - - // indicates the grant for possible persisting on the URI. - authPersistableUriPermission: boolean; - - // indicates the grant for possible persisting on the URI. - authPrefixUriPermission: boolean; - - // support distributed scheduling system start up multiple devices - abilitySliceMultiDevice: boolean; - - // indicates that an ability using the service template is started regardless of whether the - // host application has been started. - startForegroundAbility: boolean; - - // install the specified ability if it's not installed. - installOnDemand: boolean; - - // return result to origin ability slice - abilitySliceForwardResult: boolean; - - // install the specified ability with background mode if it's not installed. - installWithBackgroundMode: boolean; -} - /** * Want is the basic communication component of the system. * @name Want - * @since 3 + * @since 6 * @sysCap AAFwk * @devices phone, tablet * @permission N/A */ -export declare interface Want { + export declare interface Want { /** * device id * @default - * @devices phone, tablet - * @since 3 + * @since 6 * @sysCap AAFwk */ deviceId?: string; @@ -85,7 +35,7 @@ export declare interface Want { * bundle name * @default - * @devices phone, tablet - * @since 3 + * @since 6 * @sysCap AAFwk */ bundleName?: string; @@ -94,7 +44,7 @@ export declare interface Want { * ability name * @default - * @devices phone, tablet - * @since 3 + * @since 6 * @sysCap AAFwk */ abilityName?: string; @@ -102,7 +52,7 @@ export declare interface Want { /** * The description of a URI in a Want. * @devices phone, tablet - * @since 3 + * @since 6 * @sysCap AAFwk * @default - */ @@ -111,7 +61,7 @@ export declare interface Want { /** * The description of the type in this Want. * @devices phone, tablet - * @since 3 + * @since 6 * @sysCap AAFwk * @default - */ @@ -120,16 +70,16 @@ export declare interface Want { /** * The options of the flags in this Want. * @devices phone, tablet - * @since 3 + * @since 6 * @sysCap AAFwk * @default - */ - options?: WantOptions; + flags?: number; /** * The description of an action in an want. * @devices phone, tablet - * @since 3 + * @since 6 * @sysCap AAFwk * @default - */ @@ -138,7 +88,7 @@ export declare interface Want { /** * The description of the WantParams object in an Want * @devices phone, tablet - * @since 3 + * @since 6 * @sysCap AAFwk * @default - */ @@ -147,7 +97,7 @@ export declare interface Want { /** * The description of a entities in a Want. * @devices phone, tablet - * @since 3 + * @since 6 * @sysCap AAFwk * @default - */ diff --git a/interfaces/kits/js/app/abilitymissioninfo.d.ts b/interfaces/kits/js/app/abilityMissionInfo.d.ts similarity index 34% rename from interfaces/kits/js/app/abilitymissioninfo.d.ts rename to interfaces/kits/js/app/abilityMissionInfo.d.ts index 75a376e6865..eb7d23cb39e 100644 --- a/interfaces/kits/js/app/abilitymissioninfo.d.ts +++ b/interfaces/kits/js/app/abilityMissionInfo.d.ts @@ -12,86 +12,46 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { ElementName } from '../bundle/elementname'; + +import { ElementName } from '../bundle/elementName'; /** - * @name Task stack information corresponding to ability - * @since 3 - * @SysCap appexecfwk - * @import import AbilityMissionInfo from '@ohos.AbilityMissionInfo' + * @name Mission information corresponding to ability + * @since 7 + * @SysCap SystemCapability.Appexecfwk + * @import import AbilityMissionInfo from 'app/abilityMissionInfo' * @permission N/A - * @devices phone, tablet + * @devices phone, tablet, tv, wearable */ export interface AbilityMissionInfo { /** - * Unique identification of task stack information corresponding to ability - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk + * @default Unique identification of task stack information corresponding to ability + * @since 7 + * @SysCap SystemCapability.Appexecfwk */ - id: number; + missionId: number; /** - * The component launched as the first ability in the task stack + * @default The component launched as the first ability in the task stack * This can be considered the "application" of this task stack - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk + * @since 7 + * @SysCap SystemCapability.Appexecfwk */ - baseAbility: ElementName; + bottomAbility: ElementName; /** - * The ability component at the top of the history stack of the task + * @default The ability component at the top of the history stack of the task * This is what the user is currently doing - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk + * @since 7 + * @SysCap SystemCapability.Appexecfwk */ topAbility: ElementName; /** - * The corresponding ability description information in the task stack - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk + * @default The corresponding ability description information in the task stack + * @since 7 + * @SysCap SystemCapability.Appexecfwk */ - missionDescription: MissionDescriptionInfo; + windowMode: number; } -/** - * @name Task stack description information - * @since 3 - * @SysCap appexecfwk - * @import import app from '@system.app' - * @permission N/A - * @devices phone, tablet - */ -export interface MissionDescriptionInfo { - /** - * The label of the specified ability in the task stack - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - */ - label: string; - - /** - * The path to the icon that specifies the ability in the task stack - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap appexecfwk - */ - iconPath: string; -} \ No newline at end of file diff --git a/interfaces/kits/js/app/activeProcessInfo.d.ts b/interfaces/kits/js/app/activeProcessInfo.d.ts new file mode 100644 index 00000000000..865f77595c8 --- /dev/null +++ b/interfaces/kits/js/app/activeProcessInfo.d.ts @@ -0,0 +1,53 @@ +/* + * 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. + */ + + +/** + * @name This class saves process information about an application + * @since 7 + * @SysCap SystemCapability.Appexecfwk + * @import import app from 'app/activeProcessInfo' + * @permission N/A + * @devices phone, tablet, tv, wearable + */ +export interface ActiveProcessInfo { + /** + * @default process id + * @since 7 + * @SysCap SystemCapability.Appexecfwk + */ + pid: number; + + /** + * @default user id + * @since 7 + * @SysCap SystemCapability.Appexecfwk + */ + uid: number; + + /** + * @default the name of the process + * @since 7 + * @SysCap SystemCapability.Appexecfwk + */ + processName: string; + + /** + * @default an array of the bundleNames running in the process + * @since 7 + * @SysCap SystemCapability.Appexecfwk + */ + bundleNames: Array; +} diff --git a/interfaces/kits/js/app/context.d.ts b/interfaces/kits/js/app/context.d.ts new file mode 100755 index 00000000000..2dc41d7f460 --- /dev/null +++ b/interfaces/kits/js/app/context.d.ts @@ -0,0 +1,98 @@ +/* +* Copyright (c) 2021 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import { AsyncCallback } from '../basic'; + +/** + * @name the result of requestPermissionsFromUser with asynchronous callback + * @since 7 + * @SysCap SystemCapability.Appexecfwk + * @permission N/A + * @devices phone, tablet, tv, wearable + */ +interface PermissionRequestResult { + /** + * @default The request code passed in by the user + * @since 7 + * @SysCap SystemCapability.Appexecfwk + */ + requestCode: number; + + /** + * @default The permissions passed in by the user + * @since 7 + * @SysCap SystemCapability.Appexecfwk + */ + permissions: Array; + + /** + * @default The results for the corresponding request permissions + * @since 7 + * @SysCap SystemCapability.Appexecfwk + */ + authResults: Array; +} + +interface PermissionOptions { + /** + * @default The process id + * @since 7 + * @SysCap SystemCapability.Appexecfwk + */ + pid?: number; + + /** + * @default The user id + * @since 7 + * @SysCap SystemCapability.Appexecfwk + */ + uid?: number; +} + +/** +* Requests certain permissions from the system. +* @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. +* @param requestCode Indicates the request code to be passed to the PermissionRequestResult +* @since 7 +* @sysCap SystemCapability.Appexecfwk +* @devices phone, tablet, tv, wearable +*/ +export interface Context { + /** + * Verify whether the specified permission is allowed for a particular + * pid and uid running in the system. + * @param permission The name of the specified permission + * @param options process id and user id + * @since 7 + * @sysCap SystemCapability.Appexecfwk + * @devices phone, tablet, tv, wearable + * @return asynchronous callback with {@code 0} if the PID + * and UID have the permission; callback with {@code -1} otherwise. + */ + verifyPermission(permission: string, callback: AsyncCallback): void; + verifyPermission(permission: string, options: PermissionOptions, callback: AsyncCallback): void; + verifyPermission(permission: string, options?: PermissionOptions): Promise; + + /** + * Requests certain permissions from the system. + * required for granting a certain permission. + * @devices phone + * @since 7 + * @sysCap AAFwk + * @param - + * @return Return grant result + */ + requestPermissionsFromUser(permissions: Array, requestCode: number, resultCallback: AsyncCallback): void; +} \ No newline at end of file diff --git a/interfaces/kits/js/bundle/abilityinfo.d.ts b/interfaces/kits/js/bundle/abilityInfo.d.ts similarity index 92% rename from interfaces/kits/js/bundle/abilityinfo.d.ts rename to interfaces/kits/js/bundle/abilityInfo.d.ts index 106ad326f82..08ccc709df0 100644 --- a/interfaces/kits/js/bundle/abilityinfo.d.ts +++ b/interfaces/kits/js/bundle/abilityInfo.d.ts @@ -1,57 +1,59 @@ -/* - * 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 { ApplicationInfo } from './applicationinfo'; -import bundle from './../@ohos.bundle'; - -/** - * @name AbilityInfo - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ -export interface AbilityInfo { - readonly bundleName: string; - readonly name: string; - readonly label: string; - readonly description: string; - readonly icon: string; - readonly labelId: number; - readonly descriptionId: number; - readonly iconId: number; - readonly moduleName: string; - readonly process: string; - readonly targetAbility: string; - readonly backgroundModes: number; - readonly isVisible: boolean; - readonly formEnabled: boolean; - readonly type: bundle.AbilityType; - readonly subType: bundle.AbilitySubType; - readonly orientation: bundle.DisplayOrientation; - readonly launchMode: bundle.LaunchMode; - readonly permissions: Array; - readonly deviceTypes: Array; - readonly deviceCapabilities: Array; - readonly readPermission: string; - readonly writePermission: string; - readonly applicationInfo: ApplicationInfo; - readonly formEntity: number; - readonly minFormHeight: number; - readonly defaultFormHeight: number; - readonly minFormWidth: number; - readonly defaultFormWidth: number; - readonly uri: string; -} \ No newline at end of file +/* + * 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 { ApplicationInfo } from './applicationInfo'; +import { CustomizeData } from './customizeData' +import bundle from './../@ohos.bundle'; + +/** + * @name AbilityInfo + * @since 3 + * @SysCap BMS + * @import NA + * @permission NA + * @devices phone, tablet + */ +export interface AbilityInfo { + readonly bundleName: string; + readonly name: string; + readonly label: string; + readonly description: string; + readonly icon: string; + readonly labelId: number; + readonly descriptionId: number; + readonly iconId: number; + readonly moduleName: string; + readonly process: string; + readonly targetAbility: string; + readonly backgroundModes: number; + readonly isVisible: boolean; + readonly formEnabled: boolean; + readonly type: bundle.AbilityType; + readonly subType: bundle.AbilitySubType; + readonly orientation: bundle.DisplayOrientation; + readonly launchMode: bundle.LaunchMode; + readonly permissions: Array; + readonly deviceTypes: Array; + readonly deviceCapabilities: Array; + readonly readPermission: string; + readonly writePermission: string; + readonly applicationInfo: ApplicationInfo; + readonly formEntity: number; + readonly minFormHeight: number; + readonly defaultFormHeight: number; + readonly minFormWidth: number; + readonly defaultFormWidth: number; + readonly uri: string; + customizeData: Map>; +} diff --git a/interfaces/kits/js/bundle/applicationinfo.d.ts b/interfaces/kits/js/bundle/applicationInfo.d.ts similarity index 90% rename from interfaces/kits/js/bundle/applicationinfo.d.ts rename to interfaces/kits/js/bundle/applicationInfo.d.ts index 50ccc0058d5..86f76f69cbf 100644 --- a/interfaces/kits/js/bundle/applicationinfo.d.ts +++ b/interfaces/kits/js/bundle/applicationInfo.d.ts @@ -1,42 +1,43 @@ -/* - * 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 { ModuleInfo } from './moduleinfo'; - -/** - * @name ApplicationInfo - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ -export interface ApplicationInfo { - readonly name: string; - readonly description: string; - readonly descriptionId: number; - readonly systemApp: boolean; - readonly enabled: boolean; - readonly label: string; - readonly labelId: string; - readonly icon: string; - readonly iconId: string; - readonly process: string; - readonly supportedModes: number; - readonly moduleSourceDirs: Array; - readonly permissions: Array; - readonly moduleInfos: Array; - flags: number; - readonly entryDir: string; +/* + * 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 { ModuleInfo } from './moduleInfo'; +import { CustomizeData } from './customizeData' + +/** + * @name ApplicationInfo + * @since 3 + * @SysCap BMS + * @import NA + * @permission NA + * @devices phone, tablet + */ +export interface ApplicationInfo { + readonly name: string; + readonly description: string; + readonly descriptionId: number; + readonly systemApp: boolean; + readonly enabled: boolean; + readonly label: string; + readonly labelId: string; + readonly icon: string; + readonly iconId: string; + readonly process: string; + readonly supportedModes: number; + readonly moduleSourceDirs: Array; + readonly permissions: Array; + readonly moduleInfos: Array; + readonly entryDir: string; + customizeData: Map; } \ No newline at end of file diff --git a/interfaces/kits/js/bundle/bundleinfo.d.ts b/interfaces/kits/js/bundle/bundleInfo.d.ts similarity index 84% rename from interfaces/kits/js/bundle/bundleinfo.d.ts rename to interfaces/kits/js/bundle/bundleInfo.d.ts index 2ec1b7df6af..58c69d4616c 100644 --- a/interfaces/kits/js/bundle/bundleinfo.d.ts +++ b/interfaces/kits/js/bundle/bundleInfo.d.ts @@ -1,77 +1,74 @@ -/* - * 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 { AbilityInfo } from './abilityinfo'; -import { ApplicationInfo } from './applicationinfo'; -import { HapModuleInfo } from './hapmoduleinfo'; - -/** - * @name UsedScene - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ -export interface UsedScene { - abilities: Array; - when: string; -} - -/** - * @name ReqPermissionDetail - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ -export interface ReqPermissionDetail { - name: string; - reason: string; - usedScene: UsedScene; -} - -/** - * @name BundleInfo - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ -export interface BundleInfo { - readonly name: string; - readonly type: string; - readonly appId: string; - readonly uid: number; - readonly installTime: number; - readonly updateTime: number; - readonly appInfo: ApplicationInfo; - readonly abilityInfos: Array; - readonly reqPermissions: Array; - readonly reqPermissionDetails: Array; - readonly vendor: string; - readonly versionCode: number; - readonly versionName: string; - readonly compatibleVersion: number; - readonly targetVersion: number; - readonly isCompressNativeLibs: boolean; - readonly hapModuleInfos: Array; - readonly entryModuleName: string; - readonly cpuAbi: string; - readonly isSilentInstallation: string; - readonly minCompatibleVersionCode: number; - readonly entryInstallationFree: boolean; -} \ No newline at end of file +/* + * 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 { AbilityInfo } from './abilityInfo'; +import { ApplicationInfo } from './applicationInfo'; + +/** + * @name UsedScene + * @since 3 + * @SysCap BMS + * @import NA + * @permission NA + * @devices phone, tablet + */ +export interface UsedScene { + abilities: Array; + when: string; +} + +/** + * @name ReqPermissionDetail + * @since 3 + * @SysCap BMS + * @import NA + * @permission NA + * @devices phone, tablet + */ +export interface ReqPermissionDetail { + name: string; + reason: string; + usedScene: UsedScene; +} + +/** + * @name BundleInfo + * @since 3 + * @SysCap BMS + * @import NA + * @permission NA + * @devices phone, tablet + */ +export interface BundleInfo { + readonly name: string; + readonly type: string; + readonly appId: string; + readonly uid: number; + readonly installTime: number; + readonly updateTime: number; + readonly appInfo: ApplicationInfo; + readonly abilityInfos: Array; + readonly reqPermissions: Array; + readonly vendor: string; + readonly versionCode: number; + readonly versionName: string; + readonly compatibleVersion: number; + readonly targetVersion: number; + readonly isCompressNativeLibs: boolean; + readonly entryModuleName: string; + readonly cpuAbi: string; + readonly isSilentInstallation: string; + readonly minCompatibleVersionCode: number; + readonly entryInstallationFree: boolean; +} diff --git a/interfaces/kits/js/bundle/bundleinstaller.d.ts b/interfaces/kits/js/bundle/bundleInstaller.d.ts similarity index 94% rename from interfaces/kits/js/bundle/bundleinstaller.d.ts rename to interfaces/kits/js/bundle/bundleInstaller.d.ts index fe2f5200df7..8e4a49e0768 100644 --- a/interfaces/kits/js/bundle/bundleinstaller.d.ts +++ b/interfaces/kits/js/bundle/bundleInstaller.d.ts @@ -1,86 +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. - */ - -import { AsyncCallback } from './../.basic'; -import bundle from './../@ohos.bundle'; - -/** - * @name InstallParam - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ -export interface InstallParam { - userId: number; - installFlag: number; - isKeepData: boolean; -} - -/** - * @name InstallStatus - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ -export interface InstallStatus { - status: bundle.InstallErrorCode; - /** - * The install result string message. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap BMS - */ - statusMessage: string; -} - -/** - * @name BundleInstaller - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ -export interface BundleInstaller { - /** - * Install an application in a HAP. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param bundleFilePaths Indicates the paths of the HAP. - * @param InstallParam Indicates the userId and whether keep data. - * @return InstallStatus - */ - install(bundleFilePaths: Array, param: InstallParam, callback: AsyncCallback): void; - - /** - * Uninstall an application. - * - * @devices phone, tablet - * @since 3 - * @SysCap BMS - * @param bundleName Indicates the bundle name. - * @param InstallParam Indicates the userId and whether keep data. - * @return InstallStatus - */ - uninstall(bundleName: string, param: InstallParam, callback: AsyncCallback): void; +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AsyncCallback } from './../basic'; +import bundle from './../@ohos.bundle'; + +/** + * @name InstallParam + * @since 3 + * @SysCap BMS + * @import NA + * @permission NA + * @devices phone, tablet + */ +export interface InstallParam { + userId: number; + installFlag: number; + isKeepData: boolean; +} + +/** + * @name InstallStatus + * @since 3 + * @SysCap BMS + * @import NA + * @permission NA + * @devices phone, tablet + */ +export interface InstallStatus { + status: bundle.InstallErrorCode; + /** + * The install result string message. + * + * @default - + * @devices phone, tablet + * @since 3 + * @SysCap BMS + */ + statusMessage: string; +} + +/** + * @name BundleInstaller + * @since 3 + * @SysCap BMS + * @import NA + * @permission NA + * @devices phone, tablet + */ +export interface BundleInstaller { + /** + * Install an application in a HAP. + * + * @devices phone, tablet + * @since 3 + * @SysCap BMS + * @param bundleFilePaths Indicates the paths of the HAP. + * @param InstallParam Indicates the userId and whether keep data. + * @return InstallStatus + */ + install(bundleFilePaths: Array, param: InstallParam, callback: AsyncCallback): void; + + /** + * Uninstall an application. + * + * @devices phone, tablet + * @since 3 + * @SysCap BMS + * @param bundleName Indicates the bundle name. + * @param InstallParam Indicates the userId and whether keep data. + * @return InstallStatus + */ + uninstall(bundleName: string, param: InstallParam, callback: AsyncCallback): void; } \ No newline at end of file diff --git a/interfaces/kits/js/bundle/customizeData.d.ts b/interfaces/kits/js/bundle/customizeData.d.ts new file mode 100644 index 00000000000..68258099d6e --- /dev/null +++ b/interfaces/kits/js/bundle/customizeData.d.ts @@ -0,0 +1,19 @@ +/* + * 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. + */ + +export interface CustomizeData { + name: string; + value: string; +} \ No newline at end of file diff --git a/interfaces/kits/js/bundle/elementname.d.ts b/interfaces/kits/js/bundle/elementName.d.ts similarity index 100% rename from interfaces/kits/js/bundle/elementname.d.ts rename to interfaces/kits/js/bundle/elementName.d.ts diff --git a/interfaces/kits/js/bundle/moduleinfo.d.ts b/interfaces/kits/js/bundle/moduleInfo.d.ts similarity index 100% rename from interfaces/kits/js/bundle/moduleinfo.d.ts rename to interfaces/kits/js/bundle/moduleInfo.d.ts diff --git a/interfaces/kits/js/bundle/hapmoduleinfo.d.ts b/interfaces/kits/js/bundle/moduleUsageRecord.d.ts similarity index 52% rename from interfaces/kits/js/bundle/hapmoduleinfo.d.ts rename to interfaces/kits/js/bundle/moduleUsageRecord.d.ts index 161fbef3997..8cc84046b05 100644 --- a/interfaces/kits/js/bundle/hapmoduleinfo.d.ts +++ b/interfaces/kits/js/bundle/moduleUsageRecord.d.ts @@ -12,30 +12,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {AbilityInfo} from "./abilityinfo"; -/** - * @name HapModuleInfo - * @since 3 - * @SysCap BMS - * @import NA - * @permission NA - * @devices phone, tablet - */ -export interface HapModuleInfo { +export interface ModuleUsageRecord { + readonly bundleName: string; + readonly appLabelId: number; readonly name: string; - readonly description: string; - readonly descriptionId: number; - readonly icon: string; - readonly label: string; readonly labelId: number; - readonly iconId: number; - readonly backgroundImg: string; - readonly supportedModes: number; - readonly reqCapabilities: Array; - readonly deviceTypes: Array; - readonly abilityInfos: Array; - readonly moduleName: string; - readonly mainAbilityName: string; - readonly installationFree: boolean; + readonly descriptionId: number; + readonly abilityName: string; + readonly abilityLabelId: number; + readonly abilityDescriptionId: number; + readonly abilityIconId: number; + readonly launchedCount: number; + readonly lastLaunchTime: number; + readonly isRemoved: boolean; + readonly installationFreeSupported: boolean; } \ No newline at end of file diff --git a/interfaces/kits/js/bundle/shortcutInfo.d.ts b/interfaces/kits/js/bundle/shortcutInfo.d.ts new file mode 100644 index 00000000000..1e6ce78bf9d --- /dev/null +++ b/interfaces/kits/js/bundle/shortcutInfo.d.ts @@ -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. + */ +export interface ShortcutIntent{ + readonly targetBundle: string; + readonly targetClass: string; +} + +export interface ShortcutInfo { + readonly id: string; + readonly bundleName: string; + readonly hostAbility: string; + readonly icon: string; + readonly label: string; + readonly disableMessage: string; + readonly intents: Array; + readonly isStatic?: boolean + readonly isHomeShortcut?: boolean; + readonly isEnabled?: boolean; +} \ No newline at end of file diff --git a/interfaces/kits/napi/BUILD.gn b/interfaces/kits/napi/BUILD.gn old mode 100755 new mode 100644 index ca3fe779c28..2bc97e911df --- a/interfaces/kits/napi/BUILD.gn +++ b/interfaces/kits/napi/BUILD.gn @@ -18,7 +18,9 @@ group("napi_packages") { "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/abilityManager:abilitymanager", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataUriUtils:datauriutils", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility:featureability", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/formAbility:form", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/particleAbility:particleability", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/wantConstant:wantconstant", ] } diff --git a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp index c0fe1f2636a..bbce255c6a1 100644 --- a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp +++ b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp @@ -209,7 +209,8 @@ napi_value NAPI_QueryRecentAbilityMissionInfosWrap( napi_value resourceName; napi_create_string_latin1(env, "NAPI_QueryRecentAbilityMissionInfosCallBack", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -260,7 +261,8 @@ napi_value NAPI_QueryRecentAbilityMissionInfosWrap( NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); async_callback_info->deferred = deferred; - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -340,6 +342,141 @@ napi_value NAPI_QueryRecentAbilityMissionInfos(napi_env env, napi_callback_info return ((callBackMode) ? (nullptr) : (ret)); } +napi_value NAPI_GetpreviousAbilityMissionInfosWrap(napi_env env, napi_callback_info info, bool callBackMode, + AsyncPreviousMissionInfosCallbackInfo *async_callback_info) +{ + HILOG_INFO("NAPI_GetpreviousAbilityMissionInfosWrap called..."); + if (callBackMode) { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_GetpreviousAbilityMissionInfosWrap", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("getpreviousAbilityMissionInfos called(CallBack Mode)..."); + AsyncPreviousMissionInfosCallbackInfo *async_callback_info = + (AsyncPreviousMissionInfosCallbackInfo *)data; + HILOG_INFO("maxMissionNum = [%{public}d]", async_callback_info->maxMissionNum); + + GetAbilityManagerInstance()->GetRecentMissions( + async_callback_info->maxMissionNum, 1, async_callback_info->previousMissionInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("getpreviousAbilityMissionInfos compeleted(CallBack Mode)..."); + AsyncPreviousMissionInfosCallbackInfo *async_callback_info = + (AsyncPreviousMissionInfosCallbackInfo *)data; + napi_value result[2] = {0}; + napi_value callback; + napi_value undefined; + napi_value callResult = 0; + + result[0] = GetCallbackErrorValue(async_callback_info->env, BUSINESS_ERROR_CODE_OK); + napi_create_array(env, &result[1]); + GetRecentMissionsForResult(env, async_callback_info->previousMissionInfo, result[1]); + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, async_callback_info->callback[0], &callback); + napi_call_function(env, undefined, callback, 2, &result[0], &callResult); + + if (async_callback_info->callback[0] != nullptr) { + napi_delete_reference(env, async_callback_info->callback[0]); + } + napi_delete_async_work(env, async_callback_info->asyncWork); + delete async_callback_info; + }, + (void *)async_callback_info, + &async_callback_info->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, async_callback_info->asyncWork)); + // create reutrn + napi_value ret = 0; + NAPI_CALL(env, napi_create_int32(env, 1, &ret)); + return ret; + } else { + napi_value resourceName; + napi_create_string_latin1( + env, "NAPI_GetpreviousAbilityMissionInfosWrapPromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + async_callback_info->deferred = deferred; + + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("getpreviousAbilityMissionInfos called(Promise Mode)..."); + AsyncPreviousMissionInfosCallbackInfo *async_callback_info = + (AsyncPreviousMissionInfosCallbackInfo *)data; + HILOG_INFO("maxMissionNum = [%{public}d]", async_callback_info->maxMissionNum); + + GetAbilityManagerInstance()->GetRecentMissions( + async_callback_info->maxMissionNum, 1, async_callback_info->previousMissionInfo); + HILOG_INFO("size = [%{public}zu]", async_callback_info->previousMissionInfo.size()); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("getpreviousAbilityMissionInfos compeleted(Promise Mode)..."); + AsyncPreviousMissionInfosCallbackInfo *async_callback_info = + (AsyncPreviousMissionInfosCallbackInfo *)data; + napi_value result; + napi_create_array(env, &result); + GetRecentMissionsForResult(env, async_callback_info->previousMissionInfo, result); + napi_resolve_deferred(async_callback_info->env, async_callback_info->deferred, result); + napi_delete_async_work(env, async_callback_info->asyncWork); + delete async_callback_info; + }, + (void *)async_callback_info, + &async_callback_info->asyncWork); + napi_queue_async_work(env, async_callback_info->asyncWork); + return promise; + } +} + +napi_value NAPI_GetPreviousAbilityMissionInfos(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + napi_value argv[argc]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}zu]", argc); + + napi_valuetype valuetype0; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype0)); + NAPI_ASSERT(env, valuetype0 == napi_number, "Wrong argument type. Numbers expected."); + + int32_t value0; + NAPI_CALL(env, napi_get_value_int32(env, argv[0], &value0)); + + bool callBackMode = false; + if (argc >= 2) { + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + + AsyncPreviousMissionInfosCallbackInfo *async_callback_info = + new (std::nothrow) AsyncPreviousMissionInfosCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; + if (async_callback_info == nullptr) { + return nullptr; + } + + async_callback_info->maxMissionNum = value0; + if (callBackMode) { + napi_create_reference(env, argv[1], 1, &async_callback_info->callback[0]); + } + + napi_value ret = NAPI_GetpreviousAbilityMissionInfosWrap(env, info, callBackMode, async_callback_info); + if (ret == nullptr) { + delete async_callback_info; + async_callback_info = nullptr; + } + + return ((callBackMode) ? (nullptr) : (ret)); +} + napi_value NAPI_QueryRunningAbilityMissionInfosWrap( napi_env env, napi_callback_info info, bool callBackMode, AsyncMissionInfosCallbackInfo *async_callback_info) { @@ -348,7 +485,8 @@ napi_value NAPI_QueryRunningAbilityMissionInfosWrap( napi_value resourceName; napi_create_string_latin1(env, "NAPI_QueryRunningAbilityMissionInfosCallBack", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -400,7 +538,8 @@ napi_value NAPI_QueryRunningAbilityMissionInfosWrap( NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); async_callback_info->deferred = deferred; - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -483,7 +622,8 @@ napi_value NAPI_GetAllRunningProcessesWrap( napi_value resourceName; napi_create_string_latin1(env, "NAPI_GetAllRunningProcessesCallBack", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -529,7 +669,8 @@ napi_value NAPI_GetAllRunningProcessesWrap( NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); async_callback_info->deferred = deferred; - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -596,7 +737,8 @@ napi_value NAPI_RemoveMissionWrap( napi_value resourceName; napi_create_string_latin1(env, "NAPI_RemoveMissionCallBack", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -643,7 +785,8 @@ napi_value NAPI_RemoveMissionWrap( NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); async_callback_info->deferred = deferred; - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -717,7 +860,8 @@ napi_value NAPI_RemoveMissionsWrap( napi_value resourceName; napi_create_string_latin1(env, "NAPI_RemoveMissionsCallBack", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -764,7 +908,8 @@ napi_value NAPI_RemoveMissionsWrap( NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); async_callback_info->deferred = deferred; - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -849,7 +994,8 @@ napi_value NAPI_ClearMissionsWrap( napi_value resourceName; napi_create_string_latin1(env, "NAPI_ClearMissionsCallBack", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -896,7 +1042,8 @@ napi_value NAPI_ClearMissionsWrap( NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); async_callback_info->deferred = deferred; - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -962,7 +1109,8 @@ napi_value NAPI_MoveMissionToTopWrap( napi_value resourceName; napi_create_string_latin1(env, "NAPI_MoveMissionToTopCallBack", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -1009,7 +1157,8 @@ napi_value NAPI_MoveMissionToTopWrap( NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); async_callback_info->deferred = deferred; - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -1082,7 +1231,8 @@ napi_value NAPI_KillProcessesByBundleNameWrap( napi_value resourceName; napi_create_string_latin1(env, "NAPI_KillProcessesByBundleNameCallBack", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -1129,7 +1279,8 @@ napi_value NAPI_KillProcessesByBundleNameWrap( NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); async_callback_info->deferred = deferred; - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -1199,7 +1350,8 @@ napi_value NAPI_ClearUpApplicationDataWrap(napi_env env, napi_callback_info info napi_value resourceName; napi_create_string_latin1(env, "NAPI_ClearUpApplicationDataCallBack", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { @@ -1247,7 +1399,8 @@ napi_value NAPI_ClearUpApplicationDataWrap(napi_env env, napi_callback_info info NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); async_callback_info->deferred = deferred; - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, [](napi_env env, void *data) { diff --git a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.h b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.h index 609de4a7640..91af878ddea 100644 --- a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.h +++ b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.h @@ -111,9 +111,19 @@ struct AsyncClearUpApplicationDataCallbackInfo { int32_t result; }; +struct AsyncPreviousMissionInfosCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + int32_t maxMissionNum = 0; + std::vector previousMissionInfo; +}; + napi_value NAPI_GetAllRunningProcesses(napi_env env, napi_callback_info info); napi_value NAPI_QueryRunningAbilityMissionInfos(napi_env env, napi_callback_info info); napi_value NAPI_QueryRecentAbilityMissionInfos(napi_env env, napi_callback_info info); +napi_value NAPI_GetPreviousAbilityMissionInfos(napi_env env, napi_callback_info info); napi_value NAPI_RemoveMission(napi_env env, napi_callback_info info); napi_value NAPI_RemoveMissions(napi_env env, napi_callback_info info); napi_value NAPI_ClearMissions(napi_env env, napi_callback_info info); diff --git a/interfaces/kits/napi/aafwk/abilityManager/native_module.cpp b/interfaces/kits/napi/aafwk/abilityManager/native_module.cpp index 2a6e72c0336..ecb52951b52 100644 --- a/interfaces/kits/napi/aafwk/abilityManager/native_module.cpp +++ b/interfaces/kits/napi/aafwk/abilityManager/native_module.cpp @@ -40,10 +40,14 @@ static napi_value Init(napi_env env, napi_value exports) CreateWeightReasonCodeObject(env, nWeightReasonCode); napi_property_descriptor desc[] = {DECLARE_NAPI_FUNCTION("getAllRunningProcesses", NAPI_GetAllRunningProcesses), + DECLARE_NAPI_FUNCTION("getActiveProcessInfos", NAPI_GetAllRunningProcesses), DECLARE_NAPI_FUNCTION("queryRunningAbilityMissionInfos", NAPI_QueryRunningAbilityMissionInfos), + DECLARE_NAPI_FUNCTION("getActiveAbilityMissionInfos", NAPI_QueryRunningAbilityMissionInfos), DECLARE_NAPI_FUNCTION("queryRecentAbilityMissionInfos", NAPI_QueryRecentAbilityMissionInfos), + DECLARE_NAPI_FUNCTION("getPreviousAbilityMissionInfos", NAPI_GetPreviousAbilityMissionInfos), DECLARE_NAPI_FUNCTION("removeMission", NAPI_RemoveMission), DECLARE_NAPI_FUNCTION("removeMissions", NAPI_RemoveMissions), + DECLARE_NAPI_FUNCTION("deleteMissions", NAPI_RemoveMissions), DECLARE_NAPI_FUNCTION("clearMissions", NAPI_ClearMissions), DECLARE_NAPI_FUNCTION("moveMissionToTop", NAPI_MoveMissionToTop), DECLARE_NAPI_FUNCTION("killProcessesByBundleName", NAPI_KillProcessesByBundleName), diff --git a/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn b/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn index 4150e48cc61..e7987859215 100755 --- a/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn +++ b/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn @@ -31,6 +31,7 @@ ohos_shared_library("datauriutils") { deps = [ "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", "//foundation/ace/napi:ace_napi", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", @@ -47,7 +48,7 @@ ohos_shared_library("datauriutils") { "ipc:ipc_core", ] - relative_install_dir = "module/dataUriUtils" + relative_install_dir = "module/ability" subsystem_name = "aafwk" part_name = "aafwk_standard" diff --git a/interfaces/kits/napi/aafwk/dataUriUtils/napi_data_uri_utils.cpp b/interfaces/kits/napi/aafwk/dataUriUtils/napi_data_uri_utils.cpp index 8029bcac7c8..277399ae0f0 100644 --- a/interfaces/kits/napi/aafwk/dataUriUtils/napi_data_uri_utils.cpp +++ b/interfaces/kits/napi/aafwk/dataUriUtils/napi_data_uri_utils.cpp @@ -55,13 +55,14 @@ napi_value DataUriUtilsInit(napi_env env, napi_value exports) */ napi_value NAPI_GetIdSync(napi_env env, napi_callback_info info) { + HILOG_INFO("%{public}s,called", __func__); size_t requireArgc = 1; size_t argc = 1; napi_value args[1] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); if (argc > requireArgc) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; + return WrapVoidToJS(env); } napi_valuetype valuetype; @@ -71,7 +72,9 @@ napi_value NAPI_GetIdSync(napi_env env, napi_callback_info info) Uri uri(NapiValueToStringUtf8(env, args[0])); napi_value id = nullptr; - NAPI_CALL(env, napi_create_int64(env, DataUriUtils::GetId(uri), &id)); + int64_t result = DataUriUtils::GetId(uri); + NAPI_CALL(env, napi_create_int64(env, result, &id)); + HILOG_INFO("%{public}s, uri=%{public}s, id=%{public}lld.", __func__, uri.ToString().c_str(), result); return id; } @@ -86,13 +89,14 @@ napi_value NAPI_GetIdSync(napi_env env, napi_callback_info info) */ napi_value NAPI_AttachIdSync(napi_env env, napi_callback_info info) { + HILOG_INFO("%{public}s,called", __func__); size_t requireArgc = 2; size_t argc = 2; napi_value args[2] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); if (argc > requireArgc) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; + return WrapVoidToJS(env); } napi_valuetype valuetype; @@ -103,11 +107,16 @@ napi_value NAPI_AttachIdSync(napi_env env, napi_callback_info info) int64_t id; NAPI_CALL(env, napi_get_value_int64(env, args[1], &id)); + std::string result = DataUriUtils::AttachId(uri, id).ToString(); napi_value uriAttached = nullptr; - NAPI_CALL(env, - napi_create_string_utf8( - env, DataUriUtils::AttachId(uri, id).ToString().c_str(), NAPI_AUTO_LENGTH, &uriAttached)); + NAPI_CALL(env, napi_create_string_utf8(env, result.c_str(), NAPI_AUTO_LENGTH, &uriAttached)); + + HILOG_INFO("%{public}s, uri=%{public}s, id=%{public}lld, result=%{public}s.", + __func__, + uri.ToString().c_str(), + id, + result.c_str()); return uriAttached; } @@ -122,13 +131,14 @@ napi_value NAPI_AttachIdSync(napi_env env, napi_callback_info info) */ napi_value NAPI_DeleteIdSync(napi_env env, napi_callback_info info) { + HILOG_INFO("%{public}s,called", __func__); size_t requireArgc = 1; size_t argc = 1; napi_value args[1] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); if (argc > requireArgc) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; + return WrapVoidToJS(env); } napi_valuetype valuetype; @@ -137,9 +147,11 @@ napi_value NAPI_DeleteIdSync(napi_env env, napi_callback_info info) Uri uri(NapiValueToStringUtf8(env, args[0])); + std::string result = DataUriUtils::DeleteId(uri).ToString(); napi_value uriDeleted = nullptr; - NAPI_CALL(env, - napi_create_string_utf8(env, DataUriUtils::DeleteId(uri).ToString().c_str(), NAPI_AUTO_LENGTH, &uriDeleted)); + NAPI_CALL(env, napi_create_string_utf8(env, result.c_str(), NAPI_AUTO_LENGTH, &uriDeleted)); + + HILOG_INFO("%{public}s, uri=%{public}s, result=%{public}s.", __func__, uri.ToString().c_str(), result.c_str()); return uriDeleted; } @@ -154,13 +166,14 @@ napi_value NAPI_DeleteIdSync(napi_env env, napi_callback_info info) */ napi_value NAPI_UpdateIdSync(napi_env env, napi_callback_info info) { + HILOG_INFO("%{public}s,called", __func__); size_t requireArgc = 2; size_t argc = 2; napi_value args[2] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); if (argc > requireArgc) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; + return WrapVoidToJS(env); } napi_valuetype valuetype; @@ -172,10 +185,16 @@ napi_value NAPI_UpdateIdSync(napi_env env, napi_callback_info info) int64_t id; NAPI_CALL(env, napi_get_value_int64(env, args[1], &id)); + std::string result = DataUriUtils::UpdateId(uri, id).ToString(); + napi_value uriUpdated = nullptr; - NAPI_CALL(env, - napi_create_string_utf8( - env, DataUriUtils::UpdateId(uri, id).ToString().c_str(), NAPI_AUTO_LENGTH, &uriUpdated)); + NAPI_CALL(env, napi_create_string_utf8(env, result.c_str(), NAPI_AUTO_LENGTH, &uriUpdated)); + + HILOG_INFO("%{public}s, uri=%{public}s, id=%{public}lld, result=%{public}s.", + __func__, + uri.ToString().c_str(), + id, + result.c_str()); return uriUpdated; } diff --git a/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp b/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp index dad2a33f8cc..f9840299aab 100755 --- a/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp @@ -22,6 +22,7 @@ #include "napi_context.h" #include "element_name.h" #include "napi_data_ability_helper.h" +#include "../inner/napi_common/napi_common_ability.h" using namespace OHOS::AAFwk; using namespace OHOS::AppExecFwk; @@ -31,8 +32,6 @@ namespace AppExecFwk { extern napi_value g_classContext; extern napi_value g_dataAbilityHelper; -CallbackInfo g_aceCallbackInfo; - /** * @brief FeatureAbility NAPI module registration. * @@ -48,7 +47,9 @@ napi_value FeatureAbilityInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("startAbility", NAPI_StartAbility), DECLARE_NAPI_FUNCTION("startAbilityForResult", NAPI_StartAbilityForResult), DECLARE_NAPI_FUNCTION("finishWithResult", NAPI_SetResult), + DECLARE_NAPI_FUNCTION("terminateSelfWithResult", NAPI_SetResult), DECLARE_NAPI_FUNCTION("terminateAbility", NAPI_TerminateAbility), + DECLARE_NAPI_FUNCTION("terminateSelf", NAPI_TerminateAbility), DECLARE_NAPI_FUNCTION("hasWindowFocus", NAPI_HasWindowFocus), DECLARE_NAPI_FUNCTION("getContext", NAPI_GetContext), DECLARE_NAPI_FUNCTION("getWant", NAPI_GetWant), @@ -62,6 +63,9 @@ napi_value FeatureAbilityInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("getAbilityInfo", NAPI_GetAbilityInfo), DECLARE_NAPI_FUNCTION("getHapModuleInfo", NAPI_GetHapModuleInfo), DECLARE_NAPI_FUNCTION("getDataAbilityHelper", NAPI_GetDataAbilityHelper), + DECLARE_NAPI_FUNCTION("acquireDataAbilityHelper", NAPI_AcquireDataAbilityHelper), + DECLARE_NAPI_FUNCTION("connectAbility", NAPI_FAConnectAbility), + DECLARE_NAPI_FUNCTION("disconnectAbility", NAPI_FADisConnectAbility), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties)); @@ -78,158 +82,8 @@ napi_value FeatureAbilityInit(napi_env env, napi_value exports) */ napi_value NAPI_StartAbility(napi_env env, napi_callback_info info) { - HILOG_INFO("%{public}s,called", __func__); - AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); - if (asyncCallbackInfo == nullptr) { - return nullptr; - } - - napi_value ret = StartAbilityWrap(env, info, asyncCallbackInfo); - if (ret == nullptr) { - if (asyncCallbackInfo != nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - } - } - return ret; -} - -/** - * @brief StartAbility processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param asyncCallbackInfo Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value StartAbilityWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo) -{ - - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = 2; - const size_t argcPromise = 1; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - CallAbilityParam param; - if (UnwrapParam(param, env, args[0]) == nullptr) { - HILOG_ERROR("%{public}s, call UnwrapParam failed.", __func__); - return nullptr; - } - asyncCallbackInfo->param = param; - asyncCallbackInfo->aceCallback = &g_aceCallbackInfo; - - if (argcAsync > argcPromise) { - ret = StartAbilityAsync(env, args, argcAsync, argcPromise, asyncCallbackInfo); - } else { - ret = StartAbilityPromise(env, asyncCallbackInfo); - } - - return ret; -} - -napi_value StartAbilityAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AsyncCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, args[argcPromise], &valuetype); - if (valuetype == napi_function) { - napi_create_reference(env, args[argcPromise], 1, &asyncCallbackInfo->cbInfo.callback); - } - - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { - HILOG_INFO("NAPI_StartAbility, worker pool thread execute."); - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - if (asyncCallbackInfo != nullptr) { - AbilityProcess::GetInstance()->StartAbility( - asyncCallbackInfo->ability, asyncCallbackInfo->param, *asyncCallbackInfo->aceCallback); - } - }, - [](napi_env env, napi_status status, void *data) { - HILOG_INFO("NAPI_StartAbility, main event thread complete."); - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - napi_value callback = 0; - napi_value undefined = 0; - napi_value result[ARGS_TWO] = {0}; - napi_value callResult = 0; - napi_get_undefined(env, &undefined); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - napi_create_int32(env, 0, &result[PARAM1]); - napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); - napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); - - if (asyncCallbackInfo->cbInfo.callback != nullptr) { - napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); - } - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - }, - (void *)asyncCallbackInfo, - &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - napi_value result = 0; - napi_get_null(env, &result); - return result; -} - -napi_value StartAbilityPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); - napi_deferred deferred; - napi_value promise = 0; - napi_create_promise(env, &deferred, &promise); - asyncCallbackInfo->deferred = deferred; - - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { - HILOG_INFO("NAPI_StartAbility, worker pool thread execute."); - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - if (asyncCallbackInfo != nullptr) { - AbilityProcess::GetInstance()->StartAbility( - asyncCallbackInfo->ability, asyncCallbackInfo->param, *asyncCallbackInfo->aceCallback); - } - }, - [](napi_env env, napi_status status, void *data) { - HILOG_INFO("NAPI_StartAbility, main event thread complete."); - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - napi_value result = 0; - napi_create_int32(env, 0, &result); - napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - }, - (void *)asyncCallbackInfo, - &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - return promise; + HILOG_INFO("%{public}s called.", __func__); + return NAPI_StartAbilityCommon(env, info, AbilityType::PAGE); } /** @@ -242,10 +96,10 @@ napi_value StartAbilityPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInf */ napi_value NAPI_StartAbilityForResult(napi_env env, napi_callback_info info) { - HILOG_INFO("%{public}s,called env=%{public}p", __func__, env); + HILOG_INFO("%{public}s,called.", __func__); AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); if (asyncCallbackInfo == nullptr) { - return nullptr; + return WrapVoidToJS(env); } napi_value ret = StartAbilityForResultWrap(env, info, asyncCallbackInfo); @@ -254,7 +108,9 @@ napi_value NAPI_StartAbilityForResult(napi_env env, napi_callback_info info) delete asyncCallbackInfo; asyncCallbackInfo = nullptr; } + ret = WrapVoidToJS(env); } + HILOG_INFO("%{public}s,end.", __func__); return ret; } @@ -268,10 +124,9 @@ napi_value NAPI_StartAbilityForResult(napi_env env, napi_callback_info info) */ napi_value StartAbilityForResultWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo) { - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = 3; - const size_t argcPromise = 2; + size_t argcAsync = 2; + const size_t argcPromise = 1; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = 0; @@ -283,20 +138,18 @@ napi_value StartAbilityForResultWrap(napi_env env, napi_callback_info info, Asyn } CallAbilityParam param; - if (UnwrapParam(param, env, args[0]) == nullptr) { - HILOG_ERROR("%{public}s, call UnwrapParam failed.", __func__); + if (UnwrapForResultParam(param, env, args[0]) == nullptr) { + HILOG_ERROR("%{public}s, call UnwrapForResultParam failed.", __func__); return nullptr; } asyncCallbackInfo->param = param; - asyncCallbackInfo->aceCallback = &g_aceCallbackInfo; - - g_aceCallbackInfo.env = env; + asyncCallbackInfo->aceCallback.env = env; if (argcAsync > PARAM1) { napi_valuetype valuetype = napi_undefined; napi_typeof(env, args[PARAM1], &valuetype); if (valuetype == napi_function) { // resultCallback: AsyncCallback - napi_create_reference(env, args[PARAM1], 1, &g_aceCallbackInfo.callback); + napi_create_reference(env, args[PARAM1], 1, &(asyncCallbackInfo->aceCallback.callback)); } } @@ -305,7 +158,7 @@ napi_value StartAbilityForResultWrap(napi_env env, napi_callback_info info, Asyn } else { ret = StartAbilityForResultPromise(env, asyncCallbackInfo); } - + HILOG_INFO("%{public}s,end.", __func__); return ret; } @@ -320,15 +173,6 @@ napi_value StartAbilityForResultAsync( napi_value resourceName = 0; napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); - g_aceCallbackInfo.env = env; - if (argcAsync > PARAM2) { - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, args[PARAM2], &valuetype); - if (valuetype == napi_function) { - // callback: AsyncCallback - napi_create_reference(env, args[PARAM2], 1, &asyncCallbackInfo->cbInfo.callback); - } - } napi_create_async_work( env, nullptr, @@ -338,33 +182,29 @@ napi_value StartAbilityForResultAsync( AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; if (asyncCallbackInfo != nullptr) { AbilityProcess::GetInstance()->StartAbility( - asyncCallbackInfo->ability, asyncCallbackInfo->param, *asyncCallbackInfo->aceCallback); + asyncCallbackInfo->ability, asyncCallbackInfo->param, asyncCallbackInfo->aceCallback); + } else { + HILOG_ERROR("NAPI_StartAbilityForResult, asyncCallbackInfo == nullptr"); } + HILOG_INFO("NAPI_StartAbilityForResult, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_StartAbilityForResult, main event thread complete."); AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - napi_value callback = 0; - napi_value undefined = 0; - napi_value result[ARGS_TWO] = {0}; - napi_value callResult = 0; - napi_get_undefined(env, &undefined); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - napi_create_int32(env, 0, &result[PARAM1]); - napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); - napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); - + // remove asynccallback from startabilityforresult if (asyncCallbackInfo->cbInfo.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + HILOG_INFO("NAPI_StartAbilityForResult, main event thread complete end."); }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); napi_value result = 0; napi_get_null(env, &result); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); return result; } @@ -375,12 +215,13 @@ napi_value StartAbilityForResultPromise(napi_env env, AsyncCallbackInfo *asyncCa HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } - napi_value resourceName; + napi_value resourceName = 0; napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); napi_deferred deferred; napi_value promise = 0; napi_create_promise(env, &deferred, &promise); - asyncCallbackInfo->deferred = deferred; + asyncCallbackInfo->aceCallback.callback = nullptr; + asyncCallbackInfo->aceCallback.deferred = deferred; napi_create_async_work( env, @@ -391,21 +232,24 @@ napi_value StartAbilityForResultPromise(napi_env env, AsyncCallbackInfo *asyncCa AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; if (asyncCallbackInfo != nullptr) { AbilityProcess::GetInstance()->StartAbility( - asyncCallbackInfo->ability, asyncCallbackInfo->param, *asyncCallbackInfo->aceCallback); + asyncCallbackInfo->ability, asyncCallbackInfo->param, asyncCallbackInfo->aceCallback); + } else { + HILOG_ERROR("NAPI_StartAbilityForResult, asyncCallbackInfo == nullptr"); } + HILOG_INFO("NAPI_StartAbilityForResult, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_StartAbilityForResult, main event thread complete."); AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - napi_value result = 0; - napi_create_int32(env, 0, &result); - napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); + // resolve it when call onAbilityResult napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + HILOG_INFO("NAPI_StartAbilityForResult, main event thread complete end."); }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + HILOG_INFO("%{public}s, promise end.", __func__); return promise; } @@ -422,16 +266,20 @@ napi_value NAPI_SetResult(napi_env env, napi_callback_info info) HILOG_INFO("%{public}s,called", __func__); AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); if (asyncCallbackInfo == nullptr) { - return nullptr; + HILOG_ERROR("%{public}s,asyncCallbackInfo == nullptr", __func__); + return WrapVoidToJS(env); } napi_value ret = SetResultWrap(env, info, asyncCallbackInfo); if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (asyncCallbackInfo != nullptr) { delete asyncCallbackInfo; asyncCallbackInfo = nullptr; } + ret = WrapVoidToJS(env); } + HILOG_INFO("%{public}s,end", __func__); return ret; } @@ -445,7 +293,6 @@ napi_value NAPI_SetResult(napi_env env, napi_callback_info info) */ napi_value SetResultWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo) { - HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = 2; const size_t argcPromise = 1; @@ -471,7 +318,7 @@ napi_value SetResultWrap(napi_env env, napi_callback_info info, AsyncCallbackInf } else { ret = SetResultPromise(env, asyncCallbackInfo); } - + HILOG_INFO("%{public}s,end", __func__); return ret; } @@ -502,7 +349,10 @@ napi_value SetResultAsync( if (asyncCallbackInfo->ability != nullptr) { asyncCallbackInfo->ability->SetResult( asyncCallbackInfo->param.requestCode, asyncCallbackInfo->param.want); + } else { + HILOG_ERROR("NAPI_SetResult, ability == nullptr"); } + HILOG_INFO("NAPI_SetResult, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_SetResult, main event thread complete."); @@ -522,12 +372,14 @@ napi_value SetResultAsync( } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + HILOG_INFO("NAPI_SetResult, main event thread complete end."); }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); napi_value result = 0; napi_get_null(env, &result); + HILOG_INFO("%{public}s, asyncCallback end", __func__); return result; } @@ -555,7 +407,10 @@ napi_value SetResultPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) if (asyncCallbackInfo->ability != nullptr) { asyncCallbackInfo->ability->SetResult( asyncCallbackInfo->param.requestCode, asyncCallbackInfo->param.want); + } else { + HILOG_ERROR("NAPI_SetResult, ability == nullptr"); } + HILOG_INFO("NAPI_SetResult, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_SetResult, main event thread complete."); @@ -565,10 +420,12 @@ napi_value SetResultPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + HILOG_INFO("NAPI_SetResult, main event thread complete end."); }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + HILOG_INFO("%{public}s, promise end", __func__); return promise; } @@ -585,16 +442,20 @@ napi_value NAPI_TerminateAbility(napi_env env, napi_callback_info info) HILOG_INFO("%{public}s,called", __func__); AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); if (asyncCallbackInfo == nullptr) { - return nullptr; + HILOG_ERROR("%{public}s,asyncCallbackInfo == nullptr", __func__); + return WrapVoidToJS(env); } napi_value ret = TerminateAbilityWrap(env, info, asyncCallbackInfo); if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (asyncCallbackInfo != nullptr) { delete asyncCallbackInfo; asyncCallbackInfo = nullptr; } + ret = WrapVoidToJS(env); } + HILOG_INFO("%{public}s,end", __func__); return ret; } @@ -631,7 +492,7 @@ napi_value TerminateAbilityWrap(napi_env env, napi_callback_info info, AsyncCall } else { ret = TerminateAbilityPromise(env, asyncCallbackInfo); } - + HILOG_INFO("%{public}s, asyncCallback end", __func__); return ret; } @@ -661,7 +522,10 @@ napi_value TerminateAbilityAsync( AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; if (asyncCallbackInfo->ability != nullptr) { asyncCallbackInfo->ability->TerminateAbility(); + } else { + HILOG_ERROR("NAPI_TerminateAbility, ability == nullptr"); } + HILOG_INFO("NAPI_TerminateAbility, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_TerminateAbility, main event thread complete."); @@ -681,12 +545,14 @@ napi_value TerminateAbilityAsync( } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + HILOG_INFO("NAPI_TerminateAbility, main event thread complete end."); }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); napi_value result = 0; napi_get_null(env, &result); + HILOG_INFO("%{public}s, asyncCallback end", __func__); return result; } @@ -714,7 +580,10 @@ napi_value TerminateAbilityPromise(napi_env env, AsyncCallbackInfo *asyncCallbac AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; if (asyncCallbackInfo->ability != nullptr) { asyncCallbackInfo->ability->TerminateAbility(); + } else { + HILOG_INFO("NAPI_TerminateAbility, ability == nullptr"); } + HILOG_INFO("NAPI_TerminateAbility, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_TerminateAbility, main event thread complete."); @@ -724,10 +593,12 @@ napi_value TerminateAbilityPromise(napi_env env, AsyncCallbackInfo *asyncCallbac napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + HILOG_INFO("NAPI_TerminateAbility, main event thread complete end."); }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + HILOG_INFO("%{public}s, promise end", __func__); return promise; } @@ -744,16 +615,20 @@ napi_value NAPI_HasWindowFocus(napi_env env, napi_callback_info info) HILOG_INFO("%{public}s,called", __func__); AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); if (asyncCallbackInfo == nullptr) { - return nullptr; + HILOG_ERROR("%{public}s,asyncCallbackInfo == nullptr", __func__); + return WrapVoidToJS(env); } napi_value ret = HasWindowFocusWrap(env, info, asyncCallbackInfo); if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (asyncCallbackInfo != nullptr) { delete asyncCallbackInfo; asyncCallbackInfo = nullptr; } + ret = WrapVoidToJS(env); } + HILOG_INFO("%{public}s,end", __func__); return ret; } @@ -767,31 +642,19 @@ napi_value NAPI_HasWindowFocus(napi_env env, napi_callback_info info) */ napi_value NAPI_GetContext(napi_env env, napi_callback_info info) { - HILOG_INFO("%{public}s,called", __func__); - AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); - if (asyncCallbackInfo == nullptr) { - return nullptr; - } - - napi_value ret = GetContextWrap(env, info, asyncCallbackInfo); - if (ret == nullptr) { - if (asyncCallbackInfo != nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - } - } - return ret; + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetContextCommon(env, info, AbilityType::PAGE); } /** - * @brief GetContext processing function. + * @brief HasWindowFocus processing function. * * @param env The environment that the Node-API call is invoked under. * @param asyncCallbackInfo Process data asynchronously. * * @return Return JS data successfully, otherwise return nullptr. */ -napi_value GetContextWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo) +napi_value HasWindowFocusWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo) { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (asyncCallbackInfo == nullptr) { @@ -812,15 +675,15 @@ napi_value GetContextWrap(napi_env env, napi_callback_info info, AsyncCallbackIn } if (argcAsync > argcPromise) { - ret = GetContextAsync(env, args, argcAsync, argcPromise, asyncCallbackInfo); + ret = HasWindowFocusAsync(env, args, argcAsync, argcPromise, asyncCallbackInfo); } else { - ret = GetContextPromise(env, asyncCallbackInfo); + ret = HasWindowFocusPromise(env, asyncCallbackInfo); } - + HILOG_INFO("%{public}s, asyncCallback end.", __func__); return ret; } -napi_value GetContextAsync( +napi_value HasWindowFocusAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AsyncCallbackInfo *asyncCallbackInfo) { HILOG_INFO("%{public}s, asyncCallback.", __func__); @@ -840,9 +703,18 @@ napi_value GetContextAsync( env, nullptr, resourceName, - [](napi_env env, void *data) { HILOG_INFO("GetContextAsync, worker pool thread execute."); }, + [](napi_env env, void *data) { + HILOG_INFO("NAPI_HasWindowFocus, worker pool thread execute."); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + if (asyncCallbackInfo->ability != nullptr) { + asyncCallbackInfo->native_result = asyncCallbackInfo->ability->HasWindowFocus(); + } else { + HILOG_ERROR("NAPI_HasWindowFocus, ability == nullptr"); + } + HILOG_INFO("NAPI_HasWindowFocus, worker pool thread execute end."); + }, [](napi_env env, napi_status status, void *data) { - HILOG_INFO("GetContextAsync, main event thread complete."); + HILOG_INFO("NAPI_HasWindowFocus, main event thread complete."); AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; napi_value callback = 0; napi_value undefined = 0; @@ -850,7 +722,7 @@ napi_value GetContextAsync( napi_value callResult = 0; napi_get_undefined(env, &undefined); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - napi_new_instance(env, g_classContext, 0, nullptr, &result[PARAM1]); + napi_get_boolean(env, asyncCallbackInfo->native_result, &result[PARAM1]); napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); @@ -860,16 +732,18 @@ napi_value GetContextAsync( napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; asyncCallbackInfo = nullptr; + HILOG_INFO("NAPI_HasWindowFocus, main event thread complete end."); }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); napi_value result = 0; napi_get_null(env, &result); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); return result; } -napi_value GetContextPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) +napi_value HasWindowFocusPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) { HILOG_INFO("%{public}s, promise.", __func__); if (asyncCallbackInfo == nullptr) { @@ -887,188 +761,74 @@ napi_value GetContextPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) env, nullptr, resourceName, - [](napi_env env, void *data) { HILOG_INFO("GetContextPromise, worker pool thread execute."); }, + [](napi_env env, void *data) { + HILOG_INFO("NAPI_HasWindowFocus, worker pool thread execute."); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + if (asyncCallbackInfo->ability != nullptr) { + asyncCallbackInfo->native_result = asyncCallbackInfo->ability->HasWindowFocus(); + } else { + HILOG_INFO("NAPI_HasWindowFocus, ability == nullptr"); + } + HILOG_INFO("NAPI_HasWindowFocus, worker pool thread execute end."); + }, [](napi_env env, napi_status status, void *data) { - HILOG_INFO("GetContextPromise, main event thread complete."); + HILOG_INFO("NAPI_HasWindowFocus, main event thread complete."); AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; napi_value result = 0; - napi_new_instance(env, g_classContext, 0, nullptr, &result); + napi_get_boolean(env, asyncCallbackInfo->native_result, &result); napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; asyncCallbackInfo = nullptr; + HILOG_INFO("NAPI_HasWindowFocus, main event thread complete end."); }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - + HILOG_INFO("%{public}s, promise end.", __func__); return promise; } +EXTERN_C_START /** - * @brief HasWindowFocus processing function. + * @brief The interface of onAbilityResult provided for ACE to call back to JS. * - * @param env The environment that the Node-API call is invoked under. - * @param asyncCallbackInfo Process data asynchronously. + * @param requestCode Indicates the request code returned after the ability is started. + * @param resultCode Indicates the result code returned after the ability is started. + * @param resultData Indicates the data returned after the ability is started. + * @param cb The environment and call back info that the Node-API call is invoked under. * - * @return Return JS data successfully, otherwise return nullptr. + * @return The return value from NAPI C++ to JS for the module. */ -napi_value HasWindowFocusWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo) +void CallOnAbilityResult(int requestCode, int resultCode, const Want &resultData, CallbackInfo cb) { - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, asyncCallbackInfo == nullptr.", __func__); - return nullptr; - } + HILOG_INFO("%{public}s,called", __func__); + uv_loop_s *loop = nullptr; - size_t argcAsync = 1; - const size_t argcPromise = 0; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(cb.env, &loop); +#endif // NAPI_VERSION >= 2 - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + HILOG_ERROR("%{public}s, work == nullptr.", __func__); + return; } - - if (argcAsync > argcPromise) { - ret = HasWindowFocusAsync(env, args, argcAsync, argcPromise, asyncCallbackInfo); - } else { - ret = HasWindowFocusPromise(env, asyncCallbackInfo); + OnAbilityCallback *onAbilityCB = new (std::nothrow) OnAbilityCallback{ + .requestCode = requestCode, + .resultCode = resultCode, + .resultData = resultData, + .cb = cb, + }; + if (onAbilityCB == nullptr) { + HILOG_ERROR("%{public}s, onAbilityCB == nullptr.", __func__); + delete work; + work = nullptr; + return; } + work->data = (void *)onAbilityCB; - return ret; -} - -napi_value HasWindowFocusAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AsyncCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, args[argcPromise], &valuetype); - if (valuetype == napi_function) { - napi_create_reference(env, args[argcPromise], 1, &asyncCallbackInfo->cbInfo.callback); - } - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { - HILOG_INFO("NAPI_HasWindowFocus, worker pool thread execute."); - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - if (asyncCallbackInfo->ability != nullptr) { - asyncCallbackInfo->native_result = asyncCallbackInfo->ability->HasWindowFocus(); - } - }, - [](napi_env env, napi_status status, void *data) { - HILOG_INFO("NAPI_HasWindowFocus, main event thread complete."); - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - napi_value callback = 0; - napi_value undefined = 0; - napi_value result[ARGS_TWO] = {0}; - napi_value callResult = 0; - napi_get_undefined(env, &undefined); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - napi_get_boolean(env, asyncCallbackInfo->native_result, &result[PARAM1]); - napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); - napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); - - if (asyncCallbackInfo->cbInfo.callback != nullptr) { - napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); - } - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - }, - (void *)asyncCallbackInfo, - &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - napi_value result = 0; - napi_get_null(env, &result); - return result; -} - -napi_value HasWindowFocusPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); - napi_deferred deferred; - napi_value promise = 0; - napi_create_promise(env, &deferred, &promise); - asyncCallbackInfo->deferred = deferred; - - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { - HILOG_INFO("NAPI_HasWindowFocus, worker pool thread execute."); - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - if (asyncCallbackInfo->ability != nullptr) { - asyncCallbackInfo->native_result = asyncCallbackInfo->ability->HasWindowFocus(); - } - }, - [](napi_env env, napi_status status, void *data) { - HILOG_INFO("NAPI_HasWindowFocus, main event thread complete."); - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - napi_value result = 0; - napi_get_boolean(env, asyncCallbackInfo->native_result, &result); - napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - }, - (void *)asyncCallbackInfo, - &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - - return promise; -} - -/** - * @brief The interface of onAbilityResult provided for ACE to call back to JS. - * - * @param requestCode Indicates the request code returned after the ability is started. - * @param resultCode Indicates the result code returned after the ability is started. - * @param resultData Indicates the data returned after the ability is started. - * @param cb The environment and call back info that the Node-API call is invoked under. - * - * @return The return value from NAPI C++ to JS for the module. - */ -void CallOnAbilityResult(int requestCode, int resultCode, const Want &resultData, CallbackInfo cb) -{ - HILOG_INFO("%{public}s,called env=%{public}p", __func__, cb.env); - - uv_loop_s *loop = nullptr; - -#if NAPI_VERSION >= 2 - napi_get_uv_event_loop(cb.env, &loop); -#endif // NAPI_VERSION >= 2 - - uv_work_t *work = new uv_work_t; - OnAbilityCallback *onAbilityCB = new (std::nothrow) OnAbilityCallback{ - .requestCode = requestCode, - .resultCode = resultCode, - .resultData = resultData, - .cb = cb, - }; - work->data = (void *)onAbilityCB; - - uv_queue_work( + int rev = uv_queue_work( loop, work, [](uv_work_t *work) {}, @@ -1080,32 +840,51 @@ void CallOnAbilityResult(int requestCode, int resultCode, const Want &resultData result[PARAM0] = GetCallbackErrorValue(event->cb.env, NO_ERROR); napi_create_object(event->cb.env, &result[PARAM1]); - // create requestCode - napi_value jsValue = 0; - napi_create_int32(event->cb.env, event->requestCode, &jsValue); - napi_set_named_property(event->cb.env, result[PARAM1], "requestCode", jsValue); // create resultCode + napi_value jsValue = 0; napi_create_int32(event->cb.env, event->resultCode, &jsValue); napi_set_named_property(event->cb.env, result[PARAM1], "resultCode", jsValue); // create want napi_value jsWant = WrapWant(event->cb.env, event->resultData); napi_set_named_property(event->cb.env, result[PARAM1], "want", jsWant); - napi_value callback = 0; - napi_value undefined = 0; - napi_get_undefined(event->cb.env, &undefined); - napi_value callResult = 0; - napi_get_reference_value(event->cb.env, event->cb.callback, &callback); - napi_call_function(event->cb.env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); if (event->cb.callback != nullptr) { - napi_delete_reference(event->cb.env, event->cb.callback); + // asynccallback + HILOG_INFO("CallOnAbilityResult, asynccallback"); + napi_value callback = 0; + napi_value undefined = 0; + napi_get_undefined(event->cb.env, &undefined); + napi_value callResult = 0; + napi_get_reference_value(event->cb.env, event->cb.callback, &callback); + + napi_call_function(event->cb.env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); + if (event->cb.callback != nullptr) { + napi_delete_reference(event->cb.env, event->cb.callback); + } + HILOG_INFO("CallOnAbilityResult, asynccallback end"); + } else { + // promise + HILOG_INFO("CallOnAbilityResult, promise"); + napi_resolve_deferred(event->cb.env, event->cb.deferred, result[PARAM1]); + HILOG_INFO("CallOnAbilityResult, promise end"); } + delete event; delete work; + work = nullptr; + event = nullptr; + HILOG_INFO("CallOnAbilityResult, uv_queue_work end"); }); - return; + if (rev != 0) { + delete onAbilityCB; + onAbilityCB = nullptr; + delete work; + work = nullptr; + } + HILOG_INFO("%{public}s,end", __func__); } +EXTERN_C_END bool InnerUnwrapWant(napi_env env, napi_value args, Want &want) { @@ -1113,11 +892,13 @@ bool InnerUnwrapWant(napi_env env, napi_value args, Want &want) napi_valuetype valueType = napi_undefined; NAPI_CALL_BASE(env, napi_typeof(env, args, &valueType), false); if (valueType != napi_object) { + HILOG_ERROR("%{public}s wrong argument type", __func__); return false; } napi_value jsWant = GetPropertyValueByPropertyName(env, args, "want", napi_object); if (jsWant == nullptr) { + HILOG_ERROR("%{public}s jsWant == nullptr", __func__); return false; } @@ -1133,7 +914,7 @@ bool InnerUnwrapWant(napi_env env, napi_value args, Want &want) * * @return The return value from NAPI C++ to JS for the module. */ -napi_value UnwrapParam(CallAbilityParam ¶m, napi_env env, napi_value args) +napi_value UnwrapForResultParam(CallAbilityParam ¶m, napi_env env, napi_value args) { HILOG_INFO("%{public}s,called", __func__); // unwrap the param @@ -1142,17 +923,10 @@ napi_value UnwrapParam(CallAbilityParam ¶m, napi_env env, napi_value args) // unwrap the param : want object InnerUnwrapWant(env, args, param.want); - // unwrap the param : requestCode (optional) - napi_value requestCodeProp = nullptr; - NAPI_CALL(env, napi_get_named_property(env, args, "requestCode", &requestCodeProp)); - NAPI_CALL(env, napi_typeof(env, requestCodeProp, &valueType)); - // there is requestCode in param, set forResultOption = true - if (valueType == napi_number) { - NAPI_CALL(env, napi_get_value_int32(env, requestCodeProp, ¶m.requestCode)); - param.forResultOption = true; - } else { - param.forResultOption = false; - } + // dummy requestCode for NativeC++ interface and onabilityresult callback + param.requestCode = dummyRequestCode_; + param.forResultOption = true; + dummyRequestCode_ < INT64_MAX ? dummyRequestCode_++ : dummyRequestCode_ = 0; HILOG_INFO("%{public}s, reqCode=%{public}d forResultOption=%{public}d.", __func__, param.requestCode, @@ -1169,6 +943,7 @@ napi_value UnwrapParam(CallAbilityParam ¶m, napi_env env, napi_value args) napi_value result; NAPI_CALL(env, napi_create_int32(env, 1, &result)); + HILOG_INFO("%{public}s,end", __func__); return result; } @@ -1201,2681 +976,148 @@ napi_value UnwrapAbilityResult(CallAbilityParam ¶m, napi_env env, napi_value napi_value result; NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; -} - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to AsyncCallbackInfo on success, nullptr on failure - */ -AsyncCallbackInfo *CreateAsyncCallbackInfo(napi_env env) -{ - napi_value global = 0; - NAPI_CALL(env, napi_get_global(env, &global)); - - napi_value abilityObj = 0; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); - - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - - AsyncCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo{ - .cbInfo.env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .ability = ability, - .native_result = false, - }; - return asyncCallbackInfo; -} - -napi_value GetWantAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AsyncCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, args[argcPromise], &valuetype); - if (valuetype == napi_function) { - napi_create_reference(env, args[argcPromise], 1, &asyncCallbackInfo->cbInfo.callback); - } - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { - HILOG_INFO("GetWantAsync, worker pool thread execute."); - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - if (asyncCallbackInfo != nullptr && asyncCallbackInfo->ability != nullptr) { - std::shared_ptr ptrWant = asyncCallbackInfo->ability->GetWant(); - if (ptrWant != nullptr) { - asyncCallbackInfo->param.want = *ptrWant; - } - } - }, - [](napi_env env, napi_status status, void *data) { - HILOG_INFO("GetWantAsync, main event thread complete."); - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - napi_value callback = 0; - napi_value undefined = 0; - napi_value result[ARGS_TWO] = {0}; - napi_value callResult = 0; - napi_get_undefined(env, &undefined); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - result[PARAM1] = WrapWant(env, asyncCallbackInfo->param.want); - napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); - napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); - - if (asyncCallbackInfo->cbInfo.callback != nullptr) { - napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); - } - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - }, - (void *)asyncCallbackInfo, - &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - napi_value result = 0; - napi_get_null(env, &result); - return result; -} - -napi_value GetWantPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); - napi_deferred deferred; - napi_value promise = 0; - napi_create_promise(env, &deferred, &promise); - asyncCallbackInfo->deferred = deferred; - - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { - HILOG_INFO("GetWantPromise, worker pool thread execute."); - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - - if (asyncCallbackInfo != nullptr && asyncCallbackInfo->ability != nullptr) { - std::shared_ptr ptrWant = asyncCallbackInfo->ability->GetWant(); - - if (ptrWant != nullptr) { - asyncCallbackInfo->param.want = *ptrWant; - } - } - }, - [](napi_env env, napi_status status, void *data) { - HILOG_INFO("GetWantPromise, main event thread complete."); - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - napi_value result = WrapWant(env, asyncCallbackInfo->param.want); - napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - }, - (void *)asyncCallbackInfo, - &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - - return promise; -} - -/** - * @brief GetWantWrap processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param asyncCallbackInfo Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetWantWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, asyncCallbackInfo == nullptr.", __func__); - return nullptr; - } - - size_t argcAsync = 1; - const size_t argcPromise = 0; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - if (argcAsync > argcPromise) { - ret = GetWantAsync(env, args, argcAsync, argcPromise, asyncCallbackInfo); - } else { - ret = GetWantPromise(env, asyncCallbackInfo); - } - - return ret; -} - -/** - * @brief Get want. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_GetWant(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); - if (asyncCallbackInfo == nullptr) { - return nullptr; - } - - napi_value ret = GetWantWrap(env, info, asyncCallbackInfo); - if (ret == nullptr) { - if (asyncCallbackInfo != nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - } - } - return ret; -} - -/** - * @brief Obtains information about the current application. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_GetApplicationInfo(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - AppInfoCB *appInfoCB = CreateAppInfoCBInfo(env); - if (appInfoCB == nullptr) { - return nullptr; - } - - napi_value ret = GetApplicationInfoWrap(env, info, appInfoCB); - if (ret == nullptr) { - if (appInfoCB != nullptr) { - delete appInfoCB; - appInfoCB = nullptr; - } - } - return ret; -} - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to AppInfoCB on success, nullptr on failure. - */ -AppInfoCB *CreateAppInfoCBInfo(napi_env env) -{ - napi_value global = nullptr; - NAPI_CALL(env, napi_get_global(env, &global)); - - napi_value abilityObj = nullptr; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); - - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - - AppInfoCB *appInfoCB = new (std::nothrow) AppInfoCB{ - .cbBase.cbInfo.env = env, - .cbBase.asyncWork = nullptr, - .cbBase.deferred = nullptr, - .cbBase.ability = ability, - }; - return appInfoCB; -} - -/** - * @brief GetApplicationInfo processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param appInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetApplicationInfoWrap(napi_env env, napi_callback_info info, AppInfoCB *appInfoCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (appInfoCB == nullptr) { - HILOG_ERROR("%{public}s, appInfoCB == nullptr.", __func__); - return nullptr; - } - - size_t argcAsync = 1; - const size_t argcPromise = 0; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - if (argcAsync > argcPromise) { - ret = GetApplicationInfoAsync(env, args, argcAsync, argcPromise, appInfoCB); - } else { - ret = GetApplicationInfoPromise(env, appInfoCB); - } - - return ret; -} - -/** - * @brief GetApplicationInfo Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param appInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetApplicationInfoAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AppInfoCB *appInfoCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || appInfoCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &appInfoCB->cbBase.cbInfo.callback)); - } - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetAppInfoExecuteCB, - GetAppInfoAsyncCompleteCB, - (void *)appInfoCB, - &appInfoCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, appInfoCB->cbBase.asyncWork)); - napi_value result = nullptr; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -/** - * @brief GetApplicationInfo Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param appInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetApplicationInfoPromise(napi_env env, AppInfoCB *appInfoCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (appInfoCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - appInfoCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetAppInfoExecuteCB, - GetAppInfoPromiseCompleteCB, - (void *)appInfoCB, - &appInfoCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, appInfoCB->cbBase.asyncWork)); - - return promise; -} - -/** - * @brief GetApplicationInfo asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAppInfoExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_GetApplicationInfo, worker pool thread execute."); - AppInfoCB *appInfoCB = (AppInfoCB *)data; - if (appInfoCB->cbBase.ability != nullptr) { - std::shared_ptr appInfoPtr = appInfoCB->cbBase.ability->GetApplicationInfo(); - if (appInfoPtr != nullptr) { - SaveAppInfo(appInfoCB->appInfo, *appInfoPtr); - } - } -} - -void SaveAppInfo(AppInfo_ &appInfo, const ApplicationInfo &appInfoOrg) -{ - HILOG_INFO("%{public}s.", __func__); - appInfo.name = appInfoOrg.name; - appInfo.description = appInfoOrg.description; - appInfo.descriptionId = appInfoOrg.descriptionId; - appInfo.systemApp = appInfoOrg.isSystemApp; - appInfo.enabled = appInfoOrg.enabled; - appInfo.label = appInfoOrg.label; - appInfo.labelId = std::to_string(appInfoOrg.labelId); - appInfo.icon = appInfoOrg.iconPath; - appInfo.iconId = std::to_string(appInfoOrg.iconId); - appInfo.process = appInfoOrg.process; - appInfo.supportedModes = appInfoOrg.supportedModes; - for (size_t i = 0; i < appInfoOrg.moduleInfos.size(); i++) { - appInfo.moduleSourceDirs.emplace_back(appInfoOrg.moduleInfos.at(i).moduleSourceDir); - } - for (size_t i = 0; i < appInfoOrg.permissions.size(); i++) { - appInfo.permissions.emplace_back(appInfoOrg.permissions.at(i)); - } - for (size_t i = 0; i < appInfoOrg.moduleInfos.size(); i++) { - appInfo.moduleInfos.emplace_back(appInfoOrg.moduleInfos.at(i)); - } - appInfo.flags = appInfoOrg.flags; - appInfo.entryDir = appInfoOrg.entryDir; -} - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAppInfoAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); - AppInfoCB *appInfoCB = (AppInfoCB *)data; - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - result[PARAM1] = WrapAppInfo(env, appInfoCB->appInfo); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, appInfoCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (appInfoCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, appInfoCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, appInfoCB->cbBase.asyncWork)); - delete appInfoCB; - appInfoCB = nullptr; -} - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAppInfoPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); - AppInfoCB *appInfoCB = (AppInfoCB *)data; - napi_value result = WrapAppInfo(env, appInfoCB->appInfo); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, appInfoCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, appInfoCB->cbBase.asyncWork)); - delete appInfoCB; - appInfoCB = nullptr; -} - -napi_value WrapAppInfo(napi_env env, const AppInfo_ &appInfo) -{ - napi_value result = nullptr; - napi_value proValue = nullptr; - NAPI_CALL(env, napi_create_object(env, &result)); - NAPI_CALL(env, napi_create_string_utf8(env, appInfo.name.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "name", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, appInfo.description.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "description", proValue)); - - NAPI_CALL(env, napi_create_int32(env, appInfo.descriptionId, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "descriptionId", proValue)); - - NAPI_CALL(env, napi_get_boolean(env, appInfo.systemApp, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "systemApp", proValue)); - NAPI_CALL(env, napi_get_boolean(env, appInfo.enabled, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "enabled", proValue)); - NAPI_CALL(env, napi_create_string_utf8(env, appInfo.label.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "label", proValue)); - NAPI_CALL(env, napi_create_string_utf8(env, appInfo.labelId.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "labelId", proValue)); - NAPI_CALL(env, napi_create_string_utf8(env, appInfo.icon.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "icon", proValue)); - NAPI_CALL(env, napi_create_string_utf8(env, appInfo.iconId.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "iconId", proValue)); - NAPI_CALL(env, napi_create_string_utf8(env, appInfo.process.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "process", proValue)); - NAPI_CALL(env, napi_create_int32(env, appInfo.supportedModes, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "supportedModes", proValue)); - napi_value jsArrayModDirs = nullptr; - NAPI_CALL(env, napi_create_array(env, &jsArrayModDirs)); - for (size_t i = 0; i < appInfo.moduleSourceDirs.size(); i++) { - proValue = nullptr; - NAPI_CALL( - env, napi_create_string_utf8(env, appInfo.moduleSourceDirs.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_element(env, jsArrayModDirs, i, proValue)); - } - NAPI_CALL(env, napi_set_named_property(env, result, "moduleSourceDirs", jsArrayModDirs)); - napi_value jsArrayPermissions = nullptr; - NAPI_CALL(env, napi_create_array(env, &jsArrayPermissions)); - for (size_t i = 0; i < appInfo.permissions.size(); i++) { - proValue = nullptr; - NAPI_CALL(env, napi_create_string_utf8(env, appInfo.permissions.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_element(env, jsArrayPermissions, i, proValue)); - } - NAPI_CALL(env, napi_set_named_property(env, result, "permissions", jsArrayPermissions)); - napi_value jsArrayModuleInfo = nullptr; - NAPI_CALL(env, napi_create_array(env, &jsArrayModuleInfo)); - for (size_t i = 0; i < appInfo.moduleInfos.size(); i++) { - napi_value jsModuleInfoObject = nullptr; - NAPI_CALL(env, napi_create_object(env, &jsModuleInfoObject)); - proValue = nullptr; - NAPI_CALL(env, - napi_create_string_utf8(env, appInfo.moduleInfos.at(i).moduleName.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, jsModuleInfoObject, "moduleName", proValue)); - proValue = nullptr; - NAPI_CALL(env, - napi_create_string_utf8( - env, appInfo.moduleInfos.at(i).moduleSourceDir.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, jsModuleInfoObject, "moduleSourceDir", proValue)); - NAPI_CALL(env, napi_set_element(env, jsArrayModuleInfo, i, jsModuleInfoObject)); - } - NAPI_CALL(env, napi_set_named_property(env, result, "moduleInfos", jsArrayModuleInfo)); - NAPI_CALL(env, napi_create_int32(env, appInfo.flags, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "flags", proValue)); - NAPI_CALL(env, napi_create_string_utf8(env, appInfo.entryDir.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "entryDir", proValue)); - return result; -} - -/** - * @brief Obtains the type of this application. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_GetAppType(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - AppTypeCB *appTypeCB = CreateAppTypeCBInfo(env); - if (appTypeCB == nullptr) { - return nullptr; - } - - napi_value ret = GetAppTypeWrap(env, info, appTypeCB); - if (ret == nullptr) { - if (appTypeCB != nullptr) { - delete appTypeCB; - appTypeCB = nullptr; - } - } - return ret; -} - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to AppTypeCB on success, nullptr on failure. - */ -AppTypeCB *CreateAppTypeCBInfo(napi_env env) -{ - napi_value global = nullptr; - NAPI_CALL(env, napi_get_global(env, &global)); - - napi_value abilityObj = nullptr; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); - - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - - AppTypeCB *appTypeCB = new (std::nothrow) AppTypeCB{ - .cbBase.cbInfo.env = env, - .cbBase.asyncWork = nullptr, - .cbBase.deferred = nullptr, - .cbBase.ability = ability, - }; - return appTypeCB; -} - -/** - * @brief GetAppType processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param appTypeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAppTypeWrap(napi_env env, napi_callback_info info, AppTypeCB *appTypeCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (appTypeCB == nullptr) { - HILOG_ERROR("%{public}s, appTypeCB == nullptr.", __func__); - return nullptr; - } - - size_t argcAsync = 1; - const size_t argcPromise = 0; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - if (argcAsync > argcPromise) { - ret = GetAppTypeAsync(env, args, argcAsync, argcPromise, appTypeCB); - } else { - ret = GetAppTypePromise(env, appTypeCB); - } - - return ret; -} - -/** - * @brief GetAppType Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param appTypeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAppTypeAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AppTypeCB *appTypeCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || appTypeCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &appTypeCB->cbBase.cbInfo.callback)); - } - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetAppTypeExecuteCB, - GetAppTypeAsyncCompleteCB, - (void *)appTypeCB, - &appTypeCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, appTypeCB->cbBase.asyncWork)); - napi_value result = nullptr; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -/** - * @brief GetAppType Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param appTypeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAppTypePromise(napi_env env, AppTypeCB *appTypeCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (appTypeCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - appTypeCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetAppTypeExecuteCB, - GetAppTypePromiseCompleteCB, - (void *)appTypeCB, - &appTypeCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, appTypeCB->cbBase.asyncWork)); - - return promise; -} - -/** - * @brief GetAppType asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAppTypeExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_GetApplicationInfo, worker pool thread execute."); - AppTypeCB *appTypeCB = (AppTypeCB *)data; - if (appTypeCB->cbBase.ability != nullptr) { - appTypeCB->name = appTypeCB->cbBase.ability->GetAppType(); - } -} - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAppTypeAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); - AppTypeCB *appTypeCB = (AppTypeCB *)data; - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - - NAPI_CALL_RETURN_VOID(env, - napi_create_string_utf8( - env, appTypeCB->cbBase.ability->GetAppType().c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); - - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, appTypeCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (appTypeCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, appTypeCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, appTypeCB->cbBase.asyncWork)); - delete appTypeCB; - appTypeCB = nullptr; -} - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAppTypePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("GetAppTypePromiseCompleteCB, main event thread complete."); - AppTypeCB *appTypeCB = (AppTypeCB *)data; - napi_value result = nullptr; - NAPI_CALL_RETURN_VOID( - env, napi_create_string_utf8(env, appTypeCB->cbBase.ability->GetAppType().c_str(), NAPI_AUTO_LENGTH, &result)); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, appTypeCB->cbBase.deferred, result)); - - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, appTypeCB->cbBase.asyncWork)); - delete appTypeCB; - appTypeCB = nullptr; -} - -/** - * @brief Obtains the elementName object of the current ability. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_GetElementName(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - ElementNameCB *elementNameCB = CreateElementNameCBInfo(env); - if (elementNameCB == nullptr) { - return nullptr; - } - - napi_value ret = GetElementNameWrap(env, info, elementNameCB); - if (ret == nullptr) { - if (elementNameCB != nullptr) { - delete elementNameCB; - elementNameCB = nullptr; - } - } - return ret; -} - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to ElementNameCB on success, nullptr on failure. - */ -ElementNameCB *CreateElementNameCBInfo(napi_env env) -{ - napi_value global = nullptr; - NAPI_CALL(env, napi_get_global(env, &global)); - - napi_value abilityObj = nullptr; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); - - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - - ElementNameCB *elementNameCB = new (std::nothrow) ElementNameCB{ - .cbBase.cbInfo.env = env, - .cbBase.asyncWork = nullptr, - .cbBase.deferred = nullptr, - .cbBase.ability = ability, - }; - return elementNameCB; -} - -/** - * @brief GetElementName processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param elementNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetElementNameWrap(napi_env env, napi_callback_info info, ElementNameCB *elementNameCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (elementNameCB == nullptr) { - HILOG_ERROR("%{public}s, appInfoCB == nullptr.", __func__); - return nullptr; - } - - size_t argcAsync = 1; - const size_t argcPromise = 0; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - if (argcAsync > argcPromise) { - ret = GetElementNameAsync(env, args, argcAsync, argcPromise, elementNameCB); - } else { - ret = GetElementNamePromise(env, elementNameCB); - } - - return ret; -} - -/** - * @brief GetElementName Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param elementNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetElementNameAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, ElementNameCB *elementNameCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || elementNameCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &elementNameCB->cbBase.cbInfo.callback)); - } - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetElementNameExecuteCB, - GetElementNameAsyncCompleteCB, - (void *)elementNameCB, - &elementNameCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, elementNameCB->cbBase.asyncWork)); - napi_value result = nullptr; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -/** - * @brief GetElementName Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param elementNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetElementNamePromise(napi_env env, ElementNameCB *elementNameCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (elementNameCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - elementNameCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetElementNameExecuteCB, - GetElementNamePromiseCompleteCB, - (void *)elementNameCB, - &elementNameCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, elementNameCB->cbBase.asyncWork)); - - return promise; -} - -/** - * @brief GetElementName asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetElementNameExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_GetApplicationInfo, worker pool thread execute."); - ElementNameCB *elementNameCB = (ElementNameCB *)data; - if (elementNameCB->cbBase.ability != nullptr) { - std::shared_ptr elementName = elementNameCB->cbBase.ability->GetElementName(); - if (elementNameCB != nullptr) { - elementNameCB->deviceId = elementName->GetDeviceID(); - elementNameCB->bundleName = elementName->GetBundleName(); - elementNameCB->abilityName = elementName->GetAbilityName(); - elementNameCB->uri = elementNameCB->cbBase.ability->GetWant()->GetUriString(); - elementNameCB->shortName = ""; - } - } -} - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetElementNameAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); - ElementNameCB *elementNameCB = (ElementNameCB *)data; - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - result[PARAM1] = WrapElementName(env, elementNameCB); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, elementNameCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (elementNameCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, elementNameCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, elementNameCB->cbBase.asyncWork)); - delete elementNameCB; - elementNameCB = nullptr; -} - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetElementNamePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); - ElementNameCB *elementNameCB = (ElementNameCB *)data; - napi_value result = WrapElementName(env, elementNameCB); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, elementNameCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, elementNameCB->cbBase.asyncWork)); - delete elementNameCB; - elementNameCB = nullptr; -} - -napi_value WrapElementName(napi_env env, ElementNameCB *elementNameCB) -{ - if (elementNameCB == nullptr) { - HILOG_ERROR("Invalid param(appInfoCB = nullptr)"); - return nullptr; - } - napi_value result = nullptr; - napi_value proValue = nullptr; - NAPI_CALL(env, napi_create_object(env, &result)); - NAPI_CALL(env, napi_create_string_utf8(env, elementNameCB->abilityName.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "abilityName", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, elementNameCB->bundleName.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "bundleName", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, elementNameCB->deviceId.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "deviceId", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, elementNameCB->shortName.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "shortName", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, elementNameCB->uri.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "uri", proValue)); - - return result; -} - -/** - * @brief Obtains the class name in this ability name, without the prefixed bundle name. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_GetAbilityName(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - AbilityNameCB *ablityNameCB = CreateAbilityNameCBInfo(env); - if (ablityNameCB == nullptr) { - return nullptr; - } - - napi_value ret = GetAbilityNameWrap(env, info, ablityNameCB); - if (ret == nullptr) { - if (ablityNameCB != nullptr) { - delete ablityNameCB; - ablityNameCB = nullptr; - } - } - return ret; -} - -/** - * @brief Obtains the process Info this application. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_GetProcessInfo(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - ProcessInfoCB *processInfoCB = CreateProcessInfoCBInfo(env); - if (processInfoCB == nullptr) { - return nullptr; - } - - napi_value ret = GetProcessInfoWrap(env, info, processInfoCB); - if (ret == nullptr) { - if (processInfoCB != nullptr) { - delete processInfoCB; - processInfoCB = nullptr; - } - } - return ret; -} - -/** - * @brief Obtains the name of the current process. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_GetProcessName(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - - ProcessNameCB *processNameCB = CreateProcessNameCBInfo(env); - if (processNameCB == nullptr) { - return nullptr; - } - - napi_value ret = GetProcessNameWrap(env, info, processNameCB); - if (ret == nullptr) { - if (processNameCB != nullptr) { - delete processNameCB; - processNameCB = nullptr; - } - } - return ret; -} - -/** - * @brief Obtains the bundle name of the ability that called the current ability. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_GetCallingBundle(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - CallingBundleCB *calloingBundleCB = CreateCallingBundleCBInfo(env); - if (calloingBundleCB == nullptr) { - return nullptr; - } - - napi_value ret = GetCallingBundleWrap(env, info, calloingBundleCB); - if (ret == nullptr) { - if (calloingBundleCB != nullptr) { - delete calloingBundleCB; - calloingBundleCB = nullptr; - } - } - return ret; -} - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to AbilityNameCB on success, nullptr on failure. - */ -AbilityNameCB *CreateAbilityNameCBInfo(napi_env env) -{ - napi_value global = nullptr; - NAPI_CALL(env, napi_get_global(env, &global)); - - napi_value abilityObj = nullptr; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); - - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - - AbilityNameCB *abilityNameCB = new (std::nothrow) AbilityNameCB{ - .cbBase.cbInfo.env = env, - .cbBase.asyncWork = nullptr, - .cbBase.deferred = nullptr, - .cbBase.ability = ability, - }; - HILOG_INFO("%{public}s, asyncCallback.", __func__); - return abilityNameCB; -} - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to ProcessInfoCB on success, nullptr on failure. - */ -ProcessInfoCB *CreateProcessInfoCBInfo(napi_env env) -{ - napi_value global = nullptr; - NAPI_CALL(env, napi_get_global(env, &global)); - - napi_value abilityObj = nullptr; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); - - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - - ProcessInfoCB *processInfoCB = new (std::nothrow) ProcessInfoCB{ - .cbBase.cbInfo.env = env, - .cbBase.asyncWork = nullptr, - .cbBase.deferred = nullptr, - .cbBase.ability = ability, - }; - return processInfoCB; -} - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to ProcessNameCB on success, nullptr on failure. - */ -ProcessNameCB *CreateProcessNameCBInfo(napi_env env) -{ - napi_value global = nullptr; - NAPI_CALL(env, napi_get_global(env, &global)); - - napi_value abilityObj = nullptr; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); - - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - - ProcessNameCB *processNameCB = new (std::nothrow) ProcessNameCB{ - .cbBase.cbInfo.env = env, - .cbBase.asyncWork = nullptr, - .cbBase.deferred = nullptr, - .cbBase.ability = ability, - }; - return processNameCB; -} - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to CallingBundleCB on success, nullptr on failure. - */ -CallingBundleCB *CreateCallingBundleCBInfo(napi_env env) -{ - napi_value global = nullptr; - NAPI_CALL(env, napi_get_global(env, &global)); - - napi_value abilityObj = nullptr; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); - - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - - CallingBundleCB *callingBundleCB = new (std::nothrow) CallingBundleCB{ - .cbBase.cbInfo.env = env, - .cbBase.asyncWork = nullptr, - .cbBase.deferred = nullptr, - .cbBase.ability = ability, - }; - return callingBundleCB; -} - -/** - * @brief GetAbilityName processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param abilityNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAbilityNameWrap(napi_env env, napi_callback_info info, AbilityNameCB *abilityNameCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (abilityNameCB == nullptr) { - HILOG_ERROR("%{public}s, abilityNameCB == nullptr.", __func__); - return nullptr; - } - - size_t argcAsync = 1; - const size_t argcPromise = 0; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - if (argcAsync > argcPromise) { - ret = GetAbilityNameAsync(env, args, argcAsync, argcPromise, abilityNameCB); - } else { - ret = GetAbilityNamePromise(env, abilityNameCB); - } - - return ret; -} - -/** - * @brief GetProcessInfo processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param ProcessInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetProcessInfoWrap(napi_env env, napi_callback_info info, ProcessInfoCB *processInfoCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (processInfoCB == nullptr) { - HILOG_ERROR("%{public}s, processInfoCB == nullptr.", __func__); - return nullptr; - } - - size_t argcAsync = 1; - const size_t argcPromise = 0; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - if (argcAsync > argcPromise) { - ret = GetProcessInfoAsync(env, args, argcAsync, argcPromise, processInfoCB); - } else { - ret = GetProcessInfoPromise(env, processInfoCB); - } - - return ret; -} - -/** - * @brief GetProcessName processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param ProcessNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetProcessNameWrap(napi_env env, napi_callback_info info, ProcessNameCB *processNameCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (processNameCB == nullptr) { - HILOG_ERROR("%{public}s, processNameCB == nullptr.", __func__); - return nullptr; - } - - size_t argcAsync = 1; - const size_t argcPromise = 0; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - if (argcAsync > argcPromise) { - ret = GetProcessNameAsync(env, args, argcAsync, argcPromise, processNameCB); - } else { - ret = GetProcessNamePromise(env, processNameCB); - } - - return ret; -} - -/** - * @brief GetCallingBundle processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param CallingBundleCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetCallingBundleWrap(napi_env env, napi_callback_info info, CallingBundleCB *callingBundleCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (callingBundleCB == nullptr) { - HILOG_ERROR("%{public}s, callingBundleCB == nullptr.", __func__); - return nullptr; - } - - size_t argcAsync = 1; - const size_t argcPromise = 0; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - if (argcAsync > argcPromise) { - ret = GetCallingBundleAsync(env, args, argcAsync, argcPromise, callingBundleCB); - } else { - ret = GetCallingBundlePromise(env, callingBundleCB); - } - - return ret; -} - -/** - * @brief GetAbilityName Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param abilityNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAbilityNameAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AbilityNameCB *abilityNameCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || abilityNameCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &abilityNameCB->cbBase.cbInfo.callback)); - } - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetAbilityNameExecuteCB, - GetAbilityNameAsyncCompleteCB, - (void *)abilityNameCB, - &abilityNameCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, abilityNameCB->cbBase.asyncWork)); - napi_value result = nullptr; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -/** - * @brief GetProcessInfo Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param ProcessInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetProcessInfoAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, ProcessInfoCB *processInfoCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || processInfoCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &processInfoCB->cbBase.cbInfo.callback)); - } - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetProcessInfoExecuteCB, - GetProcessInfoAsyncCompleteCB, - (void *)processInfoCB, - &processInfoCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, processInfoCB->cbBase.asyncWork)); - napi_value result = nullptr; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -/** - * @brief GetProcessName Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param ProcessNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetProcessNameAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, ProcessNameCB *processNameCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || processNameCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &processNameCB->cbBase.cbInfo.callback)); - } - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetProcessNameExecuteCB, - GetProcessNameAsyncCompleteCB, - (void *)processNameCB, - &processNameCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, processNameCB->cbBase.asyncWork)); - napi_value result = nullptr; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -/** - * @brief GetCallingBundle Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param CallingBundleCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetCallingBundleAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, CallingBundleCB *callingBundleCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || callingBundleCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &callingBundleCB->cbBase.cbInfo.callback)); - } - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetCallingBundleExecuteCB, - GetCallingBundleAsyncCompleteCB, - (void *)callingBundleCB, - &callingBundleCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, callingBundleCB->cbBase.asyncWork)); - napi_value result = nullptr; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -/** - * @brief GetAbilityName Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param abilityNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAbilityNamePromise(napi_env env, AbilityNameCB *abilityNameCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (abilityNameCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - abilityNameCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetAbilityNameExecuteCB, - GetAbilityNamePromiseCompleteCB, - (void *)abilityNameCB, - &abilityNameCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, abilityNameCB->cbBase.asyncWork)); - - return promise; -} - -/** - * @brief GetProcessInfo Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param ProcessInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetProcessInfoPromise(napi_env env, ProcessInfoCB *processInfoCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (processInfoCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - processInfoCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetProcessInfoExecuteCB, - GetProcessInfoPromiseCompleteCB, - (void *)processInfoCB, - &processInfoCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, processInfoCB->cbBase.asyncWork)); - - return promise; -} - -/** - * @brief GetProcessName Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param ProcessNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetProcessNamePromise(napi_env env, ProcessNameCB *processNameCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (processNameCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - processNameCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetProcessNameExecuteCB, - GetProcessNamePromiseCompleteCB, - (void *)processNameCB, - &processNameCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, processNameCB->cbBase.asyncWork)); - - return promise; -} - -/** - * @brief GetCallingBundle Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param CallingBundleCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetCallingBundlePromise(napi_env env, CallingBundleCB *callingBundleCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (callingBundleCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - callingBundleCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetCallingBundleExecuteCB, - GetCallingBundlePromiseCompleteCB, - (void *)callingBundleCB, - &callingBundleCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, callingBundleCB->cbBase.asyncWork)); - - return promise; -} - -/** - * @brief GetAbilityName asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAbilityNameExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_GetAbilityName, worker pool thread execute."); - AbilityNameCB *abilityNameCB = (AbilityNameCB *)data; - if (abilityNameCB->cbBase.ability != nullptr) { - abilityNameCB->name = abilityNameCB->cbBase.ability->GetAbilityName(); - } -} - -/** - * @brief GetProcessInfo asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetProcessInfoExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_GetProcessInfo, worker pool thread execute."); - ProcessInfoCB *processInfoCB = (ProcessInfoCB *)data; - if (processInfoCB->cbBase.ability != nullptr) { - std::shared_ptr processInfoPtr = processInfoCB->cbBase.ability->GetProcessInfo(); - if (processInfoPtr != nullptr) { - processInfoCB->processName = processInfoPtr->GetProcessName(); - processInfoCB->pid = processInfoPtr->GetPid(); - } - } -} - -/** - * @brief GetProcessName asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetProcessNameExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_GetProcessName, worker pool thread execute."); - ProcessNameCB *processNameCB = (ProcessNameCB *)data; - if (processNameCB->cbBase.ability != nullptr) { - processNameCB->processName = processNameCB->cbBase.ability->GetProcessName(); - } -} - -/** - * @brief GetCallingBundle asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetCallingBundleExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_GetCallingBundle, worker pool thread execute."); - CallingBundleCB *callingBundleCB = (CallingBundleCB *)data; - if (callingBundleCB->cbBase.ability != nullptr) { - callingBundleCB->callingBundleName = callingBundleCB->cbBase.ability->GetCallingBundle(); - } -} - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAbilityNameAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetAbilityName, main event thread complete."); - AbilityNameCB *abilityNameCB = (AbilityNameCB *)data; - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - result[PARAM1] = WrapAbilityName(env, abilityNameCB); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, abilityNameCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - if (abilityNameCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, abilityNameCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, abilityNameCB->cbBase.asyncWork)); - delete abilityNameCB; - abilityNameCB = nullptr; -} - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetProcessInfoAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetProcessInfo, main event thread complete."); - ProcessInfoCB *processInfoCB = (ProcessInfoCB *)data; - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - result[PARAM1] = WrapProcessInfo(env, processInfoCB); - - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, processInfoCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (processInfoCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, processInfoCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, processInfoCB->cbBase.asyncWork)); - delete processInfoCB; - processInfoCB = nullptr; -} - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetProcessNameAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetProcessName, main event thread complete."); - ProcessNameCB *processNameCB = (ProcessNameCB *)data; - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - result[PARAM1] = WrapProcessName(env, processNameCB); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, processNameCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (processNameCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, processNameCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, processNameCB->cbBase.asyncWork)); - delete processNameCB; - processNameCB = nullptr; -} - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetCallingBundleAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetCallingBundle, main event thread complete."); - CallingBundleCB *callingBundleCB = (CallingBundleCB *)data; - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - result[PARAM1] = WrapCallingBundle(env, callingBundleCB); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, callingBundleCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (callingBundleCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, callingBundleCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, callingBundleCB->cbBase.asyncWork)); - delete callingBundleCB; - callingBundleCB = nullptr; -} - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAbilityNamePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetAbilityName, main event thread complete."); - AbilityNameCB *abilityNameCB = (AbilityNameCB *)data; - napi_value result = WrapAbilityName(env, abilityNameCB); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, abilityNameCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, abilityNameCB->cbBase.asyncWork)); - delete abilityNameCB; - abilityNameCB = nullptr; -} - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetProcessInfoPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetProcessInfo, main event thread complete."); - ProcessInfoCB *processInfoCB = (ProcessInfoCB *)data; - napi_value result = WrapProcessInfo(env, processInfoCB); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, processInfoCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, processInfoCB->cbBase.asyncWork)); - delete processInfoCB; - processInfoCB = nullptr; -} - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetProcessNamePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetProcessName, main event thread complete."); - ProcessNameCB *processNameCB = (ProcessNameCB *)data; - napi_value result = WrapProcessName(env, processNameCB); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, processNameCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, processNameCB->cbBase.asyncWork)); - delete processNameCB; - processNameCB = nullptr; -} - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetCallingBundlePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetCallingBundle, main event thread complete."); - CallingBundleCB *callingBundleCB = (CallingBundleCB *)data; - napi_value result = WrapCallingBundle(env, callingBundleCB); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, callingBundleCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, callingBundleCB->cbBase.asyncWork)); - delete callingBundleCB; - callingBundleCB = nullptr; -} - -napi_value WrapAbilityName(napi_env env, AbilityNameCB *abilityNameCB) -{ - if (abilityNameCB == nullptr) { - HILOG_ERROR("Invalid param(abilityNameCB == nullptr)"); - return nullptr; - } - napi_value result = nullptr; - NAPI_CALL(env, napi_create_string_utf8(env, abilityNameCB->name.c_str(), NAPI_AUTO_LENGTH, &result)); - - return result; -} - -napi_value WrapProcessInfo(napi_env env, ProcessInfoCB *processInfoCB) -{ - if (processInfoCB == nullptr) { - HILOG_ERROR("Invalid param(processInfoCB == nullptr)"); - return nullptr; - } - napi_value result = nullptr; - napi_value proValue = nullptr; - NAPI_CALL(env, napi_create_object(env, &result)); - NAPI_CALL(env, napi_create_int32(env, processInfoCB->pid, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "pid", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, processInfoCB->processName.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "processName", proValue)); - - return result; -} - -napi_value WrapProcessName(napi_env env, ProcessNameCB *processNameCB) -{ - if (processNameCB == nullptr) { - HILOG_ERROR("Invalid param(processNameCB == nullptr)"); - return nullptr; - } - napi_value result = nullptr; - NAPI_CALL(env, napi_create_string_utf8(env, processNameCB->processName.c_str(), NAPI_AUTO_LENGTH, &result)); - - return result; -} - -napi_value WrapCallingBundle(napi_env env, CallingBundleCB *callingBundleCB) -{ - if (callingBundleCB == nullptr) { - HILOG_ERROR("Invalid param(callingBundleCB == nullptr)"); - return nullptr; - } - napi_value result = nullptr; - NAPI_CALL(env, napi_create_string_utf8(env, callingBundleCB->callingBundleName.c_str(), NAPI_AUTO_LENGTH, &result)); - - return result; -} - -/** - * @brief Obtains information about the current ability. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_GetAbilityInfo(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - AbilityInfoCB *abilityInfoCB = CreateAbilityInfoCBInfo(env); - if (abilityInfoCB == nullptr) { - return nullptr; - } - - napi_value ret = GetAbilityInfoWrap(env, info, abilityInfoCB); - if (ret == nullptr) { - if (abilityInfoCB != nullptr) { - delete abilityInfoCB; - abilityInfoCB = nullptr; - } - } - return ret; -} - -/** - * @brief GetAbilityInfo processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param abilityInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAbilityInfoWrap(napi_env env, napi_callback_info info, AbilityInfoCB *abilityInfoCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (abilityInfoCB == nullptr) { - HILOG_ERROR("%{public}s, abilityInfoCB == nullptr.", __func__); - return nullptr; - } - - size_t argcAsync = 1; - const size_t argcPromise = 0; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - if (argcAsync > argcPromise) { - ret = GetAbilityInfoAsync(env, args, argcAsync, argcPromise, abilityInfoCB); - } else { - ret = GetAbilityInfoPromise(env, abilityInfoCB); - } - - return ret; -} - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to AbilityInfoCB on success, nullptr on failure. - */ -AbilityInfoCB *CreateAbilityInfoCBInfo(napi_env env) -{ - napi_value global = nullptr; - NAPI_CALL(env, napi_get_global(env, &global)); - - napi_value abilityObj = nullptr; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); - - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - - AbilityInfoCB *abilityInfoCB = new (std::nothrow) AbilityInfoCB{ - .cbBase.cbInfo.env = env, - .cbBase.asyncWork = nullptr, - .cbBase.deferred = nullptr, - .cbBase.ability = ability, - }; - return abilityInfoCB; -} - -/** - * @brief GetAbilityInfo Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param abilityInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAbilityInfoAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AbilityInfoCB *abilityInfoCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || abilityInfoCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &abilityInfoCB->cbBase.cbInfo.callback)); - } - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetAbilityInfoExecuteCB, - GetAbilityInfoAsyncCompleteCB, - (void *)abilityInfoCB, - &abilityInfoCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, abilityInfoCB->cbBase.asyncWork)); - napi_value result = nullptr; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -/** - * @brief GetAbilityInfo Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param abilityInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAbilityInfoPromise(napi_env env, AbilityInfoCB *abilityInfoCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (abilityInfoCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - abilityInfoCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetAbilityInfoExecuteCB, - GetAbilityInfoPromiseCompleteCB, - (void *)abilityInfoCB, - &abilityInfoCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, abilityInfoCB->cbBase.asyncWork)); - - return promise; -} - -/** - * @brief GetAbilityInfo asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAbilityInfoExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_GetApplicationInfo, worker pool thread execute."); - AbilityInfoCB *abilityInfoCB = (AbilityInfoCB *)data; - if (abilityInfoCB->cbBase.ability != nullptr) { - std::shared_ptr abilityInfoPtr = abilityInfoCB->cbBase.ability->GetAbilityInfo(); - if (abilityInfoPtr != nullptr) { - SaveAbilityInfo(abilityInfoCB->abilityInfo, *abilityInfoPtr); - } - } -} - -void SaveAbilityInfo(AbilityInfo_ &abilityInfo, const AbilityInfo &abilityInfoOrg) -{ - abilityInfo.bundleName = abilityInfoOrg.bundleName; - abilityInfo.name = abilityInfoOrg.name; - abilityInfo.label = abilityInfoOrg.label; - abilityInfo.description = abilityInfoOrg.description; - abilityInfo.icon = abilityInfoOrg.iconPath; - abilityInfo.labelId = abilityInfoOrg.applicationInfo.labelId; - abilityInfo.descriptionId = abilityInfoOrg.applicationInfo.descriptionId; - abilityInfo.iconId = abilityInfoOrg.applicationInfo.iconId; - abilityInfo.moduleName = abilityInfoOrg.moduleName; - abilityInfo.process = abilityInfoOrg.process; - abilityInfo.isVisible = abilityInfoOrg.visible; - - abilityInfo.type = static_cast(abilityInfoOrg.type); - abilityInfo.orientation = static_cast(abilityInfoOrg.orientation); - abilityInfo.launchMode = static_cast(abilityInfoOrg.launchMode); - - abilityInfo.uri = abilityInfoOrg.uri; - abilityInfo.targetAbility = abilityInfoOrg.targetAbility; - - for (size_t i = 0; i < abilityInfoOrg.permissions.size(); i++) { - abilityInfo.permissions.emplace_back(abilityInfoOrg.permissions.at(i)); - } - for (size_t i = 0; i < abilityInfoOrg.deviceTypes.size(); i++) { - abilityInfo.deviceTypes.emplace_back(abilityInfoOrg.deviceTypes.at(i)); - } - for (size_t i = 0; i < abilityInfoOrg.deviceCapabilities.size(); i++) { - abilityInfo.deviceCapabilities.emplace_back(abilityInfoOrg.deviceCapabilities.at(i)); - } - - SaveAppInfo(abilityInfo.appInfo, abilityInfoOrg.applicationInfo); - - abilityInfo.readPermission = abilityInfoOrg.readPermission; - abilityInfo.writePermission = abilityInfoOrg.writePermission; - abilityInfo.formEntity = 0; // no data - abilityInfo.minFormHeight = 0; // no data - abilityInfo.defaultFormHeight = 0; // no data - abilityInfo.minFormWidth = 0; // no data - abilityInfo.defaultFormWidth = 0; // no data - abilityInfo.backgroundModes = 0; // no data - abilityInfo.subType = 0; // no data - abilityInfo.formEnabled = false; // no data -} - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAbilityInfoAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); - AbilityInfoCB *abilityInfoCB = (AbilityInfoCB *)data; - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - result[PARAM1] = WrapAbilityInfo(env, abilityInfoCB->abilityInfo); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, abilityInfoCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (abilityInfoCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, abilityInfoCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, abilityInfoCB->cbBase.asyncWork)); - delete abilityInfoCB; - abilityInfoCB = nullptr; -} - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAbilityInfoPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); - AbilityInfoCB *abilityInfoCB = (AbilityInfoCB *)data; - napi_value result = WrapAbilityInfo(env, abilityInfoCB->abilityInfo); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, abilityInfoCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, abilityInfoCB->cbBase.asyncWork)); - delete abilityInfoCB; - abilityInfoCB = nullptr; -} - -napi_value WrapAbilityInfo(napi_env env, const AbilityInfo_ &abilityInfo) -{ - napi_value result = nullptr; - napi_value proValue = nullptr; - NAPI_CALL(env, napi_create_object(env, &result)); - NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.bundleName.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "bundleName", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.name.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "name", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.label.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "label", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.description.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "description", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.icon.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "icon", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.moduleName.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "moduleName", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.process.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "process", proValue)); - - NAPI_CALL(env, napi_create_int32(env, static_cast(abilityInfo.type), &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "type", proValue)); - - NAPI_CALL(env, napi_create_int32(env, static_cast(abilityInfo.orientation), &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "orientation", proValue)); - - NAPI_CALL(env, napi_create_int32(env, static_cast(abilityInfo.launchMode), &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "launchMode", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.uri.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "uri", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.readPermission.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "readPermission", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.writePermission.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "writePermission", proValue)); - - NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.targetAbility.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "targetAbility", proValue)); - - NAPI_CALL(env, napi_create_int32(env, abilityInfo.labelId, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "labelId", proValue)); - - NAPI_CALL(env, napi_create_int32(env, abilityInfo.descriptionId, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "descriptionId", proValue)); - - NAPI_CALL(env, napi_create_int32(env, abilityInfo.iconId, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "iconId", proValue)); - - NAPI_CALL(env, napi_create_int32(env, abilityInfo.formEntity, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "formEntity", proValue)); - - NAPI_CALL(env, napi_create_int32(env, abilityInfo.minFormHeight, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "minFormHeight", proValue)); - - NAPI_CALL(env, napi_create_int32(env, abilityInfo.defaultFormHeight, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "defaultFormHeight", proValue)); - - NAPI_CALL(env, napi_create_int32(env, abilityInfo.minFormWidth, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "minFormWidth", proValue)); - - NAPI_CALL(env, napi_create_int32(env, abilityInfo.defaultFormWidth, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "defaultFormWidth", proValue)); - - NAPI_CALL(env, napi_create_int32(env, abilityInfo.backgroundModes, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "backgroundModes", proValue)); - - NAPI_CALL(env, napi_create_int32(env, abilityInfo.subType, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "subType", proValue)); - - NAPI_CALL(env, napi_get_boolean(env, abilityInfo.isVisible, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "isVisible", proValue)); - - NAPI_CALL(env, napi_get_boolean(env, abilityInfo.formEnabled, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "formEnabled", proValue)); - - napi_value jsArrayPermissions = nullptr; - NAPI_CALL(env, napi_create_array(env, &jsArrayPermissions)); - for (size_t i = 0; i < abilityInfo.permissions.size(); i++) { - proValue = nullptr; - NAPI_CALL( - env, napi_create_string_utf8(env, abilityInfo.permissions.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_element(env, jsArrayPermissions, i, proValue)); - } - NAPI_CALL(env, napi_set_named_property(env, result, "permissions", jsArrayPermissions)); - - napi_value jsArrayDeviceCapabilities = nullptr; - NAPI_CALL(env, napi_create_array(env, &jsArrayDeviceCapabilities)); - for (size_t i = 0; i < abilityInfo.deviceCapabilities.size(); i++) { - proValue = nullptr; - NAPI_CALL(env, - napi_create_string_utf8(env, abilityInfo.deviceCapabilities.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_element(env, jsArrayDeviceCapabilities, i, proValue)); - } - NAPI_CALL(env, napi_set_named_property(env, result, "deviceCapabilities", jsArrayDeviceCapabilities)); - - napi_value jsArrayDeviceTypes = nullptr; - NAPI_CALL(env, napi_create_array(env, &jsArrayDeviceTypes)); - for (size_t i = 0; i < abilityInfo.deviceTypes.size(); i++) { - proValue = nullptr; - NAPI_CALL( - env, napi_create_string_utf8(env, abilityInfo.deviceTypes.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_element(env, jsArrayDeviceTypes, i, proValue)); - } - NAPI_CALL(env, napi_set_named_property(env, result, "deviceTypes", jsArrayDeviceTypes)); - - napi_value appInfo = nullptr; - appInfo = WrapAppInfo(env, abilityInfo.appInfo); - NAPI_CALL(env, napi_set_named_property(env, result, "applicationInfo", appInfo)); - - return result; -} - -napi_value NAPI_GetHapModuleInfo(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - HapModuleInfoCB *hapModuleInfoCB = CreateHapModuleInfoCBInfo(env); - if (hapModuleInfoCB == nullptr) { - return nullptr; - } - - napi_value ret = GetHapModuleInfoWrap(env, info, hapModuleInfoCB); - if (ret == nullptr) { - if (hapModuleInfoCB != nullptr) { - delete hapModuleInfoCB; - hapModuleInfoCB = nullptr; - } - } - return ret; + HILOG_INFO("%{public}s,end", __func__); + return result; } /** - * @brief Create asynchronous data. + * @brief Get want. * * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. * - * @return Return a pointer to HapModuleInfoCB on success, nullptr on failure. + * @return The return value from NAPI C++ to JS for the module. */ -HapModuleInfoCB *CreateHapModuleInfoCBInfo(napi_env env) +napi_value NAPI_GetWant(napi_env env, napi_callback_info info) { - napi_value global = nullptr; - NAPI_CALL(env, napi_get_global(env, &global)); - - napi_value abilityObj = nullptr; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); - - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - - HapModuleInfoCB *hapModuleInfoCB = new (std::nothrow) HapModuleInfoCB{ - .cbBase.cbInfo.env = env, - .cbBase.asyncWork = nullptr, - .cbBase.deferred = nullptr, - .cbBase.ability = ability, - }; - return hapModuleInfoCB; + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetWantCommon(env, info, AbilityType::PAGE); } -napi_value GetHapModuleInfoWrap(napi_env env, napi_callback_info info, HapModuleInfoCB *hapModuleInfoCB) +/** + * @brief Obtains information about the current application. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetApplicationInfo(napi_env env, napi_callback_info info) { - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (hapModuleInfoCB == nullptr) { - HILOG_ERROR("%{public}s, hapModuleInfoCB == nullptr.", __func__); - return nullptr; - } - - size_t argcAsync = 1; - const size_t argcPromise = 0; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - if (argcAsync > argcPromise) { - ret = GetHapModuleInfoAsync(env, args, argcAsync, argcPromise, hapModuleInfoCB); - } else { - ret = GetHapModuleInfoPromise(env, hapModuleInfoCB); - } - - return ret; + HILOG_INFO("%{public}s,called", __func__); + return NAPI_GetApplicationInfoCommon(env, info, AbilityType::PAGE); } /** - * @brief GetHapModuleInfo Async. + * @brief Obtains the type of this application. * * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param hapModuleInfoCB Process data asynchronously. + * @param info The callback info passed into the callback function. * - * @return Return JS data successfully, otherwise return nullptr. + * @return The return value from NAPI C++ to JS for the module. */ -napi_value GetHapModuleInfoAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, HapModuleInfoCB *hapModuleInfoCB) +napi_value NAPI_GetAppType(napi_env env, napi_callback_info info) { - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || hapModuleInfoCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &hapModuleInfoCB->cbBase.cbInfo.callback)); - } - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetHapModuleInfoExecuteCB, - GetHapModuleInfoAsyncCompleteCB, - (void *)hapModuleInfoCB, - &hapModuleInfoCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, hapModuleInfoCB->cbBase.asyncWork)); - napi_value result = nullptr; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetAppTypeCommon(env, info, AbilityType::PAGE); } /** - * @brief GetHapModuleInfo Promise. + * @brief Obtains the elementName object of the current ability. * * @param env The environment that the Node-API call is invoked under. - * @param hapModuleInfoCB Process data asynchronously. + * @param info The callback info passed into the callback function. * - * @return Return JS data successfully, otherwise return nullptr. + * @return The return value from NAPI C++ to JS for the module. */ -napi_value GetHapModuleInfoPromise(napi_env env, HapModuleInfoCB *hapModuleInfoCB) +napi_value NAPI_GetElementName(napi_env env, napi_callback_info info) { - HILOG_INFO("%{public}s, promise.", __func__); - if (hapModuleInfoCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = nullptr; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - hapModuleInfoCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetHapModuleInfoExecuteCB, - GetHapModuleInfoPromiseCompleteCB, - (void *)hapModuleInfoCB, - &hapModuleInfoCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, hapModuleInfoCB->cbBase.asyncWork)); - - return promise; + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetElementNameCommon(env, info, AbilityType::PAGE); } -void GetHapModuleInfoExecuteCB(napi_env env, void *data) +/** + * @brief Obtains the class name in this ability name, without the prefixed bundle name. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetAbilityName(napi_env env, napi_callback_info info) { - HILOG_INFO("NAPI_GetHapModuleInfo, worker pool thread execute."); - HapModuleInfoCB *hapModuleInfoCB = (HapModuleInfoCB *)data; - if (hapModuleInfoCB->cbBase.ability != nullptr) { - std::shared_ptr hapModuleInfoPtr = hapModuleInfoCB->cbBase.ability->GetHapModuleInfo(); - if (hapModuleInfoPtr != nullptr) { - SaveHapModuleInfo(hapModuleInfoCB->hapModuleInfo, *hapModuleInfoPtr); - } - } + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetAbilityNameCommon(env, info, AbilityType::PAGE); } -void SaveHapModuleInfo(HapModuleInfo_ &hapModuleInfo, const HapModuleInfo &hapModuleInfoOrg) +/** + * @brief Obtains the process Info this application. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetProcessInfo(napi_env env, napi_callback_info info) { - - hapModuleInfo.name = hapModuleInfoOrg.name; - hapModuleInfo.description = hapModuleInfoOrg.description; - hapModuleInfo.icon = hapModuleInfoOrg.iconPath; - hapModuleInfo.label = hapModuleInfoOrg.label; - hapModuleInfo.backgroundImg = hapModuleInfoOrg.backgroundImg; - hapModuleInfo.moduleName = hapModuleInfoOrg.moduleName; - hapModuleInfo.supportedModes = hapModuleInfoOrg.supportedModes; - hapModuleInfo.descriptionId = 0; // no data - hapModuleInfo.labelId = 0; // no data - hapModuleInfo.iconId = 0; // no data - hapModuleInfo.mainAbilityName = ""; // no data - hapModuleInfo.installationFree = false; // no data - - for (size_t i = 0; i < hapModuleInfoOrg.reqCapabilities.size(); i++) { - hapModuleInfo.reqCapabilities.emplace_back(hapModuleInfoOrg.reqCapabilities.at(i)); - } - - for (size_t i = 0; i < hapModuleInfoOrg.deviceTypes.size(); i++) { - hapModuleInfo.deviceTypes.emplace_back(hapModuleInfoOrg.deviceTypes.at(i)); - } - - for (size_t i = 0; i < hapModuleInfoOrg.abilityInfos.size(); i++) { - AbilityInfo_ abilityInfo; - SaveAbilityInfo(abilityInfo, hapModuleInfoOrg.abilityInfos.at(i)); - hapModuleInfo.abilityInfos.emplace_back(abilityInfo); - } + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetProcessInfoCommon(env, info, AbilityType::PAGE); } -void GetHapModuleInfoAsyncCompleteCB(napi_env env, napi_status status, void *data) +/** + * @brief Obtains the name of the current process. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetProcessName(napi_env env, napi_callback_info info) { - HILOG_INFO("NAPI_GetHapModuleInfo, main event thread complete."); - HapModuleInfoCB *hapModuleInfoCB = (HapModuleInfoCB *)data; - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - result[PARAM1] = WrapHapModuleInfo(env, *hapModuleInfoCB); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, hapModuleInfoCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (hapModuleInfoCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, hapModuleInfoCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, hapModuleInfoCB->cbBase.asyncWork)); - delete hapModuleInfoCB; - hapModuleInfoCB = nullptr; + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetProcessNameCommon(env, info, AbilityType::PAGE); } -void GetHapModuleInfoPromiseCompleteCB(napi_env env, napi_status status, void *data) +/** + * @brief Obtains the bundle name of the ability that called the current ability. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetCallingBundle(napi_env env, napi_callback_info info) { - HILOG_INFO("NAPI_GetHapModuleInfo, main event thread complete."); - HapModuleInfoCB *hapModuleInfoCB = (HapModuleInfoCB *)data; - napi_value result = WrapHapModuleInfo(env, *hapModuleInfoCB); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, hapModuleInfoCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, hapModuleInfoCB->cbBase.asyncWork)); - delete hapModuleInfoCB; - hapModuleInfoCB = nullptr; + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetCallingBundleCommon(env, info, AbilityType::PAGE); } -napi_value WrapHapModuleInfo(napi_env env, const HapModuleInfoCB &hapModuleInfoCB) +/** + * @brief Obtains information about the current ability. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetAbilityInfo(napi_env env, napi_callback_info info) { - napi_value result = nullptr; - napi_value proValue = nullptr; - NAPI_CALL(env, napi_create_object(env, &result)); - NAPI_CALL( - env, napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.name.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "name", proValue)); - - NAPI_CALL(env, - napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.description.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "description", proValue)); - - NAPI_CALL( - env, napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.icon.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "icon", proValue)); - - NAPI_CALL( - env, napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.label.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "label", proValue)); - - NAPI_CALL(env, - napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.backgroundImg.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "backgroundImg", proValue)); - - NAPI_CALL(env, - napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.moduleName.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "moduleName", proValue)); - - NAPI_CALL(env, napi_create_int32(env, hapModuleInfoCB.hapModuleInfo.supportedModes, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "supportedModes", proValue)); - - NAPI_CALL(env, napi_create_int32(env, hapModuleInfoCB.hapModuleInfo.descriptionId, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "descriptionId", proValue)); - - NAPI_CALL(env, napi_create_int32(env, hapModuleInfoCB.hapModuleInfo.labelId, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "labelId", proValue)); - - NAPI_CALL(env, napi_create_int32(env, hapModuleInfoCB.hapModuleInfo.iconId, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "iconId", proValue)); - - NAPI_CALL(env, - napi_create_string_utf8( - env, hapModuleInfoCB.hapModuleInfo.mainAbilityName.c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "mainAbilityName", proValue)); - - NAPI_CALL(env, napi_get_boolean(env, hapModuleInfoCB.hapModuleInfo.installationFree, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, result, "installationFree", proValue)); - - napi_value jsArrayreqCapabilities = nullptr; - NAPI_CALL(env, napi_create_array(env, &jsArrayreqCapabilities)); - for (size_t i = 0; i < hapModuleInfoCB.hapModuleInfo.reqCapabilities.size(); i++) { - proValue = nullptr; - NAPI_CALL(env, - napi_create_string_utf8( - env, hapModuleInfoCB.hapModuleInfo.reqCapabilities.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_element(env, jsArrayreqCapabilities, i, proValue)); - } - NAPI_CALL(env, napi_set_named_property(env, result, "reqCapabilities", jsArrayreqCapabilities)); - - napi_value jsArraydeviceTypes = nullptr; - NAPI_CALL(env, napi_create_array(env, &jsArraydeviceTypes)); - for (size_t i = 0; i < hapModuleInfoCB.hapModuleInfo.deviceTypes.size(); i++) { - proValue = nullptr; - NAPI_CALL(env, - napi_create_string_utf8( - env, hapModuleInfoCB.hapModuleInfo.deviceTypes.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_element(env, jsArraydeviceTypes, i, proValue)); - } - NAPI_CALL(env, napi_set_named_property(env, result, "deviceTypes", jsArraydeviceTypes)); - - napi_value abilityInfos = nullptr; - NAPI_CALL(env, napi_create_array(env, &abilityInfos)); - for (size_t i = 0; i < hapModuleInfoCB.hapModuleInfo.abilityInfos.size(); i++) { - napi_value abilityInfo = nullptr; - abilityInfo = WrapAbilityInfo(env, hapModuleInfoCB.hapModuleInfo.abilityInfos.at(i)); - NAPI_CALL(env, napi_set_element(env, abilityInfos, i, abilityInfo)); - } - NAPI_CALL(env, napi_set_named_property(env, result, "abilityInfos", abilityInfos)); + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetAbilityInfoCommon(env, info, AbilityType::PAGE); +} - return result; +/** + * @brief Obtains the HapModuleInfo object of the application. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetHapModuleInfo(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetHapModuleInfoCommon(env, info, AbilityType::PAGE); } /** @@ -3896,14 +1138,20 @@ napi_value NAPI_GetDataAbilityHelper(napi_env env, napi_callback_info info) .cbBase.ability = nullptr, .result = nullptr, }; - + if (dataAbilityHelperCB == nullptr) { + HILOG_ERROR("%{public}s, dataAbilityHelperCB == nullptr", __func__); + return WrapVoidToJS(env); + } napi_value ret = GetDataAbilityHelperWrap(env, info, dataAbilityHelperCB); if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr", __func__); if (dataAbilityHelperCB != nullptr) { delete dataAbilityHelperCB; dataAbilityHelperCB = nullptr; } + ret = WrapVoidToJS(env); } + HILOG_INFO("%{public}s,end", __func__); return ret; } @@ -3917,8 +1165,12 @@ napi_value NAPI_GetDataAbilityHelper(napi_env env, napi_callback_info info) */ napi_value GetDataAbilityHelperWrap(napi_env env, napi_callback_info info, DataAbilityHelperCB *dataAbilityHelperCB) { - HILOG_INFO("%{public}s,called", __func__); + if (dataAbilityHelperCB == nullptr) { + HILOG_ERROR("%{public}s,dataAbilityHelperCB == nullptr", __func__); + return nullptr; + } + size_t argcAsync = 2; const size_t argcPromise = 1; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; @@ -3942,7 +1194,7 @@ napi_value GetDataAbilityHelperWrap(napi_env env, napi_callback_info info, DataA } else { ret = GetDataAbilityHelperPromise(env, dataAbilityHelperCB); } - + HILOG_INFO("%{public}s,end", __func__); return ret; } @@ -3975,6 +1227,7 @@ napi_value GetDataAbilityHelperAsync(napi_env env, napi_value *args, size_t argc NAPI_CALL(env, napi_queue_async_work(env, dataAbilityHelperCB->cbBase.asyncWork)); napi_value result = 0; NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end", __func__); return result; } @@ -4002,6 +1255,7 @@ napi_value GetDataAbilityHelperPromise(napi_env env, DataAbilityHelperCB *dataAb (void *)dataAbilityHelperCB, &dataAbilityHelperCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, dataAbilityHelperCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); return promise; } @@ -4029,6 +1283,7 @@ void GetDataAbilityHelperAsyncCompleteCB(napi_env env, napi_status status, void NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, dataAbilityHelperCB->cbBase.asyncWork)); delete dataAbilityHelperCB; dataAbilityHelperCB = nullptr; + HILOG_INFO("NAPI_GetDataAbilityHelper, main event thread complete end."); } void GetDataAbilityHelperPromiseCompleteCB(napi_env env, napi_status status, void *data) @@ -4045,7 +1300,110 @@ void GetDataAbilityHelperPromiseCompleteCB(napi_env env, napi_status status, voi NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, dataAbilityHelperCB->cbBase.asyncWork)); delete dataAbilityHelperCB; dataAbilityHelperCB = nullptr; + HILOG_INFO("NAPI_GetDataAbilityHelper, main event thread complete end."); +} + +/** + * @brief FeatureAbility NAPI method : acquireDataAbilityHelper. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_AcquireDataAbilityHelper(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DataAbilityHelperCB *dataAbilityHelperCB = new (std::nothrow) DataAbilityHelperCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = nullptr, + .result = nullptr, + }; + if (dataAbilityHelperCB == nullptr) { + HILOG_ERROR("%{public}s, dataAbilityHelperCB == nullptr", __func__); + return WrapVoidToJS(env); + } + napi_value ret = AcquireDataAbilityHelperWrap(env, info, dataAbilityHelperCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr", __func__); + if (dataAbilityHelperCB != nullptr) { + delete dataAbilityHelperCB; + dataAbilityHelperCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +/** + * @brief acquireDataAbilityHelper processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param dataAbilityHelperCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value AcquireDataAbilityHelperWrap(napi_env env, napi_callback_info info, DataAbilityHelperCB *dataAbilityHelperCB) +{ + HILOG_INFO("%{public}s,called", __func__); + if (dataAbilityHelperCB == nullptr) { + HILOG_ERROR("%{public}s,dataAbilityHelperCB == nullptr", __func__); + return nullptr; + } + + size_t requireArgc = ARGS_ONE; + size_t argc = ARGS_ONE; + napi_value args[ARGS_ONE] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + if (argc > requireArgc) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype != napi_string) { + HILOG_ERROR("%{public}s, Wrong argument type.", __func__); + return nullptr; + } + + napi_value result = nullptr; + NAPI_CALL(env, napi_new_instance(env, g_dataAbilityHelper, 1, &args[PARAM0], &result)); + delete dataAbilityHelperCB; + dataAbilityHelperCB = nullptr; + HILOG_INFO("%{public}s,end", __func__); + return result; +} + +/** + * @brief FeatureAbility NAPI method : connectAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_FAConnectAbility(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_ConnectAbilityCommon(env, info, AbilityType::PAGE); } +/** + * @brief FeatureAbility NAPI method : disConnectAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_FADisConnectAbility(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_DisConnectAbilityCommon(env, info, AbilityType::PAGE); +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/featureAbility/feature_ability.h b/interfaces/kits/napi/aafwk/featureAbility/feature_ability.h old mode 100644 new mode 100755 index 2061040bc01..047572efe02 --- a/interfaces/kits/napi/aafwk/featureAbility/feature_ability.h +++ b/interfaces/kits/napi/aafwk/featureAbility/feature_ability.h @@ -15,7 +15,7 @@ #ifndef OHOS_APPEXECFWK_FEATURE_ABILITY_H #define OHOS_APPEXECFWK_FEATURE_ABILITY_H -#include "feature_ability_common.h" +#include "../inner/napi_common/feature_ability_common.h" using Want = OHOS::AAFwk::Want; namespace OHOS { @@ -30,6 +30,7 @@ namespace AppExecFwk { */ napi_value FeatureAbilityInit(napi_env env, napi_value exports); +EXTERN_C_START /** * @brief The interface of onAbilityResult provided for ACE to call back to JS. * @@ -41,6 +42,7 @@ napi_value FeatureAbilityInit(napi_env env, napi_value exports); * @return The return value from NAPI C++ to JS for the module. */ void CallOnAbilityResult(int requestCode, int resultCode, const Want &resultData, CallbackInfo callbackInfo); +EXTERN_C_END /** * @brief FeatureAbility NAPI method : startAbility. @@ -203,35 +205,36 @@ napi_value NAPI_GetAbilityInfo(napi_env env, napi_callback_info info); napi_value NAPI_GetDataAbilityHelper(napi_env env, napi_callback_info info); /** - * @brief Parse the parameters. + * @brief FeatureAbility NAPI method : acquireDataAbilityHelper. * - * @param param Indicates the parameters saved the parse result. * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. + * @param info The callback info passed into the callback function. * * @return The return value from NAPI C++ to JS for the module. */ -napi_value UnwrapParam(CallAbilityParam ¶m, napi_env env, napi_value args); +napi_value NAPI_AcquireDataAbilityHelper(napi_env env, napi_callback_info info); /** - * @brief Parse the abilityResult parameters. + * @brief Parse the parameters. * - * @param param Indicates the abilityResult parameters saved the parse result. + * @param param Indicates the parameters saved the parse result. * @param env The environment that the Node-API call is invoked under. * @param args Indicates the arguments passed into the callback. * * @return The return value from NAPI C++ to JS for the module. */ -napi_value UnwrapAbilityResult(CallAbilityParam ¶m, napi_env env, napi_value args); +napi_value UnwrapForResultParam(CallAbilityParam ¶m, napi_env env, napi_value args); /** - * @brief Create asynchronous data. + * @brief Parse the abilityResult parameters. * + * @param param Indicates the abilityResult parameters saved the parse result. * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. * - * @return Return a pointer to AsyncCallbackInfo on success, nullptr on failure. + * @return The return value from NAPI C++ to JS for the module. */ -AsyncCallbackInfo *CreateAsyncCallbackInfo(napi_env env); +napi_value UnwrapAbilityResult(CallAbilityParam ¶m, napi_env env, napi_value args); /** * @brief Create asynchronous data. @@ -242,51 +245,6 @@ AsyncCallbackInfo *CreateAsyncCallbackInfo(napi_env env); */ AppInfoCB *CreateAppInfoCBInfo(napi_env env); -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to AbilityNameCB on success, nullptr on failure. - */ -AbilityNameCB *CreateAbilityNameCBInfo(napi_env env); - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to ProcessInfoCB on success, nullptr on failure. - */ -ProcessInfoCB *CreateProcessInfoCBInfo(napi_env env); - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to ProcessNameCB on success, nullptr on failure. - */ -ProcessNameCB *CreateProcessNameCBInfo(napi_env env); - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to CallingBundleCB on success, nullptr on failure. - */ -CallingBundleCB *CreateCallingBundleCBInfo(napi_env env); - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to AbilityInfoCB on success, nullptr on failure. - */ -AbilityInfoCB *CreateAbilityInfoCBInfo(napi_env env); - /** * @brief HasWindowFocus processing function. * @@ -300,24 +258,6 @@ napi_value HasWindowFocusAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AsyncCallbackInfo *asyncCallbackInfo); napi_value HasWindowFocusPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo); -napi_value GetContextWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo); -napi_value GetContextAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AsyncCallbackInfo *asyncCallbackInfo); -napi_value GetContextPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo); - -/** - * @brief GetWantWrap processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param asyncCallbackInfo Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetWantWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo); -napi_value GetWantAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AsyncCallbackInfo *asyncCallbackInfo); -napi_value GetWantPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo); - /** * @brief TerminateAbility processing function. * @@ -344,19 +284,6 @@ napi_value SetResultAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AsyncCallbackInfo *asyncCallbackInfo); napi_value SetResultPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo); -/** - * @brief StartAbility processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param asyncCallbackInfo Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value StartAbilityWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo); -napi_value StartAbilityAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AsyncCallbackInfo *asyncCallbackInfo); -napi_value StartAbilityPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo); - /** * @brief StartAbilityForResult processing function. * @@ -370,496 +297,6 @@ napi_value StartAbilityForResultAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AsyncCallbackInfo *asyncCallbackInfo); napi_value StartAbilityForResultPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo); -/** - * @brief GetApplicationInfo processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param appInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetApplicationInfoWrap(napi_env env, napi_callback_info info, AppInfoCB *appInfoCB); - -/** - * @brief GetApplicationInfo Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param appInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetApplicationInfoAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AppInfoCB *appInfoCB); - -/** - * @brief GetApplicationInfo Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param appInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetApplicationInfoPromise(napi_env env, AppInfoCB *appInfoCB); - -/** - * @brief GetApplicationInfo asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAppInfoExecuteCB(napi_env env, void *data); - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAppInfoAsyncCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAppInfoPromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value WrapAppInfo(napi_env env, const AppInfo_ &appInfo); -void SaveAppInfo(AppInfo_ &appInfo, const ApplicationInfo &appInfoOrg); - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to AppTypeCB on success, nullptr on failure. - */ -AppTypeCB *CreateAppTypeCBInfo(napi_env env); - -/** - * @brief GetAppType processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param appTypeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAppTypeWrap(napi_env env, napi_callback_info info, AppTypeCB *appTypeCB); - -/** - * @brief GetAppType Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param appTypeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAppTypeAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AppTypeCB *appTypeCB); - -/** - * @brief GetAppType Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param appTypeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAppTypePromise(napi_env env, AppTypeCB *appTypeCB); - -/** - * @brief GetAppType asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAppTypeExecuteCB(napi_env env, void *data); - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAppTypeAsyncCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAppTypePromiseCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to ElementNameCB on success, nullptr on failure. - */ -ElementNameCB *CreateElementNameCBInfo(napi_env env); - -/** - * @brief GetElementName processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param elementNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetElementNameWrap(napi_env env, napi_callback_info info, ElementNameCB *elementNameCB); - -/** - * @brief GetElementName Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param elementNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetElementNameAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, ElementNameCB *elementNameCB); - -/** - * @brief GetElementName Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param elementNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetElementNamePromise(napi_env env, ElementNameCB *elementNameCB); - -/** - * @brief GetElementName asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetElementNameExecuteCB(napi_env env, void *data); - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetElementNameAsyncCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetElementNamePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value WrapElementName(napi_env env, ElementNameCB *elementNameCB); - -/** - * @brief GetAbilityName processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param abilityNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAbilityNameWrap(napi_env env, napi_callback_info info, AbilityNameCB *abilityNameCB); - -/** - * @brief GetAbilityName Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param abilityNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAbilityNameAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AbilityNameCB *abilityNameCB); - -/** - * @brief GetAbilityName Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param abilityNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAbilityNamePromise(napi_env env, AbilityNameCB *abilityNameCB); - -/** - * @brief GetAbilityName asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAbilityNameExecuteCB(napi_env env, void *data); - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAbilityNameAsyncCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAbilityNamePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value WrapAbilityName(napi_env env, AbilityNameCB *abilityNameCB); - -/** - * @brief GetProcessInfo processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param ProcessInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetProcessInfoWrap(napi_env env, napi_callback_info info, ProcessInfoCB *ProcessInfoCB); - -/** - * @brief GetProcessInfo Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param ProcessInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetProcessInfoAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, ProcessInfoCB *ProcessInfoCB); - -/** - * @brief GetProcessInfo Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param ProcessInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetProcessInfoPromise(napi_env env, ProcessInfoCB *ProcessInfoCB); - -/** - * @brief GetProcessInfo asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetProcessInfoExecuteCB(napi_env env, void *data); - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetProcessInfoAsyncCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetProcessInfoPromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value WrapProcessInfo(napi_env env, ProcessInfoCB *ProcessInfoCB); - -/** - * @brief GetProcessName processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param ProcessNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetProcessNameWrap(napi_env env, napi_callback_info info, ProcessNameCB *ProcessNameCB); - -/** - * @brief GetProcessName Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param ProcessNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetProcessNameAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, ProcessNameCB *ProcessNameCB); - -/** - * @brief GetProcessName Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param ProcessNameCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetProcessNamePromise(napi_env env, ProcessNameCB *ProcessNameCB); - -/** - * @brief GetProcessName asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetProcessNameExecuteCB(napi_env env, void *data); - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetProcessNameAsyncCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetProcessNamePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value WrapProcessName(napi_env env, ProcessNameCB *ProcessNameCB); - -/** - * @brief GetCallingBundle processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param CallingBundleCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetCallingBundleWrap(napi_env env, napi_callback_info info, CallingBundleCB *CallingBundleCB); - -/** - * @brief GetCallingBundle Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param CallingBundleCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetCallingBundleAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, CallingBundleCB *CallingBundleCB); - -/** - * @brief GetCallingBundle Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param CallingBundleCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetCallingBundlePromise(napi_env env, CallingBundleCB *CallingBundleCB); - -/** - * @brief GetCallingBundle asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetCallingBundleExecuteCB(napi_env env, void *data); - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetCallingBundleAsyncCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetCallingBundlePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value WrapCallingBundle(napi_env env, CallingBundleCB *CallingBundleCB); - -/** - * @brief GetAbilityInfo processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param abilityInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAbilityInfoWrap(napi_env env, napi_callback_info info, AbilityInfoCB *abilityInfoCB); - -/** - * @brief GetAbilityInfo Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param abilityInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAbilityInfoAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AbilityInfoCB *abilityInfoCB); - -/** - * @brief GetAbilityInfo Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param abilityInfoCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetAbilityInfoPromise(napi_env env, AbilityInfoCB *abilityInfoCB); - -/** - * @brief GetAbilityInfo asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAbilityInfoExecuteCB(napi_env env, void *data); - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAbilityInfoAsyncCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetAbilityInfoPromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value WrapAbilityInfo(napi_env env, const AbilityInfo_ &abilityInfo); -void SaveAbilityInfo(AbilityInfo_ &abilityInfo, const AbilityInfo &abilityInfoOrg); - /** * @brief Obtains the HapModuleInfo object of the application. * @@ -871,54 +308,37 @@ void SaveAbilityInfo(AbilityInfo_ &abilityInfo, const AbilityInfo &abilityInfoOr napi_value NAPI_GetHapModuleInfo(napi_env env, napi_callback_info info); /** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to HapModuleInfoCB on success, nullptr on failure. - */ -HapModuleInfoCB *CreateHapModuleInfoCBInfo(napi_env env); - -/** - * @brief GetHapModuleInfo processing function. + * @brief getDataAbilityHelper processing function. * * @param env The environment that the Node-API call is invoked under. - * @param hapModuleInfoCB Process data asynchronously. + * @param dataAbilityHelperCB Process data asynchronously. * * @return Return JS data successfully, otherwise return nullptr. */ -napi_value GetHapModuleInfoWrap(napi_env env, napi_callback_info info, HapModuleInfoCB *hapModuleInfoCB); +napi_value GetDataAbilityHelperWrap(napi_env env, napi_callback_info info, DataAbilityHelperCB *dataAbilityHelperCB); /** - * @brief GetHapModuleInfo Async. + * @brief GetDataAbilityHelper Async. * * @param env The environment that the Node-API call is invoked under. * @param args Indicates the arguments passed into the callback. * @param argcPromise Asynchronous data processing. - * @param hapModuleInfoCB Process data asynchronously. + * @param dataAbilityHelperCB Process data asynchronously. * * @return Return JS data successfully, otherwise return nullptr. */ -napi_value GetHapModuleInfoAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, HapModuleInfoCB *hapModuleInfoCB); +napi_value GetDataAbilityHelperAsync(napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, + DataAbilityHelperCB *dataAbilityHelperCB); /** - * @brief GetHapModuleInfo Promise. + * @brief GetDataAbilityHelper Promise. * * @param env The environment that the Node-API call is invoked under. - * @param hapModuleInfoCB Process data asynchronously. + * @param dataAbilityHelperCB Process data asynchronously. * * @return Return JS data successfully, otherwise return nullptr. */ -napi_value GetHapModuleInfoPromise(napi_env env, HapModuleInfoCB *hapModuleInfoCB); - -/** - * @brief GetHapModuleInfo asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetHapModuleInfoExecuteCB(napi_env env, void *data); +napi_value GetDataAbilityHelperPromise(napi_env env, DataAbilityHelperCB *dataAbilityHelperCB); /** * @brief The callback at the end of the asynchronous callback. @@ -926,7 +346,7 @@ void GetHapModuleInfoExecuteCB(napi_env env, void *data); * @param env The environment that the Node-API call is invoked under. * @param data Point to asynchronous processing of data. */ -void GetHapModuleInfoAsyncCompleteCB(napi_env env, napi_status status, void *data); +void GetDataAbilityHelperAsyncCompleteCB(napi_env env, napi_status status, void *data); /** * @brief The callback at the end of the Promise callback. @@ -934,58 +354,39 @@ void GetHapModuleInfoAsyncCompleteCB(napi_env env, napi_status status, void *dat * @param env The environment that the Node-API call is invoked under. * @param data Point to asynchronous processing of data. */ -void GetHapModuleInfoPromiseCompleteCB(napi_env env, napi_status status, void *data); -napi_value WrapHapModuleInfo(napi_env env, const HapModuleInfoCB &hapModuleInfoCB); -void SaveHapModuleInfo(HapModuleInfo_ &hapModuleInfo, const HapModuleInfo &hapModuleInfoOrg); - -/** - * @brief getDataAbilityHelper processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param dataAbilityHelperCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value GetDataAbilityHelperWrap(napi_env env, napi_callback_info info, DataAbilityHelperCB *dataAbilityHelperCB); +void GetDataAbilityHelperPromiseCompleteCB(napi_env env, napi_status status, void *data); /** - * @brief GetDataAbilityHelper Async. + * @brief acquireDataAbilityHelper processing function. * * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. * @param dataAbilityHelperCB Process data asynchronously. * * @return Return JS data successfully, otherwise return nullptr. */ -napi_value GetDataAbilityHelperAsync(napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, - DataAbilityHelperCB *dataAbilityHelperCB); +napi_value AcquireDataAbilityHelperWrap( + napi_env env, napi_callback_info info, DataAbilityHelperCB *dataAbilityHelperCB); /** - * @brief GetDataAbilityHelper Promise. + * @brief FeatureAbility NAPI method : connectAbility. * * @param env The environment that the Node-API call is invoked under. - * @param dataAbilityHelperCB Process data asynchronously. + * @param info The callback info passed into the callback function. * - * @return Return JS data successfully, otherwise return nullptr. + * @return The return value from NAPI C++ to JS for the module. */ -napi_value GetDataAbilityHelperPromise(napi_env env, DataAbilityHelperCB *dataAbilityHelperCB); +napi_value NAPI_FAConnectAbility(napi_env env, napi_callback_info info); /** - * @brief The callback at the end of the asynchronous callback. + * @brief FeatureAbility NAPI method : disconnectAbility. * * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void GetDataAbilityHelperAsyncCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief The callback at the end of the Promise callback. + * @param info The callback info passed into the callback function. * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. + * @return The return value from NAPI C++ to JS for the module. */ -void GetDataAbilityHelperPromiseCompleteCB(napi_env env, napi_status status, void *data); +napi_value NAPI_FADisConnectAbility(napi_env env, napi_callback_info info); +static int64_t dummyRequestCode_ = 0; } // namespace AppExecFwk } // namespace OHOS #endif /* OHOS_APPEXECFWK_FEATURE_ABILITY_H */ diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp b/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp index c4aa2b24141..22659c5b5b1 100755 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp @@ -19,13 +19,13 @@ #include "hilog_wrapper.h" #include "ability_process.h" #include "feature_ability_common.h" +#include "../inner/napi_common/napi_common_ability.h" using namespace OHOS::AAFwk; using namespace OHOS::AppExecFwk; namespace OHOS { namespace AppExecFwk { -napi_value g_classContext; CallbackInfo aceCallbackInfoPermission; @@ -83,8 +83,8 @@ void VerifySelfPermissionExecuteCallbackWork(napi_env env, void *data) } asyncCallbackInfo->native_data.data_type = NVT_INT32; - std::string permission(asyncCallbackInfo->param.paramArgs.GetStringValue("permission")); - asyncCallbackInfo->native_data.int32_value = asyncCallbackInfo->ability->VerifySelfPermission(permission); + asyncCallbackInfo->native_data.int32_value = asyncCallbackInfo->ability->VerifySelfPermission( + asyncCallbackInfo->param.paramArgs.GetStringValue("permission")); } /** @@ -150,8 +150,7 @@ napi_value NAPI_VerifySelfPermission(napi_env env, napi_callback_info info) napi_value rev = NAPI_VerifySelfPermissionWrap(env, info, asyncCallbackInfo); if (rev == nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; + FreeAsyncJSCallbackInfo(&asyncCallbackInfo); rev = WrapVoidToJS(env); } return rev; @@ -163,17 +162,19 @@ bool UnwrapRequestPermissionsFromUser( HILOG_INFO("%{public}s called, argc=%{public}zu", __func__, argc); const size_t argcMax = 3; - if (argc > argcMax || argc < argcMax - 1) { + if (argc != argcMax) { HILOG_INFO("%{public}s called, parameters is invalid", __func__); return false; } - if (argc == argcMax) { - if (!CreateAsyncCallback(env, argv[PARAM2], asyncCallbackInfo)) { - HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); - return false; - } + aceCallbackInfoPermission.env = env; + napi_valuetype valuetype = napi_undefined; + NAPI_CALL_BASE(env, napi_typeof(env, argv[PARAM2], &valuetype), false); + if (valuetype != napi_function) { + HILOG_INFO("%{public}s called, parameters is invalid", __func__); + return false; } + NAPI_CALL_BASE(env, napi_create_reference(env, argv[PARAM2], 1, &aceCallbackInfoPermission.callback), false); std::vector permissionList; if (!UnwrapArrayStringFromJS(env, argv[PARAM0], permissionList)) { @@ -250,6 +251,21 @@ void RequestPermissionsFromUserExecutePromiseWork(napi_env env, void *data) asyncCallbackInfo->ability, permissionParam, *asyncCallbackInfo->aceCallback); } +void RequestPermissionsFromUserCompleteAsyncCallbackWork(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + + AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called, asyncCallbackInfo is null", __func__); + return; + } + + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +} + /** * @brief RequestPermissionsFromUser processing function. * @@ -276,21 +292,11 @@ napi_value NAPI_RequestPermissionsFromUserWrap( asyncCallbackInfo->aceCallback = &aceCallbackInfoPermission; AsyncParamEx asyncParamEx; - if (asyncCallbackInfo->cbInfo.callback != nullptr) { - HILOG_INFO("%{public}s called. asyncCallback.", __func__); - asyncParamEx.resource = "NAPI_RequestPermissionsFromUserCallback"; - asyncParamEx.execute = RequestPermissionsFromUserExecuteCallbackWork; - asyncParamEx.complete = CompleteAsyncCallbackWork; - - return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); - } else { - HILOG_INFO("%{public}s called. promise.", __func__); - asyncParamEx.resource = "NAPI_RequestPermissionsFromUserPromise"; - asyncParamEx.execute = RequestPermissionsFromUserExecutePromiseWork; - asyncParamEx.complete = CompletePromiseCallbackWork; + asyncParamEx.resource = "NAPI_RequestPermissionsFromUserCallback"; + asyncParamEx.execute = RequestPermissionsFromUserExecuteCallbackWork; + asyncParamEx.complete = RequestPermissionsFromUserCompleteAsyncCallbackWork; - return ExecutePromiseCallbackWork(env, asyncCallbackInfo, &asyncParamEx); - } + return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); } /** @@ -313,96 +319,19 @@ napi_value NAPI_RequestPermissionsFromUser(napi_env env, napi_callback_info info napi_value rev = NAPI_RequestPermissionsFromUserWrap(env, info, asyncCallbackInfo); if (rev == nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - rev = WrapVoidToJS(env); - } - return rev; -} - -/** - * @brief OnRequestPermissionsFromUserResult processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param asyncCallbackInfo Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value NAPI_OnRequestPermissionsFromUserResultWrap( - napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s called", __func__); - size_t argc = ARGS_MAX_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value jsthis = 0; - void *data = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &jsthis, &data)); - - if (argc > 0) { - HILOG_INFO("%{public}s called, argc=%{public}zu", __func__, argc); - - napi_value resourceName = 0; - NAPI_CALL(env, - napi_create_string_latin1(env, "NAPI_OnRequestPermissionsFromUserResult", NAPI_AUTO_LENGTH, &resourceName)); - - aceCallbackInfoPermission.env = env; - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, args[PARAM0], 1, &aceCallbackInfoPermission.callback); - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - [](napi_env env, void *data) { - HILOG_INFO("Context::NAPI_OnRequestPermissionsFromUserResult worker pool thread execute."); - }, - [](napi_env env, napi_status status, void *data) { - HILOG_INFO("Conext::NAPI_OnRequestPermissionsFromUserResult main event thread complete."); - - AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; - if (asyncCallbackInfo != nullptr) { - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - } - }, - (void *)asyncCallbackInfo, - &asyncCallbackInfo->asyncWork)); - - NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); - } - - return WrapInt32ToJS(env, 1); -} - -/** - * @brief Called back after permissions are requested by using - * AbilityContext.requestPermissionsFromUser(java.lang.String[],int). - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - */ -napi_value NAPI_OnRequestPermissionsFromUserResult(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s called.", __func__); - - AsyncJSCallbackInfo *asyncCallbackInfo = CreateAsyncJSCallbackInfo(env); - if (asyncCallbackInfo == nullptr) { - HILOG_INFO("%{public}s called. Invoke CreateAsyncJSCallbackInfo failed.", __func__); - return WrapVoidToJS(env); - } + if (aceCallbackInfoPermission.callback != nullptr && aceCallbackInfoPermission.env != nullptr) { + napi_delete_reference(aceCallbackInfoPermission.env, aceCallbackInfoPermission.callback); + } + aceCallbackInfoPermission.env = nullptr; + aceCallbackInfoPermission.callback = nullptr; - napi_value rev = NAPI_OnRequestPermissionsFromUserResultWrap(env, info, asyncCallbackInfo); - if (rev == nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; + FreeAsyncJSCallbackInfo(&asyncCallbackInfo); rev = WrapVoidToJS(env); } return rev; } +EXTERN_C_START /** * @brief The interface of onRequestPermissionsFromUserResult provided for ACE to call back to JS. * @@ -415,13 +344,21 @@ void CallOnRequestPermissionsFromUserResult(int requestCode, const std::vector &grantResults, CallbackInfo callbackInfo) { HILOG_INFO("%{public}s,called env=%{public}p", __func__, callbackInfo.env); + + if (permissions.empty()) { + HILOG_ERROR("%{public}s, the string vector permissions is empty.", __func__); + } uv_loop_s *loop = nullptr; #if NAPI_VERSION >= 2 napi_get_uv_event_loop(callbackInfo.env, &loop); #endif // NAPI_VERSION >= 2 - uv_work_t *work = new uv_work_t; + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + HILOG_ERROR("%{public}s, work==null.", __func__); + return; + } OnRequestPermissionsFromUserResultCallback *onRequestPermissionCB = new (std::nothrow) OnRequestPermissionsFromUserResultCallback{ .requestCode = requestCode, @@ -429,9 +366,16 @@ void CallOnRequestPermissionsFromUserResult(int requestCode, const std::vectordata = (void *)onRequestPermissionCB; - uv_queue_work(loop, + int rev = uv_queue_work( + loop, work, [](uv_work_t *work) {}, [](uv_work_t *work, int status) { @@ -469,7 +413,7 @@ void CallOnRequestPermissionsFromUserResult(int requestCode, const std::vectorcb.env, event->grantResults[i], &perValue); napi_set_element(event->cb.env, grantArray, i, perValue); } - napi_set_named_property(event->cb.env, result[PARAM1], "grantResults", grantArray); + napi_set_named_property(event->cb.env, result[PARAM1], "authResults", grantArray); // call CB function napi_value callback = 0; @@ -485,83 +429,18 @@ void CallOnRequestPermissionsFromUserResult(int requestCode, const std::vectorerror_code = NAPI_ERR_NO_ERROR; - asyncCallbackInfo->native_data.data_type = NVT_NONE; - if (asyncCallbackInfo->ability == nullptr) { - asyncCallbackInfo->error_code = NAPI_ERR_ACE_ABILITY; - return; - } - - asyncCallbackInfo->native_data.data_type = NVT_STRING; - asyncCallbackInfo->native_data.str_value = asyncCallbackInfo->ability->GetBundleName(); - HILOG_INFO("%{public}s called. bundleName=%{public}s", __func__, asyncCallbackInfo->native_data.str_value.c_str()); -} - -/** - * @brief GetBundleName processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param asyncCallbackInfo Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value NAPI_GetBundleNameWrap(napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s called", __func__); - size_t argc = ARGS_MAX_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value jsthis = 0; - void *data = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &jsthis, &data)); - - if (argc > ARGS_ONE) { - HILOG_INFO("%{public}s called, parameters is invalid.", __func__); - return nullptr; - } - - if (argc == ARGS_ONE) { - if (!CreateAsyncCallback(env, args[PARAM0], asyncCallbackInfo)) { - HILOG_INFO("%{public}s called, the first parameter is invalid.", __func__); - return nullptr; - } - } - - AsyncParamEx asyncParamEx; - if (asyncCallbackInfo->cbInfo.callback != nullptr) { - HILOG_INFO("%{public}s called. asyncCallback.", __func__); - asyncParamEx.resource = "NAPI_GetBundleNameCallback"; - asyncParamEx.execute = GetBundleNameExecuteCallback; - asyncParamEx.complete = CompleteAsyncCallbackWork; - - return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); - } else { - HILOG_INFO("%{public}s called. promise.", __func__); - asyncParamEx.resource = "NAPI_GetBundleNamePromise"; - asyncParamEx.execute = GetBundleNameExecuteCallback; - asyncParamEx.complete = CompletePromiseCallbackWork; - - return ExecutePromiseCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + if (rev != 0) { + delete onRequestPermissionCB; + onRequestPermissionCB = nullptr; + delete work; + work = nullptr; } } +EXTERN_C_END /** * @brief Get bundle name. @@ -574,20 +453,7 @@ napi_value NAPI_GetBundleNameWrap(napi_env env, napi_callback_info info, AsyncJS napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s called", __func__); - - AsyncJSCallbackInfo *asyncCallbackInfo = CreateAsyncJSCallbackInfo(env); - if (asyncCallbackInfo == nullptr) { - HILOG_INFO("%{public}s called. Invoke CreateAsyncJSCallbackInfo failed.", __func__); - return WrapVoidToJS(env); - } - - napi_value rev = NAPI_GetBundleNameWrap(env, info, asyncCallbackInfo); - if (rev == nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - rev = WrapVoidToJS(env); - } - return rev; + return NAPI_GetBundleNameCommon(env, info, AbilityType::PAGE); } void CanRequestPermissionExecuteCallback(napi_env env, void *data) @@ -658,46 +524,77 @@ napi_value NAPI_CanRequestPermission(napi_env env, napi_callback_info info) napi_value rev = NAPI_CanRequestPermissionWrap(env, info, asyncCallbackInfo); if (rev == nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; + FreeAsyncJSCallbackInfo(&asyncCallbackInfo); rev = WrapVoidToJS(env); } return rev; } +bool UnwrapVerifyPermissionOptions(napi_env env, napi_value argv, AsyncJSCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called", __func__); + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called, asyncCallbackInfo is null", __func__); + return false; + } + + if (!IsTypeForNapiValue(env, argv, napi_object)) { + HILOG_INFO("%{public}s called, type of parameter is error.", __func__); + return false; + } + + int value = 0; + if (UnwrapInt32ByPropertyName(env, argv, "pid", value)) { + asyncCallbackInfo->param.paramArgs.PutIntValue("pid", value); + } + + value = 0; + if (UnwrapInt32ByPropertyName(env, argv, "uid", value)) { + asyncCallbackInfo->param.paramArgs.PutIntValue("uid", value); + } + return true; +} + bool UnwrapParamVerifyPermission(napi_env env, size_t argc, napi_value *argv, AsyncJSCallbackInfo *asyncCallbackInfo) { HILOG_INFO("%{public}s called, argc=%{public}zu", __func__, argc); - const size_t argcMax = 4; - if (argc > argcMax || argc < argcMax - 1) { + const size_t argcMax = ARGS_THREE; + if (argc > argcMax || argc < 1) { HILOG_INFO("%{public}s called, Params is invalid.", __func__); return false; } - if (argc == argcMax) { - if (!CreateAsyncCallback(env, argv[PARAM3], asyncCallbackInfo)) { - HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); - return false; - } - } - std::string permission(""); if (!UnwrapStringFromJS2(env, argv[PARAM0], permission)) { HILOG_INFO("%{public}s called, the first parameter is invalid.", __func__); return false; } - - int pid = 0; - NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM1], &pid)); - - int uid = 0; - NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM2], &uid)); - asyncCallbackInfo->param.paramArgs.PutStringValue("permission", permission); - asyncCallbackInfo->param.paramArgs.PutIntValue("pid", pid); - asyncCallbackInfo->param.paramArgs.PutIntValue("uid", uid); + if (argc == argcMax) { + if (!CreateAsyncCallback(env, argv[PARAM2], asyncCallbackInfo)) { + HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); + return false; + } + + if (!UnwrapVerifyPermissionOptions(env, argv[PARAM1], asyncCallbackInfo)) { + HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); + return false; + } + } else if (argc == ARGS_TWO) { + if (!CreateAsyncCallback(env, argv[PARAM1], asyncCallbackInfo)) { + if (!UnwrapVerifyPermissionOptions(env, argv[PARAM1], asyncCallbackInfo)) { + HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); + return false; + } + } + } else if (argc == ARGS_ONE) { + asyncCallbackInfo->cbInfo.callback = nullptr; + } else { + HILOG_INFO("%{public}s called, the parameter is invalid.", __func__); + return false; + } return true; } @@ -720,11 +617,17 @@ void VerifyPermissionExecuteCallback(napi_env env, void *data) } std::string permission(asyncCallbackInfo->param.paramArgs.GetStringValue("permission").c_str()); + bool hasUid = asyncCallbackInfo->param.paramArgs.HasKey("uid"); int pid = asyncCallbackInfo->param.paramArgs.GetIntValue("pid"); int uid = asyncCallbackInfo->param.paramArgs.GetIntValue("uid"); asyncCallbackInfo->native_data.data_type = NVT_INT32; - asyncCallbackInfo->native_data.int32_value = asyncCallbackInfo->ability->VerifyPermission(permission, pid, uid); + + if (hasUid) { + asyncCallbackInfo->native_data.int32_value = asyncCallbackInfo->ability->VerifyPermission(permission, pid, uid); + } else { + asyncCallbackInfo->native_data.int32_value = asyncCallbackInfo->ability->VerifySelfPermission(permission); + } } napi_value NAPI_VerifyPermissionWrap(napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) @@ -771,8 +674,7 @@ napi_value NAPI_VerifyPermission(napi_env env, napi_callback_info info) napi_value rev = NAPI_VerifyPermissionWrap(env, info, asyncCallbackInfo); if (rev == nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; + FreeAsyncJSCallbackInfo(&asyncCallbackInfo); rev = WrapVoidToJS(env); } return rev; @@ -847,8 +749,7 @@ napi_value NAPI_VerifyCallingPermission(napi_env env, napi_callback_info info) napi_value rev = NAPI_VerifyCallingPermissionWrap(env, info, asyncCallbackInfo); if (rev == nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; + FreeAsyncJSCallbackInfo(&asyncCallbackInfo); rev = WrapVoidToJS(env); } return rev; @@ -923,8 +824,7 @@ napi_value NAPI_VerifyCallingOrSelfPermission(napi_env env, napi_callback_info i napi_value rev = NAPI_VerifyCallingOrSelfPermissionWrap(env, info, asyncCallbackInfo); if (rev == nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; + FreeAsyncJSCallbackInfo(&asyncCallbackInfo); rev = WrapVoidToJS(env); } return rev; @@ -945,7 +845,6 @@ napi_value ContextPermissionInit(napi_env env, napi_value exports) napi_property_descriptor properties[] = { DECLARE_NAPI_FUNCTION("verifySelfPermission", NAPI_VerifySelfPermission), DECLARE_NAPI_FUNCTION("requestPermissionsFromUser", NAPI_RequestPermissionsFromUser), - DECLARE_NAPI_FUNCTION("onRequestPermissionsFromUserResult", NAPI_OnRequestPermissionsFromUserResult), DECLARE_NAPI_FUNCTION("getBundleName", NAPI_GetBundleName), DECLARE_NAPI_FUNCTION("canRequestPermission", NAPI_CanRequestPermission), DECLARE_NAPI_FUNCTION("verifyPermission", NAPI_VerifyPermission), @@ -961,7 +860,7 @@ napi_value ContextPermissionInit(napi_env env, napi_value exports) nullptr, sizeof(properties) / sizeof(*properties), properties, - &g_classContext)); + GetGlobalClassContext())); return exports; } diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_context.h b/interfaces/kits/napi/aafwk/featureAbility/napi_context.h index f146698eddd..f6a1eb27373 100755 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_context.h +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_context.h @@ -48,6 +48,7 @@ struct OnRequestPermissionsFromUserResultCallback { */ napi_value ContextPermissionInit(napi_env env, napi_value exports); +EXTERN_C_START /** * @brief The interface of onRequestPermissionsFromUserResult provided for ACE to call back to JS. * @@ -58,7 +59,7 @@ napi_value ContextPermissionInit(napi_env env, napi_value exports); */ void CallOnRequestPermissionsFromUserResult(int requestCode, const std::vector &permissions, const std::vector &grantResults, OHOS::AppExecFwk::CallbackInfo callbackInfo); - +EXTERN_C_END napi_value ContextConstructor(napi_env env, napi_callback_info info); } // namespace AppExecFwk diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp index 088fc84e363..097d4c54d77 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp @@ -41,21 +41,17 @@ napi_value DataAbilityHelperInit(napi_env env, napi_value exports) { HILOG_INFO("%{public}s,called", __func__); napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("insert", NAPI_Insert), // NotifyChange - // DECLARE_NAPI_FUNCTION("delete", NAPI_StartAbilityForResult), // NotifyChange - // DECLARE_NAPI_FUNCTION("query", NAPI_SetResult), - // DECLARE_NAPI_FUNCTION("update", NAPI_TerminateAbility), // NotifyChange - // DECLARE_NAPI_FUNCTION("call", NAPI_HasWindowFocus), - // DECLARE_NAPI_FUNCTION("batchInsert", NAPI_GetContext), // NotifyChange - // DECLARE_NAPI_FUNCTION("openFile", NAPI_GetWant), - // DECLARE_NAPI_FUNCTION("executeBatch", NAPI_GetApplicationInfo), - // DECLARE_NAPI_FUNCTION("getType", NAPI_GetAppType), - // DECLARE_NAPI_FUNCTION("getFileTypes", NAPI_GetAppType), - // DECLARE_NAPI_FUNCTION("normalizeUri", NAPI_GetAppType), - // DECLARE_NAPI_FUNCTION("denormalizeUri", NAPI_GetAppType), - // DECLARE_NAPI_FUNCTION("realse", NAPI_GetAppType), - // DECLARE_NAPI_FUNCTION("on", NAPI_GetElementName), - // DECLARE_NAPI_FUNCTION("off", NAPI_GetAbilityName), + DECLARE_NAPI_FUNCTION("insert", NAPI_Insert), + DECLARE_NAPI_FUNCTION("delete", NAPI_Delete), + DECLARE_NAPI_FUNCTION("query", NAPI_Query), + DECLARE_NAPI_FUNCTION("update", NAPI_Update), + DECLARE_NAPI_FUNCTION("batchInsert", NAPI_BatchInsert), + DECLARE_NAPI_FUNCTION("openFile", NAPI_OpenFile), + DECLARE_NAPI_FUNCTION("getType", NAPI_GetType), + DECLARE_NAPI_FUNCTION("getFileTypes", NAPI_GetFileTypes), + DECLARE_NAPI_FUNCTION("normalizeUri", NAPI_NormalizeUri), + DECLARE_NAPI_FUNCTION("denormalizeUri", NAPI_DenormalizeUri), + DECLARE_NAPI_FUNCTION("release", NAPI_Release), }; NAPI_CALL(env, napi_define_class(env, @@ -77,8 +73,9 @@ napi_value DataAbilityHelperConstructor(napi_env env, napi_callback_info info) napi_value argv[1]; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); - NAPI_ASSERT(env, argc > 1, "Wrong number of arguments"); + NAPI_ASSERT(env, argc > 0, "Wrong number of arguments"); std::string strUri = NapiValueToStringUtf8(env, argv[0]); + HILOG_INFO("%{public}s,strUri = %{public}s", __func__, strUri.c_str()); napi_value global = nullptr; NAPI_CALL(env, napi_get_global(env, &global)); @@ -89,23 +86,41 @@ napi_value DataAbilityHelperConstructor(napi_env env, napi_callback_info info) Ability *ability = nullptr; NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + HILOG_INFO("ability = %{public}p strUri = %{public}s", ability, strUri.c_str()); + HILOG_INFO("g_dataAbilityHelperList.size = %{public}d", g_dataAbilityHelperList.size()); std::shared_ptr dataAbilityHelper = - DataAbilityHelper::Creator(std::shared_ptr(ability), std::make_shared(strUri)); + DataAbilityHelper::Creator(ability->GetContext(), std::make_shared(strUri)); HILOG_INFO("dataAbilityHelper = %{public}p", dataAbilityHelper.get()); g_dataAbilityHelperList.emplace_back(dataAbilityHelper); + HILOG_INFO("g_dataAbilityHelperList.size = %{public}d", g_dataAbilityHelperList.size()); napi_wrap( env, thisVar, dataAbilityHelper.get(), [](napi_env env, void *data, void *hint) { - std::shared_ptr objectInfo = - std::shared_ptr((DataAbilityHelper *)data); - HILOG_INFO("dataAbilityHelper this = %{public}p, destruct", objectInfo.get()); + DataAbilityHelper *objectInfo = (DataAbilityHelper *)data; + HILOG_INFO("DataAbilityHelper finalize_cb objectInfo = %{public}p", objectInfo); + HILOG_INFO("DataAbilityHelper finalize_cb registerInstances_.size = %{public}d", registerInstances_.size()); + auto helper = std::find_if(registerInstances_.begin(), + registerInstances_.end(), + [&objectInfo](const DAHelperOnOffCB *helper) { return helper->dataAbilityHelper == objectInfo; }); + if (helper != registerInstances_.end()) { + HILOG_INFO("DataAbilityHelper finalize_cb find helper"); + (*helper)->dataAbilityHelper->Release(); + delete *helper; + registerInstances_.erase(helper); + } + HILOG_INFO("DataAbilityHelper finalize_cb registerInstances_.size = %{public}d", registerInstances_.size()); + HILOG_INFO("DataAbilityHelper finalize_cb g_dataAbilityHelperList.size = %{public}d", + g_dataAbilityHelperList.size()); g_dataAbilityHelperList.remove_if( [objectInfo](const std::shared_ptr &dataAbilityHelper) { - return objectInfo == dataAbilityHelper; + return objectInfo == dataAbilityHelper.get(); }); + HILOG_INFO("DataAbilityHelper finalize_cb g_dataAbilityHelperList.size = %{public}d", + g_dataAbilityHelperList.size()); + HILOG_INFO("DataAbilityHelper finalize_cb end."); }, nullptr, nullptr); @@ -131,14 +146,21 @@ napi_value NAPI_Insert(napi_env env, napi_callback_info info) .cbBase.deferred = nullptr, .cbBase.ability = nullptr, }; + if (insertCB == nullptr) { + HILOG_ERROR("%{public}s, insertCB == nullptr.", __func__); + return WrapVoidToJS(env); + } napi_value ret = InsertWrap(env, info, insertCB); if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr.", __func__); if (insertCB != nullptr) { delete insertCB; insertCB = nullptr; } + ret = WrapVoidToJS(env); } + HILOG_INFO("%{public}s,called end", __func__); return ret; } @@ -152,7 +174,6 @@ napi_value NAPI_Insert(napi_env env, napi_callback_info info) */ napi_value InsertWrap(napi_env env, napi_callback_info info, DAHelperInsertCB *insertCB) { - HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = ARGS_THREE; const size_t argcPromise = ARGS_TWO; @@ -172,6 +193,9 @@ napi_value InsertWrap(napi_env env, napi_callback_info info, DAHelperInsertCB *i if (valuetype == napi_string) { insertCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); HILOG_INFO("%{public}s,uri=%{public}s", __func__, insertCB->uri.c_str()); + } else { + HILOG_ERROR("%{public}s, Wrong argument type.", __func__); + return nullptr; } std::string strValue; @@ -182,7 +206,7 @@ napi_value InsertWrap(napi_env env, napi_callback_info info, DAHelperInsertCB *i DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("DataAbilityHelper objectInfo = %{public}p", objectInfo); + HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); insertCB->dataAbilityHelper = objectInfo; if (argcAsync > argcPromise) { @@ -190,7 +214,7 @@ napi_value InsertWrap(napi_env env, napi_callback_info info, DAHelperInsertCB *i } else { ret = InsertPromise(env, insertCB); } - + HILOG_INFO("%{public}s,end", __func__); return ret; } @@ -222,6 +246,7 @@ napi_value InsertAsync( NAPI_CALL(env, napi_queue_async_work(env, insertCB->cbBase.asyncWork)); napi_value result = 0; NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end", __func__); return result; } @@ -248,6 +273,7 @@ napi_value InsertPromise(napi_env env, DAHelperInsertCB *insertCB) (void *)insertCB, &insertCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, insertCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end", __func__); return promise; } @@ -258,8 +284,10 @@ void InsertExecuteCB(napi_env env, void *data) if (insertCB->dataAbilityHelper != nullptr) { OHOS::Uri uri(insertCB->uri); insertCB->result = insertCB->dataAbilityHelper->Insert(uri, insertCB->valueBucket); - // insertCB->dataAbilityHelper->NotifyChange(uri); + } else { + HILOG_ERROR("NAPI_Insert, dataAbilityHelper == nullptr."); } + HILOG_INFO("NAPI_Insert, worker pool thread execute end."); } void InsertAsyncCompleteCB(napi_env env, napi_status status, void *data) @@ -283,6 +311,7 @@ void InsertAsyncCompleteCB(napi_env env, napi_status status, void *data) NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); delete insertCB; insertCB = nullptr; + HILOG_INFO("NAPI_Insert, main event thread complete end."); } void InsertPromiseCompleteCB(napi_env env, napi_status status, void *data) @@ -295,6 +324,7 @@ void InsertPromiseCompleteCB(napi_env env, napi_status status, void *data) NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); delete insertCB; insertCB = nullptr; + HILOG_INFO("NAPI_Insert, main event thread complete end."); } /** @@ -316,23 +346,1948 @@ napi_value UnwrapValuesBucket(std::string &value, napi_env env, napi_value args) return nullptr; } - napi_value jsObject = nullptr; - jsObject = GetPropertyValueByPropertyName(env, args, "valueBucket", napi_object); - if (jsObject == nullptr) { - HILOG_ERROR("%{public}s, jsObject == nullptr.", __func__); - return nullptr; - } - std::string strValue = ""; - if (UnwrapStringByPropertyName(env, jsObject, "value", strValue)) { + if (UnwrapStringByPropertyName(env, args, "value", strValue)) { HILOG_INFO("%{public}s,strValue=%{public}s", __func__, strValue.c_str()); value = strValue; + } else { + HILOG_ERROR("%{public}s, value == nullptr.", __func__); + return nullptr; } napi_value result; NAPI_CALL(env, napi_create_int32(env, 1, &result)); + HILOG_INFO("%{public}s,end", __func__); + return result; +} + +napi_value NAPI_GetType(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DAHelperGetTypeCB *gettypeCB = new (std::nothrow) DAHelperGetTypeCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = nullptr, + }; + + napi_value ret = GetTypeWrap(env, info, gettypeCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (gettypeCB != nullptr) { + delete gettypeCB; + gettypeCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value GetTypeWrap(napi_env env, napi_callback_info info, DAHelperGetTypeCB *gettypeCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_TWO; + const size_t argcPromise = ARGS_ONE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + gettypeCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, gettypeCB->uri.c_str()); + } else { + HILOG_ERROR("%{public}s, Wrong argument type.", __func__); + return nullptr; + } + + DataAbilityHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); + gettypeCB->dataAbilityHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = GetTypeAsync(env, args, argcAsync, argcPromise, gettypeCB); + } else { + ret = GetTypePromise(env, gettypeCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value GetTypeAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperGetTypeCB *gettypeCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || gettypeCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &gettypeCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetTypeExecuteCB, + GetTypeAsyncCompleteCB, + (void *)gettypeCB, + &gettypeCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, gettypeCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end", __func__); + return result; +} + +napi_value GetTypePromise(napi_env env, DAHelperGetTypeCB *gettypeCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (gettypeCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + gettypeCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetTypeExecuteCB, + GetTypePromiseCompleteCB, + (void *)gettypeCB, + &gettypeCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, gettypeCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void GetTypeExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_GetType, worker pool thread execute."); + DAHelperGetTypeCB *gettypeCB = (DAHelperGetTypeCB *)data; + if (gettypeCB->dataAbilityHelper != nullptr) { + OHOS::Uri uri(gettypeCB->uri); + gettypeCB->result = gettypeCB->dataAbilityHelper->GetType(uri); + } else { + HILOG_ERROR("NAPI_GetType, dataAbilityHelper == nullptr."); + } + HILOG_INFO("NAPI_GetType, worker pool thread execute end."); +} + +void GetTypeAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetType, main event thread complete."); + DAHelperGetTypeCB *gettypeCB = (DAHelperGetTypeCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, gettypeCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + napi_create_string_utf8(env, gettypeCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1]); + + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (gettypeCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, gettypeCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, gettypeCB->cbBase.asyncWork)); + delete gettypeCB; + gettypeCB = nullptr; + HILOG_INFO("NAPI_GetType, main event thread complete end."); +} + +void GetTypePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetType, main event thread complete."); + DAHelperGetTypeCB *gettypeCB = (DAHelperGetTypeCB *)data; + napi_value result = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, gettypeCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, gettypeCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, gettypeCB->cbBase.asyncWork)); + delete gettypeCB; + gettypeCB = nullptr; + HILOG_INFO("NAPI_GetType, main event thread complete end."); +} + +napi_value NAPI_GetFileTypes(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DAHelperGetFileTypesCB *getfiletypesCB = new (std::nothrow) DAHelperGetFileTypesCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = nullptr, + }; + + napi_value ret = GetFileTypesWrap(env, info, getfiletypesCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (getfiletypesCB != nullptr) { + delete getfiletypesCB; + getfiletypesCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value GetFileTypesWrap(napi_env env, napi_callback_info info, DAHelperGetFileTypesCB *getfiletypesCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + getfiletypesCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, getfiletypesCB->uri.c_str()); + } + + NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); + if (valuetype == napi_string) { + getfiletypesCB->mimeTypeFilter = NapiValueToStringUtf8(env, args[PARAM1]); + HILOG_INFO("%{public}s,mimeTypeFilter=%{public}s", __func__, getfiletypesCB->mimeTypeFilter.c_str()); + } + + DataAbilityHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); + getfiletypesCB->dataAbilityHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = GetFileTypesAsync(env, args, argcAsync, argcPromise, getfiletypesCB); + } else { + ret = GetFileTypesPromise(env, getfiletypesCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} +napi_value GetFileTypesAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperGetFileTypesCB *getfiletypesCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || getfiletypesCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &getfiletypesCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetFileTypesExecuteCB, + GetFileTypesAsyncCompleteCB, + (void *)getfiletypesCB, + &getfiletypesCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, getfiletypesCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); return result; } +napi_value GetFileTypesPromise(napi_env env, DAHelperGetFileTypesCB *getfiletypesCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (getfiletypesCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + getfiletypesCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetFileTypesExecuteCB, + GetFileTypesPromiseCompleteCB, + (void *)getfiletypesCB, + &getfiletypesCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, getfiletypesCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void GetFileTypesExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_GetFileTypes, worker pool thread execute."); + DAHelperGetFileTypesCB *getfiletypesCB = (DAHelperGetFileTypesCB *)data; + if (getfiletypesCB->dataAbilityHelper != nullptr) { + OHOS::Uri uri(getfiletypesCB->uri); + HILOG_INFO("NAPI_GetFileTypes, uri:%{public}s", uri.ToString().c_str()); + HILOG_INFO("NAPI_GetFileTypes, mimeTypeFilter:%{public}s", getfiletypesCB->mimeTypeFilter.c_str()); + getfiletypesCB->result = getfiletypesCB->dataAbilityHelper->GetFileTypes(uri, getfiletypesCB->mimeTypeFilter); + } else { + HILOG_INFO("NAPI_GetFileTypes, dataAbilityHelper == nullptr."); + } + HILOG_INFO("NAPI_GetFileTypes, worker pool thread execute end."); +} + +void GetFileTypesAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetFileTypes, main event thread complete."); + DAHelperGetFileTypesCB *getfiletypesCB = (DAHelperGetFileTypesCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, getfiletypesCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + result[PARAM1] = WrapGetFileTypesCB(env, *getfiletypesCB); + + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (getfiletypesCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, getfiletypesCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, getfiletypesCB->cbBase.asyncWork)); + delete getfiletypesCB; + getfiletypesCB = nullptr; + HILOG_INFO("NAPI_GetFileTypes, main event thread complete end."); +} + +napi_value WrapGetFileTypesCB(napi_env env, const DAHelperGetFileTypesCB &getfiletypesCB) +{ + HILOG_INFO("WrapGetFileTypesCB, called."); + HILOG_INFO("NAPI_GetFileTypes, result.size:%{public}d", getfiletypesCB.result.size()); + for (size_t i = 0; i < getfiletypesCB.result.size(); i++) { + HILOG_INFO("NAPI_GetFileTypes, result[%{public}d]:%{public}s", i, getfiletypesCB.result.at(i).c_str()); + } + napi_value proValue = nullptr; + + napi_value jsArrayresult = nullptr; + NAPI_CALL(env, napi_create_array(env, &jsArrayresult)); + for (size_t i = 0; i < getfiletypesCB.result.size(); i++) { + proValue = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, getfiletypesCB.result.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_element(env, jsArrayresult, i, proValue)); + } + HILOG_INFO("WrapGetFileTypesCB, end."); + return jsArrayresult; +} + +void GetFileTypesPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetFileTypes, main event thread complete."); + DAHelperGetFileTypesCB *getfiletypesCB = (DAHelperGetFileTypesCB *)data; + napi_value result = nullptr; + + result = WrapGetFileTypesCB(env, *getfiletypesCB); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, getfiletypesCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, getfiletypesCB->cbBase.asyncWork)); + delete getfiletypesCB; + getfiletypesCB = nullptr; + HILOG_INFO("NAPI_GetFileTypes, main event thread complete end."); +} + +napi_value NAPI_NormalizeUri(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DAHelperNormalizeUriCB *normalizeuriCB = new (std::nothrow) DAHelperNormalizeUriCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = nullptr, + }; + + napi_value ret = NormalizeUriWrap(env, info, normalizeuriCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (normalizeuriCB != nullptr) { + delete normalizeuriCB; + normalizeuriCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value NormalizeUriWrap(napi_env env, napi_callback_info info, DAHelperNormalizeUriCB *normalizeuriCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_TWO; + const size_t argcPromise = ARGS_ONE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + normalizeuriCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, normalizeuriCB->uri.c_str()); + } + + DataAbilityHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); + normalizeuriCB->dataAbilityHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = NormalizeUriAsync(env, args, argcAsync, argcPromise, normalizeuriCB); + } else { + ret = NormalizeUriPromise(env, normalizeuriCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} +napi_value NormalizeUriAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperNormalizeUriCB *normalizeuriCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || normalizeuriCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &normalizeuriCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + NormalizeUriExecuteCB, + NormalizeUriAsyncCompleteCB, + (void *)normalizeuriCB, + &normalizeuriCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, normalizeuriCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value NormalizeUriPromise(napi_env env, DAHelperNormalizeUriCB *normalizeuriCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (normalizeuriCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + normalizeuriCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + NormalizeUriExecuteCB, + NormalizeUriPromiseCompleteCB, + (void *)normalizeuriCB, + &normalizeuriCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, normalizeuriCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void NormalizeUriExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_NormalizeUri, worker pool thread execute."); + DAHelperNormalizeUriCB *normalizeuriCB = (DAHelperNormalizeUriCB *)data; + Uri uriValue(normalizeuriCB->uri); + if (normalizeuriCB->dataAbilityHelper != nullptr) { + OHOS::Uri uri(normalizeuriCB->uri); + uriValue = normalizeuriCB->dataAbilityHelper->NormalizeUri(uri); + normalizeuriCB->result = uriValue.ToString(); + } else { + HILOG_INFO("NAPI_NormalizeUri, dataAbilityHelper == nullptr"); + } + HILOG_INFO("NAPI_NormalizeUri, worker pool thread execute end."); +} + +void NormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_NormalizeUri, main event thread complete."); + DAHelperNormalizeUriCB *normalizeuriCB = (DAHelperNormalizeUriCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, normalizeuriCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, normalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); + + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (normalizeuriCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, normalizeuriCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, normalizeuriCB->cbBase.asyncWork)); + delete normalizeuriCB; + normalizeuriCB = nullptr; + HILOG_INFO("NAPI_NormalizeUri, main event thread complete end."); +} + +void NormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_NormalizeUri, main event thread complete."); + DAHelperNormalizeUriCB *normalizeuriCB = (DAHelperNormalizeUriCB *)data; + napi_value result = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, normalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, normalizeuriCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, normalizeuriCB->cbBase.asyncWork)); + delete normalizeuriCB; + normalizeuriCB = nullptr; + HILOG_INFO("NAPI_NormalizeUri, main event thread complete end."); +} + +napi_value NAPI_DenormalizeUri(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DAHelperDenormalizeUriCB *denormalizeuriCB = new (std::nothrow) DAHelperDenormalizeUriCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = nullptr, + }; + + napi_value ret = DenormalizeUriWrap(env, info, denormalizeuriCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (denormalizeuriCB != nullptr) { + delete denormalizeuriCB; + denormalizeuriCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value DenormalizeUriWrap(napi_env env, napi_callback_info info, DAHelperDenormalizeUriCB *denormalizeuriCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_TWO; + const size_t argcPromise = ARGS_ONE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + denormalizeuriCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, denormalizeuriCB->uri.c_str()); + } + + DataAbilityHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); + denormalizeuriCB->dataAbilityHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = DenormalizeUriAsync(env, args, argcAsync, argcPromise, denormalizeuriCB); + } else { + ret = DenormalizeUriPromise(env, denormalizeuriCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} +napi_value DenormalizeUriAsync(napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, + DAHelperDenormalizeUriCB *denormalizeuriCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || denormalizeuriCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &denormalizeuriCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + DenormalizeUriExecuteCB, + DenormalizeUriAsyncCompleteCB, + (void *)denormalizeuriCB, + &denormalizeuriCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, denormalizeuriCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value DenormalizeUriPromise(napi_env env, DAHelperDenormalizeUriCB *denormalizeuriCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (denormalizeuriCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + denormalizeuriCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + DenormalizeUriExecuteCB, + DenormalizeUriPromiseCompleteCB, + (void *)denormalizeuriCB, + &denormalizeuriCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, denormalizeuriCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void DenormalizeUriExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_DenormalizeUri, worker pool thread execute."); + DAHelperDenormalizeUriCB *denormalizeuriCB = (DAHelperDenormalizeUriCB *)data; + Uri uriValue(denormalizeuriCB->uri); + if (denormalizeuriCB->dataAbilityHelper != nullptr) { + OHOS::Uri uri(denormalizeuriCB->uri); + uriValue = denormalizeuriCB->dataAbilityHelper->DenormalizeUri(uri); + denormalizeuriCB->result = uriValue.ToString(); + } else { + HILOG_ERROR("NAPI_DenormalizeUri, dataAbilityHelper == nullptr"); + } + HILOG_INFO("NAPI_DenormalizeUri, worker pool thread execute end."); +} + +void DenormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_DenormalizeUri, main event thread complete."); + DAHelperDenormalizeUriCB *denormalizeuriCB = (DAHelperDenormalizeUriCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, denormalizeuriCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, denormalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); + + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (denormalizeuriCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, denormalizeuriCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, denormalizeuriCB->cbBase.asyncWork)); + delete denormalizeuriCB; + denormalizeuriCB = nullptr; + HILOG_INFO("NAPI_DenormalizeUri, main event thread complete end."); +} + +void DenormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_DenormalizeUri, main event thread complete."); + DAHelperDenormalizeUriCB *denormalizeuriCB = (DAHelperDenormalizeUriCB *)data; + napi_value result = nullptr; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, denormalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, denormalizeuriCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, denormalizeuriCB->cbBase.asyncWork)); + delete denormalizeuriCB; + denormalizeuriCB = nullptr; + HILOG_INFO("NAPI_DenormalizeUri, main event thread complete end."); +} + +napi_value UnwrapDataAbilityPredicates(std::string &value, napi_env env, napi_value args) +{ + HILOG_INFO("%{public}s,called", __func__); + napi_valuetype valueType = napi_undefined; + napi_typeof(env, args, &valueType); + if (valueType != napi_object) { + HILOG_ERROR("%{public}s, valueType != napi_object.", __func__); + return nullptr; + } + + std::string strValue = ""; + if (UnwrapStringByPropertyName(env, args, "value", strValue)) { + HILOG_INFO("%{public}s,strValue=%{public}s", __func__, strValue.c_str()); + value = strValue; + } else { + HILOG_ERROR("%{public}s, value == nullptr.", __func__); + return nullptr; + } + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + HILOG_INFO("%{public}s,end", __func__); + return result; +} + +/** + * @brief DataAbilityHelper NAPI method : insert. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_Delete(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DAHelperDeleteCB *deleteCB = new (std::nothrow) DAHelperDeleteCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = nullptr, + }; + + napi_value ret = DeleteWrap(env, info, deleteCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (deleteCB != nullptr) { + delete deleteCB; + deleteCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +/** + * @brief Insert processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value DeleteWrap(napi_env env, napi_callback_info info, DAHelperDeleteCB *deleteCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + deleteCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, deleteCB->uri.c_str()); + } + + std::string strValue; + UnwrapDataAbilityPredicates(strValue, env, args[PARAM1]); + HILOG_INFO("%{public}s,valueBucket=%{public}s", __func__, strValue.c_str()); + DataAbilityPredicates dataAbpredicates(strValue); + deleteCB->predicates = DataAbilityPredicates(dataAbpredicates); + + DataAbilityHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); + deleteCB->dataAbilityHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = DeleteAsync(env, args, argcAsync, argcPromise, deleteCB); + } else { + ret = DeletePromise(env, deleteCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value DeleteAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperDeleteCB *deleteCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || deleteCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &deleteCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + DeleteExecuteCB, + DeleteAsyncCompleteCB, + (void *)deleteCB, + &deleteCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, deleteCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value DeletePromise(napi_env env, DAHelperDeleteCB *deleteCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (deleteCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + deleteCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + DeleteExecuteCB, + DeletePromiseCompleteCB, + (void *)deleteCB, + &deleteCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, deleteCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void DeleteExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_Delete, worker pool thread execute."); + DAHelperDeleteCB *deleteCB = (DAHelperDeleteCB *)data; + if (deleteCB->dataAbilityHelper != nullptr) { + OHOS::Uri uri(deleteCB->uri); + deleteCB->result = deleteCB->dataAbilityHelper->Delete(uri, deleteCB->predicates); + } else { + HILOG_ERROR("NAPI_Delete, dataAbilityHelper == nullptr"); + } + HILOG_INFO("NAPI_Delete, worker pool thread execute end."); +} + +void DeleteAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Delete, main event thread complete."); + DAHelperDeleteCB *DeleteCB = (DAHelperDeleteCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, DeleteCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + napi_create_int32(env, DeleteCB->result, &result[PARAM1]); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (DeleteCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, DeleteCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, DeleteCB->cbBase.asyncWork)); + delete DeleteCB; + DeleteCB = nullptr; + HILOG_INFO("NAPI_Delete, main event thread complete end."); +} + +void DeletePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Delete, main event thread complete."); + DAHelperDeleteCB *DeleteCB = (DAHelperDeleteCB *)data; + napi_value result = nullptr; + napi_create_int32(env, DeleteCB->result, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, DeleteCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, DeleteCB->cbBase.asyncWork)); + delete DeleteCB; + DeleteCB = nullptr; + HILOG_INFO("NAPI_Delete, main event thread complete end."); +} + +/** + * @brief DataAbilityHelper NAPI method : insert. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_Update(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DAHelperUpdateCB *updateCB = new (std::nothrow) DAHelperUpdateCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = nullptr, + }; + + napi_value ret = UpdateWrap(env, info, updateCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (updateCB != nullptr) { + delete updateCB; + updateCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +/** + * @brief Insert processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value UpdateWrap(napi_env env, napi_callback_info info, DAHelperUpdateCB *updateCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_FOUR; + const size_t argcPromise = ARGS_THREE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + updateCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, updateCB->uri.c_str()); + } + + std::string strValue; + UnwrapValuesBucket(strValue, env, args[PARAM1]); + HILOG_INFO("%{public}s,ValuesBucket=%{public}s", __func__, strValue.c_str()); + ValuesBucket valueBucket(strValue); + updateCB->valueBucket = ValuesBucket(valueBucket); + + std::string strValue2; + UnwrapDataAbilityPredicates(strValue2, env, args[PARAM2]); + HILOG_INFO("%{public}s,DataAbilityPredicates=%{public}s", __func__, strValue2.c_str()); + DataAbilityPredicates dataAbpredicates(strValue2); + updateCB->predicates = DataAbilityPredicates(dataAbpredicates); + + DataAbilityHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); + updateCB->dataAbilityHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = UpdateAsync(env, args, argcAsync, argcPromise, updateCB); + } else { + ret = UpdatePromise(env, updateCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value UpdateAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperUpdateCB *updateCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || updateCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &updateCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + UpdateExecuteCB, + UpdateAsyncCompleteCB, + (void *)updateCB, + &updateCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, updateCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value UpdatePromise(napi_env env, DAHelperUpdateCB *updateCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (updateCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + updateCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + UpdateExecuteCB, + UpdatePromiseCompleteCB, + (void *)updateCB, + &updateCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, updateCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void UpdateExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_Update, worker pool thread execute."); + DAHelperUpdateCB *updateCB = (DAHelperUpdateCB *)data; + if (updateCB->dataAbilityHelper != nullptr) { + OHOS::Uri uri(updateCB->uri); + updateCB->result = updateCB->dataAbilityHelper->Update(uri, updateCB->valueBucket, updateCB->predicates); + } else { + HILOG_ERROR("NAPI_Update, dataAbilityHelper == nullptr"); + } + HILOG_INFO("NAPI_Update, worker pool thread execute end."); +} + +void UpdateAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Update, main event thread complete."); + DAHelperUpdateCB *updateCB = (DAHelperUpdateCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, updateCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + napi_create_int32(env, updateCB->result, &result[PARAM1]); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (updateCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, updateCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); + delete updateCB; + updateCB = nullptr; + HILOG_INFO("NAPI_Update, main event thread complete end."); +} + +void UpdatePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Update, main event thread complete."); + DAHelperUpdateCB *updateCB = (DAHelperUpdateCB *)data; + napi_value result = nullptr; + napi_create_int32(env, updateCB->result, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, updateCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); + delete updateCB; + updateCB = nullptr; + HILOG_INFO("NAPI_Update, main event thread complete end."); +} + +/** + * @brief DataAbilityHelper NAPI method : insert. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_OpenFile(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DAHelperOpenFileCB *openFileCB = new (std::nothrow) DAHelperOpenFileCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = nullptr, + }; + + napi_value ret = OpenFileWrap(env, info, openFileCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (openFileCB != nullptr) { + delete openFileCB; + openFileCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +/** + * @brief Insert processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value OpenFileWrap(napi_env env, napi_callback_info info, DAHelperOpenFileCB *openFileCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + openFileCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, openFileCB->uri.c_str()); + } + + NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); + if (valuetype == napi_string) { + openFileCB->mode = NapiValueToStringUtf8(env, args[PARAM1]); + HILOG_INFO("%{public}s,mode=%{public}s", __func__, openFileCB->mode.c_str()); + } + + DataAbilityHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); + openFileCB->dataAbilityHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = OpenFileAsync(env, args, argcAsync, argcPromise, openFileCB); + } else { + ret = OpenFilePromise(env, openFileCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value OpenFileAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperOpenFileCB *openFileCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || openFileCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &openFileCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + OpenFileExecuteCB, + OpenFileAsyncCompleteCB, + (void *)openFileCB, + &openFileCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, openFileCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value OpenFilePromise(napi_env env, DAHelperOpenFileCB *openFileCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (openFileCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + openFileCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + OpenFileExecuteCB, + OpenFilePromiseCompleteCB, + (void *)openFileCB, + &openFileCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, openFileCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void OpenFileExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_OpenFile, worker pool thread execute."); + DAHelperOpenFileCB *OpenFileCB = (DAHelperOpenFileCB *)data; + if (OpenFileCB->dataAbilityHelper != nullptr) { + OHOS::Uri uri(OpenFileCB->uri); + OpenFileCB->result = OpenFileCB->dataAbilityHelper->OpenFile(uri, OpenFileCB->mode); + } else { + HILOG_ERROR("NAPI_OpenFile, dataAbilityHelper == nullptr"); + } + HILOG_INFO("NAPI_OpenFile, worker pool thread execute end."); +} + +void OpenFileAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_OpenFile, main event thread complete."); + DAHelperOpenFileCB *OpenFileCB = (DAHelperOpenFileCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, OpenFileCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + napi_create_int32(env, OpenFileCB->result, &result[PARAM1]); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (OpenFileCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, OpenFileCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, OpenFileCB->cbBase.asyncWork)); + delete OpenFileCB; + OpenFileCB = nullptr; + HILOG_INFO("NAPI_OpenFile, main event thread complete end."); +} + +void OpenFilePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_OpenFileCB, main event thread complete."); + DAHelperOpenFileCB *OpenFileCB = (DAHelperOpenFileCB *)data; + napi_value result = nullptr; + napi_create_int32(env, OpenFileCB->result, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, OpenFileCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, OpenFileCB->cbBase.asyncWork)); + delete OpenFileCB; + OpenFileCB = nullptr; + HILOG_INFO("NAPI_OpenFileCB, main event thread complete end."); +} + +/** + * @brief DataAbilityHelper NAPI method : insert. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_BatchInsert(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DAHelperBatchInsertCB *BatchInsertCB = new (std::nothrow) DAHelperBatchInsertCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = nullptr, + }; + + napi_value ret = BatchInsertWrap(env, info, BatchInsertCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (BatchInsertCB != nullptr) { + delete BatchInsertCB; + BatchInsertCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +std::vector NapiValueObject(napi_env env, napi_value param) +{ + HILOG_INFO("%{public}s,called", __func__); + std::vector result; + UnwrapArrayObjectFromJS(env, param, result); + return result; +} + +bool UnwrapArrayObjectFromJS(napi_env env, napi_value param, std::vector &value) +{ + HILOG_INFO("%{public}s,called", __func__); + uint32_t arraySize = 0; + napi_value jsValue = nullptr; + std::string strValue = ""; + + if (!IsArrayForNapiValue(env, param, arraySize)) { + HILOG_INFO("%{public}s, IsArrayForNapiValue is false", __func__); + return false; + } + + value.clear(); + for (uint32_t i = 0; i < arraySize; i++) { + jsValue = nullptr; + strValue = ""; + if (napi_get_element(env, param, i, &jsValue) != napi_ok) { + HILOG_INFO("%{public}s, napi_get_element is false", __func__); + return false; + } + + UnwrapValuesBucket(strValue, env, jsValue); + ValuesBucket valueBucket(strValue); + + value.push_back(valueBucket); + } + HILOG_INFO("%{public}s,end", __func__); + return true; +} + +/** + * @brief Insert processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value BatchInsertWrap(napi_env env, napi_callback_info info, DAHelperBatchInsertCB *batchInsertCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + batchInsertCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, batchInsertCB->uri.c_str()); + } + + batchInsertCB->values = NapiValueObject(env, args[PARAM1]); + + DataAbilityHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); + batchInsertCB->dataAbilityHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = BatchInsertAsync(env, args, argcAsync, argcPromise, batchInsertCB); + } else { + ret = BatchInsertPromise(env, batchInsertCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value BatchInsertAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperBatchInsertCB *batchInsertCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || batchInsertCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &batchInsertCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + BatchInsertExecuteCB, + BatchInsertAsyncCompleteCB, + (void *)batchInsertCB, + &batchInsertCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, batchInsertCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value BatchInsertPromise(napi_env env, DAHelperBatchInsertCB *batchInsertCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (batchInsertCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + batchInsertCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + BatchInsertExecuteCB, + BatchInsertPromiseCompleteCB, + (void *)batchInsertCB, + &batchInsertCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, batchInsertCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void BatchInsertExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_BatchInsert, worker pool thread execute."); + DAHelperBatchInsertCB *batchInsertCB = (DAHelperBatchInsertCB *)data; + if (batchInsertCB->dataAbilityHelper != nullptr) { + OHOS::Uri uri(batchInsertCB->uri); + batchInsertCB->result = batchInsertCB->dataAbilityHelper->BatchInsert(uri, batchInsertCB->values); + } else { + HILOG_ERROR("NAPI_BatchInsert, dataAbilityHelper == nullptr"); + } + HILOG_INFO("NAPI_BatchInsert, worker pool thread execute end."); +} + +void BatchInsertAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_BatchInsert, main event thread complete."); + DAHelperBatchInsertCB *BatchInsertCB = (DAHelperBatchInsertCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, BatchInsertCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + napi_create_int32(env, BatchInsertCB->result, &result[PARAM1]); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (BatchInsertCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, BatchInsertCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, BatchInsertCB->cbBase.asyncWork)); + delete BatchInsertCB; + BatchInsertCB = nullptr; + HILOG_INFO("NAPI_BatchInsert, main event thread complete end."); +} + +void BatchInsertPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_BatchInsertCB, main event thread complete."); + DAHelperBatchInsertCB *BatchInsertCB = (DAHelperBatchInsertCB *)data; + napi_value result = nullptr; + napi_create_int32(env, BatchInsertCB->result, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, BatchInsertCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, BatchInsertCB->cbBase.asyncWork)); + delete BatchInsertCB; + BatchInsertCB = nullptr; + HILOG_INFO("NAPI_BatchInsertCB, main event thread complete end."); +} + +/** + * @brief DataAbilityHelper NAPI method : insert. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_Query(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DAHelperQueryCB *QueryCB = new (std::nothrow) DAHelperQueryCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = nullptr, + }; + + napi_value ret = QueryWrap(env, info, QueryCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (QueryCB != nullptr) { + delete QueryCB; + QueryCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +/** + * @brief Insert processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value QueryWrap(napi_env env, napi_callback_info info, DAHelperQueryCB *queryCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_FOUR; + const size_t argcPromise = ARGS_THREE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + queryCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, queryCB->uri.c_str()); + } + + std::vector result; + bool arrayStringbool = false; + arrayStringbool = NapiValueToArrayStringUtf8(env, args[PARAM1], result); + if (arrayStringbool == false) { + HILOG_ERROR("%{public}s, The return value of arraystringbool is false", __func__); + return nullptr; + } + queryCB->columns = result; + for (size_t i = 0; i < queryCB->columns.size(); i++) { + HILOG_INFO("%{public}s,columns=%{public}s", __func__, queryCB->columns.at(i).c_str()); + } + + std::string strValue; + UnwrapDataAbilityPredicates(strValue, env, args[PARAM2]); + HILOG_INFO("%{public}s,dataAbilityPredicates=%{public}s", __func__, strValue.c_str()); + DataAbilityPredicates dataAbilityPredicates(strValue); + queryCB->predicates = DataAbilityPredicates(dataAbilityPredicates); + + DataAbilityHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); + queryCB->dataAbilityHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = QueryAsync(env, args, argcAsync, argcPromise, queryCB); + } else { + ret = QueryPromise(env, queryCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value QueryAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperQueryCB *queryCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || queryCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &queryCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + QueryExecuteCB, + QueryAsyncCompleteCB, + (void *)queryCB, + &queryCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, queryCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value QueryPromise(napi_env env, DAHelperQueryCB *queryCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (queryCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + queryCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + QueryExecuteCB, + QueryPromiseCompleteCB, + (void *)queryCB, + &queryCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, queryCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void QueryPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_DAHelperQueryCB, main event thread complete."); + DAHelperQueryCB *QueryCB = (DAHelperQueryCB *)data; + napi_value result = nullptr; + result = WrapResultSet(env, QueryCB->result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, QueryCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, QueryCB->cbBase.asyncWork)); + delete QueryCB; + QueryCB = nullptr; + HILOG_INFO("NAPI_DAHelperQueryCB, main event thread complete end."); +} + +void QueryExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_Query, worker pool thread execute."); + DAHelperQueryCB *queryCB = (DAHelperQueryCB *)data; + std::shared_ptr resultset = nullptr; + if (queryCB->dataAbilityHelper != nullptr) { + OHOS::Uri uri(queryCB->uri); + resultset = queryCB->dataAbilityHelper->Query(uri, queryCB->columns, queryCB->predicates); + if (resultset != nullptr) { + queryCB->result.testInf_ = resultset->testInf_; + } else { + HILOG_INFO("NAPI_Query, resultset == nullptr."); + } + } else { + HILOG_ERROR("NAPI_Query, dataAbilityHelper == nullptr"); + } + HILOG_INFO("NAPI_Query, worker pool thread execute end."); +} + +void QueryAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Query, main event thread complete."); + DAHelperQueryCB *queryCB = (DAHelperQueryCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, queryCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + result[PARAM1] = WrapResultSet(env, queryCB->result); + + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (queryCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, queryCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, queryCB->cbBase.asyncWork)); + delete queryCB; + queryCB = nullptr; + HILOG_INFO("NAPI_Query, main event thread complete end."); +} + +napi_value WrapResultSet(napi_env env, const ResultSet &resultSet) +{ + HILOG_INFO("%{public}s,called", __func__); + napi_value result = nullptr; + napi_value proValue = nullptr; + NAPI_CALL(env, napi_create_object(env, &result)); + NAPI_CALL(env, napi_create_string_utf8(env, resultSet.testInf_.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "value", proValue)); + HILOG_INFO("%{public}s,end", __func__); + return result; +} + +napi_value NAPI_Release(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DAHelperReleaseCB *releaseCB = new (std::nothrow) DAHelperReleaseCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + }; + + napi_value ret = ReleaseWrap(env, info, releaseCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (releaseCB != nullptr) { + delete releaseCB; + releaseCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value ReleaseWrap(napi_env env, napi_callback_info info, DAHelperReleaseCB *releaseCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_TWO; + const size_t argcPromise = ARGS_ONE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = nullptr; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + DataAbilityHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("DataAbilityHelper ReleaseWrap objectInfo = %{public}p", objectInfo); + releaseCB->dataAbilityHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = ReleaseAsync(env, args, argcAsync, argcPromise, releaseCB); + } else { + ret = ReleasePromise(env, releaseCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value ReleaseAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperReleaseCB *releaseCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || releaseCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &releaseCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + ReleaseExecuteCB, + ReleaseAsyncCompleteCB, + (void *)releaseCB, + &releaseCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, releaseCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value ReleasePromise(napi_env env, DAHelperReleaseCB *releaseCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (releaseCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + releaseCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + ReleaseExecuteCB, + ReleasePromiseCompleteCB, + (void *)releaseCB, + &releaseCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, releaseCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void ReleaseExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_Release, worker pool thread execute."); + DAHelperReleaseCB *releaseCB = (DAHelperReleaseCB *)data; + if (releaseCB->dataAbilityHelper != nullptr) { + releaseCB->result = releaseCB->dataAbilityHelper->Release(); + } else { + HILOG_ERROR("NAPI_Release, dataAbilityHelper == nullptr"); + } + HILOG_INFO("NAPI_Release, worker pool thread execute end."); +} + +void ReleaseAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Release, main event thread complete."); + DAHelperReleaseCB *releaseCB = (DAHelperReleaseCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, releaseCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + napi_get_boolean(env, releaseCB->result, &result[PARAM1]); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (releaseCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, releaseCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, releaseCB->cbBase.asyncWork)); + delete releaseCB; + releaseCB = nullptr; + HILOG_INFO("NAPI_Release, main event thread complete end."); +} + +void ReleasePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Release, main event thread complete."); + DAHelperReleaseCB *releaseCB = (DAHelperReleaseCB *)data; + napi_value result = nullptr; + napi_get_boolean(env, releaseCB->result, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, releaseCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, releaseCB->cbBase.asyncWork)); + delete releaseCB; + releaseCB = nullptr; + HILOG_INFO("NAPI_Release, main event thread complete end."); +} + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.h b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.h index 52585b3e9b0..5289835da5b 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.h +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.h @@ -107,6 +107,141 @@ void InsertPromiseCompleteCB(napi_env env, napi_status status, void *data); * @return The return value from NAPI C++ to JS for the module. */ napi_value UnwrapValuesBucket(std::string &value, napi_env env, napi_value args); + +static std::vector registerInstances_; +napi_value NAPI_Release(napi_env env, napi_callback_info info); + +napi_value ReleaseWrap(napi_env env, napi_callback_info info, DAHelperReleaseCB *releaseCB); + +napi_value ReleaseAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperReleaseCB *releaseCB); + +napi_value ReleasePromise(napi_env env, DAHelperReleaseCB *releaseCB); + +void ReleaseExecuteCB(napi_env env, void *data); + +void ReleaseAsyncCompleteCB(napi_env env, napi_status status, void *data); + +void ReleasePromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_GetType(napi_env env, napi_callback_info info); +napi_value NAPI_GetType(napi_env env, napi_callback_info info); +napi_value GetTypeWrap(napi_env env, napi_callback_info info, DAHelperGetTypeCB *gettypeCB); +napi_value GetTypeAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperGetTypeCB *gettypeCB); +napi_value GetTypePromise(napi_env env, DAHelperGetTypeCB *gettypeCB); +void GetTypeExecuteCB(napi_env env, void *data); +void GetTypeAsyncCompleteCB(napi_env env, napi_status status, void *data); +void GetTypePromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_GetFileTypes(napi_env env, napi_callback_info info); +napi_value NAPI_GetFileTypes(napi_env env, napi_callback_info info); +napi_value GetFileTypesWrap(napi_env env, napi_callback_info info, DAHelperGetFileTypesCB *getfiletypesCB); +napi_value GetFileTypesAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperGetFileTypesCB *getfiletypesCB); +napi_value GetFileTypesPromise(napi_env env, DAHelperGetFileTypesCB *getfiletypesCB); +void GetFileTypesExecuteCB(napi_env env, void *data); +void GetFileTypesAsyncCompleteCB(napi_env env, napi_status status, void *data); +void GetFileTypesPromiseCompleteCB(napi_env env, napi_status status, void *data); +napi_value WrapGetFileTypesCB(napi_env env, const DAHelperGetFileTypesCB &getfiletypesCB); + +napi_value NAPI_NormalizeUri(napi_env env, napi_callback_info info); +napi_value NAPI_NormalizeUri(napi_env env, napi_callback_info info); +napi_value NormalizeUriWrap(napi_env env, napi_callback_info info, DAHelperNormalizeUriCB *normalizeuriCB); +napi_value NormalizeUriAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperNormalizeUriCB *normalizeuriCB); +napi_value NormalizeUriPromise(napi_env env, DAHelperNormalizeUriCB *normalizeuriCB); +void NormalizeUriExecuteCB(napi_env env, void *data); +void NormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data); +void NormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_DenormalizeUri(napi_env env, napi_callback_info info); +napi_value NAPI_DenormalizeUri(napi_env env, napi_callback_info info); +napi_value DenormalizeUriWrap(napi_env env, napi_callback_info info, DAHelperDenormalizeUriCB *denormalizeuriCB); +napi_value DenormalizeUriAsync(napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, + DAHelperDenormalizeUriCB *denormalizeuriCB); +napi_value DenormalizeUriPromise(napi_env env, DAHelperDenormalizeUriCB *denormalizeuriCB); +void DenormalizeUriExecuteCB(napi_env env, void *data); +void DenormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data); +void DenormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_Delete(napi_env env, napi_callback_info info); + +napi_value DeleteWrap(napi_env env, napi_callback_info info, DAHelperDeleteCB *deleteCB); +napi_value DeleteAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperDeleteCB *deleteCB); + +napi_value DeletePromise(napi_env env, DAHelperDeleteCB *deleteCB); + +void DeleteExecuteCB(napi_env env, void *data); + +void DeleteAsyncCompleteCB(napi_env env, napi_status status, void *data); + +void DeletePromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_Update(napi_env env, napi_callback_info info); + +napi_value UpdateWrap(napi_env env, napi_callback_info info, DAHelperUpdateCB *updateCB); +napi_value UpdateAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperUpdateCB *updateCB); + +napi_value UpdatePromise(napi_env env, DAHelperUpdateCB *updateCB); + +void UpdateExecuteCB(napi_env env, void *data); + +void UpdateAsyncCompleteCB(napi_env env, napi_status status, void *data); + +void UpdatePromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_OpenFile(napi_env env, napi_callback_info info); + +napi_value OpenFileWrap(napi_env env, napi_callback_info info, DAHelperOpenFileCB *openFileCB); +napi_value OpenFileAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperOpenFileCB *openFileCB); + +napi_value OpenFilePromise(napi_env env, DAHelperOpenFileCB *openFileCB); + +void OpenFileExecuteCB(napi_env env, void *data); + +void OpenFileAsyncCompleteCB(napi_env env, napi_status status, void *data); + +void OpenFilePromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_BatchInsert(napi_env env, napi_callback_info info); + +napi_value BatchInsertWrap(napi_env env, napi_callback_info info, DAHelperBatchInsertCB *batchInsertCB); +napi_value BatchInsertAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperBatchInsertCB *batchInsertCB); + +napi_value BatchInsertPromise(napi_env env, DAHelperBatchInsertCB *batchInsertCB); + +void BatchInsertExecuteCB(napi_env env, void *data); + +void BatchInsertAsyncCompleteCB(napi_env env, napi_status status, void *data); + +void BatchInsertPromiseCompleteCB(napi_env env, napi_status status, void *data); + +std::vector NapiValueObject(napi_env env, napi_value param); + +bool UnwrapArrayObjectFromJS(napi_env env, napi_value param, std::vector &value); + +napi_value NAPI_Query(napi_env env, napi_callback_info info); + +napi_value QueryWrap(napi_env env, napi_callback_info info, DAHelperQueryCB *queryCB); + +napi_value QueryAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperQueryCB *queryCB); + +napi_value QueryPromise(napi_env env, DAHelperQueryCB *queryCB); + +void QueryExecuteCB(napi_env env, void *data); + +void QueryAsyncCompleteCB(napi_env env, napi_status status, void *data); + +void QueryPromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value WrapResultSet(napi_env env, const ResultSet &resultSet); + } // namespace AppExecFwk } // namespace OHOS #endif /* OHOS_APPEXECFWK_NAPI_DATA_ABILITY_HELPER_H */ diff --git a/interfaces/kits/napi/aafwk/formAbility/BUILD.gn b/interfaces/kits/napi/aafwk/formAbility/BUILD.gn new file mode 100644 index 00000000000..8d81898f43d --- /dev/null +++ b/interfaces/kits/napi/aafwk/formAbility/BUILD.gn @@ -0,0 +1,47 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#import("//build/config/ohos/rules.gni") +import("//build/ohos.gni") +ohos_shared_library("form") { + include_dirs = [ + "//foundation/ace/napi/interfaces/kits", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/formAbility", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + ] + + sources = [ + "napi_form_ability.cpp", + "native_module.cpp", + ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/ace/napi:ace_napi", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/kits:appkit_native", + ] + + external_deps = [ + "aafwk_standard:ability_manager", + "aafwk_standard:want", + "hiviewdfx_hilog_native:libhilog", + ] + + relative_install_dir = "module" + + subsystem_name = "aafwk" + part_name = "aafwk_standard" +} diff --git a/interfaces/kits/napi/aafwk/formAbility/napi_form_ability.cpp b/interfaces/kits/napi/aafwk/formAbility/napi_form_ability.cpp new file mode 100644 index 00000000000..fe1078acb8c --- /dev/null +++ b/interfaces/kits/napi/aafwk/formAbility/napi_form_ability.cpp @@ -0,0 +1,3327 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "napi_form_ability.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include +#include +#include + +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace { + constexpr size_t ARGS_SIZE_ONE = 1; + constexpr size_t ARGS_SIZE_TWO = 2; + constexpr size_t ARGS_SIZE_THREE = 3; +} + +/** + * @brief Get a C++ string value from Node-API + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[in] value This is an opaque pointer that is used to represent a JavaScript value + * + * @return Return a C++ string + */ +static std::string GetStringFromNAPI(napi_env env, napi_value value) +{ + std::string result; + size_t size = 0; + + if (napi_get_value_string_utf8(env, value, nullptr, 0, &size) != napi_ok) { + HILOG_ERROR("%{public}s, can not get string size", __func__); + return ""; + } + result.reserve(size + 1); + result.resize(size); + if (napi_get_value_string_utf8(env, value, result.data(), (size + 1), &size) != napi_ok) { + HILOG_ERROR("%{public}s, can not get string value", __func__); + return ""; + } + return result; +} + +/** + * @brief NapiGetNull + * + * @param[in] env The environment that the Node-API call is invoked under + * + * @return napi_value + */ +napi_value NapiGetNull(napi_env env) +{ + napi_value result = 0; + napi_get_null(env, &result); + + return result; +} + +/** + * @brief Parse form info from JavaScript value + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] formReqInfo This is a C++ value, parsed from JavaScript + * @param[in] args This is an opaque pointer that is used to represent a JavaScript value + * + * @return Return an opaque pointer that is used to represent a JavaScript value + */ +static napi_value ParseNapiIntoFormInfo(napi_env env, + FormReqInfo &formReqInfo, + napi_value args) +{ + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, args, &valueType)); + NAPI_ASSERT(env, valueType == napi_object, "The arguments[0] type of acquireForm is incorrect,\ + expected type is object."); + + napi_value wantProp = nullptr; + napi_status status = napi_get_named_property(env, args, "want", &wantProp); + NAPI_ASSERT(env, status == napi_ok, "The arguments[0] info of acquireForm is incorrect,\ + expected key is want."); + + // elementName + napi_value elementNameProp = nullptr; + status = napi_get_named_property(env, wantProp, "elementName", &elementNameProp); + NAPI_ASSERT(env, status == napi_ok, "The arguments[0] want info of acquireForm is incorrect,\ + expected key is elementName."); + napi_typeof(env, elementNameProp, &valueType); + NAPI_ASSERT(env, valueType == napi_object, "The arguments[0] elementName type of acquireForm is incorrect,\ + expected type is object."); + + // elementName:deviceId property + napi_value prop = nullptr; + status = napi_get_named_property(env, elementNameProp, "deviceId", &prop); + NAPI_ASSERT(env, status == napi_ok, "The arguments[0] elementName info of acquireForm is incorrect,\ + expected key is deviceId."); + + napi_typeof(env, prop, &valueType); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] deviceId type of acquireForm is incorrect,\ + expected type is string."); + + formReqInfo.deviceId = GetStringFromNAPI(env, prop); + HILOG_DEBUG("%{public}s, acquireForm deviceId=%{public}s.", __func__, formReqInfo.deviceId.c_str()); + + // elementName:bundleName property + prop = nullptr; + status = napi_get_named_property(env, elementNameProp, "bundleName", &prop); + NAPI_ASSERT(env, status == napi_ok, "The arguments[0] elementName info of acquireForm is incorrect,\ + expected key is bundleName."); + napi_typeof(env, prop, &valueType); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] bundleName type of acquireForm is incorrect,\ + expected type is string."); + + formReqInfo.bundleName = GetStringFromNAPI(env, prop); + HILOG_DEBUG("%{public}s, acquireForm bundleName=%{public}s.", __func__, formReqInfo.bundleName.c_str()); + + // elementName:abilityName property + prop = nullptr; + status = napi_get_named_property(env, elementNameProp, "abilityName", &prop); + NAPI_ASSERT(env, status == napi_ok, "The arguments[0] elementName info of acquireForm is incorrect,\ + expected key is abilityName."); + + napi_typeof(env, prop, &valueType); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] abilityName type of acquireForm is incorrect,\ + expected type is string."); + + formReqInfo.abilityName = GetStringFromNAPI(env, prop); + HILOG_DEBUG("%{public}s, acquireForm abilityName=%{public}s.", __func__, formReqInfo.abilityName.c_str()); + + // formReqInfo:formId property + prop = nullptr; + status = napi_get_named_property(env, wantProp, "formId", &prop); + if(status == napi_ok ) { + napi_typeof(env, prop, &valueType); + HILOG_DEBUG("%{public}s, acquireForm formId type=%{public}d.", __func__, valueType); + + if(valueType == napi_undefined || valueType == napi_null) { + formReqInfo.formId = 0; + } else if (valueType == napi_number) { + status = napi_get_value_int64(env, prop, &formReqInfo.formId); + } else if (valueType == napi_string) { +// try { + std::string strFormId = GetStringFromNAPI(env, prop); + formReqInfo.formId = std::stoll(strFormId); + // } catch (const std::invalid_argument&) { + // NAPI_ASSERT(env, false, "The formId is incorrect, expected type is number, string, undefined OR null"); + // } catch (const std::out_of_range&) { + // NAPI_ASSERT(env, false, "The formId is incorrect, expected the value doesn't exceed 64 bits."); + // } catch (const std::exception &) { + // NAPI_ASSERT(env, false, "The formId is incorrect, expected type is number or string and no more than 64 bits."); + // } + } else { + NAPI_ASSERT(env, false, "The formId must be number, string, undefined OR null"); + } + } else { + formReqInfo.formId = 0; + } + HILOG_DEBUG("%{public}s, acquireForm formId=%{public}lld.", __func__, formReqInfo.formId); + + // formReqInfo:formName property + prop = nullptr; + status = napi_get_named_property(env, wantProp, "formName", &prop); + NAPI_ASSERT(env, status == napi_ok, "The arguments[0] want info of acquireForm is incorrect,\ + expected key is formName."); + + napi_typeof(env, prop, &valueType); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] formName type of acquireForm is incorrect,\ + expected type is string."); + + formReqInfo.formName = GetStringFromNAPI(env, prop); + HILOG_DEBUG("%{public}s, acquireForm formName=%{public}s.", __func__, formReqInfo.formName.c_str()); + + // formReqInfo:moduleName property + prop = nullptr; + status = napi_get_named_property(env, wantProp, "moduleName", &prop); + NAPI_ASSERT(env, status == napi_ok, "The arguments[0] want info of acquireForm is incorrect,\ + expected key is moduleName."); + napi_typeof(env, prop, &valueType); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] moduleName type of acquireForm is incorrect,\ + expected type is string."); + + formReqInfo.moduleName = GetStringFromNAPI(env, prop); + HILOG_DEBUG("%{public}s, acquireForm moduleName=%{public}s.", __func__, formReqInfo.moduleName.c_str()); + + // formReqInfo:tempFormFlag property + prop = nullptr; + status = napi_get_named_property(env, wantProp, "tempFormFlag", &prop); + NAPI_ASSERT(env, status == napi_ok, "The arguments[0] want info of acquireForm is incorrect,\ + expected key is tempFormFlag."); + + napi_typeof(env, prop, &valueType); + NAPI_ASSERT(env, valueType == napi_boolean, "The arguments[0] tempFormFlag type of acquireForm is incorrect,\ + expected type is boolean."); + + status = napi_get_value_bool(env, prop, &formReqInfo.tempFormFlag); + NAPI_ASSERT(env, status == napi_ok, "The arguments[0] tempFormFlag is incorrect,\ + get value failed."); + + HILOG_DEBUG("%{public}s, acquireForm tempFormFlag=%{public}d.", __func__, formReqInfo.tempFormFlag); + + // // formReqInfo:formWidth property + // prop = nullptr; + // status = napi_get_named_property(env, wantProp, "formWidth", &prop); + // NAPI_ASSERT(env, status == napi_ok, "The arguments[0] want info of acquireForm is incorrect,\ + // expected key is formWidth."); + // napi_typeof(env, prop, &valueType); + // NAPI_ASSERT(env, valueType == napi_number, "The arguments[0] formWidth type of acquireForm is incorrect,\ + // expected type is number."); + // status = napi_get_value_int32(env, prop, &formReqInfo.formWidth); + // NAPI_ASSERT(env, status == napi_ok, "The arguments[0] formWidth is incorrect,\ + // get value failed."); + // HILOG_DEBUG("%{public}s, acquireForm formWidth=%{public}d.", __func__, formReqInfo.formWidth); + + // // formReqInfo:formHeight property + // prop = nullptr; + // status = napi_get_named_property(env, wantProp, "formHeight", &prop); + // NAPI_ASSERT(env, status == napi_ok, "The arguments[0] want info of acquireForm is incorrect,\ + // expected key is formHeight."); + // napi_typeof(env, prop, &valueType); + // NAPI_ASSERT(env, valueType == napi_number, "The arguments[0] formHeight type of acquireForm is incorrect,\ + // expected type is number."); + // status = napi_get_value_int32(env, prop, &formReqInfo.formHeight); + // NAPI_ASSERT(env, status == napi_ok, "The arguments[0] formHeight is incorrect,\ + // get value failed."); + // HILOG_DEBUG("%{public}s, acquireForm formHeight=%{public}d.", __func__, formReqInfo.formHeight); + + // formReqInfo:formDimension property + prop = nullptr; + status = napi_get_named_property(env, wantProp, "formDimension", &prop); + NAPI_ASSERT(env, status == napi_ok, "The arguments[0] want info of acquireForm is incorrect,\ + expected key is formDimension."); + napi_typeof(env, prop, &valueType); + NAPI_ASSERT(env, valueType == napi_number, "The arguments[0] formDimension type of acquireForm is incorrect,\ + expected type is number."); + status = napi_get_value_int32(env, prop, &formReqInfo.formDimension); + NAPI_ASSERT(env, status == napi_ok, "The arguments[0] formDimension is incorrect,\ + get value failed."); + HILOG_DEBUG("%{public}s, acquireForm formDimension=%{public}d.", __func__, formReqInfo.formDimension); + + return NapiGetNull(env); +} + +/** + * @brief Parse arguments of the callback function from JavaScript value + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] jsCallbackInfo This is a C++ value, parsed from JavaScript + * @param[in] args This is an opaque pointer that is used to represent a JavaScript value + * + * @return Return an opaque pointer that is used to represent a JavaScript value + */ +static napi_value ParseJsObjectCallbackParam(napi_env env, + JsCallbackInfo &jsCallbackInfo, + napi_value args) +{ + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, args, &valueType)); + NAPI_ASSERT(env, valueType == napi_object, "The arguments[1] type of acquireForm is incorrect,\ + expected type is object."); + + napi_value callbackProp = nullptr; + napi_status status = napi_get_named_property(env, args, "callback", &callbackProp); + NAPI_ASSERT(env, status == napi_ok, "The arguments[1] callback of acquireForm is incorrect,\ + expected key is callback."); + + // get callback: onAcquired + napi_value prop = nullptr; + status = napi_get_named_property(env, callbackProp, "onAcquired", &prop); + NAPI_ASSERT(env, status == napi_ok, "The arguments[1] callback of acquireForm is incorrect,\ + expected key is onAcquired."); + + napi_typeof(env, prop, &valueType); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[1] type of onAcquired is incorrect,\ + expected type is function."); + + napi_create_reference(env, prop, 1, &jsCallbackInfo.onAcquired); + + // get callback: onError + prop = nullptr; + status = napi_get_named_property(env, callbackProp, "onError", &prop); + NAPI_ASSERT(env, status == napi_ok, "The arguments[1] callback of acquireForm is incorrect,\ + expected key is onError."); + + napi_typeof(env, prop, &valueType); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[1] type of onError is incorrect,\ + expected type is function."); + + napi_create_reference(env, prop, 1, &jsCallbackInfo.onError); + + HILOG_DEBUG("%{public}s end", __func__); + + return NapiGetNull(env); +} + +/** + * @brief Parse form JavaScript info into Node-API + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[in] formInfo it is used for return forminfo to JavaScript + * @param[out] result This is an opaque pointer that is used to represent a JavaScript value + * + * @return void + */ +static void ParseFormJsInfoIntoNapi(napi_env env, const FormJsInfo &formInfo, napi_value &result) +{ + // formId + napi_value formId; + std::string strFormId = std::to_string(formInfo.formId); + napi_create_string_utf8(env, strFormId.c_str(), NAPI_AUTO_LENGTH, &formId); + HILOG_DEBUG("%{public}s, formId=%{public}lld.", __func__, formInfo.formId); + napi_set_named_property(env, result, "formId", formId); + + // formName + napi_value formName; + napi_create_string_utf8(env, formInfo.formName.c_str(), NAPI_AUTO_LENGTH, &formName); + HILOG_DEBUG("%{public}s, formName=%{public}s.", __func__, formInfo.formName.c_str()); + napi_set_named_property(env, result, "formName", formName); + + // bundleName + napi_value bundleName; + napi_create_string_utf8(env, formInfo.bundleName.c_str(), NAPI_AUTO_LENGTH, &bundleName); + HILOG_DEBUG("%{public}s, bundleName=%{public}s.", __func__, formInfo.bundleName.c_str()); + napi_set_named_property(env, result, "bundleName", bundleName); + + // abilityName + napi_value abilityName; + napi_create_string_utf8(env, formInfo.abilityName.c_str(), NAPI_AUTO_LENGTH, &abilityName); + HILOG_DEBUG("%{public}s, abilityName=%{public}s.", __func__, formInfo.abilityName.c_str()); + napi_set_named_property(env, result, "abilityName", abilityName); + + // formTempFlg + napi_value formTempFlg; + napi_create_int32(env, formInfo.formTempFlg, &formTempFlg); + HILOG_DEBUG("%{public}s, formTempFlg=%{public}d.", __func__, formInfo.formTempFlg); + napi_set_named_property(env, result, "formTempFlg", formTempFlg); + + // htmlPath + napi_value htmlPath; + napi_create_string_utf8(env, formInfo.htmlPath.c_str(), NAPI_AUTO_LENGTH, &htmlPath); + HILOG_DEBUG("%{public}s, htmlPath=%{public}s.", __func__, formInfo.htmlPath.c_str()); + napi_set_named_property(env, result, "htmlPath", htmlPath); + + // cssPath + napi_value cssPath; + napi_create_string_utf8(env, formInfo.cssPath.c_str(), NAPI_AUTO_LENGTH, &cssPath); + HILOG_DEBUG("%{public}s, cssPath=%{public}s.", __func__, formInfo.cssPath.c_str()); + napi_set_named_property(env, result, "cssPath", cssPath); + + // jsPath + napi_value jsPath; + napi_create_string_utf8(env, formInfo.jsPath.c_str(), NAPI_AUTO_LENGTH, &jsPath); + HILOG_DEBUG("%{public}s, jsPath=%{public}s.", __func__, formInfo.jsPath.c_str()); + napi_set_named_property(env, result, "jsPath", jsPath); + + // fileReousePath + napi_value fileReousePath; + napi_create_string_utf8(env, formInfo.fileReousePath.c_str(), NAPI_AUTO_LENGTH, &fileReousePath); + HILOG_DEBUG("%{public}s, fileReousePath=%{public}s.", __func__, formInfo.fileReousePath.c_str()); + napi_set_named_property(env, result, "fileReousePath", fileReousePath); + + // formData + napi_value formData; + napi_create_string_utf8(env, formInfo.formData.c_str(), NAPI_AUTO_LENGTH, &formData); + HILOG_DEBUG("%{public}s, formData=%{public}s.", __func__, formInfo.formData.c_str()); + napi_set_named_property(env, result, "formData", formData); + + return; +} + +/** + * @brief Parse form info into Node-API + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[in] formInfo it is used for return forminfo to JavaScript + * @param[out] result This is an opaque pointer that is used to represent a JavaScript value + * + * @return void + */ +static void ParseFormInfoIntoNapi(napi_env env, const FormInfo &formInfo, napi_value &result) +{ + // bundleName + napi_value bundleName; + napi_create_string_utf8(env, formInfo.bundleName.c_str(), NAPI_AUTO_LENGTH, &bundleName); + HILOG_DEBUG("%{public}s, bundleName=%{public}s.", __func__, formInfo.bundleName.c_str()); + napi_set_named_property(env, result, "bundleName", bundleName); + + // moduleName + napi_value moduleName; + napi_create_string_utf8(env, formInfo.moduleName.c_str(), NAPI_AUTO_LENGTH, &moduleName); + HILOG_DEBUG("%{public}s, moduleName=%{public}s.", __func__, formInfo.moduleName.c_str()); + napi_set_named_property(env, result, "moduleName", moduleName); + + // abilityName + napi_value abilityName; + napi_create_string_utf8(env, formInfo.abilityName.c_str(), NAPI_AUTO_LENGTH, &abilityName); + HILOG_DEBUG("%{public}s, abilityName=%{public}s.", __func__, formInfo.abilityName.c_str()); + napi_set_named_property(env, result, "abilityName", abilityName); + + // name + napi_value name; + napi_create_string_utf8(env, formInfo.name.c_str(), NAPI_AUTO_LENGTH, &name); + HILOG_DEBUG("%{public}s, name=%{public}s.", __func__, formInfo.name.c_str()); + napi_set_named_property(env, result, "name", name); + + // description + napi_value description; + napi_create_string_utf8(env, formInfo.description.c_str(), NAPI_AUTO_LENGTH, &description); + HILOG_DEBUG("%{public}s, description=%{public}s.", __func__, formInfo.description.c_str()); + napi_set_named_property(env, result, "description", description); + + // descriptionId + napi_value descriptionId; + napi_create_int32(env, formInfo.descriptionId, &descriptionId); + HILOG_DEBUG("%{public}s, descriptionId=%{public}d.", __func__, formInfo.descriptionId); + napi_set_named_property(env, result, "descriptionId", descriptionId); + + // type + napi_value type; + FormType formType = formInfo.type; + napi_create_int32(env, (int32_t)formType, &type); + HILOG_DEBUG("%{public}s, formInfo_type=%{public}d.", __func__, (int32_t)formType); + napi_set_named_property(env, result, "type", type); + + // jsComponentName + napi_value jsComponentName; + napi_create_string_utf8(env, formInfo.jsComponentName.c_str(), NAPI_AUTO_LENGTH, &jsComponentName); + HILOG_DEBUG("%{public}s, jsComponentName=%{public}s.", __func__, formInfo.jsComponentName.c_str()); + napi_set_named_property(env, result, "jsComponentName", jsComponentName); + + // colorMode + napi_value colorMode; + FormsColorMode formsColorMode = formInfo.colorMode; + napi_create_int32(env, (int32_t)formsColorMode, &colorMode); + HILOG_DEBUG("%{public}s, formInfo_type=%{public}d.", __func__, (int32_t)formsColorMode); + napi_set_named_property(env, result, "colorMode", colorMode); + + // defaultFlag + napi_value defaultFlag; + napi_create_int32(env, (int32_t)formInfo.defaultFlag, &defaultFlag); + HILOG_DEBUG("%{public}s, defaultFlag=%{public}d.", __func__, formInfo.defaultFlag); + napi_set_named_property(env, result, "defaultFlag", defaultFlag); + + // formVisibleNotify + napi_value formVisibleNotify; + napi_create_int32(env, (int32_t)formInfo.formVisibleNotify, &formVisibleNotify); + HILOG_DEBUG("%{public}s, formVisibleNotify=%{public}d.", __func__, formInfo.formVisibleNotify); + napi_set_named_property(env, result, "formVisibleNotify", formVisibleNotify); + + // formConfigAbility + napi_value formConfigAbility; + napi_create_string_utf8(env, formInfo.formConfigAbility.c_str(), NAPI_AUTO_LENGTH, &formConfigAbility); + HILOG_DEBUG("%{public}s, formConfigAbility=%{public}s.", __func__, formInfo.formConfigAbility.c_str()); + napi_set_named_property(env, result, "formConfigAbility", formConfigAbility); + + // updateDuration + napi_value updateDuration; + napi_create_int32(env, formInfo.updateDuration, &updateDuration); + HILOG_DEBUG("%{public}s, updateDuration=%{public}d.", __func__, formInfo.updateDuration); + napi_set_named_property(env, result, "updateDuration", updateDuration); + + // defaultDimension + napi_value defaultDimension; + napi_create_int32(env, formInfo.defaultDimension, &defaultDimension); + HILOG_DEBUG("%{public}s, defaultDimension=%{public}d.", __func__, formInfo.defaultDimension); + napi_set_named_property(env, result, "defaultDimension", defaultDimension); + + // supportDimensions + napi_value supportDimensions; + napi_create_array(env, &supportDimensions); + int iDimensionsCount = 0; + for (auto dimension : formInfo.supportDimensions) { + napi_value dimensionInfo = nullptr; + napi_create_int32(env, dimension, &dimensionInfo); + napi_set_element(env, supportDimensions, iDimensionsCount, dimensionInfo); + ++iDimensionsCount; + } + HILOG_DEBUG("%{public}s, supportDimensions size=%{public}d.", __func__, formInfo.supportDimensions.size()); + napi_set_named_property(env, result, "supportDimensions", supportDimensions); + + // customizeDatas + napi_value customizeDatas; + napi_create_array(env, &customizeDatas); + int iCustomizeDatasCount = 0; + for (auto customizeData : formInfo.customizeDatas) { + + napi_value customizeDataInfo = nullptr; + napi_create_array(env, &customizeDataInfo); + + // customizeData : name + napi_value customizeDataName; + napi_create_string_utf8(env, customizeData.name.c_str(), NAPI_AUTO_LENGTH, &customizeDataName); + HILOG_DEBUG("%{public}s, customizeData.name=%{public}s.", __func__, customizeData.name.c_str()); + napi_set_named_property(env, customizeDataInfo, "name", customizeDataName); + + // customizeData : value + napi_value customizeDataValue; + napi_create_string_utf8(env, customizeData.value.c_str(), NAPI_AUTO_LENGTH, &customizeDataValue); + HILOG_DEBUG("%{public}s, customizeData.value=%{public}s.", __func__, customizeData.value.c_str()); + napi_set_named_property(env, customizeDataInfo, "value", customizeDataValue); + + napi_set_element(env, customizeDatas, iCustomizeDatasCount, customizeDataInfo); + ++iDimensionsCount; + } + HILOG_DEBUG("%{public}s, customizeDatas size=%{public}d.", __func__, formInfo.customizeDatas.size()); + napi_set_named_property(env, result, "supportDimensions", customizeDatas); + + // relatedBundleName + napi_value relatedBundleName; + napi_create_string_utf8(env, formInfo.relatedBundleName.c_str(), NAPI_AUTO_LENGTH, &relatedBundleName); + HILOG_DEBUG("%{public}s, relatedBundleName=%{public}s.", __func__, formInfo.relatedBundleName.c_str()); + napi_set_named_property(env, result, "relatedBundleName", relatedBundleName); + + return; +} + +/** + * @brief Receive the native kit reply and trigger JavaScript function object to be called from Node-API + * + * @param[in] result Receive the result from the native kit + * @param[in] formInfo This C++ forminfo will be parsed by JavaScript + * + * @return void + */ +void NapiFormAbility::OnAcquired(const int32_t result, const OHOS::AppExecFwk::FormJsInfo &formJsInfo) const +{ + HILOG_INFO("%{public}s called, OnAcquired result[%{public}d] env[%{public}p]", + __func__, result, jsCallbackInfomation.env); + + uv_loop_s *loop = nullptr; + +#if NAPI_VERSION >= 2 + HILOG_INFO("%{public}s called, napi_get_uv_event_loop start", __func__); + napi_get_uv_event_loop(jsCallbackInfomation.env, &loop); + HILOG_INFO("%{public}s called, napi_get_uv_event_loop end", __func__); +#endif // NAPI_VERSION >= 2 + + AddFormCallbackInfo *addFormCallbackInfo = new + (std::nothrow) AddFormCallbackInfo { + .jsCallbackInfo = jsCallbackInfomation, + .result = result, + .formInfo = formJsInfo, + .asyncWork = nullptr, + }; + + uv_work_t *work = new uv_work_t; + work->data = (void *)addFormCallbackInfo; + HILOG_INFO("%{public}s called, start uv_queue_work", __func__); + uv_queue_work( + loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + HILOG_INFO("%{public}s, uv_queue_work enter", __func__); + + AddFormCallbackInfo *event = (AddFormCallbackInfo *)work->data; + if(event->result == 0) { + napi_value result; + napi_create_object(event->jsCallbackInfo.env, &result); + ParseFormJsInfoIntoNapi(event->jsCallbackInfo.env, event->formInfo, result); + napi_value callback = 0; + if(event->jsCallbackInfo.onAcquired == NULL) { + HILOG_ERROR("%{public}s, AcquireForm uv_queue_work onAcquired == NULL", __func__); + } + + napi_get_reference_value(event->jsCallbackInfo.env, event->jsCallbackInfo.onAcquired, &callback); + napi_value callResult = 0; + napi_value undefined = 0; + napi_get_undefined(event->jsCallbackInfo.env, &undefined); + napi_call_function(event->jsCallbackInfo.env, undefined, callback, 1, &result, &callResult); + } else { + napi_value result; + napi_create_int32(event->jsCallbackInfo.env, event->result, &result); + napi_value callback = 0; + napi_get_reference_value(event->jsCallbackInfo.env, event->jsCallbackInfo.onError, &callback); + napi_value callResult = 0; + napi_value undefined = 0; + napi_get_undefined(event->jsCallbackInfo.env, &undefined); + napi_call_function(event->jsCallbackInfo.env, undefined, callback, 1, &result, &callResult); + } + + delete event; + delete work; + HILOG_INFO("%{public}s, uv_queue_work end", __func__); + }); + + return; + +} + +/** + * @brief Receive the native kit reply and trigger JavaScript function object to be called from Node-API + * + * @param[in] result Receive the result from the native kit + * @param[in] formInfo This C++ forminfo will be parsed by JavaScript + * + * @return void + */ +void NapiFormAbility::OnUpdate(const int32_t result, const OHOS::AppExecFwk::FormJsInfo &formJsInfo) const +{ + HILOG_INFO("%{public}s called, OnUpdate result[%{public}d] env[%{public}p]", + __func__, result, jsCallbackInfomation.env); + + uv_loop_s *loop = nullptr; + +#if NAPI_VERSION >= 2 + HILOG_INFO("%{public}s called, napi_get_uv_event_loop start", __func__); + napi_get_uv_event_loop(jsCallbackInfomation.env, &loop); + HILOG_INFO("%{public}s called, napi_get_uv_event_loop end", __func__); +#endif // NAPI_VERSION >= 2 + + AddFormCallbackInfo *addFormCallbackInfo = new + (std::nothrow) AddFormCallbackInfo { + .jsCallbackInfo = jsCallbackInfomation, + .result = result, + .formInfo = formJsInfo, + .asyncWork = nullptr, + }; + + uv_work_t *work = new uv_work_t; + work->data = (void *)addFormCallbackInfo; + + HILOG_INFO("%{public}s called, start uv_queue_work", __func__); + + uv_queue_work( + loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + HILOG_INFO("%{public}s, uv_queue_work enter", __func__); + + AddFormCallbackInfo *event = (AddFormCallbackInfo *)work->data; + if(event->result == 0) { + napi_value result; + napi_create_object(event->jsCallbackInfo.env, &result); + ParseFormJsInfoIntoNapi(event->jsCallbackInfo.env, event->formInfo, result); + napi_value callback = 0; + if(event->jsCallbackInfo.onAcquired == NULL) { + HILOG_ERROR("%{public}s, uv_queue_work onAcquired == NULL", __func__); + } + + napi_get_reference_value(event->jsCallbackInfo.env, event->jsCallbackInfo.onAcquired, &callback); + napi_value callResult = 0; + napi_value undefined = 0; + napi_get_undefined(event->jsCallbackInfo.env, &undefined); + napi_call_function(event->jsCallbackInfo.env, undefined, callback, 1, &result, &callResult); + } else { + napi_value result; + napi_create_int32(event->jsCallbackInfo.env, event->result, &result); + napi_value callback = 0; + napi_get_reference_value(event->jsCallbackInfo.env, event->jsCallbackInfo.onError, &callback); + napi_value callResult = 0; + napi_value undefined = 0; + napi_get_undefined(event->jsCallbackInfo.env, &undefined); + napi_call_function(event->jsCallbackInfo.env, undefined, callback, 1, &result, &callResult); + } + + delete event; + delete work; + HILOG_INFO("%{public}s called, uv_queue_work end", __func__); + }); + + return; +} + +/** + * @brief Receive the native kit reply and trigger JavaScript function object to be called from Node-API + * + * @param[in] result Receive the uninstall message from the native kit + * @param[in] formInfo This C++ forminfo will be parsed by JavaScript + * + * @return void + */ +void NapiFormAbility::OnFormUninstall(const int64_t formId) const +{ +} + +/** + * @brief Call native kit function: AcquireForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerAcquireForm(napi_env env, AsyncAddFormCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + + // Set Want info begin + Want want; + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, asyncCallbackInfo->param.formDimension); + // want.SetParam(Constants::PARAM_FORM_WIDTH_KEY, asyncCallbackInfo->param.formWidth); + // want.SetParam(Constants::PARAM_FORM_HEIGHT_KEY, asyncCallbackInfo->param.formHeight); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, asyncCallbackInfo->param.formName); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, asyncCallbackInfo->param.moduleName); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, asyncCallbackInfo->param.tempFormFlag); + want.SetElementName(asyncCallbackInfo->param.deviceId, + asyncCallbackInfo->param.bundleName, + asyncCallbackInfo->param.abilityName); + // Set Want info end + + std::shared_ptr callbackInfo(asyncCallbackInfo->napiFormAbility); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + bool ret = ability->AcquireForm(asyncCallbackInfo->param.formId, want, callbackInfo); + if (ret) { + asyncCallbackInfo->result = 1; + } else { + asyncCallbackInfo->result = 0; + } +} + + +/** + * @brief The implementation of Node-API interface: acquireForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_AcquireForm(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called, AcquireForm env[%{public}p]", __func__, env); + + napi_value thisVar = nullptr; + void* data = nullptr; + + // Check the number of the arguments + size_t argc = ARGS_SIZE_THREE; + napi_value argv[ARGS_SIZE_THREE] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + if (argc > ARGS_SIZE_THREE) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + // Parse form info from JavaScript value + FormReqInfo formReqInfo; + if (ParseNapiIntoFormInfo(env, formReqInfo, argv[0]) == nullptr) { + return NapiGetNull(env); + } + + // Obtains the C++ instance + NapiFormAbility* napiFormAbility = nullptr; + napi_status status = napi_unwrap(env, thisVar, (void **)&napiFormAbility); + if(status == napi_ok) { + HILOG_DEBUG("%{public}s, status == napi_ok", __func__); + } else { + HILOG_DEBUG("%{public}s, status != napi_ok", __func__); + } + + if(napiFormAbility == nullptr) { + HILOG_DEBUG("%{public}s, napiFormAbility == nullptr", __func__); + } else { + HILOG_DEBUG("%{public}s, napiFormAbility != nullptr", __func__); + } + + NAPI_ASSERT(env, status == napi_ok, "When acquireForm is called,\ + napi_unwrap obtains the C++ instance failed!"); + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + + // Parse arguments of the callback function from JavaScript value + napiFormAbility->jsCallbackInfomation.env = env; + if (ParseJsObjectCallbackParam(env, napiFormAbility->jsCallbackInfomation, argv[1]) == nullptr) { + return NapiGetNull(env); + } + + AsyncAddFormCallbackInfo *asyncCallbackInfo = new + AsyncAddFormCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .param = formReqInfo, + .napiFormAbility = napiFormAbility, + }; + + if (argc == ARGS_SIZE_THREE) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[2], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[2] type of acquireForm is incorrect,\ + expected type is function."); + + napi_create_reference(env, argv[2], 1, &asyncCallbackInfo->callback); + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + AsyncAddFormCallbackInfo *asyncCallbackInfo = (AsyncAddFormCallbackInfo *)data; + InnerAcquireForm(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + AsyncAddFormCallbackInfo *asyncCallbackInfo = (AsyncAddFormCallbackInfo *)data; + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + if (asyncCallbackInfo->callback != nullptr) { + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_value callback; + napi_value undefined; + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, undefined, callback, 1, &result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value result = 0; + napi_get_null(env, &result); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + AsyncAddFormCallbackInfo *asyncCallbackInfo = (AsyncAddFormCallbackInfo *)data; + InnerAcquireForm(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + AsyncAddFormCallbackInfo *asyncCallbackInfo = (AsyncAddFormCallbackInfo *)data; + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: DeleteForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerDelForm(napi_env env, AsyncDelFormCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + bool ret = ability->DeleteForm(asyncCallbackInfo->formId); + if (ret) { + asyncCallbackInfo->result = 1; + } else { + asyncCallbackInfo->result = 0; + } + HILOG_DEBUG("%{public}s, end", __func__); +} + +/** + * @brief The implementation of Node-API interface: deleteForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_DeleteForm(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > ARGS_SIZE_TWO) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + // Check the value type of the arguments + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] type of deleteForm is incorrect,\ + expected type is string."); + + std::string strFormId = GetStringFromNAPI(env, argv[0]); + int64_t formId = std::stoll(strFormId); + + AsyncDelFormCallbackInfo *asyncCallbackInfo = new + AsyncDelFormCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .formId = 0, + .result = 0, + }; + asyncCallbackInfo->formId = formId; + + if (argc == ARGS_SIZE_TWO) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[1] type of deleteForm is incorrect,\ + expected type is function."); + + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback); + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + AsyncDelFormCallbackInfo *asyncCallbackInfo = (AsyncDelFormCallbackInfo *)data; + InnerDelForm(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + AsyncDelFormCallbackInfo *asyncCallbackInfo = (AsyncDelFormCallbackInfo *)data; + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + if (asyncCallbackInfo->callback != nullptr) { + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_value callback; + napi_value undefined; + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, undefined, callback, 1, &result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + AsyncDelFormCallbackInfo *asyncCallbackInfo = (AsyncDelFormCallbackInfo *)data; + InnerDelForm(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + AsyncDelFormCallbackInfo *asyncCallbackInfo = (AsyncDelFormCallbackInfo *)data; + + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: ReleaseForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerReleaseForm(napi_env env, AsyncReleaseFormCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + bool ret = ability->ReleaseForm(asyncCallbackInfo->formId, asyncCallbackInfo->isReleaseCache); + if (ret) { + asyncCallbackInfo->result = 1; + } else { + asyncCallbackInfo->result = 0; + } + HILOG_DEBUG("%{public}s end", __func__); +} + +/** + * @brief The implementation of Node-API interface: releaseForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_ReleaseForm(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_THREE; + napi_value argv[ARGS_SIZE_THREE] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc < ARGS_SIZE_TWO || argc > ARGS_SIZE_THREE ) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + // Check the value type of the arguments + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] type of releaseForm is incorrect,\ + expected type is string."); + + std::string strFormId = GetStringFromNAPI(env, argv[0]); + int64_t formId = std::stoll(strFormId); + + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT(env, valueType == napi_boolean, "The arguments[1] type of releaseForm is incorrect,\ + expected type is boolean."); + + bool isReleaseCache; + napi_get_value_bool(env, argv[1], &isReleaseCache); + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + AsyncReleaseFormCallbackInfo *asyncCallbackInfo = new + AsyncReleaseFormCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .formId = formId, + .isReleaseCache = isReleaseCache, + .result = 0, + }; + + if (argc == ARGS_SIZE_THREE) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[2], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[2] type of releaseForm is incorrect,\ + expected type is function."); + + napi_create_reference(env, argv[2], 1, &asyncCallbackInfo->callback); + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + AsyncReleaseFormCallbackInfo *asyncCallbackInfo = (AsyncReleaseFormCallbackInfo *)data; + InnerReleaseForm(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + AsyncReleaseFormCallbackInfo *asyncCallbackInfo = (AsyncReleaseFormCallbackInfo *)data; + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + if (asyncCallbackInfo->callback != nullptr) { + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_value callback; + napi_value undefined; + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, undefined, callback, 1, &result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise running,", __func__); + AsyncReleaseFormCallbackInfo *asyncCallbackInfo = (AsyncReleaseFormCallbackInfo *)data; + InnerReleaseForm(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + AsyncReleaseFormCallbackInfo *asyncCallbackInfo = (AsyncReleaseFormCallbackInfo *)data; + + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: RequestForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerRequestForm(napi_env env, AsyncRequestFormCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + bool ret = ability->RequestForm(asyncCallbackInfo->formId); + if (ret) { + asyncCallbackInfo->result = 1; + } else { + asyncCallbackInfo->result = 0; + } + HILOG_DEBUG("%{public}s, end", __func__); +} + +/** + * @brief The implementation of Node-API interface: requestForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_RequestForm(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > ARGS_SIZE_TWO) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + // Check the value type of the arguments + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] type of requestForm is incorrect,\ + expected type is string."); + + std::string strFormId = GetStringFromNAPI(env, argv[0]); + int64_t formId = std::stoll(strFormId); + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + AsyncRequestFormCallbackInfo *asyncCallbackInfo = new + AsyncRequestFormCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .formId = formId, + .result = 0, + }; + + if (argc == ARGS_SIZE_TWO) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[1] type of requestForm is incorrect,\ + expected type is function."); + + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback); + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + AsyncRequestFormCallbackInfo *asyncCallbackInfo = (AsyncRequestFormCallbackInfo *)data; + InnerRequestForm(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + AsyncRequestFormCallbackInfo *asyncCallbackInfo = (AsyncRequestFormCallbackInfo *)data; + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + if (asyncCallbackInfo->callback != nullptr) { + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_value callback; + napi_value undefined; + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, undefined, callback, 1, &result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + AsyncRequestFormCallbackInfo *asyncCallbackInfo = (AsyncRequestFormCallbackInfo *)data; + InnerRequestForm(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + AsyncRequestFormCallbackInfo *asyncCallbackInfo = (AsyncRequestFormCallbackInfo *)data; + + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: SetFormNextRefreshTime + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerSetFormNextRefreshTime(napi_env env, AsyncNextRefreshTimeFormCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + bool ret = ability->SetFormNextRefreshTime(asyncCallbackInfo->formId, asyncCallbackInfo->time); + if (ret) { + asyncCallbackInfo->result = 1; + } else { + asyncCallbackInfo->result = 0; + } + HILOG_DEBUG("%{public}s, end", __func__); +} + +/** + * @brief The implementation of Node-API interface: setFormNextRefreshTime + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_SetFormNextRefreshTime(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_THREE; + napi_value argv[ARGS_SIZE_THREE] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > ARGS_SIZE_THREE || argc < ARGS_SIZE_TWO) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + // Check the value type of the arguments + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] type of setFormNextRefreshTime is incorrect,\ + expected type is string."); + + std::string strFormId = GetStringFromNAPI(env, argv[0]); + int64_t formId = std::stoll(strFormId); + + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT(env, valueType == napi_number, "The arguments[1] type of setFormNextRefreshTime is incorrect,\ + expected type is number."); + + int32_t time; + napi_get_value_int32(env, argv[1], &time); + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + AsyncNextRefreshTimeFormCallbackInfo *asyncCallbackInfo = new + AsyncNextRefreshTimeFormCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .formId = formId, + .time = time, + .result = 0, + }; + + if (argc == ARGS_SIZE_THREE) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[2], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[2] type of setFormNextRefreshTime is incorrect,\ + expected type is function."); + + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback); + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + + AsyncNextRefreshTimeFormCallbackInfo *asyncCallbackInfo = + (AsyncNextRefreshTimeFormCallbackInfo *)data; + + InnerSetFormNextRefreshTime(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + AsyncNextRefreshTimeFormCallbackInfo *asyncCallbackInfo = + (AsyncNextRefreshTimeFormCallbackInfo *)data; + + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + if (asyncCallbackInfo->callback != nullptr) { + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_value callback; + napi_value undefined; + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, undefined, callback, 1, &result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + AsyncNextRefreshTimeFormCallbackInfo *asyncCallbackInfo = + (AsyncNextRefreshTimeFormCallbackInfo *)data; + + InnerSetFormNextRefreshTime(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + AsyncNextRefreshTimeFormCallbackInfo *asyncCallbackInfo = + (AsyncNextRefreshTimeFormCallbackInfo *)data; + + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: UpdateForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerUpdateForm(napi_env env, AsyncUpdateFormCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + bool ret = ability->UpdateForm(asyncCallbackInfo->formId, *asyncCallbackInfo->formProviderData); + if (ret) { + asyncCallbackInfo->result = 1; + } else { + asyncCallbackInfo->result = 0; + } + HILOG_DEBUG("%{public}s, end", __func__); +} + +/** + * @brief The implementation of Node-API interface: updateForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_UpdateForm(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_THREE; + napi_value argv[ARGS_SIZE_THREE] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > ARGS_SIZE_THREE || argc < ARGS_SIZE_TWO) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + // Check the value type of the arguments + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] type of updateForm is incorrect,\ + expected type is string."); + + std::string strFormId = GetStringFromNAPI(env, argv[0]); + int64_t formId = std::stoll(strFormId); + + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[1] type of updateForm is incorrect,\ + expected type is string."); + + OHOS::AppExecFwk::FormProviderData *formProviderData = nullptr; + napi_unwrap(env, argv[1], (void**)&formProviderData); + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + AsyncUpdateFormCallbackInfo *asyncCallbackInfo = new + AsyncUpdateFormCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .formId = formId, + .formProviderData = std::shared_ptr(formProviderData), + .result = 0, + }; + + if (argc == ARGS_SIZE_THREE) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[2], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[2] type of updateForm is incorrect,\ + expected type is function."); + + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback); + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + AsyncUpdateFormCallbackInfo *asyncCallbackInfo = (AsyncUpdateFormCallbackInfo *)data; + InnerUpdateForm(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + AsyncUpdateFormCallbackInfo *asyncCallbackInfo = (AsyncUpdateFormCallbackInfo *)data; + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + if (asyncCallbackInfo->callback != nullptr) { + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_value callback; + napi_value undefined; + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, undefined, callback, 1, &result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + AsyncUpdateFormCallbackInfo *asyncCallbackInfo = (AsyncUpdateFormCallbackInfo *)data; + InnerUpdateForm(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + AsyncUpdateFormCallbackInfo *asyncCallbackInfo = (AsyncUpdateFormCallbackInfo *)data; + + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: CastTempForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerCastTempForm(napi_env env, AsyncCastTempFormCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + bool ret = ability->CastTempForm(asyncCallbackInfo->formId); + if (ret) { + asyncCallbackInfo->result = 1; + } else { + asyncCallbackInfo->result = 0; + } + HILOG_DEBUG("%{public}s, end", __func__); +} + +/** + * @brief The implementation of Node-API interface: castTempForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_CastTempForm(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > ARGS_SIZE_TWO) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + // Check the value type of the arguments + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] type of castTempForm is incorrect,\ + expected type is string."); + + std::string strFormId = GetStringFromNAPI(env, argv[0]); + int64_t formId = std::stoll(strFormId); + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + AsyncCastTempFormCallbackInfo *asyncCallbackInfo = new + AsyncCastTempFormCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .formId = formId, + .result = 0, + }; + + if (argc == ARGS_SIZE_TWO) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[1] type of castTempForm is incorrect,\ + expected type is function."); + + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback); + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + AsyncCastTempFormCallbackInfo *asyncCallbackInfo = (AsyncCastTempFormCallbackInfo *)data; + InnerCastTempForm(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + AsyncCastTempFormCallbackInfo *asyncCallbackInfo = (AsyncCastTempFormCallbackInfo *)data; + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + if (asyncCallbackInfo->callback != nullptr) { + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_value callback; + napi_value undefined; + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, undefined, callback, 1, &result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + AsyncCastTempFormCallbackInfo *asyncCallbackInfo = (AsyncCastTempFormCallbackInfo *)data; + InnerCastTempForm(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + AsyncCastTempFormCallbackInfo *asyncCallbackInfo = (AsyncCastTempFormCallbackInfo *)data; + + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: NotifyVisibleForms + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerNotifyVisibleForms(napi_env env, AsyncNotifyVisibleFormsCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + ability->NotifyVisibleForms(asyncCallbackInfo->formIds); + HILOG_DEBUG("%{public}s, end", __func__); +} + +/** + * @brief The implementation of Node-API interface: notifyVisibleForms + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_NotifyVisibleForms(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > ARGS_SIZE_TWO) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + uint32_t arrayLength = 0; + NAPI_CALL(env, napi_get_array_length(env, argv[0], &arrayLength)); + NAPI_ASSERT(env, arrayLength > 0, "The arguments[0] value of notifyVisibleForms is incorrect,\ + this array is empty."); + + std::vector formIds; + formIds.clear(); + napi_valuetype valueType; + for (size_t i = 0; i < arrayLength; i++) { + napi_value napiFormId; + napi_get_element(env, argv[0], i, &napiFormId); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, napiFormId, &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] value type of notifyVisibleForms is incorrect,\ + expected type is string."); + + std::string strFormId = GetStringFromNAPI(env, napiFormId); + int64_t formIdValue = std::stoll(strFormId); + + formIds.push_back(formIdValue); + } + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + AsyncNotifyVisibleFormsCallbackInfo *asyncCallbackInfo = new + AsyncNotifyVisibleFormsCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .formIds = formIds, + .result = 1, + }; + + if (argc == ARGS_SIZE_TWO) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[1] type of notifyVisibleForms is incorrect,\ + expected type is function."); + + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback); + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + + AsyncNotifyVisibleFormsCallbackInfo *asyncCallbackInfo = + (AsyncNotifyVisibleFormsCallbackInfo *)data; + + InnerNotifyVisibleForms(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + AsyncNotifyVisibleFormsCallbackInfo *asyncCallbackInfo = + (AsyncNotifyVisibleFormsCallbackInfo *)data; + + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + if (asyncCallbackInfo->callback != nullptr) { + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_value callback; + napi_value undefined; + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, undefined, callback, 1, &result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + + AsyncNotifyVisibleFormsCallbackInfo *asyncCallbackInfo = + (AsyncNotifyVisibleFormsCallbackInfo *)data; + + InnerNotifyVisibleForms(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + + AsyncNotifyVisibleFormsCallbackInfo *asyncCallbackInfo = + (AsyncNotifyVisibleFormsCallbackInfo *)data; + + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: NotifyInvisibleForms + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerNotifyInvisibleForms(napi_env env, AsyncNotifyInvisibleFormsCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + ability->NotifyInvisibleForms(asyncCallbackInfo->formIds); + HILOG_DEBUG("%{public}s, end", __func__); +} + +/** + * @brief The implementation of Node-API interface: notifyInvisibleForms + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_NotifyInvisibleForms(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > ARGS_SIZE_TWO) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + uint32_t arrayLength = 0; + NAPI_CALL(env, napi_get_array_length(env, argv[0], &arrayLength)); + NAPI_ASSERT(env, arrayLength > 0, "The arguments[0] value of notifyInvisibleForms is incorrect,\ + this array is empty."); + + std::vector formIds; + formIds.clear(); + napi_valuetype valueType; + for (size_t i = 0; i < arrayLength; i++) { + napi_value napiFormId; + napi_get_element(env, argv[0], i, &napiFormId); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, napiFormId, &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] value type of notifyInvisibleForms \ + is incorrect, expected type is string."); + + std::string strFormId = GetStringFromNAPI(env, napiFormId); + int64_t formIdValue = std::stoll(strFormId); + + formIds.push_back(formIdValue); + } + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + AsyncNotifyInvisibleFormsCallbackInfo *asyncCallbackInfo = new + AsyncNotifyInvisibleFormsCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .formIds = formIds, + .result = 1, + }; + + if (argc == ARGS_SIZE_TWO) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[1] type of notifyInvisibleForms is incorrect,\ + expected type is function."); + + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback); + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + + AsyncNotifyInvisibleFormsCallbackInfo *asyncCallbackInfo = + (AsyncNotifyInvisibleFormsCallbackInfo *)data; + + InnerNotifyInvisibleForms(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + AsyncNotifyInvisibleFormsCallbackInfo *asyncCallbackInfo = + (AsyncNotifyInvisibleFormsCallbackInfo *)data; + + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + if (asyncCallbackInfo->callback != nullptr) { + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_value callback; + napi_value undefined; + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, undefined, callback, 1, &result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + + AsyncNotifyInvisibleFormsCallbackInfo *asyncCallbackInfo = + (AsyncNotifyInvisibleFormsCallbackInfo *)data; + + InnerNotifyInvisibleForms(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + + AsyncNotifyInvisibleFormsCallbackInfo *asyncCallbackInfo = + (AsyncNotifyInvisibleFormsCallbackInfo *)data; + + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: EnableUpdateForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerEnableFormsUpdate(napi_env env, AsyncEnableUpdateFormCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + bool ret = ability->EnableUpdateForm(asyncCallbackInfo->formIds); + if (ret) { + asyncCallbackInfo->result = 1; + } else { + asyncCallbackInfo->result = 0; + } + HILOG_DEBUG("%{public}s, end", __func__); +} + +/** + * @brief The implementation of Node-API interface: enableFormsUpdate + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_EnableFormsUpdate(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > ARGS_SIZE_TWO) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + uint32_t arrayLength = 0; + NAPI_CALL(env, napi_get_array_length(env, argv[0], &arrayLength)); + NAPI_ASSERT(env, arrayLength > 0, "The arguments[0] value of enableFormsUpdate \ + is incorrect, this array is empty."); + + std::vector formIds; + formIds.clear(); + napi_valuetype valueType; + for (size_t i = 0; i < arrayLength; i++) { + napi_value napiFormId; + napi_get_element(env, argv[0], i, &napiFormId); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, napiFormId, &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] value type of enableFormsUpdate \ + is incorrect, expected type is string."); + + std::string strFormId = GetStringFromNAPI(env, napiFormId); + int64_t formIdValue = std::stoll(strFormId); + + formIds.push_back(formIdValue); + } + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + AsyncEnableUpdateFormCallbackInfo *asyncCallbackInfo = new + AsyncEnableUpdateFormCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .formIds = formIds, + .result = 0, + }; + + if (argc == ARGS_SIZE_TWO) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[1] type of enableFormsUpdate \ + is incorrect, expected type is function."); + + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback); + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + + AsyncEnableUpdateFormCallbackInfo *asyncCallbackInfo = + (AsyncEnableUpdateFormCallbackInfo *)data; + + InnerEnableFormsUpdate(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + AsyncEnableUpdateFormCallbackInfo *asyncCallbackInfo = + (AsyncEnableUpdateFormCallbackInfo *)data; + + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + if (asyncCallbackInfo->callback != nullptr) { + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_value callback; + napi_value undefined; + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, undefined, callback, 1, &result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + AsyncEnableUpdateFormCallbackInfo *asyncCallbackInfo = + (AsyncEnableUpdateFormCallbackInfo *)data; + + InnerEnableFormsUpdate(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + + AsyncEnableUpdateFormCallbackInfo *asyncCallbackInfo = + (AsyncEnableUpdateFormCallbackInfo *)data; + + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: DisableUpdateForm + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerDisableFormsUpdate(napi_env env, AsyncDisableUpdateFormCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + bool ret = ability->DisableUpdateForm(asyncCallbackInfo->formIds); + if (ret) { + asyncCallbackInfo->result = 1; + } else { + asyncCallbackInfo->result = 0; + } + HILOG_DEBUG("%{public}s, end", __func__); +} + +/** + * @brief The implementation of Node-API interface: disableFormsUpdate + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_DisableFormsUpdate(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > ARGS_SIZE_TWO) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + uint32_t arrayLength = 0; + NAPI_CALL(env, napi_get_array_length(env, argv[0], &arrayLength)); + NAPI_ASSERT(env, arrayLength > 0, "The arguments[0] value of disableFormsUpdate \ + is incorrect, this array is empty."); + + std::vector formIds; + formIds.clear(); + napi_valuetype valueType; + for (size_t i = 0; i < arrayLength; i++) { + napi_value napiFormId; + napi_get_element(env, argv[0], i, &napiFormId); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, napiFormId, &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] value type of disableFormsUpdate \ + is incorrect, expected type is string."); + + std::string strFormId = GetStringFromNAPI(env, napiFormId); + int64_t formIdValue = std::stoll(strFormId); + + formIds.push_back(formIdValue); + } + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + AsyncDisableUpdateFormCallbackInfo *asyncCallbackInfo = new + AsyncDisableUpdateFormCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .formIds = formIds, + .result = 0, + }; + + if (argc == ARGS_SIZE_TWO) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[1] type of disableFormsUpdate \ + is incorrect, expected type is function."); + + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback); + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + + AsyncDisableUpdateFormCallbackInfo *asyncCallbackInfo = + (AsyncDisableUpdateFormCallbackInfo *)data; + + InnerDisableFormsUpdate(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + AsyncDisableUpdateFormCallbackInfo *asyncCallbackInfo = + (AsyncDisableUpdateFormCallbackInfo *)data; + + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + if (asyncCallbackInfo->callback != nullptr) { + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_value callback; + napi_value undefined; + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, undefined, callback, 1, &result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + + AsyncDisableUpdateFormCallbackInfo *asyncCallbackInfo = + (AsyncDisableUpdateFormCallbackInfo *)data; + + InnerDisableFormsUpdate(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + + AsyncDisableUpdateFormCallbackInfo *asyncCallbackInfo = + (AsyncDisableUpdateFormCallbackInfo *)data; + + napi_value result; + napi_create_int32(env, asyncCallbackInfo->result, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: CheckFMSReady + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerCheckFMSReady(napi_env env, AsyncCheckFMSReadyCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + asyncCallbackInfo->isFMSReady = ability->CheckFMSReady(); + HILOG_DEBUG("%{public}s, end", __func__); +} + +/** + * @brief The implementation of Node-API interface: checkFMSReady + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_CheckFMSReady(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > ARGS_SIZE_ONE) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + AsyncCheckFMSReadyCallbackInfo *asyncCallbackInfo = new + AsyncCheckFMSReadyCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .isFMSReady = false, + }; + + if (argc == ARGS_SIZE_ONE) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[0] type of checkFMSReady is incorrect,\ + expected type is function."); + + napi_create_reference(env, argv[0], 1, &asyncCallbackInfo->callback); + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + + AsyncCheckFMSReadyCallbackInfo *asyncCallbackInfo = + (AsyncCheckFMSReadyCallbackInfo *)data; + + InnerCheckFMSReady(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + AsyncCheckFMSReadyCallbackInfo *asyncCallbackInfo = + (AsyncCheckFMSReadyCallbackInfo *)data; + + if (asyncCallbackInfo->callback != nullptr) { + napi_value isFMSReadyResult; + napi_create_int32(env, asyncCallbackInfo->isFMSReady, &isFMSReadyResult); + napi_value callback; + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, nullptr, callback, 1, &isFMSReadyResult, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + + AsyncCheckFMSReadyCallbackInfo *asyncCallbackInfo = + (AsyncCheckFMSReadyCallbackInfo *)data; + + InnerCheckFMSReady(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + + AsyncCheckFMSReadyCallbackInfo *asyncCallbackInfo = + (AsyncCheckFMSReadyCallbackInfo *)data; + + napi_value result; + napi_create_int32(env, asyncCallbackInfo->isFMSReady, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: GetAllFormsInfo + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerGetAllFormsInfo(napi_env env, AsyncGetAllFormsCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + bool ret = ability->GetAllFormsInfo(asyncCallbackInfo->formInfos); + if (ret) { + asyncCallbackInfo->result = 1; + } else { + asyncCallbackInfo->result = 0; + } + HILOG_DEBUG("%{public}s, end", __func__); +} + +/** + * @brief The implementation of Node-API interface: getAllFormsInfo + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_GetAllFormsInfo(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > ARGS_SIZE_ONE) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + std::vector formInfos; + formInfos.clear(); + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + AsyncGetAllFormsCallbackInfo *asyncCallbackInfo = new + AsyncGetAllFormsCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .formInfos = formInfos, + .result = 0, + }; + + if (argc == ARGS_SIZE_ONE) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[0] type of getAllFormsInfo is incorrect,\ + expected type is function."); + + napi_create_reference(env, argv[0], 1, &asyncCallbackInfo->callback); + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + + AsyncGetAllFormsCallbackInfo *asyncCallbackInfo = + (AsyncGetAllFormsCallbackInfo *)data; + + InnerGetAllFormsInfo(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + AsyncGetAllFormsCallbackInfo *asyncCallbackInfo = + (AsyncGetAllFormsCallbackInfo *)data; + + napi_value arrayFormInfos; + napi_create_array(env, &arrayFormInfos); + if (asyncCallbackInfo->result) { + int iFormInfoCount = 0; + for (auto formInfo : asyncCallbackInfo->formInfos) { + napi_value formInfoObject = nullptr; + napi_create_object(env, &formInfoObject); + ParseFormInfoIntoNapi(env, formInfo, formInfoObject); + napi_set_element(env, arrayFormInfos, iFormInfoCount, formInfoObject); + ++iFormInfoCount; + } + } + + if (asyncCallbackInfo->callback != nullptr) { + napi_value callbackValues[2] = {0}; + napi_value callback; + napi_value resultCode; + napi_create_int32(env, asyncCallbackInfo->result, &resultCode); + callbackValues[0] = resultCode; + callbackValues[1] = arrayFormInfos; + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, nullptr, callback, 2, callbackValues, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + + AsyncGetAllFormsCallbackInfo *asyncCallbackInfo = + (AsyncGetAllFormsCallbackInfo *)data; + + InnerGetAllFormsInfo(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + + AsyncGetAllFormsCallbackInfo *asyncCallbackInfo = + (AsyncGetAllFormsCallbackInfo *)data; + + napi_value arrayFormInfos; + napi_create_array(env, &arrayFormInfos); + if (asyncCallbackInfo->result) { + int iFormInfoCount = 0; + for (auto formInfo : asyncCallbackInfo->formInfos) { + napi_value formInfoObject = nullptr; + napi_create_object(env, &formInfoObject); + ParseFormInfoIntoNapi(env, formInfo, formInfoObject); + napi_set_element(env, arrayFormInfos, iFormInfoCount, formInfoObject); + ++iFormInfoCount; + } + } + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, arrayFormInfos); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: GetFormsInfoByApp + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerGetFormsInfoByApp(napi_env env, AsyncGetFormsInfoByAppCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + bool ret = ability->GetFormsInfoByApp(asyncCallbackInfo->bundleName, + asyncCallbackInfo->formInfos); + if (ret) { + asyncCallbackInfo->result = 1; + } else { + asyncCallbackInfo->result = 0; + } + HILOG_DEBUG("%{public}s, end", __func__); +} + +/** + * @brief The implementation of Node-API interface: getFormsInfoByApp + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_GetFormsInfoByApp(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > ARGS_SIZE_TWO) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + // Check the value type of the arguments + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] type of getFormsInfoByApp is incorrect,\ + expected type is string."); + + std::string bundleNameInfo = GetStringFromNAPI(env, argv[0]); + HILOG_INFO("%{public}s, bundleName=%{public}s.", __func__, bundleNameInfo.c_str()); + + std::vector formInfos; + formInfos.clear(); + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + AsyncGetFormsInfoByAppCallbackInfo *asyncCallbackInfo = new + AsyncGetFormsInfoByAppCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .formInfos = formInfos, + .bundleName = bundleNameInfo, + .result = 0, + }; + + if (argc == ARGS_SIZE_TWO) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[1] type of getFormsInfoByApp is incorrect,\ + expected type is function."); + + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback); + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + + AsyncGetFormsInfoByAppCallbackInfo *asyncCallbackInfo = + (AsyncGetFormsInfoByAppCallbackInfo *)data; + + InnerGetFormsInfoByApp(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + AsyncGetFormsInfoByAppCallbackInfo *asyncCallbackInfo = + (AsyncGetFormsInfoByAppCallbackInfo *)data; + + napi_value arrayFormInfos; + napi_create_array(env, &arrayFormInfos); + if (asyncCallbackInfo->result) { + int iFormInfoCount = 0; + for (auto formInfo : asyncCallbackInfo->formInfos) { + napi_value formInfoObject = nullptr; + napi_create_object(env, &formInfoObject); + ParseFormInfoIntoNapi(env, formInfo, formInfoObject); + napi_set_element(env, arrayFormInfos, iFormInfoCount, formInfoObject); + ++iFormInfoCount; + } + } + if (asyncCallbackInfo->callback != nullptr) { + napi_value callbackValues[2] = {0}; + napi_value callback; + napi_value resultCode; + napi_create_int32(env, asyncCallbackInfo->result, &resultCode); + callbackValues[0] = resultCode; + callbackValues[1] = arrayFormInfos; + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, nullptr, callback, 2, callbackValues, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + + AsyncGetFormsInfoByAppCallbackInfo *asyncCallbackInfo = + (AsyncGetFormsInfoByAppCallbackInfo *)data; + + InnerGetFormsInfoByApp(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + + AsyncGetFormsInfoByAppCallbackInfo *asyncCallbackInfo = + (AsyncGetFormsInfoByAppCallbackInfo *)data; + + napi_value arrayFormInfos; + napi_create_array(env, &arrayFormInfos); + if (asyncCallbackInfo->result) { + int iFormInfoCount = 0; + for (auto formInfo : asyncCallbackInfo->formInfos) { + napi_value formInfoObject = nullptr; + napi_create_object(env, &formInfoObject); + ParseFormInfoIntoNapi(env, formInfo, formInfoObject); + napi_set_element(env, arrayFormInfos, iFormInfoCount, formInfoObject); + ++iFormInfoCount; + } + } + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, arrayFormInfos); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +/** + * @brief Call native kit function: GetFormsInfoByModule + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] asyncCallbackInfo Reference, callback info via Node-API + * + * @return void + */ +static void InnerGetFormsInfoByModule(napi_env env, AsyncGetFormsInfoByModuleCallbackInfo* const asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called.", __func__); + OHOS::AppExecFwk::Ability *ability = asyncCallbackInfo->ability; + + bool ret = ability->GetFormsInfoByModule( + asyncCallbackInfo->bundleName, + asyncCallbackInfo->moduleName, + asyncCallbackInfo->formInfos); + + if (ret) { + asyncCallbackInfo->result = 1; + } else { + asyncCallbackInfo->result = 0; + } + HILOG_DEBUG("%{public}s, end", __func__); +} + +/** + * @brief The implementation of Node-API interface: getFormsInfoByModule + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[out] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +napi_value NAPI_GetFormsInfoByModule(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + // Check the number of the arguments + size_t argc = ARGS_SIZE_THREE; + napi_value argv[ARGS_SIZE_THREE] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + if (argc > ARGS_SIZE_THREE) { + HILOG_ERROR("%{public}s, wrong number of arguments.", __func__); + return nullptr; + } + HILOG_INFO("%{public}s, argc = [%{public}d]", __func__, argc); + + // Check the value type of the arguments + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[0] type of getFormsInfoByModule is incorrect,\ + expected type is string."); + + std::string bundleNameInfo = GetStringFromNAPI(env, argv[0]); + HILOG_INFO("%{public}s, bundleName=%{public}s.", __func__, bundleNameInfo.c_str()); + + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "The arguments[1] type of getFormsInfoByModule is incorrect,\ + expected type is string."); + + std::string moduleNameInfo = GetStringFromNAPI(env, argv[1]); + HILOG_INFO("%{public}s, moduleName=%{public}s.", __func__, moduleNameInfo.c_str()); + + std::vector formInfos; + formInfos.clear(); + + // get global value + napi_value global = nullptr; + napi_get_global(env, &global); + + // get ability + napi_value abilityObj = nullptr; + napi_get_named_property(env, global, "ability", &abilityObj); + + // get ability pointer + OHOS::AppExecFwk::Ability* ability = nullptr; + napi_get_value_external(env, abilityObj, (void**)&ability); + HILOG_INFO("%{public}s, ability = [%{public}p]", __func__, ability); + + AsyncGetFormsInfoByModuleCallbackInfo *asyncCallbackInfo = new + AsyncGetFormsInfoByModuleCallbackInfo { + .env = env, + .ability = ability, + .asyncWork = nullptr, + .deferred = nullptr, + .callback = nullptr, + .formInfos = formInfos, + .bundleName = bundleNameInfo, + .moduleName = moduleNameInfo, + .result = 0, + }; + + if (argc == ARGS_SIZE_THREE) { + HILOG_INFO("%{public}s, asyncCallback.", __func__); + + // Check the value type of the arguments + valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[2], &valueType)); + NAPI_ASSERT(env, valueType == napi_function, "The arguments[2] type of getFormsInfoByModule \ + is incorrect, expected type is function."); + + napi_create_reference(env, argv[2], 1, &asyncCallbackInfo->callback); + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work running", __func__); + + AsyncGetFormsInfoByModuleCallbackInfo *asyncCallbackInfo = + (AsyncGetFormsInfoByModuleCallbackInfo *)data; + + InnerGetFormsInfoByModule(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, napi_create_async_work complete", __func__); + + AsyncGetFormsInfoByModuleCallbackInfo *asyncCallbackInfo = + (AsyncGetFormsInfoByModuleCallbackInfo *)data; + + napi_value arrayFormInfos; + napi_create_array(env, &arrayFormInfos); + if (asyncCallbackInfo->result) { + int iFormInfoCount = 0; + for (auto formInfo : asyncCallbackInfo->formInfos) { + napi_value formInfoObject = nullptr; + napi_create_object(env, &formInfoObject); + ParseFormInfoIntoNapi(env, formInfo, formInfoObject); + napi_set_element(env, arrayFormInfos, iFormInfoCount, formInfoObject); + ++iFormInfoCount; + } + } + if (asyncCallbackInfo->callback != nullptr) { + napi_value callbackValues[2] = {0}; + napi_value callback; + napi_value resultCode; + napi_create_int32(env, asyncCallbackInfo->result, &resultCode); + callbackValues[0] = resultCode; + callbackValues[1] = arrayFormInfos; + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_value callResult; + napi_call_function(env, nullptr, callback, 2, callbackValues, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("%{public}s, promise.", __func__); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("%{public}s, promise runnning", __func__); + + AsyncGetFormsInfoByModuleCallbackInfo *asyncCallbackInfo = + (AsyncGetFormsInfoByModuleCallbackInfo *)data; + + InnerGetFormsInfoByModule(env, asyncCallbackInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("%{public}s, promise complete", __func__); + + AsyncGetFormsInfoByModuleCallbackInfo *asyncCallbackInfo = + (AsyncGetFormsInfoByModuleCallbackInfo *)data; + + napi_value arrayFormInfos; + napi_create_array(env, &arrayFormInfos); + if (asyncCallbackInfo->result) { + int iFormInfoCount = 0; + for (auto formInfo : asyncCallbackInfo->formInfos) { + napi_value formInfoObject = nullptr; + napi_create_object(env, &formInfoObject); + ParseFormInfoIntoNapi(env, formInfo, formInfoObject); + napi_set_element(env, arrayFormInfos, iFormInfoCount, formInfoObject); + ++iFormInfoCount; + } + } + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, arrayFormInfos); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} diff --git a/interfaces/kits/napi/aafwk/formAbility/napi_form_ability.h b/interfaces/kits/napi/aafwk/formAbility/napi_form_ability.h new file mode 100755 index 00000000000..368a3a8ead8 --- /dev/null +++ b/interfaces/kits/napi/aafwk/formAbility/napi_form_ability.h @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FORM_ABILITY_H_ +#define FORM_ABILITY_H_ + +#include "ability.h" +#include "form_info.h" +#include "form_js_info.h" +#include "form_provider_info.h" +#include "hilog_wrapper.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" +#include "nlohmann/json.hpp" +#include "want.h" + +struct FormReqInfo { + int64_t formId; + std::string formName; + std::string deviceId; + std::string bundleName; + std::string abilityName; + std::string moduleName; + bool tempFormFlag = false; + int32_t formWidth; + int32_t formHeight; + int32_t formDimension; +}; + +struct JsCallbackInfo { + napi_env env; + napi_ref onAcquired = 0; + napi_ref onError = 0; +}; + +struct AddFormCallbackInfo { + JsCallbackInfo jsCallbackInfo; + int32_t result; + OHOS::AppExecFwk::FormJsInfo formInfo; + napi_async_work asyncWork; +}; + +/** + * @brief + * The form result callback class.This callback env is same with acquireForm, + * it is used for return forminfo object to JavaScript by onAcquired or onUpdate + */ +class NapiFormAbility : public OHOS::AppExecFwk::Ability::FormCallback { +public: + NapiFormAbility(){}; + virtual ~NapiFormAbility(){}; + virtual void OnAcquired(const int32_t result, const OHOS::AppExecFwk::FormJsInfo &formJsInfo) const override; + virtual void OnUpdate(const int32_t result, const OHOS::AppExecFwk::FormJsInfo &formJsInfo) const override; + virtual void OnFormUninstall(const int64_t formId) const override; + +public: + JsCallbackInfo jsCallbackInfomation; +}; + +struct AsyncAddFormCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + FormReqInfo param; + NapiFormAbility *napiFormAbility; + int32_t result; +}; + +struct AsyncDelFormCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + int64_t formId; + int result; +}; + +struct AsyncReleaseFormCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + int64_t formId; + bool isReleaseCache; + int result; +}; + +struct AsyncRequestFormCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + int64_t formId; + int result; +}; + +struct AsyncNextRefreshTimeFormCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + int64_t formId; + int32_t time; + int result; +}; + +struct AsyncUpdateFormCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + int64_t formId; + std::shared_ptr formProviderData; + int result; +}; + +struct AsyncCastTempFormCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + int64_t formId; + int result; +}; + +struct AsyncNotifyVisibleFormsCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + std::vector formIds; + int result; +}; + +struct AsyncNotifyInvisibleFormsCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + std::vector formIds; + int result; +}; + +struct AsyncEnableUpdateFormCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + std::vector formIds; + int result; +}; + +struct AsyncDisableUpdateFormCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + std::vector formIds; + int result; +}; + +struct AsyncCheckFMSReadyCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + bool isFMSReady; +}; + +struct AsyncGetAllFormsCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + std::vector formInfos; + int result; +}; + +struct AsyncGetFormsInfoByAppCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + std::vector formInfos; + std::string bundleName; + int result; +}; + +struct AsyncGetFormsInfoByModuleCallbackInfo { + napi_env env; + OHOS::AppExecFwk::Ability *ability; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback; + std::vector formInfos; + std::string bundleName; + std::string moduleName; + int result; +}; + +napi_value NAPI_AcquireForm(napi_env env, napi_callback_info info); +napi_value NAPI_DeleteForm(napi_env env, napi_callback_info info); +napi_value NAPI_ReleaseForm(napi_env env, napi_callback_info info); +napi_value NAPI_RequestForm(napi_env env, napi_callback_info info); +napi_value NAPI_SetFormNextRefreshTime(napi_env env, napi_callback_info info); +napi_value NAPI_UpdateForm(napi_env env, napi_callback_info info); +napi_value NAPI_CastTempForm(napi_env env, napi_callback_info info); +napi_value NAPI_NotifyVisibleForms(napi_env env, napi_callback_info info); +napi_value NAPI_NotifyInvisibleForms(napi_env env, napi_callback_info info); +napi_value NAPI_EnableFormsUpdate(napi_env env, napi_callback_info info); +napi_value NAPI_DisableFormsUpdate(napi_env env, napi_callback_info info); +napi_value NAPI_CheckFMSReady(napi_env env, napi_callback_info info); +napi_value NAPI_GetAllFormsInfo(napi_env env, napi_callback_info info); +napi_value NAPI_GetFormsInfoByApp(napi_env env, napi_callback_info info); +napi_value NAPI_GetFormsInfoByModule(napi_env env, napi_callback_info info); + +#endif /* FORM_ABILITY_H_ */ diff --git a/interfaces/kits/napi/aafwk/formAbility/native_module.cpp b/interfaces/kits/napi/aafwk/formAbility/native_module.cpp new file mode 100755 index 00000000000..c0e1a3c8a5c --- /dev/null +++ b/interfaces/kits/napi/aafwk/formAbility/native_module.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include "napi_form_ability.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +/** + * @brief Constructor of JS form + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[in] info An opaque datatype that is passed to a callback function + * + * @return This is an opaque pointer that is used to represent a JavaScript value + */ +static napi_value JSFormConstructor(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + void* data = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, &data); + + auto formObject = new NapiFormAbility(); + napi_wrap( + env, thisVar, formObject, + [](napi_env env, void* data, void* hint) { + auto formObject = (NapiFormAbility*)data; + if (formObject != nullptr) { + delete formObject; + } + }, + nullptr, nullptr); + + return thisVar; +} + +EXTERN_C_START + +/** + * @brief For N-API modules registration + * + * @param[in] env The environment that the Node-API call is invoked under + * @param[in] exports An empty object via the exports parameter as a convenience + * + * @return The return value from Init is treated as the exports object for the module + */ +static napi_value Init(napi_env env, napi_value exports) +{ + napi_property_descriptor properties[] = { + DECLARE_NAPI_FUNCTION("acquireForm", NAPI_AcquireForm), + DECLARE_NAPI_FUNCTION("deleteForm", NAPI_DeleteForm), + DECLARE_NAPI_FUNCTION("releaseForm", NAPI_ReleaseForm), + DECLARE_NAPI_FUNCTION("requestForm", NAPI_RequestForm), + DECLARE_NAPI_FUNCTION("setFormNextRefreshTime", NAPI_SetFormNextRefreshTime), + DECLARE_NAPI_FUNCTION("updateForm", NAPI_UpdateForm), + DECLARE_NAPI_FUNCTION("castTempForm", NAPI_CastTempForm), + DECLARE_NAPI_FUNCTION("notifyVisibleForms", NAPI_NotifyVisibleForms), + DECLARE_NAPI_FUNCTION("notifyInvisibleForms", NAPI_NotifyInvisibleForms), + DECLARE_NAPI_FUNCTION("enableFormsUpdate", NAPI_EnableFormsUpdate), + DECLARE_NAPI_FUNCTION("disableFormsUpdate", NAPI_DisableFormsUpdate), + DECLARE_NAPI_FUNCTION("checkFMSReady", NAPI_CheckFMSReady), + DECLARE_NAPI_FUNCTION("getAllFormsInfo", NAPI_GetAllFormsInfo), + DECLARE_NAPI_FUNCTION("getFormsInfoByApp", NAPI_GetFormsInfoByApp), + DECLARE_NAPI_FUNCTION("getFormsInfoByModule", NAPI_GetFormsInfoByModule), + }; + + const char* formClassName = "FormObject"; + napi_value result = nullptr; + napi_define_class(env, + formClassName, + NAPI_AUTO_LENGTH, + JSFormConstructor, + nullptr, + sizeof(properties) / sizeof(properties[0]), + properties, + &result); + + napi_set_named_property(env, exports, formClassName, result); + + return exports; +} + +EXTERN_C_END + +// Define a Node-API module. +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "form", + .nm_priv = ((void *)0), + .reserved = {0} +}; + +// Registers a Node-API module. +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn b/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn index 018cbb2fbdd..7d9de936cde 100755 --- a/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn +++ b/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn @@ -22,6 +22,7 @@ ohos_shared_library("napi_common") { ] sources = [ + "napi_common_ability.cpp", "napi_common_util.cpp", "napi_common_want.cpp", ] diff --git a/interfaces/kits/napi/aafwk/featureAbility/feature_ability_common.h b/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h old mode 100755 new mode 100644 similarity index 62% rename from interfaces/kits/napi/aafwk/featureAbility/feature_ability_common.h rename to interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h index 51d3eeab10c..ea7d569e4fd --- a/interfaces/kits/napi/aafwk/featureAbility/feature_ability_common.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h @@ -19,8 +19,9 @@ #include "napi/native_node_api.h" #include "ability.h" #include "want.h" -#include "../inner/napi_common/napi_common.h" +#include "napi_common.h" #include "dummy_values_bucket.h" +#include "dummy_result_set.h" #include "dummy_data_ability_predicates.h" using Want = OHOS::AAFwk::Want; @@ -31,8 +32,6 @@ namespace OHOS { namespace AppExecFwk { class FeatureAbility; -#define NO_ERROR 0 - struct CallAbilityParam { Want want; int requestCode = 0; @@ -40,7 +39,6 @@ struct CallAbilityParam { std::shared_ptr setting = nullptr; }; - struct OnAbilityCallback { int requestCode = 0; int resultCode = 0; @@ -53,8 +51,10 @@ struct AsyncCallbackInfo { napi_deferred deferred; Ability *ability; CallAbilityParam param; - CallbackInfo *aceCallback; + CallbackInfo aceCallback; bool native_result; + AbilityType abilityType = AbilityType::UNKNOWN; + int errCode = 0; }; struct CBBase { @@ -62,6 +62,8 @@ struct CBBase { napi_async_work asyncWork; napi_deferred deferred; Ability *ability = nullptr; + AbilityType abilityType = AbilityType::UNKNOWN; + int errCode = 0; }; struct AppInfo_ { @@ -79,7 +81,6 @@ struct AppInfo_ { std::vector moduleSourceDirs; std::vector permissions; std::vector moduleInfos; - int32_t flags = 0; // no data std::string entryDir; }; @@ -197,11 +198,124 @@ struct DAHelperInsertCB { int result = 0; }; +class NAPIAbilityConnection; +struct AbilityConnectionCB { + napi_env env; + napi_ref callback[3] = {0}; // onConnect/onDisconnect/onFailed + int resultCode = 0; + ElementName elementName; + sptr connection; +}; +struct ConnectAbilityCB { + CBBase cbBase; + Want want; + sptr abilityConnection; + AbilityConnectionCB abilityConnectionCB; + int64_t id; + bool result; + int errCode = 0; +}; + +struct DAHelperNotifyChangeCB { + CBBase cbBase; + DataAbilityHelper *dataAbilityHelper = nullptr; + std::string uri; +}; + +// class DataAbilityObserver; +struct DAHelperOnOffCB { + CBBase cbBase; + DataAbilityHelper *dataAbilityHelper = nullptr; + // sptr observer; + std::string uri; + int result = 0; +}; + static inline std::string NapiValueToStringUtf8(napi_env env, napi_value value) { std::string result = ""; - return UnwrapStringFromJS(env, value, result); + return UnwrapStringFromJS(env, value, result); } + +static inline bool NapiValueToArrayStringUtf8(napi_env env, napi_value param, std::vector &result) +{ + return UnwrapArrayStringFromJS(env, param, result); +} + +struct DAHelperGetTypeCB { + CBBase cbBase; + DataAbilityHelper *dataAbilityHelper = nullptr; + std::string uri; + std::string result = ""; +}; + +struct DAHelperGetFileTypesCB { + CBBase cbBase; + DataAbilityHelper *dataAbilityHelper = nullptr; + std::string uri; + std::string mimeTypeFilter; + std::vector result; +}; + +struct DAHelperNormalizeUriCB { + CBBase cbBase; + DataAbilityHelper *dataAbilityHelper = nullptr; + std::string uri; + std::string result = ""; +}; +struct DAHelperDenormalizeUriCB { + CBBase cbBase; + DataAbilityHelper *dataAbilityHelper = nullptr; + std::string uri; + std::string result = ""; +}; + +struct DAHelperDeleteCB { + CBBase cbBase; + DataAbilityHelper *dataAbilityHelper = nullptr; + std::string uri; + DataAbilityPredicates predicates; + int result = 0; +}; + +struct DAHelperQueryCB { + CBBase cbBase; + DataAbilityHelper *dataAbilityHelper = nullptr; + std::string uri; + std::vector columns; + DataAbilityPredicates predicates; + ResultSet result; +}; + +struct DAHelperUpdateCB { + CBBase cbBase; + DataAbilityHelper *dataAbilityHelper = nullptr; + std::string uri; + ValuesBucket valueBucket; + DataAbilityPredicates predicates; + int result = 0; +}; +struct DAHelperBatchInsertCB { + CBBase cbBase; + DataAbilityHelper *dataAbilityHelper = nullptr; + std::string uri; + std::vector values; + int result = 0; +}; +struct DAHelperOpenFileCB { + CBBase cbBase; + DataAbilityHelper *dataAbilityHelper = nullptr; + std::string uri; + std::string mode; + int result = 0; +}; + +struct DAHelperReleaseCB { + CBBase cbBase; + DataAbilityHelper *dataAbilityHelper = nullptr; + bool result = false; +}; + } // namespace AppExecFwk } // namespace OHOS #endif /* OHOS_APPEXECFWK_FEATURE_ABILITY_COMMON_H */ diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp new file mode 100755 index 00000000000..f9bcc48c1fa --- /dev/null +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp @@ -0,0 +1,4551 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_common_ability.h" +#include +#include +#include "napi_common_util.h" +#include "securec.h" +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { + +napi_value g_classContext; +static void *g_handle = nullptr; +constexpr char SHARED_LIBRARY_RPC[] = "/system/lib/module/librpc.z.so"; +constexpr char FUNC_RPC_CREATE_JS_REMOTE_OBJECT[] = "NAPI_ohos_rpc_CreateJsRemoteObject"; +using NAPICreateJsRemoteObject = napi_value (*)(napi_env env, const sptr target); + +napi_value *GetGlobalClassContext(void) +{ + return &g_classContext; +} + +bool CheckAbilityType(AbilityType typeInAbility, AbilityType typeWant) +{ + HILOG_INFO("%{public}s called.", __func__); + switch (typeWant) { + case AbilityType::PAGE: + return typeInAbility == AbilityType::PAGE; + default: + return typeInAbility != AbilityType::PAGE; + } + HILOG_INFO("%{public}s end.", __func__); + return false; +} + +bool CheckAbilityType(const CBBase *cbBase) +{ + HILOG_INFO("%{public}s called.", __func__); + if (cbBase == nullptr) { + HILOG_ERROR("%{public}s cbBase == nullptr", __func__); + return false; + } + + const std::shared_ptr info = cbBase->ability->GetAbilityInfo(); + if (info == nullptr) { + HILOG_ERROR("%{public}s info == nullptr", __func__); + return false; + } + HILOG_INFO("%{public}s end.", __func__); + return CheckAbilityType((AbilityType)info->type, cbBase->abilityType); +} + +bool CheckAbilityType(const AsyncJSCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called.", __func__); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s asyncCallbackInfo == nullptr", __func__); + return false; + } + + if (asyncCallbackInfo->ability == nullptr) { + HILOG_ERROR("%{public}s ability == nullptr", __func__); + return false; + } + + const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); + if (info == nullptr) { + HILOG_ERROR("%{public}s info == nullptr", __func__); + return false; + } + HILOG_INFO("%{public}s end.", __func__); + return CheckAbilityType((AbilityType)info->type, asyncCallbackInfo->abilityType); +} + +bool CheckAbilityType(const AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called.", __func__); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s asyncCallbackInfo == nullptr", __func__); + return false; + } + + if (asyncCallbackInfo->ability == nullptr) { + HILOG_ERROR("%{public}s ability == nullptr", __func__); + return false; + } + + const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); + if (info == nullptr) { + HILOG_ERROR("%{public}s info == nullptr", __func__); + return false; + } + + HILOG_INFO("%{public}s end.", __func__); + return CheckAbilityType((AbilityType)info->type, asyncCallbackInfo->abilityType); +} + +void SaveAppInfo(AppInfo_ &appInfo, const ApplicationInfo &appInfoOrg) +{ + HILOG_INFO("%{public}s.", __func__); + appInfo.name = appInfoOrg.name; + appInfo.description = appInfoOrg.description; + appInfo.descriptionId = appInfoOrg.descriptionId; + appInfo.systemApp = appInfoOrg.isSystemApp; + appInfo.enabled = appInfoOrg.enabled; + appInfo.label = appInfoOrg.label; + appInfo.labelId = std::to_string(appInfoOrg.labelId); + appInfo.icon = appInfoOrg.iconPath; + appInfo.iconId = std::to_string(appInfoOrg.iconId); + appInfo.process = appInfoOrg.process; + appInfo.supportedModes = appInfoOrg.supportedModes; + for (size_t i = 0; i < appInfoOrg.moduleInfos.size(); i++) { + appInfo.moduleSourceDirs.emplace_back(appInfoOrg.moduleInfos.at(i).moduleSourceDir); + } + for (size_t i = 0; i < appInfoOrg.permissions.size(); i++) { + appInfo.permissions.emplace_back(appInfoOrg.permissions.at(i)); + } + for (size_t i = 0; i < appInfoOrg.moduleInfos.size(); i++) { + appInfo.moduleInfos.emplace_back(appInfoOrg.moduleInfos.at(i)); + } + appInfo.entryDir = appInfoOrg.entryDir; + HILOG_INFO("%{public}s end.", __func__); +} + +/** + * @brief GetApplicationInfo asynchronous processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetAppInfoExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_GetApplicationInfo, worker pool thread execute."); + AppInfoCB *appInfoCB = (AppInfoCB *)data; + appInfoCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + + if (appInfoCB->cbBase.ability == nullptr) { + HILOG_ERROR("NAPI_GetApplicationInfo, ability == nullptr"); + appInfoCB->cbBase.errCode = NAPI_ERR_ACE_ABILITY; + return; + } + + if (!CheckAbilityType(&appInfoCB->cbBase)) { + HILOG_ERROR("NAPI_GetApplicationInfo, wrong ability type"); + appInfoCB->cbBase.errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + return; + } + + std::shared_ptr appInfoPtr = appInfoCB->cbBase.ability->GetApplicationInfo(); + if (appInfoPtr != nullptr) { + SaveAppInfo(appInfoCB->appInfo, *appInfoPtr); + } else { + HILOG_ERROR("NAPI_GetApplicationInfo, appInfoPtr == nullptr"); + appInfoCB->cbBase.errCode = NAPI_ERR_ABILITY_CALL_INVALID; + } + HILOG_INFO("NAPI_GetApplicationInfo, worker pool thread execute end."); +} + +napi_value WrapAppInfo(napi_env env, const AppInfo_ &appInfo) +{ + HILOG_INFO("%{public}s.", __func__); + napi_value result = nullptr; + napi_value proValue = nullptr; + NAPI_CALL(env, napi_create_object(env, &result)); + NAPI_CALL(env, napi_create_string_utf8(env, appInfo.name.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "name", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, appInfo.description.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "description", proValue)); + + NAPI_CALL(env, napi_create_int32(env, appInfo.descriptionId, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "descriptionId", proValue)); + + NAPI_CALL(env, napi_get_boolean(env, appInfo.systemApp, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "systemApp", proValue)); + NAPI_CALL(env, napi_get_boolean(env, appInfo.enabled, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "enabled", proValue)); + NAPI_CALL(env, napi_create_string_utf8(env, appInfo.label.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "label", proValue)); + NAPI_CALL(env, napi_create_string_utf8(env, appInfo.labelId.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "labelId", proValue)); + NAPI_CALL(env, napi_create_string_utf8(env, appInfo.icon.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "icon", proValue)); + NAPI_CALL(env, napi_create_string_utf8(env, appInfo.iconId.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "iconId", proValue)); + NAPI_CALL(env, napi_create_string_utf8(env, appInfo.process.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "process", proValue)); + NAPI_CALL(env, napi_create_int32(env, appInfo.supportedModes, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "supportedModes", proValue)); + napi_value jsArrayModDirs = nullptr; + NAPI_CALL(env, napi_create_array(env, &jsArrayModDirs)); + for (size_t i = 0; i < appInfo.moduleSourceDirs.size(); i++) { + proValue = nullptr; + NAPI_CALL( + env, napi_create_string_utf8(env, appInfo.moduleSourceDirs.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_element(env, jsArrayModDirs, i, proValue)); + } + NAPI_CALL(env, napi_set_named_property(env, result, "moduleSourceDirs", jsArrayModDirs)); + napi_value jsArrayPermissions = nullptr; + NAPI_CALL(env, napi_create_array(env, &jsArrayPermissions)); + for (size_t i = 0; i < appInfo.permissions.size(); i++) { + proValue = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, appInfo.permissions.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_element(env, jsArrayPermissions, i, proValue)); + } + NAPI_CALL(env, napi_set_named_property(env, result, "permissions", jsArrayPermissions)); + napi_value jsArrayModuleInfo = nullptr; + NAPI_CALL(env, napi_create_array(env, &jsArrayModuleInfo)); + for (size_t i = 0; i < appInfo.moduleInfos.size(); i++) { + napi_value jsModuleInfoObject = nullptr; + NAPI_CALL(env, napi_create_object(env, &jsModuleInfoObject)); + proValue = nullptr; + NAPI_CALL(env, + napi_create_string_utf8(env, appInfo.moduleInfos.at(i).moduleName.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, jsModuleInfoObject, "moduleName", proValue)); + proValue = nullptr; + NAPI_CALL(env, + napi_create_string_utf8( + env, appInfo.moduleInfos.at(i).moduleSourceDir.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, jsModuleInfoObject, "moduleSourceDir", proValue)); + NAPI_CALL(env, napi_set_element(env, jsArrayModuleInfo, i, jsModuleInfoObject)); + } + NAPI_CALL(env, napi_set_named_property(env, result, "moduleInfos", jsArrayModuleInfo)); + NAPI_CALL(env, napi_create_string_utf8(env, appInfo.entryDir.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "entryDir", proValue)); + HILOG_INFO("%{public}s end.", __func__); + return result; +} + +/** + * @brief The callback at the end of the asynchronous callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetAppInfoAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); + AppInfoCB *appInfoCB = (AppInfoCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + result[PARAM0] = GetCallbackErrorValue(env, appInfoCB->cbBase.errCode); + if (appInfoCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result[PARAM1] = WrapAppInfo(env, appInfoCB->appInfo); + } else { + result[PARAM1] = WrapUndefinedToJS(env); + } + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, appInfoCB->cbBase.cbInfo.callback, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (appInfoCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, appInfoCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, appInfoCB->cbBase.asyncWork)); + delete appInfoCB; + appInfoCB = nullptr; + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete end."); +} + +/** + * @brief The callback at the end of the Promise callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetAppInfoPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); + AppInfoCB *appInfoCB = (AppInfoCB *)data; + if (appInfoCB == nullptr) { + HILOG_ERROR("NAPI_GetApplicationInfo, appInfoCB == nullptr"); + return; + } + + napi_value result = nullptr; + if (appInfoCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result = WrapAppInfo(env, appInfoCB->appInfo); + napi_resolve_deferred(env, appInfoCB->cbBase.deferred, result); + } else { + result = GetCallbackErrorValue(env, appInfoCB->cbBase.errCode); + napi_reject_deferred(env, appInfoCB->cbBase.deferred, result); + } + + napi_delete_async_work(env, appInfoCB->cbBase.asyncWork); + delete appInfoCB; + appInfoCB = nullptr; + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete end."); +} + +/** + * @brief GetApplicationInfo Async. + * + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * @param argcPromise Asynchronous data processing. + * @param appInfoCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetApplicationInfoAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AppInfoCB *appInfoCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || appInfoCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &appInfoCB->cbBase.cbInfo.callback)); + } + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetAppInfoExecuteCB, + GetAppInfoAsyncCompleteCB, + (void *)appInfoCB, + &appInfoCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, appInfoCB->cbBase.asyncWork)); + napi_value result = nullptr; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +/** + * @brief GetApplicationInfo Promise. + * + * @param env The environment that the Node-API call is invoked under. + * @param appInfoCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetApplicationInfoPromise(napi_env env, AppInfoCB *appInfoCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (appInfoCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + appInfoCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetAppInfoExecuteCB, + GetAppInfoPromiseCompleteCB, + (void *)appInfoCB, + &appInfoCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, appInfoCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +/** + * @brief GetApplicationInfo processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param appInfoCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetApplicationInfoWrap(napi_env env, napi_callback_info info, AppInfoCB *appInfoCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (appInfoCB == nullptr) { + HILOG_ERROR("%{public}s, appInfoCB == nullptr.", __func__); + return nullptr; + } + + size_t argcAsync = 1; + const size_t argcPromise = 0; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + if (argcAsync > argcPromise) { + ret = GetApplicationInfoAsync(env, args, argcAsync, argcPromise, appInfoCB); + } else { + ret = GetApplicationInfoPromise(env, appInfoCB); + } + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return ret; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to AppInfoCB on success, nullptr on failure. + */ +AppInfoCB *CreateAppInfoCBInfo(napi_env env) +{ + HILOG_INFO("%{public}s, called.", __func__); + napi_value global = nullptr; + NAPI_CALL(env, napi_get_global(env, &global)); + + napi_value abilityObj = nullptr; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + + AppInfoCB *appInfoCB = new (std::nothrow) AppInfoCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = ability, + .cbBase.abilityType = AbilityType::UNKNOWN, + .cbBase.errCode = NAPI_ERR_NO_ERROR, + }; + if (appInfoCB == nullptr) { + HILOG_ERROR("%{public}s, appInfoCB == nullptr.", __func__); + } + HILOG_INFO("%{public}s, end.", __func__); + return appInfoCB; +} + +/** + * @brief Obtains information about the current application. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetApplicationInfoCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s,called", __func__); + AppInfoCB *appInfoCB = CreateAppInfoCBInfo(env); + if (appInfoCB == nullptr) { + return WrapVoidToJS(env); + } + + appInfoCB->cbBase.abilityType = abilityType; + napi_value ret = GetApplicationInfoWrap(env, info, appInfoCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (appInfoCB != nullptr) { + delete appInfoCB; + appInfoCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +/** + * @brief GetBundleName asynchronous processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetBundleNameExecuteCallback(napi_env env, void *data) +{ + HILOG_INFO("%{public}s called", __func__); + AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s. asyncCallbackInfo is null", __func__); + return; + } + + asyncCallbackInfo->error_code = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->native_data.data_type = NVT_NONE; + if (asyncCallbackInfo->ability == nullptr) { + HILOG_ERROR("%{public}s ability == nullptr", __func__); + asyncCallbackInfo->error_code = NAPI_ERR_ACE_ABILITY; + return; + } + + if (!CheckAbilityType(asyncCallbackInfo)) { + HILOG_ERROR("%{public}s wrong ability type", __func__); + asyncCallbackInfo->error_code = NAPI_ERR_ABILITY_TYPE_INVALID; + asyncCallbackInfo->native_data.data_type = NVT_UNDEFINED; + return; + } + + asyncCallbackInfo->native_data.data_type = NVT_STRING; + asyncCallbackInfo->native_data.str_value = asyncCallbackInfo->ability->GetBundleName(); + HILOG_INFO("%{public}s end. bundleName=%{public}s", __func__, asyncCallbackInfo->native_data.str_value.c_str()); +} + +/** + * @brief GetBundleName processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param asyncCallbackInfo Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value NAPI_GetBundleNameWrap(napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called", __func__); + size_t argc = ARGS_MAX_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value jsthis = 0; + void *data = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &jsthis, &data)); + + if (argc > ARGS_ONE) { + HILOG_INFO("%{public}s called, parameters is invalid.", __func__); + return nullptr; + } + + if (argc == ARGS_ONE) { + if (!CreateAsyncCallback(env, args[PARAM0], asyncCallbackInfo)) { + HILOG_INFO("%{public}s called, the first parameter is invalid.", __func__); + return nullptr; + } + } + + AsyncParamEx asyncParamEx; + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + HILOG_INFO("%{public}s called. asyncCallback.", __func__); + asyncParamEx.resource = "NAPI_GetBundleNameCallback"; + asyncParamEx.execute = GetBundleNameExecuteCallback; + asyncParamEx.complete = CompleteAsyncCallbackWork; + + return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } else { + HILOG_INFO("%{public}s called. promise.", __func__); + asyncParamEx.resource = "NAPI_GetBundleNamePromise"; + asyncParamEx.execute = GetBundleNameExecuteCallback; + asyncParamEx.complete = CompletePromiseCallbackWork; + + return ExecutePromiseCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } +} + +/** + * @brief Get bundle name. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetBundleNameCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s called", __func__); + AsyncJSCallbackInfo *asyncCallbackInfo = CreateAsyncJSCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called. Invoke CreateAsyncJSCallbackInfo failed.", __func__); + return WrapVoidToJS(env); + } + + asyncCallbackInfo->abilityType = abilityType; + napi_value ret = NAPI_GetBundleNameWrap(env, info, asyncCallbackInfo); + if (ret == nullptr) { + HILOG_ERROR("%{public}s ret == nullptr", __func__); + FreeAsyncJSCallbackInfo(&asyncCallbackInfo); + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s end", __func__); + return ret; +} + +napi_value WrapProcessInfo(napi_env env, ProcessInfoCB *processInfoCB) +{ + HILOG_INFO("%{public}s called", __func__); + if (processInfoCB == nullptr) { + HILOG_ERROR("%{public}s Invalid param(processInfoCB == nullptr)", __func__); + return nullptr; + } + napi_value result = nullptr; + napi_value proValue = nullptr; + NAPI_CALL(env, napi_create_object(env, &result)); + NAPI_CALL(env, napi_create_int32(env, processInfoCB->pid, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "pid", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, processInfoCB->processName.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "processName", proValue)); + HILOG_INFO("%{public}s end", __func__); + return result; +} + +/** + * @brief GetProcessInfo asynchronous processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetProcessInfoExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_GetProcessInfo, worker pool thread execute."); + ProcessInfoCB *processInfoCB = (ProcessInfoCB *)data; + if (processInfoCB == nullptr) { + return; + } + + processInfoCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + if (processInfoCB->cbBase.ability == nullptr) { + HILOG_ERROR("NAPI_GetProcessInfo, ability == nullptr"); + processInfoCB->cbBase.errCode = NAPI_ERR_ACE_ABILITY; + return; + } + + if (!CheckAbilityType(&processInfoCB->cbBase)) { + HILOG_ERROR("NAPI_GetProcessInfo, wrong ability type"); + processInfoCB->cbBase.errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + return; + } + + std::shared_ptr processInfoPtr = processInfoCB->cbBase.ability->GetProcessInfo(); + if (processInfoPtr != nullptr) { + processInfoCB->processName = processInfoPtr->GetProcessName(); + processInfoCB->pid = processInfoPtr->GetPid(); + } else { + HILOG_ERROR("NAPI_GetProcessInfo, processInfoPtr == nullptr"); + processInfoCB->cbBase.errCode = NAPI_ERR_ABILITY_CALL_INVALID; + } + HILOG_INFO("NAPI_GetProcessInfo, worker pool thread execute end."); +} + +/** + * @brief The callback at the end of the asynchronous callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetProcessInfoAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetProcessInfo, main event thread complete."); + ProcessInfoCB *processInfoCB = (ProcessInfoCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + result[PARAM0] = GetCallbackErrorValue(env, processInfoCB->cbBase.errCode); + if (processInfoCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result[PARAM1] = WrapProcessInfo(env, processInfoCB); + } else { + result[PARAM1] = WrapUndefinedToJS(env); + } + + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, processInfoCB->cbBase.cbInfo.callback, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (processInfoCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, processInfoCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, processInfoCB->cbBase.asyncWork)); + delete processInfoCB; + processInfoCB = nullptr; + HILOG_INFO("NAPI_GetProcessInfo, main event thread complete end."); +} + +/** + * @brief GetProcessInfo Async. + * + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * @param argcPromise Asynchronous data processing. + * @param ProcessInfoCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetProcessInfoAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, ProcessInfoCB *processInfoCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || processInfoCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &processInfoCB->cbBase.cbInfo.callback)); + } + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetProcessInfoExecuteCB, + GetProcessInfoAsyncCompleteCB, + (void *)processInfoCB, + &processInfoCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, processInfoCB->cbBase.asyncWork)); + napi_value result = nullptr; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +/** + * @brief The callback at the end of the Promise callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetProcessInfoPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetProcessInfo, main event thread complete."); + ProcessInfoCB *processInfoCB = (ProcessInfoCB *)data; + napi_value result = nullptr; + if (processInfoCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result = WrapProcessInfo(env, processInfoCB); + napi_resolve_deferred(env, processInfoCB->cbBase.deferred, result); + } else { + result = GetCallbackErrorValue(env, processInfoCB->cbBase.errCode); + napi_reject_deferred(env, processInfoCB->cbBase.deferred, result); + } + + napi_delete_async_work(env, processInfoCB->cbBase.asyncWork); + delete processInfoCB; + processInfoCB = nullptr; + HILOG_INFO("NAPI_GetProcessInfo, main event thread complete end."); +} + +/** + * @brief GetProcessInfo Promise. + * + * @param env The environment that the Node-API call is invoked under. + * @param ProcessInfoCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetProcessInfoPromise(napi_env env, ProcessInfoCB *processInfoCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (processInfoCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + processInfoCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetProcessInfoExecuteCB, + GetProcessInfoPromiseCompleteCB, + (void *)processInfoCB, + &processInfoCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, processInfoCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +/** + * @brief GetProcessInfo processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param ProcessInfoCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetProcessInfoWrap(napi_env env, napi_callback_info info, ProcessInfoCB *processInfoCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (processInfoCB == nullptr) { + HILOG_ERROR("%{public}s, processInfoCB == nullptr.", __func__); + return nullptr; + } + + size_t argcAsync = 1; + const size_t argcPromise = 0; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + if (argcAsync > argcPromise) { + ret = GetProcessInfoAsync(env, args, argcAsync, argcPromise, processInfoCB); + } else { + ret = GetProcessInfoPromise(env, processInfoCB); + } + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return ret; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to ProcessInfoCB on success, nullptr on failure. + */ +ProcessInfoCB *CreateProcessInfoCBInfo(napi_env env) +{ + HILOG_INFO("%{public}s, called.", __func__); + napi_value global = nullptr; + NAPI_CALL(env, napi_get_global(env, &global)); + + napi_value abilityObj = nullptr; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + + ProcessInfoCB *processInfoCB = new (std::nothrow) ProcessInfoCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = ability, + }; + if (processInfoCB == nullptr) { + HILOG_ERROR("%{public}s, processInfoCB == nullptr.", __func__); + } + HILOG_INFO("%{public}s, end.", __func__); + return processInfoCB; +} + +/** + * @brief Obtains the process Info this application. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetProcessInfoCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s called.", __func__); + ProcessInfoCB *processInfoCB = CreateProcessInfoCBInfo(env); + if (processInfoCB == nullptr) { + return WrapVoidToJS(env); + } + + processInfoCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + processInfoCB->cbBase.abilityType = abilityType; + napi_value ret = GetProcessInfoWrap(env, info, processInfoCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr.", __func__); + if (processInfoCB != nullptr) { + delete processInfoCB; + processInfoCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s, end.", __func__); + return ret; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to AppTypeCB on success, nullptr on failure. + */ +AppTypeCB *CreateAppTypeCBInfo(napi_env env) +{ + HILOG_INFO("%{public}s, called.", __func__); + napi_value global = nullptr; + NAPI_CALL(env, napi_get_global(env, &global)); + + napi_value abilityObj = nullptr; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + + AppTypeCB *appTypeCB = new (std::nothrow) AppTypeCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = ability, + }; + if (appTypeCB == nullptr) { + HILOG_ERROR("%{public}s, appTypeCB == nullptr.", __func__); + } + HILOG_INFO("%{public}s, end.", __func__); + return appTypeCB; +} + +/** + * @brief GetAppType asynchronous processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetAppTypeExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_GetApplicationInfo, worker pool thread execute."); + AppTypeCB *appTypeCB = (AppTypeCB *)data; + if (appTypeCB == nullptr) { + HILOG_ERROR("NAPI_GetApplicationInfo,appTypeCB == nullptr"); + return; + } + + appTypeCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + if (appTypeCB->cbBase.ability == nullptr) { + HILOG_ERROR("NAPI_GetApplicationInfo,ability == nullptr"); + appTypeCB->cbBase.errCode = NAPI_ERR_ACE_ABILITY; + return; + } + + if (!CheckAbilityType(&appTypeCB->cbBase)) { + HILOG_ERROR("NAPI_GetApplicationInfo,wrong ability type"); + appTypeCB->cbBase.errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + return; + } + + appTypeCB->name = appTypeCB->cbBase.ability->GetAppType(); + HILOG_INFO("NAPI_GetApplicationInfo, worker pool thread execute end."); +} + +/** + * @brief The callback at the end of the asynchronous callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetAppTypeAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); + AppTypeCB *appTypeCB = (AppTypeCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + + result[PARAM0] = GetCallbackErrorValue(env, appTypeCB->cbBase.errCode); + if (appTypeCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + NAPI_CALL_RETURN_VOID(env, + napi_create_string_utf8( + env, appTypeCB->cbBase.ability->GetAppType().c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); + } else { + result[PARAM1] = WrapUndefinedToJS(env); + } + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, appTypeCB->cbBase.cbInfo.callback, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (appTypeCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, appTypeCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, appTypeCB->cbBase.asyncWork)); + delete appTypeCB; + appTypeCB = nullptr; + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete end."); +} + +/** + * @brief The callback at the end of the Promise callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetAppTypePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("GetAppTypePromiseCompleteCB, main event thread complete."); + AppTypeCB *appTypeCB = (AppTypeCB *)data; + napi_value result = nullptr; + if (appTypeCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + napi_create_string_utf8(env, appTypeCB->cbBase.ability->GetAppType().c_str(), NAPI_AUTO_LENGTH, &result); + napi_resolve_deferred(env, appTypeCB->cbBase.deferred, result); + } else { + result = GetCallbackErrorValue(env, appTypeCB->cbBase.errCode); + napi_reject_deferred(env, appTypeCB->cbBase.deferred, result); + } + + napi_delete_async_work(env, appTypeCB->cbBase.asyncWork); + delete appTypeCB; + appTypeCB = nullptr; + HILOG_INFO("GetAppTypePromiseCompleteCB, main event thread complete end."); +} + +/** + * @brief GetAppType Async. + * + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * @param argcPromise Asynchronous data processing. + * @param appTypeCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetAppTypeAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AppTypeCB *appTypeCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || appTypeCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &appTypeCB->cbBase.cbInfo.callback)); + } + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetAppTypeExecuteCB, + GetAppTypeAsyncCompleteCB, + (void *)appTypeCB, + &appTypeCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, appTypeCB->cbBase.asyncWork)); + napi_value result = nullptr; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +/** + * @brief GetAppType Promise. + * + * @param env The environment that the Node-API call is invoked under. + * @param appTypeCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetAppTypePromise(napi_env env, AppTypeCB *appTypeCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (appTypeCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + appTypeCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetAppTypeExecuteCB, + GetAppTypePromiseCompleteCB, + (void *)appTypeCB, + &appTypeCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, appTypeCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +/** + * @brief GetAppType processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param appTypeCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetAppTypeWrap(napi_env env, napi_callback_info info, AppTypeCB *appTypeCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (appTypeCB == nullptr) { + HILOG_ERROR("%{public}s, appTypeCB == nullptr.", __func__); + return nullptr; + } + + size_t argcAsync = 1; + const size_t argcPromise = 0; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + if (argcAsync > argcPromise) { + ret = GetAppTypeAsync(env, args, argcAsync, argcPromise, appTypeCB); + } else { + ret = GetAppTypePromise(env, appTypeCB); + } + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return ret; +} + +/** + * @brief Obtains the type of this application. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetAppTypeCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s called.", __func__); + AppTypeCB *appTypeCB = CreateAppTypeCBInfo(env); + if (appTypeCB == nullptr) { + return WrapVoidToJS(env); + } + + appTypeCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + appTypeCB->cbBase.abilityType = abilityType; + napi_value ret = GetAppTypeWrap(env, info, appTypeCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr.", __func__); + if (appTypeCB != nullptr) { + delete appTypeCB; + appTypeCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s, end.", __func__); + return ret; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to ElementNameCB on success, nullptr on failure. + */ +ElementNameCB *CreateElementNameCBInfo(napi_env env) +{ + HILOG_INFO("%{public}s, called.", __func__); + napi_value global = nullptr; + NAPI_CALL(env, napi_get_global(env, &global)); + + napi_value abilityObj = nullptr; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + + ElementNameCB *elementNameCB = new (std::nothrow) ElementNameCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = ability, + }; + if (elementNameCB == nullptr) { + HILOG_ERROR("%{public}s, elementNameCB == nullptr.", __func__); + } + HILOG_INFO("%{public}s, end.", __func__); + return elementNameCB; +} + +napi_value WrapElementName(napi_env env, ElementNameCB *elementNameCB) +{ + HILOG_INFO("%{public}s, called.", __func__); + if (elementNameCB == nullptr) { + HILOG_ERROR("%{public}s,Invalid param(appInfoCB = nullptr)", __func__); + return nullptr; + } + napi_value result = nullptr; + napi_value proValue = nullptr; + NAPI_CALL(env, napi_create_object(env, &result)); + NAPI_CALL(env, napi_create_string_utf8(env, elementNameCB->abilityName.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "abilityName", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, elementNameCB->bundleName.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "bundleName", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, elementNameCB->deviceId.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "deviceId", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, elementNameCB->shortName.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "shortName", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, elementNameCB->uri.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "uri", proValue)); + HILOG_INFO("%{public}s, end.", __func__); + return result; +} + +/** + * @brief GetElementName asynchronous processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetElementNameExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_GetApplicationInfo, worker pool thread execute."); + if (data == nullptr) { + HILOG_ERROR("%{public}s, data == nullptr.", __func__); + return; + } + ElementNameCB *elementNameCB = (ElementNameCB *)data; + if (elementNameCB == nullptr) { + HILOG_ERROR("NAPI_GetApplicationInfo, elementNameCB == nullptr"); + return; + } + + elementNameCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + if (elementNameCB->cbBase.ability == nullptr) { + HILOG_ERROR("NAPI_GetApplicationInfo, ability == nullptr"); + elementNameCB->cbBase.errCode = NAPI_ERR_ACE_ABILITY; + return; + } + + if (!CheckAbilityType(&elementNameCB->cbBase)) { + HILOG_ERROR("NAPI_GetApplicationInfo,wrong ability type"); + elementNameCB->cbBase.errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + return; + } + + std::shared_ptr elementName = elementNameCB->cbBase.ability->GetElementName(); + if (elementNameCB != nullptr) { + elementNameCB->deviceId = elementName->GetDeviceID(); + elementNameCB->bundleName = elementName->GetBundleName(); + elementNameCB->abilityName = elementName->GetAbilityName(); + elementNameCB->uri = elementNameCB->cbBase.ability->GetWant()->GetUriString(); + elementNameCB->shortName = ""; + } else { + elementNameCB->cbBase.errCode = NAPI_ERR_ABILITY_CALL_INVALID; + } + HILOG_INFO("NAPI_GetApplicationInfo, worker pool thread execute end."); +} + +/** + * @brief The callback at the end of the asynchronous callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetElementNameAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); + ElementNameCB *elementNameCB = (ElementNameCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + result[PARAM0] = GetCallbackErrorValue(env, elementNameCB->cbBase.errCode); + if (elementNameCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result[PARAM1] = WrapElementName(env, elementNameCB); + } else { + result[PARAM1] = WrapUndefinedToJS(env); + } + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, elementNameCB->cbBase.cbInfo.callback, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (elementNameCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, elementNameCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, elementNameCB->cbBase.asyncWork)); + delete elementNameCB; + elementNameCB = nullptr; + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete end."); +} + +/** + * @brief The callback at the end of the Promise callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetElementNamePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); + ElementNameCB *elementNameCB = (ElementNameCB *)data; + napi_value result = nullptr; + if (elementNameCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result = WrapElementName(env, elementNameCB); + napi_resolve_deferred(env, elementNameCB->cbBase.deferred, result); + } else { + result = GetCallbackErrorValue(env, elementNameCB->cbBase.errCode); + napi_reject_deferred(env, elementNameCB->cbBase.deferred, result); + } + + napi_delete_async_work(env, elementNameCB->cbBase.asyncWork); + delete elementNameCB; + elementNameCB = nullptr; + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete end."); +} + +/** + * @brief GetElementName Promise. + * + * @param env The environment that the Node-API call is invoked under. + * @param elementNameCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetElementNamePromise(napi_env env, ElementNameCB *elementNameCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (elementNameCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + elementNameCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetElementNameExecuteCB, + GetElementNamePromiseCompleteCB, + (void *)elementNameCB, + &elementNameCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, elementNameCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +/** + * @brief GetElementName Async. + * + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * @param argcPromise Asynchronous data processing. + * @param elementNameCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetElementNameAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, ElementNameCB *elementNameCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || elementNameCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &elementNameCB->cbBase.cbInfo.callback)); + } + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetElementNameExecuteCB, + GetElementNameAsyncCompleteCB, + (void *)elementNameCB, + &elementNameCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, elementNameCB->cbBase.asyncWork)); + napi_value result = nullptr; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; + HILOG_INFO("%{public}s, asyncCallback end.", __func__); +} + +/** + * @brief GetElementName processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param elementNameCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetElementNameWrap(napi_env env, napi_callback_info info, ElementNameCB *elementNameCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (elementNameCB == nullptr) { + HILOG_ERROR("%{public}s, appInfoCB == nullptr.", __func__); + return nullptr; + } + + size_t argcAsync = 1; + const size_t argcPromise = 0; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + if (argcAsync > argcPromise) { + ret = GetElementNameAsync(env, args, argcAsync, argcPromise, elementNameCB); + } else { + ret = GetElementNamePromise(env, elementNameCB); + } + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return ret; +} + +/** + * @brief Obtains the elementName object of the current ability. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetElementNameCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s called.", __func__); + ElementNameCB *elementNameCB = CreateElementNameCBInfo(env); + if (elementNameCB == nullptr) { + return WrapVoidToJS(env); + } + + elementNameCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + elementNameCB->cbBase.abilityType = abilityType; + napi_value ret = GetElementNameWrap(env, info, elementNameCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s ret == nullptr.", __func__); + if (elementNameCB != nullptr) { + delete elementNameCB; + elementNameCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to AbilityInfoCB on success, nullptr on failure. + */ +AbilityInfoCB *CreateAbilityInfoCBInfo(napi_env env) +{ + HILOG_INFO("%{public}s called.", __func__); + napi_value global = nullptr; + NAPI_CALL(env, napi_get_global(env, &global)); + + napi_value abilityObj = nullptr; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + + AbilityInfoCB *abilityInfoCB = new (std::nothrow) AbilityInfoCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = ability, + }; + if (abilityInfoCB == nullptr) { + HILOG_ERROR("%{public}s, abilityInfoCB == nullptr.", __func__); + } + HILOG_INFO("%{public}s end.", __func__); + return abilityInfoCB; +} + +void SaveAbilityInfo(AbilityInfo_ &abilityInfo, const AbilityInfo &abilityInfoOrg) +{ + HILOG_INFO("%{public}s called.", __func__); + abilityInfo.bundleName = abilityInfoOrg.bundleName; + abilityInfo.name = abilityInfoOrg.name; + abilityInfo.label = abilityInfoOrg.label; + abilityInfo.description = abilityInfoOrg.description; + abilityInfo.icon = abilityInfoOrg.iconPath; + abilityInfo.labelId = abilityInfoOrg.applicationInfo.labelId; + abilityInfo.descriptionId = abilityInfoOrg.applicationInfo.descriptionId; + abilityInfo.iconId = abilityInfoOrg.applicationInfo.iconId; + abilityInfo.moduleName = abilityInfoOrg.moduleName; + abilityInfo.process = abilityInfoOrg.process; + abilityInfo.isVisible = abilityInfoOrg.visible; + + abilityInfo.type = static_cast(abilityInfoOrg.type); + abilityInfo.orientation = static_cast(abilityInfoOrg.orientation); + abilityInfo.launchMode = static_cast(abilityInfoOrg.launchMode); + + abilityInfo.uri = abilityInfoOrg.uri; + abilityInfo.targetAbility = abilityInfoOrg.targetAbility; + + for (size_t i = 0; i < abilityInfoOrg.permissions.size(); i++) { + abilityInfo.permissions.emplace_back(abilityInfoOrg.permissions.at(i)); + } + for (size_t i = 0; i < abilityInfoOrg.deviceTypes.size(); i++) { + abilityInfo.deviceTypes.emplace_back(abilityInfoOrg.deviceTypes.at(i)); + } + for (size_t i = 0; i < abilityInfoOrg.deviceCapabilities.size(); i++) { + abilityInfo.deviceCapabilities.emplace_back(abilityInfoOrg.deviceCapabilities.at(i)); + } + + SaveAppInfo(abilityInfo.appInfo, abilityInfoOrg.applicationInfo); + + abilityInfo.readPermission = abilityInfoOrg.readPermission; + abilityInfo.writePermission = abilityInfoOrg.writePermission; + abilityInfo.formEntity = 0; // no data + abilityInfo.minFormHeight = 0; // no data + abilityInfo.defaultFormHeight = 0; // no data + abilityInfo.minFormWidth = 0; // no data + abilityInfo.defaultFormWidth = 0; // no data + abilityInfo.backgroundModes = 0; // no data + abilityInfo.subType = 0; // no data + abilityInfo.formEnabled = false; // no data + HILOG_INFO("%{public}s end.", __func__); +} + +napi_value WrapAbilityInfo(napi_env env, const AbilityInfo_ &abilityInfo) +{ + HILOG_INFO("%{public}s called.", __func__); + napi_value result = nullptr; + napi_value proValue = nullptr; + NAPI_CALL(env, napi_create_object(env, &result)); + NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.bundleName.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "bundleName", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.name.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "name", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.label.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "label", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.description.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "description", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.icon.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "icon", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.moduleName.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "moduleName", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.process.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "process", proValue)); + + NAPI_CALL(env, napi_create_int32(env, static_cast(abilityInfo.type), &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "type", proValue)); + + NAPI_CALL(env, napi_create_int32(env, static_cast(abilityInfo.orientation), &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "orientation", proValue)); + + NAPI_CALL(env, napi_create_int32(env, static_cast(abilityInfo.launchMode), &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "launchMode", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.uri.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "uri", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.readPermission.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "readPermission", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.writePermission.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "writePermission", proValue)); + + NAPI_CALL(env, napi_create_string_utf8(env, abilityInfo.targetAbility.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "targetAbility", proValue)); + + NAPI_CALL(env, napi_create_int32(env, abilityInfo.labelId, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "labelId", proValue)); + + NAPI_CALL(env, napi_create_int32(env, abilityInfo.descriptionId, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "descriptionId", proValue)); + + NAPI_CALL(env, napi_create_int32(env, abilityInfo.iconId, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "iconId", proValue)); + + NAPI_CALL(env, napi_create_int32(env, abilityInfo.formEntity, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "formEntity", proValue)); + + NAPI_CALL(env, napi_create_int32(env, abilityInfo.minFormHeight, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "minFormHeight", proValue)); + + NAPI_CALL(env, napi_create_int32(env, abilityInfo.defaultFormHeight, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "defaultFormHeight", proValue)); + + NAPI_CALL(env, napi_create_int32(env, abilityInfo.minFormWidth, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "minFormWidth", proValue)); + + NAPI_CALL(env, napi_create_int32(env, abilityInfo.defaultFormWidth, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "defaultFormWidth", proValue)); + + NAPI_CALL(env, napi_create_int32(env, abilityInfo.backgroundModes, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "backgroundModes", proValue)); + + NAPI_CALL(env, napi_create_int32(env, abilityInfo.subType, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "subType", proValue)); + + NAPI_CALL(env, napi_get_boolean(env, abilityInfo.isVisible, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "isVisible", proValue)); + + NAPI_CALL(env, napi_get_boolean(env, abilityInfo.formEnabled, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "formEnabled", proValue)); + + napi_value jsArrayPermissions = nullptr; + NAPI_CALL(env, napi_create_array(env, &jsArrayPermissions)); + for (size_t i = 0; i < abilityInfo.permissions.size(); i++) { + proValue = nullptr; + NAPI_CALL( + env, napi_create_string_utf8(env, abilityInfo.permissions.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_element(env, jsArrayPermissions, i, proValue)); + } + NAPI_CALL(env, napi_set_named_property(env, result, "permissions", jsArrayPermissions)); + + napi_value jsArrayDeviceCapabilities = nullptr; + NAPI_CALL(env, napi_create_array(env, &jsArrayDeviceCapabilities)); + for (size_t i = 0; i < abilityInfo.deviceCapabilities.size(); i++) { + proValue = nullptr; + NAPI_CALL(env, + napi_create_string_utf8(env, abilityInfo.deviceCapabilities.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_element(env, jsArrayDeviceCapabilities, i, proValue)); + } + NAPI_CALL(env, napi_set_named_property(env, result, "deviceCapabilities", jsArrayDeviceCapabilities)); + + napi_value jsArrayDeviceTypes = nullptr; + NAPI_CALL(env, napi_create_array(env, &jsArrayDeviceTypes)); + for (size_t i = 0; i < abilityInfo.deviceTypes.size(); i++) { + proValue = nullptr; + NAPI_CALL( + env, napi_create_string_utf8(env, abilityInfo.deviceTypes.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_element(env, jsArrayDeviceTypes, i, proValue)); + } + NAPI_CALL(env, napi_set_named_property(env, result, "deviceTypes", jsArrayDeviceTypes)); + + napi_value appInfo = nullptr; + appInfo = WrapAppInfo(env, abilityInfo.appInfo); + NAPI_CALL(env, napi_set_named_property(env, result, "applicationInfo", appInfo)); + HILOG_INFO("%{public}s end.", __func__); + return result; +} + +/** + * @brief GetAbilityInfo asynchronous processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetAbilityInfoExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_GetApplicationInfo, worker pool thread execute."); + AbilityInfoCB *abilityInfoCB = (AbilityInfoCB *)data; + if (abilityInfoCB == nullptr) { + HILOG_ERROR("NAPI_GetApplicationInfo, abilityInfoCB == nullptr"); + return; + } + + abilityInfoCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + if (abilityInfoCB->cbBase.ability == nullptr) { + HILOG_ERROR("NAPI_GetApplicationInfo, ability == nullptr"); + abilityInfoCB->cbBase.errCode = NAPI_ERR_ACE_ABILITY; + return; + } + + if (!CheckAbilityType(&abilityInfoCB->cbBase)) { + HILOG_ERROR("NAPI_GetApplicationInfo,wrong ability type"); + abilityInfoCB->cbBase.errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + return; + } + + std::shared_ptr abilityInfoPtr = abilityInfoCB->cbBase.ability->GetAbilityInfo(); + if (abilityInfoPtr != nullptr) { + SaveAbilityInfo(abilityInfoCB->abilityInfo, *abilityInfoPtr); + } else { + abilityInfoCB->cbBase.errCode = NAPI_ERR_ABILITY_CALL_INVALID; + } + HILOG_INFO("NAPI_GetApplicationInfo, worker pool thread execute end."); +} + +/** + * @brief The callback at the end of the asynchronous callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetAbilityInfoAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); + AbilityInfoCB *abilityInfoCB = (AbilityInfoCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + result[PARAM0] = GetCallbackErrorValue(env, abilityInfoCB->cbBase.errCode); + if (abilityInfoCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result[PARAM1] = WrapAbilityInfo(env, abilityInfoCB->abilityInfo); + } else { + result[PARAM1] = WrapUndefinedToJS(env); + } + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, abilityInfoCB->cbBase.cbInfo.callback, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (abilityInfoCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, abilityInfoCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, abilityInfoCB->cbBase.asyncWork)); + delete abilityInfoCB; + abilityInfoCB = nullptr; + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete end."); +} + +/** + * @brief The callback at the end of the Promise callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetAbilityInfoPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete."); + AbilityInfoCB *abilityInfoCB = (AbilityInfoCB *)data; + napi_value result = nullptr; + if (abilityInfoCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result = WrapAbilityInfo(env, abilityInfoCB->abilityInfo); + napi_resolve_deferred(env, abilityInfoCB->cbBase.deferred, result); + } else { + result = GetCallbackErrorValue(env, abilityInfoCB->cbBase.errCode); + napi_reject_deferred(env, abilityInfoCB->cbBase.deferred, result); + } + + napi_delete_async_work(env, abilityInfoCB->cbBase.asyncWork); + delete abilityInfoCB; + abilityInfoCB = nullptr; + HILOG_INFO("NAPI_GetApplicationInfo, main event thread complete end."); +} + +/** + * @brief GetAbilityInfo Async. + * + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * @param argcPromise Asynchronous data processing. + * @param abilityInfoCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetAbilityInfoAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AbilityInfoCB *abilityInfoCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || abilityInfoCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &abilityInfoCB->cbBase.cbInfo.callback)); + } + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetAbilityInfoExecuteCB, + GetAbilityInfoAsyncCompleteCB, + (void *)abilityInfoCB, + &abilityInfoCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, abilityInfoCB->cbBase.asyncWork)); + napi_value result = nullptr; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +/** + * @brief GetAbilityInfo Promise. + * + * @param env The environment that the Node-API call is invoked under. + * @param abilityInfoCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetAbilityInfoPromise(napi_env env, AbilityInfoCB *abilityInfoCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (abilityInfoCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + abilityInfoCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetAbilityInfoExecuteCB, + GetAbilityInfoPromiseCompleteCB, + (void *)abilityInfoCB, + &abilityInfoCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, abilityInfoCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +/** + * @brief GetAbilityInfo processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param abilityInfoCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetAbilityInfoWrap(napi_env env, napi_callback_info info, AbilityInfoCB *abilityInfoCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (abilityInfoCB == nullptr) { + HILOG_ERROR("%{public}s, abilityInfoCB == nullptr.", __func__); + return nullptr; + } + + size_t argcAsync = 1; + const size_t argcPromise = 0; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + if (argcAsync > argcPromise) { + ret = GetAbilityInfoAsync(env, args, argcAsync, argcPromise, abilityInfoCB); + } else { + ret = GetAbilityInfoPromise(env, abilityInfoCB); + } + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return ret; +} + +/** + * @brief Obtains information about the current ability. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetAbilityInfoCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s called.", __func__); + AbilityInfoCB *abilityInfoCB = CreateAbilityInfoCBInfo(env); + if (abilityInfoCB == nullptr) { + return WrapVoidToJS(env); + } + + abilityInfoCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + abilityInfoCB->cbBase.abilityType = abilityType; + napi_value ret = GetAbilityInfoWrap(env, info, abilityInfoCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s ret == nullptr", __func__); + if (abilityInfoCB != nullptr) { + delete abilityInfoCB; + abilityInfoCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to HapModuleInfoCB on success, nullptr on failure. + */ +HapModuleInfoCB *CreateHapModuleInfoCBInfo(napi_env env) +{ + HILOG_INFO("%{public}s called.", __func__); + napi_value global = nullptr; + NAPI_CALL(env, napi_get_global(env, &global)); + + napi_value abilityObj = nullptr; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + + HapModuleInfoCB *hapModuleInfoCB = new (std::nothrow) HapModuleInfoCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = ability, + }; + if (hapModuleInfoCB == nullptr) { + HILOG_ERROR("%{public}s, hapModuleInfoCB == nullptr.", __func__); + } + HILOG_INFO("%{public}s end.", __func__); + return hapModuleInfoCB; +} + +void SaveHapModuleInfo(HapModuleInfo_ &hapModuleInfo, const HapModuleInfo &hapModuleInfoOrg) +{ + HILOG_INFO("%{public}s called.", __func__); + hapModuleInfo.name = hapModuleInfoOrg.name; + hapModuleInfo.description = hapModuleInfoOrg.description; + hapModuleInfo.icon = hapModuleInfoOrg.iconPath; + hapModuleInfo.label = hapModuleInfoOrg.label; + hapModuleInfo.backgroundImg = hapModuleInfoOrg.backgroundImg; + hapModuleInfo.moduleName = hapModuleInfoOrg.moduleName; + hapModuleInfo.supportedModes = hapModuleInfoOrg.supportedModes; + hapModuleInfo.descriptionId = 0; // no data + hapModuleInfo.labelId = 0; // no data + hapModuleInfo.iconId = 0; // no data + hapModuleInfo.mainAbilityName = ""; // no data + hapModuleInfo.installationFree = false; // no data + + for (size_t i = 0; i < hapModuleInfoOrg.reqCapabilities.size(); i++) { + hapModuleInfo.reqCapabilities.emplace_back(hapModuleInfoOrg.reqCapabilities.at(i)); + } + + for (size_t i = 0; i < hapModuleInfoOrg.deviceTypes.size(); i++) { + hapModuleInfo.deviceTypes.emplace_back(hapModuleInfoOrg.deviceTypes.at(i)); + } + + for (size_t i = 0; i < hapModuleInfoOrg.abilityInfos.size(); i++) { + AbilityInfo_ abilityInfo; + SaveAbilityInfo(abilityInfo, hapModuleInfoOrg.abilityInfos.at(i)); + hapModuleInfo.abilityInfos.emplace_back(abilityInfo); + } + HILOG_INFO("%{public}s end.", __func__); +} + +napi_value WrapHapModuleInfo(napi_env env, const HapModuleInfoCB &hapModuleInfoCB) +{ + HILOG_INFO("%{public}s called.", __func__); + napi_value result = nullptr; + napi_value proValue = nullptr; + NAPI_CALL(env, napi_create_object(env, &result)); + NAPI_CALL( + env, napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.name.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "name", proValue)); + + NAPI_CALL(env, + napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.description.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "description", proValue)); + + NAPI_CALL( + env, napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.icon.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "icon", proValue)); + + NAPI_CALL( + env, napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.label.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "label", proValue)); + + NAPI_CALL(env, + napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.backgroundImg.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "backgroundImg", proValue)); + + NAPI_CALL(env, + napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.moduleName.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "moduleName", proValue)); + + NAPI_CALL(env, napi_create_int32(env, hapModuleInfoCB.hapModuleInfo.supportedModes, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "supportedModes", proValue)); + + NAPI_CALL(env, napi_create_int32(env, hapModuleInfoCB.hapModuleInfo.descriptionId, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "descriptionId", proValue)); + + NAPI_CALL(env, napi_create_int32(env, hapModuleInfoCB.hapModuleInfo.labelId, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "labelId", proValue)); + + NAPI_CALL(env, napi_create_int32(env, hapModuleInfoCB.hapModuleInfo.iconId, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "iconId", proValue)); + + NAPI_CALL(env, + napi_create_string_utf8( + env, hapModuleInfoCB.hapModuleInfo.mainAbilityName.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "mainAbilityName", proValue)); + + NAPI_CALL(env, napi_get_boolean(env, hapModuleInfoCB.hapModuleInfo.installationFree, &proValue)); + NAPI_CALL(env, napi_set_named_property(env, result, "installationFree", proValue)); + + napi_value jsArrayreqCapabilities = nullptr; + NAPI_CALL(env, napi_create_array(env, &jsArrayreqCapabilities)); + for (size_t i = 0; i < hapModuleInfoCB.hapModuleInfo.reqCapabilities.size(); i++) { + proValue = nullptr; + NAPI_CALL(env, + napi_create_string_utf8( + env, hapModuleInfoCB.hapModuleInfo.reqCapabilities.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_element(env, jsArrayreqCapabilities, i, proValue)); + } + NAPI_CALL(env, napi_set_named_property(env, result, "reqCapabilities", jsArrayreqCapabilities)); + + napi_value jsArraydeviceTypes = nullptr; + NAPI_CALL(env, napi_create_array(env, &jsArraydeviceTypes)); + for (size_t i = 0; i < hapModuleInfoCB.hapModuleInfo.deviceTypes.size(); i++) { + proValue = nullptr; + NAPI_CALL(env, + napi_create_string_utf8( + env, hapModuleInfoCB.hapModuleInfo.deviceTypes.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_element(env, jsArraydeviceTypes, i, proValue)); + } + NAPI_CALL(env, napi_set_named_property(env, result, "deviceTypes", jsArraydeviceTypes)); + + napi_value abilityInfos = nullptr; + NAPI_CALL(env, napi_create_array(env, &abilityInfos)); + for (size_t i = 0; i < hapModuleInfoCB.hapModuleInfo.abilityInfos.size(); i++) { + napi_value abilityInfo = nullptr; + abilityInfo = WrapAbilityInfo(env, hapModuleInfoCB.hapModuleInfo.abilityInfos.at(i)); + NAPI_CALL(env, napi_set_element(env, abilityInfos, i, abilityInfo)); + } + NAPI_CALL(env, napi_set_named_property(env, result, "abilityInfos", abilityInfos)); + HILOG_INFO("%{public}s end.", __func__); + return result; +} + +void GetHapModuleInfoExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_GetHapModuleInfo, worker pool thread execute."); + HapModuleInfoCB *hapModuleInfoCB = (HapModuleInfoCB *)data; + if (hapModuleInfoCB == nullptr) { + HILOG_ERROR("NAPI_GetHapModuleInfo, hapModuleInfoCB == nullptr"); + return; + } + + hapModuleInfoCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + if (hapModuleInfoCB->cbBase.ability == nullptr) { + HILOG_ERROR("NAPI_GetHapModuleInfo, ability == nullptr"); + hapModuleInfoCB->cbBase.errCode = NAPI_ERR_ACE_ABILITY; + return; + } + + if (!CheckAbilityType(&hapModuleInfoCB->cbBase)) { + HILOG_ERROR("NAPI_GetHapModuleInfo,wrong ability type"); + hapModuleInfoCB->cbBase.errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + return; + } + + std::shared_ptr hapModuleInfoPtr = hapModuleInfoCB->cbBase.ability->GetHapModuleInfo(); + if (hapModuleInfoPtr != nullptr) { + SaveHapModuleInfo(hapModuleInfoCB->hapModuleInfo, *hapModuleInfoPtr); + } else { + hapModuleInfoCB->cbBase.errCode = NAPI_ERR_ABILITY_CALL_INVALID; + } + HILOG_INFO("NAPI_GetHapModuleInfo, worker pool thread execute end."); +} + +void GetHapModuleInfoAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetHapModuleInfo, main event thread complete."); + HapModuleInfoCB *hapModuleInfoCB = (HapModuleInfoCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + result[PARAM0] = GetCallbackErrorValue(env, hapModuleInfoCB->cbBase.errCode); + if (hapModuleInfoCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result[PARAM1] = WrapHapModuleInfo(env, *hapModuleInfoCB); + } else { + result[PARAM1] = WrapUndefinedToJS(env); + } + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, hapModuleInfoCB->cbBase.cbInfo.callback, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (hapModuleInfoCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, hapModuleInfoCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, hapModuleInfoCB->cbBase.asyncWork)); + delete hapModuleInfoCB; + hapModuleInfoCB = nullptr; + HILOG_INFO("NAPI_GetHapModuleInfo, main event thread complete end."); +} + +void GetHapModuleInfoPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetHapModuleInfo, main event thread complete."); + HapModuleInfoCB *hapModuleInfoCB = (HapModuleInfoCB *)data; + napi_value result = nullptr; + if (hapModuleInfoCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result = WrapHapModuleInfo(env, *hapModuleInfoCB); + napi_resolve_deferred(env, hapModuleInfoCB->cbBase.deferred, result); + } else { + result = GetCallbackErrorValue(env, hapModuleInfoCB->cbBase.errCode); + napi_reject_deferred(env, hapModuleInfoCB->cbBase.deferred, result); + } + + napi_delete_async_work(env, hapModuleInfoCB->cbBase.asyncWork); + delete hapModuleInfoCB; + hapModuleInfoCB = nullptr; + HILOG_INFO("NAPI_GetHapModuleInfo, main event thread complete end."); +} + +/** + * @brief GetHapModuleInfo Async. + * + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * @param argcPromise Asynchronous data processing. + * @param hapModuleInfoCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetHapModuleInfoAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, HapModuleInfoCB *hapModuleInfoCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || hapModuleInfoCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &hapModuleInfoCB->cbBase.cbInfo.callback)); + } + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetHapModuleInfoExecuteCB, + GetHapModuleInfoAsyncCompleteCB, + (void *)hapModuleInfoCB, + &hapModuleInfoCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, hapModuleInfoCB->cbBase.asyncWork)); + napi_value result = nullptr; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +/** + * @brief GetHapModuleInfo Promise. + * + * @param env The environment that the Node-API call is invoked under. + * @param hapModuleInfoCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetHapModuleInfoPromise(napi_env env, HapModuleInfoCB *hapModuleInfoCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (hapModuleInfoCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + hapModuleInfoCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetHapModuleInfoExecuteCB, + GetHapModuleInfoPromiseCompleteCB, + (void *)hapModuleInfoCB, + &hapModuleInfoCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, hapModuleInfoCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +napi_value GetHapModuleInfoWrap(napi_env env, napi_callback_info info, HapModuleInfoCB *hapModuleInfoCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (hapModuleInfoCB == nullptr) { + HILOG_ERROR("%{public}s, hapModuleInfoCB == nullptr.", __func__); + return nullptr; + } + + size_t argcAsync = 1; + const size_t argcPromise = 0; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + if (argcAsync > argcPromise) { + ret = GetHapModuleInfoAsync(env, args, argcAsync, argcPromise, hapModuleInfoCB); + } else { + ret = GetHapModuleInfoPromise(env, hapModuleInfoCB); + } + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return ret; +} + +/** + * @brief Obtains the HapModuleInfo object of the application. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetHapModuleInfoCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s called.", __func__); + HapModuleInfoCB *hapModuleInfoCB = CreateHapModuleInfoCBInfo(env); + if (hapModuleInfoCB == nullptr) { + return WrapVoidToJS(env); + } + + hapModuleInfoCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + hapModuleInfoCB->cbBase.abilityType = abilityType; + napi_value ret = GetHapModuleInfoWrap(env, info, hapModuleInfoCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s ret == nullptr", __func__); + if (hapModuleInfoCB != nullptr) { + delete hapModuleInfoCB; + hapModuleInfoCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to ProcessNameCB on success, nullptr on failure. + */ +ProcessNameCB *CreateProcessNameCBInfo(napi_env env) +{ + HILOG_INFO("%{public}s called.", __func__); + napi_value global = nullptr; + NAPI_CALL(env, napi_get_global(env, &global)); + + napi_value abilityObj = nullptr; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + + ProcessNameCB *processNameCB = new (std::nothrow) ProcessNameCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = ability, + }; + if (processNameCB == nullptr) { + HILOG_ERROR("%{public}s, processNameCB == nullptr.", __func__); + } + HILOG_INFO("%{public}s end.", __func__); + return processNameCB; +} + +/** + * @brief GetProcessName asynchronous processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetProcessNameExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_GetProcessName, worker pool thread execute."); + ProcessNameCB *processNameCB = (ProcessNameCB *)data; + if (processNameCB == nullptr) { + HILOG_ERROR("NAPI_GetProcessName, processNameCB == nullptr"); + return; + } + + processNameCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + if (processNameCB->cbBase.ability == nullptr) { + HILOG_ERROR("NAPI_GetProcessName, ability == nullptr"); + processNameCB->cbBase.errCode = NAPI_ERR_ACE_ABILITY; + return; + } + + if (!CheckAbilityType(&processNameCB->cbBase)) { + HILOG_ERROR("NAPI_GetProcessName,wrong ability type"); + processNameCB->cbBase.errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + return; + } + + processNameCB->processName = processNameCB->cbBase.ability->GetProcessName(); + HILOG_INFO("NAPI_GetProcessName, worker pool thread execute end."); +} + +napi_value WrapProcessName(napi_env env, ProcessNameCB *processNameCB) +{ + HILOG_INFO("%{public}s, called.", __func__); + if (processNameCB == nullptr) { + HILOG_ERROR("%{public}s, Invalid param(processNameCB == nullptr)", __func__); + return nullptr; + } + napi_value result = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, processNameCB->processName.c_str(), NAPI_AUTO_LENGTH, &result)); + HILOG_INFO("%{public}s, end.", __func__); + return result; +} + +/** + * @brief The callback at the end of the asynchronous callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetProcessNameAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetProcessName, main event thread complete."); + ProcessNameCB *processNameCB = (ProcessNameCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + result[PARAM0] = GetCallbackErrorValue(env, processNameCB->cbBase.errCode); + if (processNameCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result[PARAM1] = WrapProcessName(env, processNameCB); + } else { + result[PARAM1] = WrapUndefinedToJS(env); + } + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, processNameCB->cbBase.cbInfo.callback, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (processNameCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, processNameCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, processNameCB->cbBase.asyncWork)); + delete processNameCB; + processNameCB = nullptr; + HILOG_INFO("NAPI_GetProcessName, main event thread complete end."); +} + +/** + * @brief The callback at the end of the Promise callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetProcessNamePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetProcessName, main event thread complete."); + ProcessNameCB *processNameCB = (ProcessNameCB *)data; + napi_value result = nullptr; + if (processNameCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result = WrapProcessName(env, processNameCB); + napi_resolve_deferred(env, processNameCB->cbBase.deferred, result); + } else { + result = GetCallbackErrorValue(env, processNameCB->cbBase.errCode); + napi_reject_deferred(env, processNameCB->cbBase.deferred, result); + } + + napi_delete_async_work(env, processNameCB->cbBase.asyncWork); + delete processNameCB; + processNameCB = nullptr; + HILOG_INFO("NAPI_GetProcessName, main event thread complete end."); +} + +/** + * @brief GetProcessName Async. + * + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * @param argcPromise Asynchronous data processing. + * @param ProcessNameCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetProcessNameAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, ProcessNameCB *processNameCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || processNameCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &processNameCB->cbBase.cbInfo.callback)); + } + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetProcessNameExecuteCB, + GetProcessNameAsyncCompleteCB, + (void *)processNameCB, + &processNameCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, processNameCB->cbBase.asyncWork)); + napi_value result = nullptr; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +/** + * @brief GetProcessName Promise. + * + * @param env The environment that the Node-API call is invoked under. + * @param ProcessNameCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetProcessNamePromise(napi_env env, ProcessNameCB *processNameCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (processNameCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + processNameCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetProcessNameExecuteCB, + GetProcessNamePromiseCompleteCB, + (void *)processNameCB, + &processNameCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, processNameCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +/** + * @brief GetProcessName processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param ProcessNameCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetProcessNameWrap(napi_env env, napi_callback_info info, ProcessNameCB *processNameCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (processNameCB == nullptr) { + HILOG_ERROR("%{public}s, processNameCB == nullptr.", __func__); + return nullptr; + } + + size_t argcAsync = 1; + const size_t argcPromise = 0; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + if (argcAsync > argcPromise) { + ret = GetProcessNameAsync(env, args, argcAsync, argcPromise, processNameCB); + } else { + ret = GetProcessNamePromise(env, processNameCB); + } + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return ret; +} + +/** + * @brief Obtains the name of the current process. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetProcessNameCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s called.", __func__); + ProcessNameCB *processNameCB = CreateProcessNameCBInfo(env); + if (processNameCB == nullptr) { + return WrapVoidToJS(env); + } + + processNameCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + processNameCB->cbBase.abilityType = abilityType; + napi_value ret = GetProcessNameWrap(env, info, processNameCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s ret == nullptr.", __func__); + if (processNameCB != nullptr) { + delete processNameCB; + processNameCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to CallingBundleCB on success, nullptr on failure. + */ +CallingBundleCB *CreateCallingBundleCBInfo(napi_env env) +{ + HILOG_INFO("%{public}s called.", __func__); + napi_value global = nullptr; + NAPI_CALL(env, napi_get_global(env, &global)); + + napi_value abilityObj = nullptr; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + + CallingBundleCB *callingBundleCB = new (std::nothrow) CallingBundleCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = ability, + }; + if (callingBundleCB == nullptr) { + HILOG_ERROR("%{public}s, callingBundleCB == nullptr.", __func__); + } + HILOG_INFO("%{public}s end.", __func__); + return callingBundleCB; +} + +/** + * @brief GetCallingBundle asynchronous processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetCallingBundleExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_GetCallingBundle, worker pool thread execute."); + CallingBundleCB *callingBundleCB = (CallingBundleCB *)data; + if (callingBundleCB == nullptr) { + HILOG_ERROR("NAPI_GetCallingBundle, callingBundleCB == nullptr"); + return; + } + + callingBundleCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + if (callingBundleCB->cbBase.ability == nullptr) { + HILOG_ERROR("NAPI_GetCallingBundle, ability == nullptr"); + callingBundleCB->cbBase.errCode = NAPI_ERR_ACE_ABILITY; + return; + } + + if (!CheckAbilityType(&callingBundleCB->cbBase)) { + HILOG_ERROR("NAPI_GetCallingBundle,wrong ability type"); + callingBundleCB->cbBase.errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + return; + } + callingBundleCB->callingBundleName = callingBundleCB->cbBase.ability->GetCallingBundle(); + HILOG_INFO("NAPI_GetCallingBundle, worker pool thread execute end."); +} + +napi_value WrapCallingBundle(napi_env env, CallingBundleCB *callingBundleCB) +{ + HILOG_INFO("%{public}s, called.", __func__); + if (callingBundleCB == nullptr) { + HILOG_ERROR("%{public}s,Invalid param(callingBundleCB == nullptr)", __func__); + return nullptr; + } + napi_value result = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, callingBundleCB->callingBundleName.c_str(), NAPI_AUTO_LENGTH, &result)); + HILOG_INFO("%{public}s, end.", __func__); + return result; +} + +/** + * @brief The callback at the end of the asynchronous callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetCallingBundleAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetCallingBundle, main event thread complete."); + CallingBundleCB *callingBundleCB = (CallingBundleCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + result[PARAM0] = GetCallbackErrorValue(env, callingBundleCB->cbBase.errCode); + if (callingBundleCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result[PARAM1] = WrapCallingBundle(env, callingBundleCB); + } else { + result[PARAM1] = WrapUndefinedToJS(env); + } + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, callingBundleCB->cbBase.cbInfo.callback, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (callingBundleCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, callingBundleCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, callingBundleCB->cbBase.asyncWork)); + delete callingBundleCB; + callingBundleCB = nullptr; + HILOG_INFO("NAPI_GetCallingBundle, main event thread complete end."); +} + +/** + * @brief The callback at the end of the Promise callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetCallingBundlePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetCallingBundle, main event thread complete."); + CallingBundleCB *callingBundleCB = (CallingBundleCB *)data; + napi_value result = nullptr; + if (callingBundleCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result = WrapCallingBundle(env, callingBundleCB); + napi_resolve_deferred(env, callingBundleCB->cbBase.deferred, result); + } else { + result = GetCallbackErrorValue(env, callingBundleCB->cbBase.errCode); + napi_reject_deferred(env, callingBundleCB->cbBase.deferred, result); + } + + napi_delete_async_work(env, callingBundleCB->cbBase.asyncWork); + delete callingBundleCB; + callingBundleCB = nullptr; + HILOG_INFO("NAPI_GetCallingBundle, main event thread complete end."); +} + +/** + * @brief GetCallingBundle Async. + * + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * @param argcPromise Asynchronous data processing. + * @param CallingBundleCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetCallingBundleAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, CallingBundleCB *callingBundleCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || callingBundleCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &callingBundleCB->cbBase.cbInfo.callback)); + } + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetCallingBundleExecuteCB, + GetCallingBundleAsyncCompleteCB, + (void *)callingBundleCB, + &callingBundleCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, callingBundleCB->cbBase.asyncWork)); + napi_value result = nullptr; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +/** + * @brief GetCallingBundle Promise. + * + * @param env The environment that the Node-API call is invoked under. + * @param CallingBundleCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetCallingBundlePromise(napi_env env, CallingBundleCB *callingBundleCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (callingBundleCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + callingBundleCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetCallingBundleExecuteCB, + GetCallingBundlePromiseCompleteCB, + (void *)callingBundleCB, + &callingBundleCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, callingBundleCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +/** + * @brief GetCallingBundle processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param CallingBundleCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetCallingBundleWrap(napi_env env, napi_callback_info info, CallingBundleCB *callingBundleCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (callingBundleCB == nullptr) { + HILOG_ERROR("%{public}s, callingBundleCB == nullptr.", __func__); + return nullptr; + } + + size_t argcAsync = 1; + const size_t argcPromise = 0; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + if (argcAsync > argcPromise) { + ret = GetCallingBundleAsync(env, args, argcAsync, argcPromise, callingBundleCB); + } else { + ret = GetCallingBundlePromise(env, callingBundleCB); + } + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return ret; +} + +/** + * @brief Obtains the bundle name of the ability that called the current ability. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetCallingBundleCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s called.", __func__); + CallingBundleCB *calloingBundleCB = CreateCallingBundleCBInfo(env); + if (calloingBundleCB == nullptr) { + return WrapVoidToJS(env); + } + + calloingBundleCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + calloingBundleCB->cbBase.abilityType = abilityType; + napi_value ret = GetCallingBundleWrap(env, info, calloingBundleCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s ret == nullptr", __func__); + if (calloingBundleCB != nullptr) { + delete calloingBundleCB; + calloingBundleCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to AsyncCallbackInfo on success, nullptr on failure + */ +AsyncCallbackInfo *CreateAsyncCallbackInfo(napi_env env) +{ + HILOG_INFO("%{public}s called.", __func__); + napi_status ret; + napi_value global = 0; + const napi_extended_error_info *errorInfo = nullptr; + ret = napi_get_global(env, &global); + if (ret != napi_ok) { + napi_get_last_error_info(env, &errorInfo); + HILOG_ERROR("%{public}s get_global=%{public}d err:%{public}s", __func__, ret, errorInfo->error_message); + } + + napi_value abilityObj = 0; + ret = napi_get_named_property(env, global, "ability", &abilityObj); + if (ret != napi_ok) { + napi_get_last_error_info(env, &errorInfo); + HILOG_ERROR("%{public}s get_named_property=%{public}d err:%{public}s", __func__, ret, errorInfo->error_message); + } + + Ability *ability = nullptr; + ret = napi_get_value_external(env, abilityObj, (void **)&ability); + if (ret != napi_ok) { + napi_get_last_error_info(env, &errorInfo); + HILOG_ERROR("%{public}s get_value_external=%{public}d err:%{public}s", __func__, ret, errorInfo->error_message); + } + + AsyncCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo{ + .cbInfo.env = env, + .asyncWork = nullptr, + .deferred = nullptr, + .ability = ability, + .native_result = false, + .errCode = NAPI_ERR_NO_ERROR, + .abilityType = AbilityType::UNKNOWN, + }; + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s asyncCallbackInfo == nullptr", __func__); + } + HILOG_INFO("%{public}s end.", __func__); + return asyncCallbackInfo; +} + +void GetContextAsyncExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("GetContextAsync, worker pool thread execute."); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("GetContextAsync, asyncCallbackInfo == nullptr"); + return; + } + asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; + if (asyncCallbackInfo->ability == nullptr) { + HILOG_ERROR("GetContextAsync, ability == nullptr"); + asyncCallbackInfo->errCode = NAPI_ERR_ACE_ABILITY; + return; + } + + if (!CheckAbilityType(asyncCallbackInfo)) { + HILOG_ERROR("GetContextAsync,wrong ability type"); + asyncCallbackInfo->errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + return; + } + HILOG_INFO("GetContextAsync, worker pool thread execute end."); +} + +napi_value GetContextAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + + napi_valuetype valuetype = napi_undefined; + napi_typeof(env, args[argcPromise], &valuetype); + if (valuetype == napi_function) { + napi_create_reference(env, args[argcPromise], 1, &asyncCallbackInfo->cbInfo.callback); + } + napi_create_async_work( + env, + nullptr, + resourceName, + GetContextAsyncExecuteCB, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetContextAsync, main event thread complete."); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + napi_value callback = 0; + napi_value undefined = 0; + napi_value result[ARGS_TWO] = {0}; + napi_value callResult = 0; + napi_get_undefined(env, &undefined); + result[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); + if (asyncCallbackInfo->errCode == NAPI_ERR_NO_ERROR) { + napi_new_instance(env, g_classContext, 0, nullptr, &result[PARAM1]); + } else { + result[PARAM1] = WrapUndefinedToJS(env); + } + napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); + napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); + + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + HILOG_INFO("GetContextAsync, main event thread complete end."); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + napi_value result = 0; + napi_get_null(env, &result); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value GetContextPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_deferred deferred; + napi_value promise = 0; + napi_create_promise(env, &deferred, &promise); + asyncCallbackInfo->deferred = deferred; + + napi_create_async_work( + env, + nullptr, + resourceName, + GetContextAsyncExecuteCB, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetContextPromise, main event thread complete."); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + napi_value result = nullptr; + if (asyncCallbackInfo->errCode == NAPI_ERR_NO_ERROR) { + napi_new_instance(env, g_classContext, 0, nullptr, &result); + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); + } else { + result = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); + napi_reject_deferred(env, asyncCallbackInfo->deferred, result); + } + + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + HILOG_INFO("GetContextPromise, main event thread complete end."); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +/** + * @brief GetContext processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param asyncCallbackInfo Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetContextWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s, called.", __func__); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, asyncCallbackInfo == nullptr.", __func__); + return nullptr; + } + + asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; + if (!CheckAbilityType(asyncCallbackInfo)) { + HILOG_ERROR("%{public}s,wrong ability type", __func__); + asyncCallbackInfo->errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + return nullptr; + } + + napi_value result = nullptr; + napi_new_instance(env, g_classContext, 0, nullptr, &result); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + HILOG_INFO("%{public}s, end.", __func__); + return result; +} + +/** + * @brief Get context. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetContextCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s, called.", __func__); + AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s asyncCallbackInfo == nullptr", __func__); + return WrapVoidToJS(env); + } + + asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->abilityType = abilityType; + napi_value ret = GetContextWrap(env, info, asyncCallbackInfo); + if (ret == nullptr) { + HILOG_ERROR("%{public}s ret == nullptr", __func__); + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s, end.", __func__); + return ret; +} + +void GetWantExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("%{public}s, called.", __func__); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, asyncCallbackInfo == nullptr", __func__); + return; + } + asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; + if (asyncCallbackInfo->ability == nullptr) { + HILOG_ERROR("%{public}s, ability == nullptr", __func__); + asyncCallbackInfo->errCode = NAPI_ERR_ACE_ABILITY; + return; + } + + if (!CheckAbilityType(asyncCallbackInfo)) { + HILOG_ERROR("%{public}s, wrong ability type", __func__); + asyncCallbackInfo->errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + return; + } + + std::shared_ptr ptrWant = asyncCallbackInfo->ability->GetWant(); + if (ptrWant != nullptr) { + asyncCallbackInfo->param.want = *ptrWant; + } else { + asyncCallbackInfo->errCode = NAPI_ERR_ABILITY_CALL_INVALID; + } + HILOG_INFO("%{public}s, end.", __func__); +} + +napi_value GetWantAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + + napi_valuetype valuetype = napi_undefined; + napi_typeof(env, args[argcPromise], &valuetype); + if (valuetype == napi_function) { + napi_create_reference(env, args[argcPromise], 1, &asyncCallbackInfo->cbInfo.callback); + } + napi_create_async_work( + env, + nullptr, + resourceName, + GetWantExecuteCB, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetWantAsync, main event thread complete."); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + napi_value callback = 0; + napi_value undefined = 0; + napi_value result[ARGS_TWO] = {0}; + napi_value callResult = 0; + napi_get_undefined(env, &undefined); + result[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); + if (asyncCallbackInfo->errCode == NAPI_ERR_NO_ERROR) { + result[PARAM1] = WrapWant(env, asyncCallbackInfo->param.want); + } else { + result[PARAM1] = WrapUndefinedToJS(env); + } + napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); + napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); + + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + HILOG_INFO("GetWantAsync, main event thread complete end."); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + napi_value result = 0; + napi_get_null(env, &result); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value GetWantPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_deferred deferred; + napi_value promise = 0; + napi_create_promise(env, &deferred, &promise); + asyncCallbackInfo->deferred = deferred; + + napi_create_async_work( + env, + nullptr, + resourceName, + GetWantExecuteCB, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetWantPromise, main event thread complete."); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + napi_value result = nullptr; + if (asyncCallbackInfo->errCode == NAPI_ERR_NO_ERROR) { + result = WrapWant(env, asyncCallbackInfo->param.want); + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); + } else { + result = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); + napi_reject_deferred(env, asyncCallbackInfo->deferred, result); + } + + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + HILOG_INFO("GetWantPromise, main event thread complete end."); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +/** + * @brief GetWantWrap processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param asyncCallbackInfo Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetWantWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, asyncCallbackInfo == nullptr.", __func__); + return nullptr; + } + + size_t argcAsync = 1; + const size_t argcPromise = 0; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + if (argcAsync > argcPromise) { + ret = GetWantAsync(env, args, argcAsync, argcPromise, asyncCallbackInfo); + } else { + ret = GetWantPromise(env, asyncCallbackInfo); + } + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return ret; +} + +/** + * @brief Get want. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetWantCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s, called.", __func__); + AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, asyncCallbackInfo == nullptr", __func__); + return WrapVoidToJS(env); + } + + asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->abilityType = abilityType; + napi_value ret = GetWantWrap(env, info, asyncCallbackInfo); + if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr", __func__); + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s, end.", __func__); + return ret; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to AbilityNameCB on success, nullptr on failure. + */ +AbilityNameCB *CreateAbilityNameCBInfo(napi_env env) +{ + HILOG_INFO("%{public}s, called.", __func__); + napi_value global = nullptr; + NAPI_CALL(env, napi_get_global(env, &global)); + + napi_value abilityObj = nullptr; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + + AbilityNameCB *abilityNameCB = new (std::nothrow) AbilityNameCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = ability, + }; + if (abilityNameCB == nullptr) { + HILOG_ERROR("%{public}s, abilityNameCB == nullptr.", __func__); + } + HILOG_INFO("%{public}s, end.", __func__); + return abilityNameCB; +} + +napi_value WrapAbilityName(napi_env env, AbilityNameCB *abilityNameCB) +{ + HILOG_INFO("%{public}s, called.", __func__); + if (abilityNameCB == nullptr) { + HILOG_ERROR("%{public}s, Invalid param(abilityNameCB == nullptr)", __func__); + return nullptr; + } + napi_value result = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, abilityNameCB->name.c_str(), NAPI_AUTO_LENGTH, &result)); + HILOG_INFO("%{public}s, end.", __func__); + return result; +} + +/** + * @brief GetAbilityName asynchronous processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetAbilityNameExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("%{public}s, called.", __func__); + AbilityNameCB *abilityNameCB = (AbilityNameCB *)data; + if (abilityNameCB == nullptr) { + HILOG_ERROR("%{public}s, abilityNameCB == nullptr", __func__); + return; + } + abilityNameCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + if (abilityNameCB->cbBase.ability == nullptr) { + HILOG_ERROR("%{public}s, ability == nullptr", __func__); + abilityNameCB->cbBase.errCode = NAPI_ERR_ACE_ABILITY; + return; + } + + if (!CheckAbilityType(&abilityNameCB->cbBase)) { + HILOG_ERROR("%{public}s, wrong ability type", __func__); + abilityNameCB->cbBase.errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + return; + } + + abilityNameCB->name = abilityNameCB->cbBase.ability->GetAbilityName(); + HILOG_INFO("%{public}s, end.", __func__); +} + +/** + * @brief The callback at the end of the asynchronous callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetAbilityNameAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("%{public}s, called.", __func__); + AbilityNameCB *abilityNameCB = (AbilityNameCB *)data; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + result[PARAM0] = GetCallbackErrorValue(env, abilityNameCB->cbBase.errCode); + if (abilityNameCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result[PARAM1] = WrapAbilityName(env, abilityNameCB); + } else { + result[PARAM1] = WrapUndefinedToJS(env); + } + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, abilityNameCB->cbBase.cbInfo.callback, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + if (abilityNameCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, abilityNameCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, abilityNameCB->cbBase.asyncWork)); + delete abilityNameCB; + abilityNameCB = nullptr; + HILOG_INFO("%{public}s, end.", __func__); +} + +/** + * @brief The callback at the end of the Promise callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void GetAbilityNamePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetAbilityName, main event thread complete."); + AbilityNameCB *abilityNameCB = (AbilityNameCB *)data; + napi_value result = nullptr; + if (abilityNameCB->cbBase.errCode == NAPI_ERR_NO_ERROR) { + result = WrapAbilityName(env, abilityNameCB); + napi_resolve_deferred(env, abilityNameCB->cbBase.deferred, result); + } else { + result = GetCallbackErrorValue(env, abilityNameCB->cbBase.errCode); + napi_reject_deferred(env, abilityNameCB->cbBase.deferred, result); + } + + napi_delete_async_work(env, abilityNameCB->cbBase.asyncWork); + delete abilityNameCB; + abilityNameCB = nullptr; + HILOG_INFO("NAPI_GetAbilityName, main event thread complete end."); +} + +/** + * @brief GetAbilityName Async. + * + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * @param argcPromise Asynchronous data processing. + * @param abilityNameCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetAbilityNameAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AbilityNameCB *abilityNameCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || abilityNameCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &abilityNameCB->cbBase.cbInfo.callback)); + } + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetAbilityNameExecuteCB, + GetAbilityNameAsyncCompleteCB, + (void *)abilityNameCB, + &abilityNameCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, abilityNameCB->cbBase.asyncWork)); + napi_value result = nullptr; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +/** + * @brief GetAbilityName Promise. + * + * @param env The environment that the Node-API call is invoked under. + * @param abilityNameCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetAbilityNamePromise(napi_env env, AbilityNameCB *abilityNameCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (abilityNameCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + abilityNameCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetAbilityNameExecuteCB, + GetAbilityNamePromiseCompleteCB, + (void *)abilityNameCB, + &abilityNameCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, abilityNameCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +/** + * @brief GetAbilityName processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param abilityNameCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value GetAbilityNameWrap(napi_env env, napi_callback_info info, AbilityNameCB *abilityNameCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (abilityNameCB == nullptr) { + HILOG_ERROR("%{public}s, abilityNameCB == nullptr.", __func__); + return nullptr; + } + + size_t argcAsync = 1; + const size_t argcPromise = 0; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + if (argcAsync > argcPromise) { + ret = GetAbilityNameAsync(env, args, argcAsync, argcPromise, abilityNameCB); + } else { + ret = GetAbilityNamePromise(env, abilityNameCB); + } + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return ret; +} + +/** + * @brief Obtains the class name in this ability name, without the prefixed bundle name. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetAbilityNameCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s called.", __func__); + AbilityNameCB *ablityNameCB = CreateAbilityNameCBInfo(env); + if (ablityNameCB == nullptr) { + HILOG_ERROR("%{public}s ablityNameCB == nullptr", __func__); + return WrapVoidToJS(env); + } + + ablityNameCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + ablityNameCB->cbBase.abilityType = abilityType; + napi_value ret = GetAbilityNameWrap(env, info, ablityNameCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s ret == nullptr", __func__); + if (ablityNameCB != nullptr) { + delete ablityNameCB; + ablityNameCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +/** + * @brief Parse the parameters. + * + * @param param Indicates the parameters saved the parse result. + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * + * @return The return value from NAPI C++ to JS for the module. + */ +bool UnwrapParamForWant(napi_env env, napi_value args, AbilityType abilityType, CallAbilityParam ¶m) +{ + HILOG_INFO("%{public}s called.", __func__); + bool ret = false; + napi_valuetype valueType = napi_undefined; + param.setting = nullptr; + NAPI_CALL_BASE(env, napi_typeof(env, args, &valueType), false); + if (valueType != napi_object) { + HILOG_ERROR("%{public}s, Wrong argument type.", __func__); + return false; + } + + napi_value jsWant = GetPropertyValueByPropertyName(env, args, "want", napi_object); + if (jsWant == nullptr) { + HILOG_ERROR("%{public}s, jsWant == nullptr", __func__); + return false; + } + + ret = UnwrapWant(env, jsWant, param.want); + + napi_value jsSettingObj = GetPropertyValueByPropertyName(env, args, "abilityStartSetting", napi_object); + if (jsSettingObj != nullptr) { + param.setting = AbilityStartSetting::GetEmptySetting(); + HILOG_INFO("%{public}s abilityStartSetting = %{public}p.", __func__, param.setting.get()); + } + + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +void StartAbilityExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s asyncCallbackInfo == nullptr", __func__); + return; + } + asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->errCode = NAPI_ERR_ACE_ABILITY; + HILOG_ERROR("%{public}s ability == nullptr", __func__); + return; + } + + if (!CheckAbilityType(asyncCallbackInfo)) { + HILOG_ERROR("%{public}s wrong ability type", __func__); + asyncCallbackInfo->errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + return; + } + + if (asyncCallbackInfo->param.setting == nullptr) { + asyncCallbackInfo->ability->StartAbility(asyncCallbackInfo->param.want); + } else { + asyncCallbackInfo->ability->StartAbility( + asyncCallbackInfo->param.want, *(asyncCallbackInfo->param.setting.get())); + } + HILOG_INFO("%{public}s end.", __func__); +} + +void StartAbilityCallbackCompletedCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + napi_value callback = 0; + napi_value undefined = 0; + napi_value result[ARGS_TWO] = {0}; + napi_value callResult = 0; + napi_get_undefined(env, &undefined); + result[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); + if (asyncCallbackInfo->errCode == NAPI_ERR_NO_ERROR) { + napi_create_int32(env, 0, &result[PARAM1]); + } else { + result[PARAM1] = WrapUndefinedToJS(env); + } + + napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); + napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); + + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + HILOG_INFO("%{public}s end.", __func__); +} + +void StartAbilityPromiseCompletedCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + napi_value result = 0; + if (asyncCallbackInfo->errCode == NAPI_ERR_NO_ERROR) { + napi_create_int32(env, 0, &result); + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); + } else { + result = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); + napi_reject_deferred(env, asyncCallbackInfo->deferred, result); + } + + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + HILOG_INFO("%{public}s, end.", __func__); + delete asyncCallbackInfo; +} + +napi_value StartAbilityAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s asyncCallback.", __func__); + if (args == nullptr || asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &asyncCallbackInfo->cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + StartAbilityExecuteCB, + StartAbilityCallbackCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + HILOG_INFO("%{public}s asyncCallback end.", __func__); + return WrapVoidToJS(env); +} + +napi_value StartAbilityPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + StartAbilityExecuteCB, + StartAbilityPromiseCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + HILOG_INFO("%{public}s, end.", __func__); + return promise; +} + +/** + * @brief StartAbility processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param asyncCallbackInfo Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value StartAbilityWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called.", __func__); + size_t argcAsync = 2; + const size_t argcPromise = 1; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + CallAbilityParam param; + if (UnwrapParamForWant(env, args[PARAM0], asyncCallbackInfo->abilityType, param) == false) { + HILOG_ERROR("%{public}s, call UnwrapParamForWant failed.", __func__); + return nullptr; + } + + asyncCallbackInfo->param = param; + if (argcAsync > argcPromise) { + ret = StartAbilityAsync(env, args, argcAsync, argcPromise, asyncCallbackInfo); + } else { + ret = StartAbilityPromise(env, asyncCallbackInfo); + } + + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +/** + * @brief startAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_StartAbilityCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s called.", __func__); + AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s asyncCallbackInfo == nullpter", __func__); + return WrapVoidToJS(env); + } + + asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->abilityType = abilityType; + napi_value ret = StartAbilityWrap(env, info, asyncCallbackInfo); + if (ret == nullptr) { + HILOG_ERROR("%{public}s ret == nullpter", __func__); + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +bool UnwrapParamStopAbilityWrap(napi_env env, size_t argc, napi_value *argv, AsyncJSCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called, argc=%{public}d", __func__, argc); + const size_t argcMax = 2; + if (argc > argcMax || argc < argcMax - 1) { + HILOG_ERROR("%{public}s, Params is invalid.", __func__); + return false; + } + + if (argc == argcMax) { + if (!CreateAsyncCallback(env, argv[PARAM1], asyncCallbackInfo)) { + HILOG_INFO("%{public}s, the second parameter is invalid.", __func__); + return false; + } + } + + return UnwrapWant(env, argv[PARAM0], asyncCallbackInfo->param.want); +} + +void StopAbilityExecuteCallback(napi_env env, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s asyncCallbackInfo is null", __func__); + return; + } + + asyncCallbackInfo->error_code = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->native_data.data_type = NVT_NONE; + + if (asyncCallbackInfo->ability == nullptr) { + HILOG_ERROR("%{public}s ability is null", __func__); + asyncCallbackInfo->error_code = NAPI_ERR_ACE_ABILITY; + return; + } + + if (!CheckAbilityType(asyncCallbackInfo)) { + HILOG_ERROR("%{public}s wrong ability type", __func__); + asyncCallbackInfo->error_code = NAPI_ERR_ABILITY_TYPE_INVALID; + asyncCallbackInfo->native_data.data_type = NVT_UNDEFINED; + return; + } + + asyncCallbackInfo->native_data.data_type = NVT_BOOL; + asyncCallbackInfo->native_data.bool_value = asyncCallbackInfo->ability->StopAbility(asyncCallbackInfo->param.want); + HILOG_INFO("%{public}s end.", __func__); +} + +napi_value StopAbilityWrap(napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called.", __func__); + size_t argc = ARGS_MAX_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value jsthis = 0; + void *data = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &jsthis, &data)); + + if (!UnwrapParamStopAbilityWrap(env, argc, args, asyncCallbackInfo)) { + HILOG_INFO("%{public}s called. Invoke UnwrapParamStopAbility fail", __func__); + return nullptr; + } + + AsyncParamEx asyncParamEx; + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + HILOG_INFO("%{public}s called. asyncCallback.", __func__); + asyncParamEx.resource = "NAPI_StopAbilityWrapCallback"; + asyncParamEx.execute = StopAbilityExecuteCallback; + asyncParamEx.complete = CompleteAsyncCallbackWork; + + return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } else { + HILOG_INFO("%{public}s called. promise.", __func__); + asyncParamEx.resource = "NAPI_StopAbilityWrapPromise"; + asyncParamEx.execute = StopAbilityExecuteCallback; + asyncParamEx.complete = CompletePromiseCallbackWork; + + return ExecutePromiseCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } +} + +/** + * @brief stopAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_StopAbilityCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s called.", __func__); + AsyncJSCallbackInfo *asyncCallbackInfo = CreateAsyncJSCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s. Invoke CreateAsyncJSCallbackInfo failed.", __func__); + return WrapVoidToJS(env); + } + + asyncCallbackInfo->error_code = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->abilityType = abilityType; + napi_value ret = StopAbilityWrap(env, info, asyncCallbackInfo); + if (ret == nullptr) { + HILOG_ERROR("%{public}s. ret == nullptr", __func__); + FreeAsyncJSCallbackInfo(&asyncCallbackInfo); + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to AbilityNameCB on success, nullptr on failure. + */ +ConnectAbilityCB *CreateConnectAbilityCBInfo(napi_env env) +{ + HILOG_INFO("%{public}s called.", __func__); + napi_value global = nullptr; + NAPI_CALL(env, napi_get_global(env, &global)); + + napi_value abilityObj = nullptr; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + + ConnectAbilityCB *connectAbilityCB = new (std::nothrow) ConnectAbilityCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = ability, + }; + if (connectAbilityCB == nullptr) { + HILOG_ERROR("%{public}s connectAbilityCB == nullptr", __func__); + } + HILOG_INFO("%{public}s end.", __func__); + return connectAbilityCB; +} + +void ConnectAbilityExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + ConnectAbilityCB *connectAbilityCB = (ConnectAbilityCB *)data; + if (connectAbilityCB == nullptr) { + HILOG_ERROR("%{public}s connectAbilityCB == nullptr.", __func__); + return; + } + connectAbilityCB->errCode = NAPI_ERR_NO_ERROR; + if (connectAbilityCB->cbBase.ability == nullptr) { + connectAbilityCB->errCode = NAPI_ERR_ACE_ABILITY; + HILOG_ERROR("%{public}s ability == nullptr.", __func__); + return; + } + + if (!CheckAbilityType(&connectAbilityCB->cbBase)) { + connectAbilityCB->errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + HILOG_ERROR("%{public}s ability type invalid.", __func__); + return; + } + + connectAbilityCB->abilityConnection->SetEnv(env); + connectAbilityCB->abilityConnection->SetConnectCBRef(connectAbilityCB->abilityConnectionCB.callback[0]); + connectAbilityCB->abilityConnection->SetDisconnectCBRef(connectAbilityCB->abilityConnectionCB.callback[1]); + connectAbilityCB->result = + connectAbilityCB->cbBase.ability->ConnectAbility(connectAbilityCB->want, connectAbilityCB->abilityConnection); + HILOG_INFO("%{public}s end.bundlename:%{public}s abilityname:%{public}s result:%{public}d", + __func__, + connectAbilityCB->want.GetBundle().c_str(), + connectAbilityCB->want.GetElement().GetAbilityName().c_str(), + connectAbilityCB->result); +} + +void ConnectAbilityCallbackCompletedCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + ConnectAbilityCB *connectAbilityCB = (ConnectAbilityCB *)data; + napi_value callback = 0; + napi_value undefined = 0; + napi_value result = 0; + napi_value callResult = 0; + napi_get_undefined(env, &undefined); + HILOG_INFO("%{public}s errCode=%{public}d result=%{public}d id=%{public}lld.", + __func__, + connectAbilityCB->errCode, + connectAbilityCB->result, + connectAbilityCB->id); + if (connectAbilityCB->errCode != NAPI_ERR_NO_ERROR || connectAbilityCB->result == false) { + HILOG_INFO("%{public}s connectAbility failed.", __func__); + // return error code in onFailed asynccallback + int errorCode = NO_ERROR; + switch (connectAbilityCB->errCode) { + case NAPI_ERR_ACE_ABILITY: + errorCode = ABILITY_NOT_FOUND; + break; + case NAPI_ERR_PARAM_INVALID: + errorCode = INVALID_PARAMETER; + break; + default: + break; + } + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, errorCode, &result)); + NAPI_CALL_RETURN_VOID( + env, napi_get_reference_value(env, connectAbilityCB->abilityConnectionCB.callback[PARAM2], &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_ONE, &result, &callResult)); + } + if (connectAbilityCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, connectAbilityCB->cbBase.cbInfo.callback)); + } + if (connectAbilityCB->abilityConnectionCB.callback[PARAM2] != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, connectAbilityCB->abilityConnectionCB.callback[PARAM2])); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, connectAbilityCB->cbBase.asyncWork)); + delete connectAbilityCB; + connectAbilityCB = nullptr; + HILOG_INFO("%{public}s end.", __func__); +} + +napi_value ConnectAbilityAsync(napi_env env, napi_value *args, size_t argcAsync, ConnectAbilityCB *connectAbilityCB) +{ + HILOG_INFO("%{public}s asyncCallback.", __func__); + if (args == nullptr || connectAbilityCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + ConnectAbilityExecuteCB, + ConnectAbilityCallbackCompletedCB, + (void *)connectAbilityCB, + &connectAbilityCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, connectAbilityCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s asyncCallback end.", __func__); + return WrapVoidToJS(env); +} + +/** + * @brief ConnectAbility processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param connectAbilityCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value ConnectAbilityWrap(napi_env env, napi_callback_info info, ConnectAbilityCB *connectAbilityCB) +{ + HILOG_INFO("%{public}s called.", __func__); + size_t argcAsync = ARGS_TWO; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync != ARGS_TWO) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + connectAbilityCB->errCode = NAPI_ERR_PARAM_INVALID; + return nullptr; + } + + if (!UnwrapWant(env, args[PARAM0], connectAbilityCB->want)) { + HILOG_INFO("%{public}s called. Invoke UnwrapWant fail", __func__); + return nullptr; + } + + HILOG_INFO("%{public}s bundlename:%{public}s abilityname:%{public}s", + __func__, + connectAbilityCB->want.GetBundle().c_str(), + connectAbilityCB->want.GetElement().GetAbilityName().c_str()); + + std::string bundleName = connectAbilityCB->want.GetBundle(); + std::string abilityName = connectAbilityCB->want.GetElement().GetAbilityName(); + auto item = std::find_if(connects_.begin(), + connects_.end(), + [&bundleName, &abilityName](const std::map>::value_type &obj) { + return (bundleName == obj.first.want.GetBundle()) && + (abilityName == obj.first.want.GetElement().GetAbilityName()); + }); + if (item != connects_.end()) { + // match bundlename && abilityname + connectAbilityCB->id = item->first.id; + connectAbilityCB->abilityConnection = item->second; + HILOG_INFO("%{public}s find connection:%{public}p exist", __func__, item->second.GetRefPtr()); + } else { + sptr conn(new (std::nothrow) NAPIAbilityConnection()); + connectAbilityCB->id = serialNumber_; + connectAbilityCB->abilityConnection = conn; + ConnecttionKey key; + key.id = connectAbilityCB->id; + key.want = connectAbilityCB->want; + connects_.emplace(key, conn); + serialNumber_ < INT64_MAX ? serialNumber_++ : serialNumber_ = 0; + HILOG_INFO("%{public}s not find connection, make new one:%{public}p.", __func__, conn.GetRefPtr()); + } + HILOG_INFO("%{public}s id:%{public}lld.", __func__, connectAbilityCB->id); + + if (argcAsync > PARAM1) { + napi_value jsMethod = nullptr; + napi_valuetype valuetype = napi_undefined; + napi_typeof(env, args[PARAM1], &valuetype); + if (valuetype == napi_object) { + NAPI_CALL(env, napi_get_named_property(env, args[PARAM1], "onConnect", &jsMethod)); + NAPI_CALL(env, napi_typeof(env, jsMethod, &valuetype)); + HILOG_INFO("%{public}s, function onConnect valuetype=%{public}d.", __func__, valuetype); + NAPI_CALL( + env, napi_create_reference(env, jsMethod, 1, &connectAbilityCB->abilityConnectionCB.callback[PARAM0])); + + NAPI_CALL(env, napi_get_named_property(env, args[PARAM1], "onDisconnect", &jsMethod)); + NAPI_CALL(env, napi_typeof(env, jsMethod, &valuetype)); + HILOG_INFO("%{public}s, function onDisconnect valuetype=%{public}d.", __func__, valuetype); + NAPI_CALL( + env, napi_create_reference(env, jsMethod, 1, &connectAbilityCB->abilityConnectionCB.callback[PARAM1])); + + NAPI_CALL(env, napi_get_named_property(env, args[PARAM1], "onFailed", &jsMethod)); + NAPI_CALL(env, napi_typeof(env, jsMethod, &valuetype)); + HILOG_INFO("%{public}s, function onFailed valuetype=%{public}d.", __func__, valuetype); + NAPI_CALL( + env, napi_create_reference(env, jsMethod, 1, &connectAbilityCB->abilityConnectionCB.callback[PARAM2])); + } else { + HILOG_ERROR("%{public}s, Wrong argument type.", __func__); + return nullptr; + } + } + + ret = ConnectAbilityAsync(env, args, argcAsync, connectAbilityCB); + if (ret != nullptr) { + // return number to js + NAPI_CALL(env, napi_create_int64(env, connectAbilityCB->id, &ret)); + HILOG_INFO("%{public}s id=%{public}lld.", __func__, connectAbilityCB->id); + } + HILOG_INFO("%{public}s called end.", __func__); + return ret; +} + +/** + * @brief ConnectAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_ConnectAbilityCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s called.", __func__); + ConnectAbilityCB *connectAbilityCB = CreateConnectAbilityCBInfo(env); + if (connectAbilityCB == nullptr) { + HILOG_ERROR("%{public}s connectAbilityCB == nullptr", __func__); + return WrapVoidToJS(env); + } + + connectAbilityCB->errCode = NAPI_ERR_NO_ERROR; + connectAbilityCB->cbBase.abilityType = abilityType; + napi_value ret = ConnectAbilityWrap(env, info, connectAbilityCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s ret == nullptr", __func__); + if (connectAbilityCB != nullptr) { + delete connectAbilityCB; + connectAbilityCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to AbilityNameCB on success, nullptr on failure. + */ +ConnectAbilityCB *CreateDisConnectAbilityCBInfo(napi_env env) +{ + HILOG_INFO("%{public}s called.", __func__); + napi_value global = nullptr; + NAPI_CALL(env, napi_get_global(env, &global)); + + napi_value abilityObj = nullptr; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + + ConnectAbilityCB *connectAbilityCB = new (std::nothrow) ConnectAbilityCB{ + .cbBase.cbInfo.env = env, + .cbBase.asyncWork = nullptr, + .cbBase.deferred = nullptr, + .cbBase.ability = ability, + }; + if (connectAbilityCB == nullptr) { + HILOG_ERROR("%{public}s connectAbilityCB == nullptr", __func__); + } + HILOG_INFO("%{public}s end.", __func__); + return connectAbilityCB; +} + +void DisConnectAbilityExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + ConnectAbilityCB *connectAbilityCB = (ConnectAbilityCB *)data; + if (connectAbilityCB == nullptr) { + HILOG_ERROR("%{public}s connectAbilityCB == nullptr.", __func__); + return; + } + connectAbilityCB->errCode = NAPI_ERR_NO_ERROR; + if (connectAbilityCB->cbBase.ability == nullptr) { + connectAbilityCB->errCode = NAPI_ERR_ACE_ABILITY; + HILOG_ERROR("%{public}s ability == nullptr.", __func__); + return; + } + + if (!CheckAbilityType(&connectAbilityCB->cbBase)) { + connectAbilityCB->errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + HILOG_ERROR("%{public}s ability type invalid.", __func__); + return; + } + + HILOG_INFO("%{public}s DisconnectAbility called.", __func__); + connectAbilityCB->cbBase.ability->DisconnectAbility(connectAbilityCB->abilityConnection); + HILOG_INFO("%{public}s end. bundlename:%{public}s abilityname:%{public}s", + __func__, + connectAbilityCB->want.GetBundle().c_str(), + connectAbilityCB->want.GetElement().GetAbilityName().c_str()); +} + +void DisConnectAbilityCallbackCompletedCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + ConnectAbilityCB *connectAbilityCB = (ConnectAbilityCB *)data; + napi_value callback = 0; + napi_value undefined = 0; + napi_value result[ARGS_TWO] = {0}; + napi_value callResult = 0; + napi_get_undefined(env, &undefined); + result[PARAM0] = GetCallbackErrorValue(env, connectAbilityCB->errCode); + if (connectAbilityCB->errCode == NAPI_ERR_NO_ERROR) { + result[PARAM1] = WrapVoidToJS(env); + } else { + result[PARAM1] = WrapUndefinedToJS(env); + } + + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, connectAbilityCB->cbBase.cbInfo.callback, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (connectAbilityCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, connectAbilityCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, connectAbilityCB->cbBase.asyncWork)); + delete connectAbilityCB; + connectAbilityCB = nullptr; + HILOG_INFO("%{public}s end.", __func__); +} + +void DisConnectAbilityPromiseCompletedCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + ConnectAbilityCB *connectAbilityCB = (ConnectAbilityCB *)data; + napi_value result = 0; + if (connectAbilityCB->errCode == NAPI_ERR_NO_ERROR) { + result = WrapVoidToJS(env); + napi_resolve_deferred(env, connectAbilityCB->cbBase.deferred, result); + } else { + result = GetCallbackErrorValue(env, connectAbilityCB->errCode); + napi_reject_deferred(env, connectAbilityCB->cbBase.deferred, result); + } + + napi_delete_async_work(env, connectAbilityCB->cbBase.asyncWork); + delete connectAbilityCB; + HILOG_INFO("%{public}s end.", __func__); +} + +napi_value DisConnectAbilityAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, ConnectAbilityCB *connectAbilityCB) +{ + HILOG_INFO("%{public}s asyncCallback.", __func__); + if (args == nullptr || connectAbilityCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &connectAbilityCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + DisConnectAbilityExecuteCB, + DisConnectAbilityCallbackCompletedCB, + (void *)connectAbilityCB, + &connectAbilityCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, connectAbilityCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s asyncCallback end.", __func__); + return WrapVoidToJS(env); +} + +napi_value DisConnectAbilityPromise(napi_env env, ConnectAbilityCB *connectAbilityCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (connectAbilityCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + connectAbilityCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + DisConnectAbilityExecuteCB, + DisConnectAbilityPromiseCompletedCB, + (void *)connectAbilityCB, + &connectAbilityCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, connectAbilityCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +/** + * @brief DisConnectAbility processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param connectAbilityCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value DisConnectAbilityWrap(napi_env env, napi_callback_info info, ConnectAbilityCB *connectAbilityCB) +{ + HILOG_INFO("%{public}s called.", __func__); + size_t argcAsync = ARGS_TWO; + const size_t argcPromise = ARGS_ONE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + napi_typeof(env, args[PARAM0], &valuetype); + if (valuetype == napi_number) { + NAPI_CALL(env, napi_get_value_int64(env, args[PARAM0], &connectAbilityCB->id)); + } + + HILOG_INFO("%{public}s id:%{public}lld", __func__, connectAbilityCB->id); + int64_t id = connectAbilityCB->id; + auto item = std::find_if(connects_.begin(), + connects_.end(), + [&id](const std::map>::value_type &obj) { + return id == obj.first.id; + }); + if (item != connects_.end()) { + // match id + connectAbilityCB->want = item->first.want; + connectAbilityCB->abilityConnection = item->second; + HILOG_INFO("%{public}s find conn ability:%{public}p exist", __func__, item->second.GetRefPtr()); + } else { + HILOG_INFO("%{public}s not find conn ability exist.", __func__); + HILOG_INFO("%{public}s there is no ability to disconnect.", __func__); + return nullptr; + } + + if (argcAsync > argcPromise) { + ret = DisConnectAbilityAsync(env, args, argcAsync, argcPromise, connectAbilityCB); + } else { + ret = DisConnectAbilityPromise(env, connectAbilityCB); + } + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +/** + * @brief DisConnectAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_DisConnectAbilityCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s called.", __func__); + ConnectAbilityCB *connectAbilityCB = CreateConnectAbilityCBInfo(env); + if (connectAbilityCB == nullptr) { + HILOG_ERROR("%{public}s connectAbilityCB == nullptr", __func__); + return WrapVoidToJS(env); + } + + connectAbilityCB->errCode = NAPI_ERR_NO_ERROR; + connectAbilityCB->cbBase.abilityType = abilityType; + napi_value ret = DisConnectAbilityWrap(env, info, connectAbilityCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s ret == nullptr", __func__); + if (connectAbilityCB != nullptr) { + delete connectAbilityCB; + connectAbilityCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +void NAPIAbilityConnection::SetEnv(const napi_env &env) +{ + env_ = env; +} + +void NAPIAbilityConnection::SetConnectCBRef(const napi_ref &ref) +{ + connectRef_ = ref; +} + +void NAPIAbilityConnection::SetDisconnectCBRef(const napi_ref &ref) +{ + disconnectRef_ = ref; +} + +void NAPIAbilityConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + HILOG_INFO("%{public}s, called.", __func__); + uv_loop_s *loop = nullptr; + +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(env_, &loop); +#endif // NAPI_VERSION >= 2 + + uv_work_t *work = new uv_work_t; + ConnectAbilityCB *connectAbilityCB = + new (std::nothrow) ConnectAbilityCB{.cbBase.cbInfo.env = env_, .cbBase.cbInfo.callback = connectRef_}; + connectAbilityCB->abilityConnectionCB.elementName = element; + connectAbilityCB->abilityConnectionCB.resultCode = resultCode; + connectAbilityCB->abilityConnectionCB.connection = remoteObject; + work->data = (void *)connectAbilityCB; + + uv_queue_work( + loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + HILOG_INFO("OnAbilityConnectDone, uv_queue_work"); + // JS Thread + ConnectAbilityCB *event = (ConnectAbilityCB *)work->data; + napi_value result[ARGS_TWO] = {0}; + result[PARAM0] = WrapElementName(event->cbBase.cbInfo.env, event->abilityConnectionCB.elementName); + + // start open rpc lib + if (g_handle == nullptr) { + g_handle = dlopen(SHARED_LIBRARY_RPC, RTLD_LAZY); + if (g_handle == nullptr) { + HILOG_ERROR( + "%{public}s, dlopen failed %{public}s. %{public}s", __func__, SHARED_LIBRARY_RPC, dlerror()); + return; + } + } + + // get function + auto func = reinterpret_cast(dlsym(g_handle, FUNC_RPC_CREATE_JS_REMOTE_OBJECT)); + if (func == nullptr) { + HILOG_ERROR("%{public}s, dlsym failed %{public}s. %{public}s", + __func__, + FUNC_RPC_CREATE_JS_REMOTE_OBJECT, + dlerror()); + dlclose(g_handle); + g_handle = nullptr; + return; + } + + // transform native remoteObject to js remoteObject + napi_value jsRemoteObject = func(event->cbBase.cbInfo.env, event->abilityConnectionCB.connection); + result[PARAM1] = jsRemoteObject; + + napi_value callback = 0; + napi_value undefined = 0; + napi_get_undefined(event->cbBase.cbInfo.env, &undefined); + napi_value callResult = 0; + napi_get_reference_value(event->cbBase.cbInfo.env, event->cbBase.cbInfo.callback, &callback); + + napi_call_function(event->cbBase.cbInfo.env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); + if (event->cbBase.cbInfo.callback != nullptr) { + napi_delete_reference(event->cbBase.cbInfo.env, event->cbBase.cbInfo.callback); + } + delete event; + delete work; + HILOG_INFO("OnAbilityConnectDone, uv_queue_work end"); + }); + HILOG_INFO("%{public}s, end.", __func__); +} + +void NAPIAbilityConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{ + HILOG_INFO("%{public}s, called.", __func__); + + uv_loop_s *loop = nullptr; + +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(env_, &loop); +#endif // NAPI_VERSION >= 2 + HILOG_INFO("OnAbilityDisconnectDone bundleName:%{public}s abilityName:%{public}s resultCode:%{public}d", + element.GetBundleName().c_str(), + element.GetAbilityName().c_str(), + resultCode); + uv_work_t *work = new uv_work_t; + ConnectAbilityCB *connectAbilityCB = + new (std::nothrow) ConnectAbilityCB{.cbBase.cbInfo.env = env_, .cbBase.cbInfo.callback = disconnectRef_}; + connectAbilityCB->abilityConnectionCB.elementName = element; + connectAbilityCB->abilityConnectionCB.resultCode = resultCode; + work->data = (void *)connectAbilityCB; + + uv_queue_work( + loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + HILOG_INFO("OnAbilityDisconnectDone, uv_queue_work"); + // JS Thread + ConnectAbilityCB *event = (ConnectAbilityCB *)work->data; + napi_value result = nullptr; + result = WrapElementName(event->cbBase.cbInfo.env, event->abilityConnectionCB.elementName); + + napi_value callback = 0; + napi_value undefined = 0; + napi_get_undefined(event->cbBase.cbInfo.env, &undefined); + napi_value callResult = 0; + napi_get_reference_value(event->cbBase.cbInfo.env, event->cbBase.cbInfo.callback, &callback); + + napi_call_function(event->cbBase.cbInfo.env, undefined, callback, ARGS_ONE, &result, &callResult); + if (event->cbBase.cbInfo.callback != nullptr) { + napi_delete_reference(event->cbBase.cbInfo.env, event->cbBase.cbInfo.callback); + } + + // release connect + HILOG_INFO("OnAbilityDisconnectDone connects_.size:%{public}d", connects_.size()); + std::string bundleName = event->abilityConnectionCB.elementName.GetBundleName(); + std::string abilityName = event->abilityConnectionCB.elementName.GetAbilityName(); + auto item = std::find_if(connects_.begin(), + connects_.end(), + [bundleName, abilityName]( + const std::map>::value_type &obj) { + return (bundleName == obj.first.want.GetBundle()) && + (abilityName == obj.first.want.GetElement().GetAbilityName()); + }); + if (item != connects_.end()) { + // match bundlename && abilityname + connects_.erase(item); + HILOG_INFO("OnAbilityDisconnectDone erase connects_.size:%{public}d", connects_.size()); + } + + delete event; + delete work; + HILOG_INFO("OnAbilityDisconnectDone, uv_queue_work end"); + }); + HILOG_INFO("%{public}s, end.", __func__); +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h new file mode 100755 index 00000000000..b8da0e21359 --- /dev/null +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APPEXECFWK_NAPI_COMMON_ABILITY_H +#define OHOS_APPEXECFWK_NAPI_COMMON_ABILITY_H +#include "feature_ability_common.h" +#include "ability_info.h" +#include "ability_connect_callback_stub.h" + +namespace OHOS { +namespace AppExecFwk { +napi_value *GetGlobalClassContext(void); +void SaveAppInfo(AppInfo_ &appInfo, const ApplicationInfo &appInfoOrg); +napi_value WrapAppInfo(napi_env env, const AppInfo_ &appInfo); +/** + * @brief Obtains information about the current application. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetApplicationInfoCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief Get bundle name. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetBundleNameCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief Obtains the process Info this application. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetProcessInfoCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief Obtains the type of this application. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetAppTypeCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief Obtains the elementName object of the current ability. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetElementNameCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief Obtains information about the current ability. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetAbilityInfoCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief Obtains the HapModuleInfo object of the application. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetHapModuleInfoCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief Obtains the name of the current process. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetProcessNameCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief Obtains the bundle name of the ability that called the current ability. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetCallingBundleCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to AsyncCallbackInfo on success, nullptr on failure + */ +AsyncCallbackInfo *CreateAsyncCallbackInfo(napi_env env); +/** + * @brief Get context. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetContextCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief Get want. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetWantCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief Obtains the class name in this ability name, without the prefixed bundle name. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetAbilityNameCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief startAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_StartAbilityCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief stopAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_StopAbilityCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +class NAPIAbilityConnection : public AAFwk::AbilityConnectionStub { +public: + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + void SetEnv(const napi_env &env); + void SetConnectCBRef(const napi_ref &ref); + void SetDisconnectCBRef(const napi_ref &ref); + +private: + napi_env env_; + napi_ref connectRef_; + napi_ref disconnectRef_; +}; + +/** + * @brief connectAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_ConnectAbilityCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +/** + * @brief disconnectAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_DisConnectAbilityCommon(napi_env env, napi_callback_info info, AbilityType abilityType); + +struct ConnecttionKey { + Want want; + int64_t id; +}; +struct key_compare { + bool operator()(const ConnecttionKey &key1, const ConnecttionKey &key2) const + { + if (key1.id < key2.id) { + return true; + } + return false; + } +}; +static std::map, key_compare> connects_; +static int64_t serialNumber_ = 0; +enum ErrorCode { + NO_ERROR = 0, + INVALID_PARAMETER = -1, + ABILITY_NOT_FOUND = -2, + PERMISSION_DENY = -3, +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_NAPI_COMMON_ABILITY_H diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_data.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_data.h index d6acdb2e489..ce44f196dc0 100755 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_data.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_data.h @@ -58,14 +58,17 @@ namespace AppExecFwk { struct CallbackInfo { napi_env env; napi_ref callback = 0; + napi_deferred deferred; }; struct CallAbilityParamData { PacMap paramArgs; + Want want; }; typedef enum { NVT_NONE = 0, + NVT_UNDEFINED, NVT_INT32, NVT_BOOL, NVT_STRING, @@ -87,6 +90,7 @@ typedef struct __AsyncJSCallbackInfo { napi_async_work asyncWork; napi_deferred deferred; Ability *ability; + AbilityType abilityType; CallAbilityParamData param; ThreadReturnData native_data; napi_value result; diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_error.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_error.h index f0efb69f97f..07f660d0b7b 100755 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_error.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_error.h @@ -21,11 +21,12 @@ namespace AppExecFwk { #define NAPI_ERR_NO_ERROR 0 #define NAPI_ERR_NO_PERMISSION -100 -#define NAPI_ERR_INNER_DATA -101 // Internal data error, data allocation fail -#define NAPI_ERR_ACE_ABILITY -102 // Failed to acquire ability object -#define NAPI_ERR_LONG_CALLBACK -103 // Failed to acquire long callack object -#define NAPI_ERR_PARAM_INVALID -104 // Parameter is invalid - +#define NAPI_ERR_INNER_DATA -101 // Internal data error, data allocation fail +#define NAPI_ERR_ACE_ABILITY -102 // Failed to acquire ability object +#define NAPI_ERR_LONG_CALLBACK -103 // Failed to acquire long callack object +#define NAPI_ERR_PARAM_INVALID -104 // Parameter is invalid +#define NAPI_ERR_ABILITY_TYPE_INVALID -105 // Type of ability is invalid +#define NAPI_ERR_ABILITY_CALL_INVALID -106 // Call the ability interface, the return value is wrong } // namespace AppExecFwk } // namespace OHOS #endif // OHOS_APPEXECFWK_NAPI_COMMON_ERROR_H diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp index 52be95fc89f..8c98e388629 100755 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp @@ -16,6 +16,7 @@ #include #include "napi_common_util.h" #include "napi_common_data.h" +#include "napi_common_error.h" #include "hilog_wrapper.h" #include "securec.h" @@ -55,6 +56,13 @@ napi_value WrapVoidToJS(napi_env env) return result; } +napi_value WrapUndefinedToJS(napi_env env) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &result)); + return result; +} + napi_value CreateJSObject(napi_env env) { napi_value result = nullptr; @@ -247,7 +255,7 @@ bool UnwrapStringFromJS2(napi_env env, napi_value param, std::string &value) if (buf == nullptr) { return false; } - memset_s(buf, sizeof(buf), 0, sizeof(buf)); + memset_s(buf, (size + 1), 0, (size + 1)); bool rev = napi_get_value_string_utf8(env, param, buf, size + 1, &size) == napi_ok; if (rev) { @@ -784,6 +792,7 @@ AsyncJSCallbackInfo *CreateAsyncJSCallbackInfo(napi_env env) .asyncWork = nullptr, .deferred = nullptr, .ability = ability, + .abilityType = AbilityType::UNKNOWN, .aceCallback = nullptr, }; if (asyncCallbackInfo != nullptr) { @@ -792,6 +801,25 @@ AsyncJSCallbackInfo *CreateAsyncJSCallbackInfo(napi_env env) return asyncCallbackInfo; } +void FreeAsyncJSCallbackInfo(AsyncJSCallbackInfo **asyncCallbackInfo) +{ + if (asyncCallbackInfo == nullptr) { + return; + } + if (*asyncCallbackInfo == nullptr) { + return; + } + + if ((*asyncCallbackInfo)->cbInfo.callback != nullptr && (*asyncCallbackInfo)->cbInfo.env != nullptr) { + napi_delete_reference((*asyncCallbackInfo)->cbInfo.env, (*asyncCallbackInfo)->cbInfo.callback); + (*asyncCallbackInfo)->cbInfo.callback = nullptr; + (*asyncCallbackInfo)->cbInfo.env = nullptr; + } + + delete (*asyncCallbackInfo); + *asyncCallbackInfo = nullptr; +} + /** * @brief Convert local data to JS data. * @@ -808,6 +836,9 @@ bool WrapThreadReturnData(napi_env env, const ThreadReturnData *data, napi_value } switch (data->data_type) { + case NVT_UNDEFINED: + NAPI_CALL_BASE(env, napi_get_undefined(env, value), false); + break; case NVT_INT32: NAPI_CALL_BASE(env, napi_create_int32(env, data->int32_value, value), false); break; @@ -854,7 +885,7 @@ bool CreateAsyncCallback(napi_env env, napi_value param, AsyncJSCallbackInfo *ca napi_ref CreateCallbackRefFromJS(napi_env env, napi_value param) { if (env == nullptr || param == nullptr) { - HILOG_INFO("%{public}s called, env or param is null", __func__); + HILOG_INFO("%{public}s called, env or param is null ", __func__); return nullptr; } @@ -996,8 +1027,13 @@ void CompletePromiseCallbackWork(napi_env env, napi_status status, void *data) } napi_value result = 0; - WrapThreadReturnData(env, &asyncCallbackInfo->native_data, &result); - napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); + if (asyncCallbackInfo->error_code == NAPI_ERR_NO_ERROR) { + WrapThreadReturnData(env, &asyncCallbackInfo->native_data, &result); + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); + } else { + result = GetCallbackErrorValue(env, asyncCallbackInfo->error_code); + napi_reject_deferred(env, asyncCallbackInfo->deferred, result); + } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; asyncCallbackInfo = nullptr; diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.h index 18ec2ae1a64..24dd48c904b 100755 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.h @@ -27,6 +27,7 @@ bool IsTypeForNapiValue(napi_env env, napi_value param, napi_valuetype expectTyp bool IsArrayForNapiValue(napi_env env, napi_value param, uint32_t &arraySize); napi_value WrapVoidToJS(napi_env env); +napi_value WrapUndefinedToJS(napi_env env); napi_value CreateJSObject(napi_env env); @@ -164,6 +165,7 @@ napi_value GetCallbackErrorValue(napi_env env, int errCode); * @return Return a pointer to AsyncJSCallbackInfo on success, nullptr on failure */ AsyncJSCallbackInfo *CreateAsyncJSCallbackInfo(napi_env env); +void FreeAsyncJSCallbackInfo(AsyncJSCallbackInfo **asyncCallbackInfo); /** * @brief Convert local data to JS data. diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp index 15ff59ba404..868f9c1dfce 100755 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp @@ -17,10 +17,19 @@ #include "napi_common_util.h" #include "hilog_wrapper.h" #include "ohos/aafwk/content/want_params_wrapper.h" +#include "ohos/aafwk/base/array_wrapper.h" +#include "ohos/aafwk/base/bool_wrapper.h" +#include "ohos/aafwk/base/byte_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/short_wrapper.h" +#include "ohos/aafwk/base/string_wrapper.h" namespace OHOS { namespace AppExecFwk { - +EXTERN_C_START /** * @brief Init param of wantOptions. * @@ -749,8 +758,8 @@ napi_value WrapWant(napi_env env, const Want &want) SetPropertyValueByPropertyName(env, jsObject, "type", jsValue); jsValue = nullptr; - jsValue = InnerWrapWantOptions(env, want); - SetPropertyValueByPropertyName(env, jsObject, "options", jsValue); + jsValue = WrapInt32ToJS(env, want.GetFlags()); + SetPropertyValueByPropertyName(env, jsObject, "flags", jsValue); jsValue = nullptr; jsValue = WrapStringToJS(env, want.GetAction()); @@ -801,7 +810,10 @@ bool UnwrapWant(napi_env env, napi_value param, Want &want) want.SetUri(natValueString); } - InnerUnwrapWantOptions(env, param, "options", want); + int32_t flags = 0; + if (UnwrapInt32ByPropertyName(env, param, "flags", flags)) { + want.SetFlags(flags); + } ElementName natElementName; UnwrapElementName(env, param, natElementName); @@ -814,5 +826,6 @@ bool UnwrapWant(napi_env env, napi_value param, Want &want) return true; } +EXTERN_C_END } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.h index 5d449d6edd3..66e06f310fa 100755 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.h @@ -25,6 +25,7 @@ namespace OHOS { namespace AppExecFwk { +EXTERN_C_START napi_value WrapElementName(napi_env env, const ElementName &elementName); bool UnwrapElementName(napi_env env, napi_value param, ElementName &elementName); @@ -35,6 +36,7 @@ bool UnwrapWantParams(napi_env env, napi_value param, AAFwk::WantParams &wantPar napi_value WrapWant(napi_env env, const Want &want); bool UnwrapWant(napi_env env, napi_value param, Want &want); +EXTERN_C_END } // namespace AppExecFwk } // namespace OHOS #endif // OHOS_APPEXECFWK_NAPI_COMMON_WANT_H diff --git a/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn b/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn new file mode 100755 index 00000000000..db9864702e1 --- /dev/null +++ b/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn @@ -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. + +# import("//build/config/ohos/rules.gni") +import("//build/ohos.gni") +ohos_shared_library("particleability") { + include_dirs = [ + "//foundation/ace/napi/interfaces/kits", + "//third_party/node/src", + "//third_party/libuv/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", + "//foundation/aafwk/standard/services/common/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + ] + + sources = [ + "native_module.cpp", + "particle_ability.cpp", + ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", + "//foundation/ace/napi:ace_napi", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/libuv:uv_static", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:ability_manager", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + relative_install_dir = "module/ability" + + subsystem_name = "aafwk" + part_name = "aafwk_standard" +} diff --git a/interfaces/kits/napi/aafwk/particleAbility/native_module.cpp b/interfaces/kits/napi/aafwk/particleAbility/native_module.cpp new file mode 100755 index 00000000000..2b856a4f689 --- /dev/null +++ b/interfaces/kits/napi/aafwk/particleAbility/native_module.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "particle_ability.h" +namespace OHOS { +namespace AppExecFwk { +EXTERN_C_START +/* + * The module initialization. + */ +static napi_value ParticleInit(napi_env env, napi_value exports) +{ + ParticleAbilityInit(env, exports); + return exports; +} +EXTERN_C_END + +/* + * The module definition. + */ +static napi_module _module = {.nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = ParticleInit, + .nm_modname = "ability.particleability", + .nm_priv = ((void *)0), + .reserved = {0}}; + +/* + * The module registration. + */ +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/particleAbility/particle_ability.cpp b/interfaces/kits/napi/aafwk/particleAbility/particle_ability.cpp new file mode 100755 index 00000000000..0150609d7e2 --- /dev/null +++ b/interfaces/kits/napi/aafwk/particleAbility/particle_ability.cpp @@ -0,0 +1,264 @@ +/* + * 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 "particle_ability.h" +#include +#include +#include +#include "securec.h" +#include "hilog_wrapper.h" +#include "../inner/napi_common/napi_common_ability.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace AppExecFwk { + +napi_value NAPI_PAGetApplicationInfo(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetApplicationInfoCommon(env, info, AbilityType::UNKNOWN); +} + +napi_value NAPI_PAGetBundleName(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetBundleNameCommon(env, info, AbilityType::UNKNOWN); +} + +napi_value NAPI_PAGetProcessInfo(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetProcessInfoCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief Obtains the type of this application. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PAGetAppType(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetAppTypeCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief Obtains the elementName object of the current ability. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PAGetElementName(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetElementNameCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief Obtains information about the current ability. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PAGetAbilityInfo(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetAbilityInfoCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief Obtains the HapModuleInfo object of the application. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PAGetHapModuleInfo(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetHapModuleInfoCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief Obtains the name of the current process. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PAProcessName(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetProcessNameCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief Obtains the bundle name of the ability that called the current ability. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PAGetCallingBundle(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetCallingBundleCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief Get context. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PAGetContext(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetContextCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief Get want. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PAGetWant(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetWantCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief Obtains the class name in this ability name, without the prefixed bundle name. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PAGetAbilityName(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_GetAbilityNameCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief ParticleAbility NAPI method : startAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PAStartAbility(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_StartAbilityCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief ParticleAbility NAPI method : stopAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PAStopAbility(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_StopAbilityCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief ParticleAbility NAPI method : connectAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PAConnectAbility(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_ConnectAbilityCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief ParticleAbility NAPI method : disconnectAbility. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PADisConnectAbility(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + return NAPI_DisConnectAbilityCommon(env, info, AbilityType::UNKNOWN); +} + +/** + * @brief ParticleAbility NAPI module registration. + * + * @param env The environment that the Node-API call is invoked under. + * @param exports An empty object via the exports parameter as a convenience. + * + * @return The return value from Init is treated as the exports object for the module. + */ +napi_value ParticleAbilityInit(napi_env env, napi_value exports) +{ + HILOG_INFO("%{public}s called.", __func__); + napi_property_descriptor properties[] = { + DECLARE_NAPI_FUNCTION("getApplicationInfo", NAPI_PAGetApplicationInfo), + DECLARE_NAPI_FUNCTION("getBundleName", NAPI_PAGetBundleName), + DECLARE_NAPI_FUNCTION("getProcessInfo", NAPI_PAGetProcessInfo), + DECLARE_NAPI_FUNCTION("getAppType", NAPI_PAGetAppType), + DECLARE_NAPI_FUNCTION("getElementName", NAPI_PAGetElementName), + DECLARE_NAPI_FUNCTION("getAbilityInfo", NAPI_PAGetAbilityInfo), + DECLARE_NAPI_FUNCTION("getHapModuleInfo", NAPI_PAGetHapModuleInfo), + DECLARE_NAPI_FUNCTION("getProcessName", NAPI_PAProcessName), + DECLARE_NAPI_FUNCTION("getCallingBundle", NAPI_PAGetCallingBundle), + DECLARE_NAPI_FUNCTION("getContext", NAPI_PAGetContext), + DECLARE_NAPI_FUNCTION("getWant", NAPI_PAGetWant), + DECLARE_NAPI_FUNCTION("getAbilityName", NAPI_PAGetAbilityName), + DECLARE_NAPI_FUNCTION("startAbility", NAPI_PAStartAbility), + DECLARE_NAPI_FUNCTION("stopAbility", NAPI_PAStopAbility), + DECLARE_NAPI_FUNCTION("connectAbility", NAPI_PAConnectAbility), + DECLARE_NAPI_FUNCTION("disconnectAbility", NAPI_PADisConnectAbility), + }; + napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties); + + return exports; +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/particleAbility/particle_ability.h b/interfaces/kits/napi/aafwk/particleAbility/particle_ability.h new file mode 100755 index 00000000000..0ee568145ac --- /dev/null +++ b/interfaces/kits/napi/aafwk/particleAbility/particle_ability.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_APPEXECFWK_PARTICLE_ABILITY_H +#define OHOS_APPEXECFWK_PARTICLE_ABILITY_H + +#include "napi/native_common.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief ParticleAbility NAPI module registration. + * + * @param env The environment that the Node-API call is invoked under. + * @param exports An empty object via the exports parameter as a convenience. + * + * @return The return value from Init is treated as the exports object for the module. + */ +napi_value ParticleAbilityInit(napi_env env, napi_value exports); + +} // namespace AppExecFwk +} // namespace OHOS +#endif /* OHOS_APPEXECFWK_PARTICLE_ABILITY_H */ diff --git a/interfaces/kits/napi/aafwk/wantConstant/want_constant.cpp b/interfaces/kits/napi/aafwk/wantConstant/want_constant.cpp index 02744dba2b6..9ae73ac4a97 100644 --- a/interfaces/kits/napi/aafwk/wantConstant/want_constant.cpp +++ b/interfaces/kits/napi/aafwk/wantConstant/want_constant.cpp @@ -34,45 +34,62 @@ napi_value WantConstantInit(napi_env env, napi_value exports) HILOG_INFO("%{public}s,called1", __func__); napi_value action = nullptr; napi_value entity = nullptr; + napi_value Flags = nullptr; napi_create_object(env, &action); napi_create_object(env, &entity); + napi_create_object(env, &Flags); - SetNamedProperty(env, action, "action.system.home", "ACTION_HOME"); - SetNamedProperty(env, action, "action.system.play", "ACTION_PLAY"); - SetNamedProperty(env, action, "action.bundle.add", "ACTION_BUNDLE_ADD"); - SetNamedProperty(env, action, "action.bundle.remove", "ACTION_BUNDLE_REMOVE"); - SetNamedProperty(env, action, "action.bundle.update", "ACTION_BUNDLE_UPDATE"); - SetNamedProperty(env, action, "ability.intent.ORDER_TAXI", "ACTION_ORDER_TAXI"); - SetNamedProperty(env, action, "ability.intent.QUERY_TRAFFIC_RESTRICTION", "ACTION_QUERY_TRAFFIC_RESTRICTION"); - SetNamedProperty(env, action, "ability.intent.PLAN_ROUTE", "ACTION_PLAN_ROUTE"); - SetNamedProperty(env, action, "ability.intent.BOOK_FLIGHT", "ACTION_BOOK_FLIGHT"); - SetNamedProperty(env, action, "ability.intent.BOOK_TRAIN_TICKET", "ACTION_BOOK_TRAIN_TICKET"); - SetNamedProperty(env, action, "ability.intent.BOOK_HOTEL", "ACTION_BOOK_HOTEL"); - SetNamedProperty(env, action, "ability.intent.QUERY_TRAVELLING_GUIDELINE", "ACTION_QUERY_TRAVELLING_GUIDELINE"); - SetNamedProperty(env, action, "ability.intent.QUERY_POI_INFO", "ACTION_QUERY_POI_INFO"); - SetNamedProperty(env, action, "ability.intent.QUERY_CONSTELLATION_FORTUNE", "ACTION_QUERY_CONSTELLATION_FORTUNE"); - SetNamedProperty(env, action, "ability.intent.QUERY_ALMANC", "ACTION_QUERY_ALMANC"); - SetNamedProperty(env, action, "ability.intent.QUERY_WEATHER", "ACTION_QUERY_WEATHER"); - SetNamedProperty(env, action, "ability.intent.QUERY_ENCYCLOPEDIA", "ACTION_QUERY_ENCYCLOPEDIA"); - SetNamedProperty(env, action, "ability.intent.QUERY_RECIPE", "ACTION_QUERY_RECIPE"); - SetNamedProperty(env, action, "ability.intent.BUY_TAKEOUT", "ACTION_BUY_TAKEOUT"); - SetNamedProperty(env, action, "ability.intent.TRANSLATE_TEXT", "ACTION_TRANSLATE_TEXT"); - SetNamedProperty(env, action, "ability.intent.BUY", "ACTION_BUY"); - SetNamedProperty(env, action, "ability.intent.QUERY_LOGISTICS_INFO", "ACTION_QUERY_LOGISTICS_INFO"); - SetNamedProperty(env, action, "ability.intent.SEND_LOGISTICS", "ACTION_SEND_LOGISTICS"); - SetNamedProperty(env, action, "ability.intent.QUERY_SPORTS_INFO", "ACTION_QUERY_SPORTS_INFO"); - SetNamedProperty(env, action, "ability.intent.QUERY_NEWS", "ACTION_QUERY_NEWS"); - SetNamedProperty(env, action, "ability.intent.QUERY_JOKE", "ACTION_QUERY_JOKE"); - SetNamedProperty(env, action, "ability.intent.WATCH_VIDEO_CLIPS", "ACTION_WATCH_VIDEO_CLIPS"); - SetNamedProperty(env, action, "ability.intent.QUERY_STOCK_INFO", "ACTION_QUERY_STOCK_INFO"); - SetNamedProperty(env, action, "ability.intent.LOCALE_CHANGED", "ACTION_LOCALE_CHANGED"); + SetNamedProperty(env, action, "ohos.want.action.home", "ACTION_HOME"); + SetNamedProperty(env, action, "ohos.want.action.dial", "ACTION_DIAL"); + SetNamedProperty(env, action, "ohos.want.action.search", "ACTION_SEARCH"); + SetNamedProperty(env, action, "ohos.settings.wireless", "ACTION_WIRELESS_SETTINGS"); + SetNamedProperty(env, action, "ohos.settings.manage.applications", "ACTION_MANAGE_APPLICATIONS_SETTINGS"); + SetNamedProperty(env, action, "ohos.settings.application.details", "ACTION_APPLICATION_DETAILS_SETTINGS"); + SetNamedProperty(env, action, "ohos.want.action.setAlarm", "ACTION_SET_ALARM"); + SetNamedProperty(env, action, "ohos.want.action.showAlarms", "ACTION_SHOW_ALARMS"); + SetNamedProperty(env, action, "ohos.want.action.snoozeAlarm", "ACTION_SNOOZE_ALARM"); + SetNamedProperty(env, action, "ohos.want.action.dismissAlarm", "ACTION_DISMISS_ALARM"); + SetNamedProperty(env, action, "ohos.want.action.dismissTimer", "ACTION_DISMISS_TIMER"); + SetNamedProperty(env, action, "ohos.want.action.sendSms", "ACTION_SEND_SMS"); + SetNamedProperty(env, action, "ohos.want.action.choose", "ACTION_CHOOSE"); + SetNamedProperty(env, action, "ohos.want.action.select", "ACTION_SELECT"); + SetNamedProperty(env, action, "ohos.want.action.sendData", "ACTION_SEND_DATA"); + SetNamedProperty(env, action, "ohos.want.action.sendMultipleData", "ACTION_SEND_MULTIPLE_DATA"); + SetNamedProperty(env, action, "ohos.want.action.scanMediaFile", "ACTION_SCAN_MEDIA_FILE"); + SetNamedProperty(env, action, "ohos.want.action.viewData", "ACTION_VIEW_DATA"); + SetNamedProperty(env, action, "ohos.want.action.editData", "ACTION_EDIT_DATA"); + SetNamedProperty(env, action, "ability.want.params.INTENT", "INTENT_PARAMS_INTENT"); + SetNamedProperty(env, action, "ability.want.params.TITLE", "INTENT_PARAMS_TITLE"); + SetNamedProperty(env, action, "ohos.action.fileSelect", "ACTION_FILE_SELECT"); + SetNamedProperty(env, action, "ability.params.stream", "PARAMS_STREAM"); + SetNamedProperty(env, entity, "entity.system.default", "ENTITY_DEFAULT"); SetNamedProperty(env, entity, "entity.system.home", "ENTITY_HOME"); + SetNamedProperty(env, entity, "entity.system.voice", "ENTITY_VOICE"); + SetNamedProperty(env, entity, "entity.system.browsable", "ENTITY_BROWSABLE"); SetNamedProperty(env, entity, "entity.system.video", "ENTITY_VIDEO"); + SetNamedProperty(env, Flags, 0x00000001, "FLAG_AUTH_READ_URI_PERMISSION"); + SetNamedProperty(env, Flags, 0x00000002, "FLAG_AUTH_WRITE_URI_PERMISSION"); + SetNamedProperty(env, Flags, 0x00000004, "FLAG_ABILITY_FORWARD_RESULT"); + SetNamedProperty(env, Flags, 0x00000008, "FLAG_ABILITY_CONTINUATION"); + SetNamedProperty(env, Flags, 0x00000010, "FLAG_NOT_OHOS_COMPONENT"); + SetNamedProperty(env, Flags, 0x00000020, "FLAG_ABILITY_FORM_ENABLED"); + SetNamedProperty(env, Flags, 0x00000040, "FLAG_AUTH_PERSISTABLE_URI_PERMISSION"); + SetNamedProperty(env, Flags, 0x00000080, "FLAG_AUTH_PREFIX_URI_PERMISSION"); + SetNamedProperty(env, Flags, 0x00000100, "FLAG_ABILITYSLICE_MULTI_DEVICE"); + SetNamedProperty(env, Flags, 0x00000200, "FLAG_START_FOREGROUND_ABILITY"); + SetNamedProperty(env, Flags, 0x00000400, "FLAG_ABILITY_CONTINUATION_REVERSIBLE"); + SetNamedProperty(env, Flags, 0x00000800, "FLAG_INSTALL_ON_DEMAND"); + SetNamedProperty(env, Flags, 0x80000000, "FLAG_INSTALL_WITH_BACKGROUND_MODE"); + SetNamedProperty(env, Flags, 0x00008000, "FLAG_ABILITY_CLEAR_MISSION"); + SetNamedProperty(env, Flags, 0x10000000, "FLAG_ABILITY_NEW_MISSION"); + SetNamedProperty(env, Flags, 0x20000000, "FLAG_ABILITY_MISSION_TOP"); + napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("Action", action), DECLARE_NAPI_PROPERTY("Entity", entity), + DECLARE_NAPI_PROPERTY("Flags", Flags), }; napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); @@ -86,6 +103,13 @@ void SetNamedProperty(napi_env env, napi_value dstObj, const char *objName, cons napi_set_named_property(env, dstObj, propName, prop); } +void SetNamedProperty(napi_env env, napi_value dstObj, const int32_t objValue, const char *propName) +{ + napi_value prop = nullptr; + napi_create_int32(env, objValue, &prop); + napi_set_named_property(env, dstObj, propName, prop); +} + napi_value ActionConstructor(napi_env env, napi_callback_info info) { napi_value jsthis = nullptr; diff --git a/interfaces/kits/napi/aafwk/wantConstant/want_constant.h b/interfaces/kits/napi/aafwk/wantConstant/want_constant.h index 5b4c251c150..5a44ae771f3 100644 --- a/interfaces/kits/napi/aafwk/wantConstant/want_constant.h +++ b/interfaces/kits/napi/aafwk/wantConstant/want_constant.h @@ -31,6 +31,7 @@ namespace AppExecFwk { napi_value WantConstantInit(napi_env env, napi_value exports); napi_value ActionConstructor(napi_env env, napi_callback_info info); void SetNamedProperty(napi_env env, napi_value dstObj, const char *objName, const char *propName); +void SetNamedProperty(napi_env env, napi_value dstObj, const int32_t objValue, const char *propName); } // namespace AppExecFwk } // namespace OHOS #endif /* OHOS_APPEXECFWK_WANT_CONSTANT_H */ diff --git a/ohos.build b/ohos.build index 3bb586dd004..6f790fe6f9a 100644 --- a/ohos.build +++ b/ohos.build @@ -7,7 +7,8 @@ "//foundation/aafwk/standard/interfaces/innerkits:innerkits_target", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/sa_profile:aafwk_sa_profile", - "//foundation/aafwk/standard/interfaces/kits/napi:napi_packages" + "//foundation/aafwk/standard/interfaces/kits/napi:napi_packages", + "//foundation/aafwk/standard/frameworks/kits/tools:tool_ability" ], "inner_kits": [ { diff --git a/services/abilitymgr/abilitymgr.gni b/services/abilitymgr/abilitymgr.gni index 5120e9c3799..6d46d2ecc91 100644 --- a/services/abilitymgr/abilitymgr.gni +++ b/services/abilitymgr/abilitymgr.gni @@ -27,6 +27,7 @@ abilityms_files = [ "${services_path}/abilitymgr/src/ability_token_stub.cpp", "${services_path}/abilitymgr/src/app_scheduler.cpp", "${services_path}/abilitymgr/src/connection_record.cpp", + "${services_path}/abilitymgr/src/data_ability_caller_recipient.cpp", "${services_path}/abilitymgr/src/data_ability_manager.cpp", "${services_path}/abilitymgr/src/data_ability_record.cpp", "${services_path}/abilitymgr/src/lifecycle_deal.cpp", @@ -56,4 +57,10 @@ abilityms_files = [ "${services_path}/abilitymgr/src/pending_want_manager.cpp", "${services_path}/abilitymgr/src/pending_want_common_event.cpp", "${services_path}/abilitymgr/src/lock_mission_container.cpp", + "${services_path}/abilitymgr/src/ability_start_setting.cpp", + "${services_path}/abilitymgr/src/mission_option.cpp", + "${services_path}/abilitymgr/src/stack_setting.cpp", + "${services_path}/abilitymgr/src/aafwk_dummy_configuration.cpp", + "${services_path}/abilitymgr/src/configuration_holder.cpp", + "${services_path}/abilitymgr/src/resume_mission_container.cpp", ] diff --git a/services/abilitymgr/include/ability_config.h b/services/abilitymgr/include/ability_config.h index a69b8cf083e..db778f7eaee 100644 --- a/services/abilitymgr/include/ability_config.h +++ b/services/abilitymgr/include/ability_config.h @@ -1,39 +1,48 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_AAFWK_ABILITY_CONFIG_H -#define OHOS_AAFWK_ABILITY_CONFIG_H - -#include - -namespace OHOS { -namespace AAFwk { -namespace AbilityConfig { -const std::string NAME_ABILITY_MGR_SERVICE = "AbilityManagerService"; -const std::string NAME_BUNDLE_MGR_SERVICE = "BundleMgrService"; -const std::string SCHEME_DATA_ABILITY = "dataability"; -const std::string SYSTEM_UI_BUNDLE_NAME = "com.ohos.systemui"; -const std::string SYSTEM_UI_STATUS_BAR = "com.ohos.systemui.statusbar.MainAbility"; -const std::string SYSTEM_UI_NAVIGATION_BAR = "com.ohos.systemui.navigationbar.MainAbility"; -const std::string SYSTEM_DIALOG_NAME = "com.ohos.systemui.systemdialog.MainAbility"; - -const std::string SYSTEM_DIALOG_REQUEST_PERMISSIONS = "OHOS_RESULT_PERMISSIONS_LIST_YES"; -const std::string SYSTEM_DIALOG_CALLER_BUNDLENAME = "OHOS_RESULT_CALLER_BUNDLERNAME"; -const std::string SYSTEM_DIALOG_KEY = "OHOS_RESULT_PERMISSION_KEY"; -} // namespace AbilityConfig -} // namespace AAFwk -} // namespace OHOS - -#endif // OHOS_AAFWK_ABILITY_CONFIG_H +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_ABILITY_CONFIG_H +#define OHOS_AAFWK_ABILITY_CONFIG_H + +#include + +namespace OHOS { +namespace AAFwk { +namespace AbilityConfig { +const std::string NAME_ABILITY_MGR_SERVICE = "AbilityManagerService"; +const std::string NAME_BUNDLE_MGR_SERVICE = "BundleMgrService"; +const std::string SCHEME_DATA_ABILITY = "dataability"; +const std::string SYSTEM_UI_BUNDLE_NAME = "com.ohos.systemui"; +const std::string SYSTEM_UI_STATUS_BAR = "com.ohos.systemui.statusbar.MainAbility"; +const std::string SYSTEM_UI_NAVIGATION_BAR = "com.ohos.systemui.navigationbar.MainAbility"; +const std::string SYSTEM_DIALOG_NAME = "com.ohos.systemui.systemdialog.MainAbility"; + +const std::string SYSTEM_DIALOG_REQUEST_PERMISSIONS = "OHOS_RESULT_PERMISSIONS_LIST_YES"; +const std::string SYSTEM_DIALOG_CALLER_BUNDLENAME = "OHOS_RESULT_CALLER_BUNDLERNAME"; +const std::string SYSTEM_DIALOG_KEY = "OHOS_RESULT_PERMISSION_KEY"; + +const std::string EVENT_SYSTEM_WINDOW_MODE_CHANGED = "common.event.SYSTEM_WINDOW_MODE_CHANGED"; +const int EVENT_CODE_SYSTEM_WINDOW_MODE_CHANGED = 1; + +const std::string MISSION_NAME_MARK_HEAD = "#"; +const std::string MISSION_NAME_SEPARATOR = ":"; + +const std::string FLOATING_WINDOW_PERMISSION = "ohos.permission.SYSTEM_FLOAT_WINDOW"; + +} // namespace AbilityConfig +} // namespace AAFwk +} // namespace OHOS + +#endif // OHOS_AAFWK_ABILITY_CONFIG_H diff --git a/services/abilitymgr/include/ability_connect_manager.h b/services/abilitymgr/include/ability_connect_manager.h index 4bcb275b49d..e5f8ceb6b40 100644 --- a/services/abilitymgr/include/ability_connect_manager.h +++ b/services/abilitymgr/include/ability_connect_manager.h @@ -127,6 +127,8 @@ public: */ void OnAbilityRequestDone(const sptr &token, const int32_t state); + void OnAppStateChanged(const AppInfo &info); + /** * AbilityTransitionDone, ability call this interface after lift cycle was changed. * diff --git a/services/abilitymgr/include/ability_manager_proxy.h b/services/abilitymgr/include/ability_manager_proxy.h index c67fa7582de..19581d41374 100644 --- a/services/abilitymgr/include/ability_manager_proxy.h +++ b/services/abilitymgr/include/ability_manager_proxy.h @@ -41,7 +41,7 @@ public: * @param requestCode, Ability request code. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, int requestCode = -1) override; + virtual int StartAbility(const Want &want, int requestCode = DEFAULT_INVAL_VALUE) override; /** * StartAbility with want, send want to ability manager service. @@ -51,7 +51,19 @@ public: * @param requestCode the resultCode of the ability to start. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, const sptr &callerToken, int requestCode = -1) override; + virtual int StartAbility( + const Want &want, const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) override; + + /** + * Starts a new ability with specific start settings. + * + * @param want Indicates the ability to start. + * @param requestCode the resultCode of the ability to start. + * @param abilityStartSetting Indicates the setting ability used to start. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) override; /** * TerminateAbility, terminate the special ability. @@ -277,6 +289,64 @@ public: */ virtual int UninstallApp(const std::string &bundleName) override; + /** + * Moving mission to the specified stack by mission option(Enter floating window mode). + * @param missionOption, target mission option + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MoveMissionToFloatingStack(const MissionOption &missionOption) override; + + /** + * Moving mission to the specified stack by mission option(Enter floating window mode). + * @param missionOption, target mission option + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MoveMissionToSplitScreenStack(const MissionOption &missionOption) override; + + /** + * Change the focus of ability in the mission stack. + * @param lostToken, the token of lost focus ability + * @param getToken, the token of get focus ability + * @return Returns ERR_OK on success, others on failure. + */ + virtual int ChangeFocusAbility( + const sptr &lostFocusToken, const sptr &getFocusToken) override; + + /** + * minimize multiwindow by mission id. + * @param missionId, the id of target mission + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MinimizeMultiWindow(int missionId) override; + + /** + * maximize multiwindow by mission id. + * @param missionId, the id of target mission + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MaximizeMultiWindow(int missionId) override; + + /** + * get missions info of floating mission stack. + * @param list, mission info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int GetFloatingMissions(std::vector &list) override; + + /** + * close multiwindow by mission id. + * @param missionId, the id of target mission. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CloseMultiWindow(int missionId) override; + + /** + * set special mission stack default settings. + * @param stackSetting, mission stack default settings. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetMissionStackSetting(const StackSetting &stackSetting) override; + /** * @brief Checks whether this ability is the first ability in a mission. * @@ -339,6 +409,14 @@ public: */ virtual int GetMissionLockModeState() override; + /** + * Updates the configuration by modifying the configuration. + * + * @param config Indicates the new configuration + * @return Returns ERR_OK on success, others on failure. + */ + virtual int UpdateConfiguration(const DummyConfiguration &config) override; + virtual sptr GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) override; diff --git a/services/abilitymgr/include/ability_manager_service.h b/services/abilitymgr/include/ability_manager_service.h index b44deaff6de..74da3e2137a 100644 --- a/services/abilitymgr/include/ability_manager_service.h +++ b/services/abilitymgr/include/ability_manager_service.h @@ -63,7 +63,7 @@ public: * @param requestCode, Ability request code. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, int requestCode = -1) override; + virtual int StartAbility(const Want &want, int requestCode = DEFAULT_INVAL_VALUE) override; /** * StartAbility with want, send want to ability manager service. @@ -73,7 +73,20 @@ public: * @param requestCode the resultCode of the ability to start. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartAbility(const Want &want, const sptr &callerToken, int requestCode = -1) override; + virtual int StartAbility( + const Want &want, const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) override; + + /** + * Starts a new ability with specific start settings. + * + * @param want Indicates the ability to start. + * @param abilityStartSetting Indicates the setting ability used to start. + * @param callerToken, caller ability token. + * @param requestCode the resultCode of the ability to start. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) override; /** * TerminateAbility, terminate the special ability. @@ -83,8 +96,8 @@ public: * @param resultWant, the Want of the ability to return. * @return Returns ERR_OK on success, others on failure. */ - virtual int TerminateAbility( - const sptr &token, int resultCode = -1, const Want *resultWant = nullptr) override; + virtual int TerminateAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override; /** * TerminateAbility, terminate the special ability. @@ -321,6 +334,64 @@ public: */ virtual int UninstallApp(const std::string &bundleName) override; + /** + * Moving mission to the specified stack by mission option(Enter floating window mode). + * @param missionOption, target mission option + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MoveMissionToFloatingStack(const MissionOption &missionOption) override; + + /** + * Moving mission to the specified stack by mission option(Enter floating window mode). + * @param missionOption, target mission option + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MoveMissionToSplitScreenStack(const MissionOption &missionOption) override; + + /** + * Change the focus of ability in the mission stack. + * @param lostToken, the token of lost focus ability + * @param getToken, the token of get focus ability + * @return Returns ERR_OK on success, others on failure. + */ + virtual int ChangeFocusAbility( + const sptr &lostFocusToken, const sptr &getFocusToken) override; + + /** + * minimize multiwindow by mission id. + * @param missionId, the id of target mission + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MinimizeMultiWindow(int missionId) override; + + /** + * maximize multiwindow by mission id. + * @param missionId, the id of target mission + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MaximizeMultiWindow(int missionId) override; + + /** + * get missions info of floating mission stack. + * @param list, mission info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int GetFloatingMissions(std::vector &list) override; + + /** + * close multiwindow by mission id. + * @param missionId, the id of target mission. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CloseMultiWindow(int missionId) override; + + /** + * set special mission stack default settings. + * @param stackSetting, mission stack default settings. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetMissionStackSetting(const StackSetting &stackSetting) override; + /** * @brief Checks whether this ability is the first ability in a mission. * @@ -383,6 +454,14 @@ public: */ virtual int GetMissionLockModeState() override; + /** + * Updates the configuration by modifying the configuration. + * + * @param config Indicates the new configuration + * @return Returns ERR_OK on success, others on failure. + */ + virtual int UpdateConfiguration(const DummyConfiguration &config) override; + /** * remove all service record. * @@ -432,6 +511,14 @@ public: void HandleActiveTimeOut(int64_t eventId); void HandleInactiveTimeOut(int64_t eventId); + void RestartAbility(const sptr &token); + void NotifyBmsAbilityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime); + + int StartAbility(const Want &want, const sptr &callerToken, int requestCode, int callerUid = -1); + + int CheckPermission(const std::string &bundleName, const std::string &permission); + // MSG 0 - 20 represents timeout message static constexpr uint32_t LOAD_TIMEOUT_MSG = 0; static constexpr uint32_t ACTIVE_TIMEOUT_MSG = 1; @@ -439,16 +526,17 @@ public: static constexpr uint32_t BACKGROUND_TIMEOUT_MSG = 3; static constexpr uint32_t TERMINATE_TIMEOUT_MSG = 4; - static constexpr uint32_t LOAD_TIMEOUT = 1000; // ms - static constexpr uint32_t ACTIVE_TIMEOUT = 5000; // ms - static constexpr uint32_t INACTIVE_TIMEOUT = 500; // ms - static constexpr uint32_t BACKGROUND_TIMEOUT = 10000; // ms - static constexpr uint32_t TERMINATE_TIMEOUT = 10000; // ms - static constexpr uint32_t CONNECT_TIMEOUT = 500; // ms - static constexpr uint32_t DISCONNECT_TIMEOUT = 500; // ms - static constexpr uint32_t COMMAND_TIMEOUT = 5000; // ms - static constexpr uint32_t SYSTEM_UI_TIMEOUT = 5000; // ms - static constexpr uint32_t RESTART_TIMEOUT = 5000; // ms + static constexpr uint32_t LOAD_TIMEOUT = 3000; // ms + static constexpr uint32_t ACTIVE_TIMEOUT = 5000; // ms + static constexpr uint32_t INACTIVE_TIMEOUT = 500; // ms + static constexpr uint32_t BACKGROUND_TIMEOUT = 10000; // ms + static constexpr uint32_t TERMINATE_TIMEOUT = 10000; // ms + static constexpr uint32_t CONNECT_TIMEOUT = 500; // ms + static constexpr uint32_t DISCONNECT_TIMEOUT = 500; // ms + static constexpr uint32_t COMMAND_TIMEOUT = 5000; // ms + static constexpr uint32_t SYSTEM_UI_TIMEOUT = 5000; // ms + static constexpr uint32_t RESTART_TIMEOUT = 5000; // ms + static constexpr uint32_t RESTART_ABILITY_TIMEOUT = 500; // ms static constexpr uint32_t MIN_DUMP_ARGUMENT_NUM = 2; static constexpr uint32_t MAX_WAIT_SYSTEM_UI_NUM = 600; @@ -462,7 +550,8 @@ public: KEY_DUMP_WAIT_QUEUE, KEY_DUMP_SERVICE, KEY_DUMP_DATA, - KEY_DUMP_SYSTEM_UI + KEY_DUMP_SYSTEM_UI, + KEY_DUMP_FOCUS_ABILITY, }; friend class AbilityStackManager; @@ -471,6 +560,8 @@ protected: void OnAbilityRequestDone(const sptr &token, const int32_t state) override; int GetUidByBundleName(std::string bundleName); + void OnAppStateChanged(const AppInfo &info) override; + private: /** * initialization of ability manager service. @@ -511,6 +602,7 @@ private: void DumpStateInner(const std::string &args, std::vector &info); void DataDumpStateInner(const std::string &args, std::vector &info); void SystemDumpStateInner(const std::string &args, std::vector &info); + void DumpFocusMapInner(const std::string &args, std::vector &info); void DumpFuncInit(); using DumpFuncType = void (AbilityManagerService::*)(const std::string &args, std::vector &info); std::map dumpFuncMap_; diff --git a/services/abilitymgr/include/ability_manager_stub.h b/services/abilitymgr/include/ability_manager_stub.h index 52a154b760e..7f2e01c1ebd 100644 --- a/services/abilitymgr/include/ability_manager_stub.h +++ b/services/abilitymgr/include/ability_manager_stub.h @@ -63,6 +63,15 @@ private: int DisconnectAbilityInner(MessageParcel &data, MessageParcel &reply); int StopServiceAbilityInner(MessageParcel &data, MessageParcel &reply); int DumpStateInner(MessageParcel &data, MessageParcel &reply); + int StartAbilityForSettingsInner(MessageParcel &data, MessageParcel &reply); + int MoveMissionToFloatingStackInner(MessageParcel &data, MessageParcel &reply); + int MoveMissionToSplitScreenStackInner(MessageParcel &data, MessageParcel &reply); + int ChangeFocusAbilityInner(MessageParcel &data, MessageParcel &reply); + int MinimizeMultiWindowInner(MessageParcel &data, MessageParcel &reply); + int MaximizeMultiWindowInner(MessageParcel &data, MessageParcel &reply); + int GetFloatingMissionsInner(MessageParcel &data, MessageParcel &reply); + int CloseMultiWindowInner(MessageParcel &data, MessageParcel &reply); + int SetMissionStackSettingInner(MessageParcel &data, MessageParcel &reply); int IsFirstInMissionInner(MessageParcel &data, MessageParcel &reply); int CompelVerifyPermissionInner(MessageParcel &data, MessageParcel &reply); int PowerOffInner(MessageParcel &data, MessageParcel &reply); @@ -71,6 +80,7 @@ private: int UnlockMissionInner(MessageParcel &data, MessageParcel &reply); int SetMissionDescriptionInfoInner(MessageParcel &data, MessageParcel &reply); int GetMissionLockModeStateInner(MessageParcel &data, MessageParcel &reply); + int UpdateConfigurationInner(MessageParcel &data, MessageParcel &reply); int GetWantSenderInner(MessageParcel &data, MessageParcel &reply); int SendWantSenderInner(MessageParcel &data, MessageParcel &reply); @@ -86,6 +96,7 @@ private: int UnregisterCancelListenerInner(MessageParcel &data, MessageParcel &reply); int GetPendingRequestWantInner(MessageParcel &data, MessageParcel &reply); + int MoveMissionToEndTestInner(MessageParcel &data, MessageParcel &reply); using RequestFuncType = int (AbilityManagerStub::*)(MessageParcel &data, MessageParcel &reply); std::map requestFuncMap_; diff --git a/services/abilitymgr/include/ability_record.h b/services/abilitymgr/include/ability_record.h index 71c3d7a05a6..b52a3b72c85 100644 --- a/services/abilitymgr/include/ability_record.h +++ b/services/abilitymgr/include/ability_record.h @@ -23,10 +23,13 @@ #include #include "ability_info.h" +#include "ability_start_setting.h" #include "ability_token_stub.h" +#include "ability_window_configuration.h" #include "app_scheduler.h" #include "application_info.h" #include "ability_record_info.h" +#include "configuration_holder.h" #include "lifecycle_deal.h" #include "lifecycle_state_info.h" #include "want.h" @@ -114,6 +117,7 @@ struct AbilityRequest { int requestCode = -1; bool restart = false; sptr callerToken; + std::shared_ptr startSetting = nullptr; void Dump(std::vector &state) { std::string dumpInfo = " want [" + want.ToUri() + "]"; @@ -131,7 +135,7 @@ struct AbilityRequest { * @class AbilityRecord * AbilityRecord records ability info and states and used to schedule ability life. */ -class AbilityRecord : public std::enable_shared_from_this { +class AbilityRecord : public ConfigurationHolder, public std::enable_shared_from_this { public: AbilityRecord(const Want &want, const AppExecFwk::AbilityInfo &abilityInfo, const AppExecFwk::ApplicationInfo &applicationInfo, int requestCode = -1); @@ -181,6 +185,11 @@ public: */ void SetMissionStackId(const int stackId); + /** + * Get ability's mission stack id. + */ + int GetMissionStackId() const; + /** * get ability's mission record. * @@ -188,6 +197,8 @@ public: */ std::shared_ptr GetMissionRecord() const; + int GetMissionRecordId() const; + /** * get ability's info. * @@ -367,12 +378,24 @@ public: */ void ProcessActivate(); + /** + * process request of activing the ability in moving. + * + */ + void ProcessActivateInMoving(); + /** * process request of inactiving the ability. * */ void ProcessInactivate(); + /** + * process request of inactiving the ability in moving. + * + */ + void ProcessInactivateInMoving(); + /** * inactive the ability. * @@ -409,9 +432,24 @@ public: */ void CommandAbility(); + /** + * save ability state. + * + */ void SaveAbilityState(); + + /** + * restore ability state. + * + */ void RestoreAbilityState(); + /** + * notify top active ability updated. + * + */ + void TopActiveAbilityChanged(bool flag); + /** * set the want for start ability. * @@ -538,6 +576,8 @@ public: */ static std::string ConvertAbilityState(const AbilityState &state); + static std::string ConvertAppState(const AppState &state); + /** * convert life cycle state to ability state . * @@ -606,16 +646,35 @@ public: bool IsAbilityState(const AbilityState &state) const; + bool SupportMultWindow() const; + void NotifyMultiWinModeChanged(const AbilityWindowConfiguration &winModeKey, bool flag); + void SetInMovingState(bool isMoving); + bool GetInMovingState() const; + + bool IsToEnd() const; + void SetToEnd(bool isToEnd); + + void SetStartSetting(const std::shared_ptr &setting); + std::shared_ptr GetStartSetting() const; + void SetPowerState(const bool isPower); bool GetPowerState() const; -private: - /** - * get system time. - * - */ - int64_t SystemTimeMillis(); + void SetRestarting(const bool isRestart); + bool IsRestarting() const; + void SetAppState(const AppState &state); + AppState GetAppState() const; + unsigned int GetIntConfigChanges(); + void ClearFlag(); + +protected: + virtual bool OnConfigurationChanged(const DummyConfiguration &config, unsigned int configChanges) override; + virtual std::shared_ptr GetParent() override; + virtual unsigned int GetChildSize() override; + virtual std::shared_ptr FindChild(unsigned int index) override; + +private: /** * get the type of ability. * @@ -625,30 +684,29 @@ private: void SendEvent(uint32_t msg, uint32_t timeOut); static int64_t abilityRecordId; - int recordId_; // record id - Want want_; // want to start this ability - AppExecFwk::AbilityInfo abilityInfo_; // the ability info get from BMS - AppExecFwk::ApplicationInfo applicationInfo_; // the ability info get from BMS - sptr token_; // used to interact with kit and wms - std::weak_ptr missionRecord_; // mission of this ability - std::weak_ptr preAbilityRecord_; // who starts this ability record - std::weak_ptr nextAbilityRecord_; // ability that started by this ability - std::weak_ptr backAbilityRecord_; // who back to this ability record - std::unique_ptr lifecycleDeal_; // life manager used to schedule life - int64_t startTime_ = 0; // records first time of ability start - bool isReady_ = false; // is ability thread attached? - bool isWindowAttached_ = false; // Is window of this ability attached? - bool isLauncherAbility_ = false; // is launcher? - int64_t eventId_ = 0; // post event id - static constexpr int64_t NANOSECONDS = 1000000000; // NANOSECONDS mean 10^9 nano second - static constexpr int64_t MICROSECONDS = 1000000; // MICROSECONDS mean 10^6 millias second + int recordId_; // record id + Want want_; // want to start this ability + AppExecFwk::AbilityInfo abilityInfo_; // the ability info get from BMS + AppExecFwk::ApplicationInfo applicationInfo_; // the ability info get from BMS + sptr token_; // used to interact with kit and wms + std::weak_ptr missionRecord_; // mission of this ability + std::weak_ptr preAbilityRecord_; // who starts this ability record + std::weak_ptr nextAbilityRecord_; // ability that started by this ability + std::weak_ptr backAbilityRecord_; // who back to this ability record + std::unique_ptr lifecycleDeal_; // life manager used to schedule life + int64_t startTime_ = 0; // records first time of ability start + bool isReady_ = false; // is ability thread attached? + bool isWindowAttached_ = false; // Is window of this ability attached? + bool isLauncherAbility_ = false; // is launcher? + int64_t eventId_ = 0; // post event id static int64_t g_abilityRecordEventId_; sptr scheduler_; // kit scheduler bool isTerminating_ = false; // is terminating ? LifeCycleStateInfo lifeCycleStateInfo_; // target life state info AbilityState currentState_; // current life state std::shared_ptr windowInfo_; // add window info - bool isCreateByConnect = false; // is created by connect ability mode? + bool isCreateByConnect_ = false; // is created by connect ability mode? + bool isToEnd_ = false; // is to end ? int requestCode_ = -1; // requestCode_: >= 0 for-result start mode; <0 for normal start mode in default. sptr schedulerDeathRecipient_; // scheduler binderDied Recipient @@ -669,14 +727,20 @@ private: // page(ability) can be started by multi-pages(abilites), so need to store this ability's caller std::list> callerList_; - bool isUninstall = false; + bool isUninstall_ = false; bool isForceTerminate_ = false; const static std::map stateToStrMap; const static std::map convertStateMap; + const static std::map appStateToStrMap_; - bool isKernalSystemAbility = false; + bool isKernalSystemAbility_ = false; bool isLauncherRoot_ = false; bool isPowerState_ = false; // ability to change state when poweroff and poweron. + + PacMap stateDatas_; // ability saved ability state data + bool isRestarting_ = false; // is restarting ? + bool isInMovingState_ = false; // whether complete multi window moving state. + AppState appState_; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/ability_scheduler_proxy.h b/services/abilitymgr/include/ability_scheduler_proxy.h index 67156c51e63..4335a80bef2 100644 --- a/services/abilitymgr/include/ability_scheduler_proxy.h +++ b/services/abilitymgr/include/ability_scheduler_proxy.h @@ -78,6 +78,8 @@ public: */ void ScheduleRestoreAbilityState(const PacMap &inState) override; + void ScheduleUpdateConfiguration(const DummyConfiguration &config) override; + /** * @brief Obtains the MIME types of files supported. * @@ -190,6 +192,48 @@ public: */ int BatchInsert(const Uri &uri, const std::vector &values) override; + /** + * @brief notify multi window mode changed. + * + * @param winModeKey Indicates ability Window display mode. + * @param flag Indicates this ability has been enter this mode. + */ + void NotifyMultiWinModeChanged(int32_t winModeKey, bool flag) override; + + /** + * @brief notify this ability is top active ability. + * + * @param flag true: Indicates this ability is top active ability + */ + void NotifyTopActiveAbilityChanged(bool flag) override; + + /** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the + * context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to + * any method that is called on the Data ability must require normalization verification and denormalization. The + * default implementation of this method returns null, indicating that this Data ability does not support URI + * normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ + Uri NormalizeUri(const Uri &uri) override; + + /** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed + * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found + * in the current environment. + */ + Uri DenormalizeUri(const Uri &uri) override; + private: bool WriteInterfaceToken(MessageParcel &data); diff --git a/services/abilitymgr/include/ability_scheduler_stub.h b/services/abilitymgr/include/ability_scheduler_stub.h index 50193495c08..c2243e84b77 100644 --- a/services/abilitymgr/include/ability_scheduler_stub.h +++ b/services/abilitymgr/include/ability_scheduler_stub.h @@ -54,6 +54,11 @@ private: int GetTypeInner(MessageParcel &data, MessageParcel &reply); int ReloadInner(MessageParcel &data, MessageParcel &reply); int BatchInsertInner(MessageParcel &data, MessageParcel &reply); + int NormalizeUriInner(MessageParcel &data, MessageParcel &reply); + int DenormalizeUriInner(MessageParcel &data, MessageParcel &reply); + int UpdateConfigurationInner(MessageParcel &data, MessageParcel &reply); + int MutiWinModeChangedInner(MessageParcel &data, MessageParcel &reply); + int TopActiveAbilityChangedInner(MessageParcel &data, MessageParcel &reply); using RequestFuncType = int (AbilitySchedulerStub::*)(MessageParcel &data, MessageParcel &reply); std::map requestFuncMap_; }; diff --git a/services/abilitymgr/include/ability_stack_manager.h b/services/abilitymgr/include/ability_stack_manager.h index 2f9a451ac01..139466ee367 100644 --- a/services/abilitymgr/include/ability_stack_manager.h +++ b/services/abilitymgr/include/ability_stack_manager.h @@ -25,16 +25,25 @@ #include "ability_info.h" #include "ability_record.h" #include "application_info.h" +#include "aafwk_dummy_configuration.h" #include "mission_record.h" #include "mission_stack.h" +#include "mission_option.h" #include "ability_mission_info.h" #include "lock_mission_container.h" +#include "resume_mission_container.h" #include "stack_info.h" #include "power_storage.h" #include "want.h" namespace OHOS { namespace AAFwk { +enum class SystemWindowMode { + DEFAULT_WINDOW_MODE = 0, + SPLITSCREEN_WINDOW_MODE, + FLOATING_WINDOW_MODE, + FLOATING_AND_SPLITSCREEN_WINDOW_MODE, +}; /** * @class AbilityStackManager * AbilityStackManager provides a facility for managing page ability life cycle. @@ -42,7 +51,6 @@ namespace AAFwk { class AbilityStackManager : public std::enable_shared_from_this { public: explicit AbilityStackManager(int userId); - ~AbilityStackManager(); /** @@ -148,6 +156,14 @@ public: */ std::shared_ptr GetMissionRecordById(int id) const; + /** + * get the mission record by record name. + * + * @param name, the record name of mission. + * @return mission record. + */ + std::shared_ptr GetMissionRecordByName(std::string name) const; + /** * get the mission record by record id from all stacks. * @@ -198,6 +214,8 @@ public: */ void OnAbilityRequestDone(const sptr &token, const int32_t state); + void OnAppStateChanged(const AppInfo &info); + /** * Remove the specified mission from the stack by mission id. * @@ -221,6 +239,11 @@ public: */ void MoveMissionStackToTop(const std::shared_ptr &stack); + int GetMaxHoldMissionsByStackId(int stackId) const; + bool SupportSyncVisualByStackId(int stackId) const; + + void SetMissionStackSetting(const StackSetting &stackSetting); + /** * complete ability life cycle . * @@ -246,6 +269,7 @@ public: void DumpMission(int missionId, std::vector &info); void DumpStack(int missionStackId, std::vector &info); void DumpStackList(std::vector &info); + void DumpFocusMap(std::vector &info); /** * get the target mission stack by want info. @@ -253,6 +277,8 @@ public: * @param want , the want for starting ability. */ std::shared_ptr GetTargetMissionStack(const AbilityRequest &abilityRequest); + std::shared_ptr GetTargetMissionStackByDefault(const AbilityRequest &abilityRequest); + std::shared_ptr GetTargetMissionStackBySetting(const AbilityRequest &abilityRequest); /** * Obtains information about ability stack that are running on the device. @@ -294,6 +320,8 @@ public: */ int MoveMissionToEnd(const sptr &token, const bool nonFirst); + int MoveMissionToEndLocked(int missionId); + /** * Ability detects death * @@ -310,6 +338,53 @@ public: void OnTimeOut(uint32_t msgId, int64_t eventId); bool IsFirstInMission(const sptr &token); + bool IsFrontInAllStack(const std::shared_ptr &stack) const; + bool IsTopInMission(const std::shared_ptr &abilityRecord) const; + + /** + * Moving some missions to the specified stack by mission option(Enter splitscreen or floating window mode). + * @param missionOption, target mission option + * @return Returns ERR_OK on success, others on failure. + */ + int MoveMissionToFloatingStack(const MissionOption &missionOption); + int MoveMissionToSplitScreenStack(const MissionOption &missionOption); + + /** + * minimize multiwindow by mission id. + * @param missionId, the id of target mission + * @return Returns ERR_OK on success, others on failure. + */ + int MinimizeMultiWindow(int missionId); + /** + * maximize multiwindow by mission id. + * @param missionId, the id of target mission + * @return Returns ERR_OK on success, others on failure. + */ + int MaximizeMultiWindow(int missionId); + + /** + * Change the focus of ability in the mission stack. + * @param lostToken, the token of lost focus ability + * @param getToken, the token of get focus ability + * @return Returns ERR_OK on success, others on failure. + */ + int ChangeFocusAbility(const sptr &lostFocusToken, const sptr &getFocusToken); + + /** + * get missions info of floating mission stack. + * @param list, mission info. + * @return Returns ERR_OK on success, others on failure. + */ + int GetFloatingMissions(std::vector &list); + + /** + * close multiwindow by mission id. + * @param missionId, the id of target mission. + * @return Returns ERR_OK on success, others on failure. + */ + int CloseMultiWindow(int missionId); + + void JudgingIsRemoveMultiScreenStack(std::shared_ptr &stack); /** * Save the top ability States and move them to the background @@ -328,6 +403,14 @@ public: const std::shared_ptr &abilityRecord, const MissionDescriptionInfo &missionDescriptionInfo); int GetMissionLockModeState(); + /** + * update configuration to ability + * @return Returns ERR_OK on success, others on failure. + */ + int UpdateConfiguration(const DummyConfiguration &config); + + void RestartAbility(const std::shared_ptr abilityRecord); + private: /** * dispatch ability life cycle . @@ -340,6 +423,9 @@ private: int DispatchInactive(const std::shared_ptr &abilityRecord, int state); int DispatchBackground(const std::shared_ptr &abilityRecord, int state); int DispatchTerminate(const std::shared_ptr &abilityRecord, int state); + int DispatchLifecycle(const std::shared_ptr &lastTopAbility, + const std::shared_ptr ¤tTopAbility, bool isTopFullScreen = false); + void ContinueLifecycle(); /** * get current top ability of stack. @@ -358,6 +444,9 @@ private: int StartAbilityLocked( const std::shared_ptr ¤tTopAbility, const AbilityRequest &abilityRequest); + int StartAbilityAsSpecialLocked( + const std::shared_ptr ¤tTopAbility, const AbilityRequest &abilityRequest); + /** * TerminateAbilityLocked. * @@ -393,7 +482,6 @@ private: /** * start waitting ability. - * */ void StartWaittingAbility(); @@ -517,12 +605,37 @@ private: */ std::shared_ptr GetAbilityRecordByEventId(int64_t eventId) const; - void ActiveTopAbility(const std::shared_ptr &abilityRecord); - void ActiveTopAbility(const bool isAll, int32_t stackId); + /** + * Get or Create mission stack by stack id, + * @param stackId, target stack id + * @param isCreateFlag, if the stack is not exist, decide whether or not to create a new mission stack, + * default is fasle. + * @return Returns target missionStack. + */ + std::shared_ptr GetOrCreateMissionStack(int stackId, bool isCreateFlag = false); + /** + * Moving some missions to the specified stack by mission option(Enter splitscreen or floating window mode). + * @param missionOption, target mission option + * @return Returns ERR_OK on success, others on failure. + */ + int MoveMissionsToStackLocked(const std::list &missionOptions); + int CheckMultiWindowCondition(const std::list &missionOptions) const; + int CheckMultiWindowCondition( + const std::shared_ptr ¤tTopAbility, const AbilityRequest &abilityRequest) const; + bool CheckMissionStackWillOverflow(const std::list &missionOptions) const; + int CompleteMoveMissionToStack( + const std::shared_ptr &missionRecord, const std::shared_ptr &stack); + int CompleteMissionMoving(std::shared_ptr &missionRecord, int stackId); + SystemWindowMode JudgingTargetSystemWindowMode(AbilityWindowConfiguration config) const; + SystemWindowMode GetTargetSystemWindowMode(const SystemWindowMode &willWinMode); + int JudgingTargetStackId(AbilityWindowConfiguration config) const; + int StartAbilityLifeCycle(std::shared_ptr lastTopAbility, + std::shared_ptr currentTopAbility, std::shared_ptr targetAbility); + + void ActiveTopAbility(const std::shared_ptr &abilityRecord); void MoveMissionAndAbility(const std::shared_ptr ¤tTopAbility, - std::shared_ptr &targetAbilityRecord, std::shared_ptr &targetMissionRecord, - const bool isSetPreMission); + std::shared_ptr &targetAbilityRecord, std::shared_ptr &targetMissionRecord); int PowerOffLocked(); int PowerOnLocked(); @@ -532,12 +645,32 @@ private: const AbilityRequest &abilityRequest, const std::shared_ptr ¤tTopAbility) const; bool CanStopInLockMissionState(const std::shared_ptr &terminateAbility) const; void SendUnlockMissionMessage(); + std::shared_ptr GetTopFullScreenStack(); + bool IsFullScreenStack(int stackId) const; + + /** + * minimize multiwindow by mission id. + * @param missionId, the id of target mission + * @return Returns ERR_OK on success, others on failure. + */ + int MinimizeMultiWindowLocked(int missionId); + int ChangeFocusAbilityLocked(const std::shared_ptr &targetAbility); + + void NotifyWindowModeChanged(const SystemWindowMode &windowMode); + + int ProcessConfigurationChange(); + + void UpdateFocusAbilityRecord( + int displayId, const std::shared_ptr &focusAbility, bool isNotify = false); + void UpdateFocusAbilityRecord(const std::shared_ptr &abilityRecord, bool isNotify = false); + void CheckMissionRecordIsResume(const std::shared_ptr &mission); + int ChangedPowerStorageAbilityToActive(std::shared_ptr &powerStorage); private: - const std::string MISSION_NAME_MARK_HEAD = "#"; - const std::string MISSION_NAME_SEPARATOR = ":"; - static constexpr int LAUNCHER_MISSION_STACK_ID = 0; - static constexpr int DEFAULT_MISSION_STACK_ID = 1; + static constexpr int MIN_MISSION_STACK_ID = LAUNCHER_MISSION_STACK_ID; + static constexpr int MAX_MISSION_STACK_ID = FLOATING_MISSION_STACK_ID; + static constexpr int MAX_CAN_MOVE_MISSIONS = 2; + int userId_; bool powerOffing_ = false; std::recursive_mutex stackLock_; @@ -549,10 +682,17 @@ private: std::list> terminateAbilityRecordList_; // abilities on terminating put in this // list. std::queue waittingAbilityQueue_; + std::list> focusWaitingList_; std::shared_ptr powerStorage_; // find AbilityRecord by windowToken. one windowToken has one and only one AbilityRecord. std::unordered_map> windowTokenToAbilityMap_; std::shared_ptr lockMissionContainer_ = nullptr; + SystemWindowMode curSysWindowMode_ = SystemWindowMode::DEFAULT_WINDOW_MODE; + bool isMultiWinMoving_ = false; + std::vector stackSettings_; + std::map> focusAbilityRecordMap_; // abilities has been focused , + // key : display id, value: focused ability + std::shared_ptr resumeMissionContainer_; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/ability_util.h b/services/abilitymgr/include/ability_util.h index 067adc9b3cc..1f3265122ee 100644 --- a/services/abilitymgr/include/ability_util.h +++ b/services/abilitymgr/include/ability_util.h @@ -19,39 +19,151 @@ #include #include "hilog_wrapper.h" #include "ability_config.h" +#include "ipc_skeleton.h" +#include "sa_mgr_client.h" +#include "bundlemgr/bundle_mgr_interface.h" +#include "system_ability_definition.h" +#include "ability_manager_errors.h" namespace OHOS { namespace AAFwk { -namespace AbilitUtil { +namespace AbilityUtil { +constexpr int32_t SYSTEM_UID = 1000; +constexpr int32_t ROOT_UID = 0; + #define CHECK_POINTER_CONTINUE(object) \ if (!object) { \ HILOG_ERROR("pointer is nullptr, %{public}s, %{public}d", __func__, __LINE__); \ continue; \ } -#define CHECK_POINTER(object) \ - if (!object) { \ - HILOG_ERROR("pointer is nullptr, %{public}s, %{public}d", __func__, __LINE__); \ - return; \ +#define CHECK_POINTER_IS_NULLPTR(object) \ + if (object == nullptr) { \ + HILOG_ERROR("pointer is nullptr."); \ + return; \ } -#define CHECK_POINTER_AND_RETURN(object, value) \ - if (!object) { \ - HILOG_ERROR("pointer is nullptr, %{public}s, %{public}d", __func__, __LINE__); \ - return value; \ +#define CHECK_POINTER(object) \ + if (!object) { \ + HILOG_ERROR("pointer is nullptr."); \ + return; \ } -#define CHECK_POINTER_RETURN_BOOL(object) \ - if (!object) { \ - HILOG_ERROR("pointer is nullptr, %{public}s, %{public}d", __func__, __LINE__); \ - return false; \ +#define CHECK_POINTER_LOG(object, log) \ + if (!object) { \ + HILOG_ERROR("%{public}s:", log); \ + return; \ + } + +#define CHECK_POINTER_AND_RETURN(object, value) \ + if (!object) { \ + HILOG_ERROR("pointer is nullptr."); \ + return value; \ + } + +#define CHECK_POINTER_AND_RETURN_LOG(object, value, log) \ + if (!object) { \ + HILOG_ERROR("%{public}s:", log); \ + return value; \ + } + +#define CHECK_POINTER_RETURN_BOOL(object) \ + if (!object) { \ + HILOG_ERROR("pointer is nullptr."); \ + return false; \ + } + +#define CHECK_RET_RETURN_RET(object, log) \ + if (object != ERR_OK) { \ + HILOG_ERROR("%{public}s, ret : %{public}d", log, object); \ + return object; \ + } + +#define CHECK_TRUE_RETURN_RET(object, value, log) \ + if (object) { \ + HILOG_WARN("%{public}s", log); \ + return value; \ } [[maybe_unused]] static bool IsSystemDialogAbility(const std::string &bundleName, const std::string &abilityName) { return (abilityName == AbilityConfig::SYSTEM_DIALOG_NAME) && (bundleName == AbilityConfig::SYSTEM_UI_BUNDLE_NAME); } -} // namespace AbilitUtil + +[[maybe_unused]] static std::string ConvertBundleNameSingleton(const std::string &bundleName, const std::string &name) +{ + std::string strName = + AbilityConfig::MISSION_NAME_MARK_HEAD + bundleName + AbilityConfig::MISSION_NAME_SEPARATOR + name; + return strName; +} + +static constexpr int64_t NANOSECONDS = 1000000000; // NANOSECONDS mean 10^9 nano second +static constexpr int64_t MICROSECONDS = 1000000; // MICROSECONDS mean 10^6 millias second +[[maybe_unused]] static int64_t SystemTimeMillis() +{ + struct timespec t; + t.tv_sec = 0; + t.tv_nsec = 0; + clock_gettime(CLOCK_MONOTONIC, &t); + return (int64_t)((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS; +} + +[[maybe_unused]] static int64_t UTCTimeSeconds() +{ + struct timespec t; + t.tv_sec = 0; + t.tv_nsec = 0; + clock_gettime(CLOCK_REALTIME, &t); + return (int64_t)(t.tv_sec); +} + +static sptr GetBundleManager() +{ + 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; + } + return iface_cast(bundleObj); +} + +[[maybe_unused]] static int JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo &abilityInfo, int callerUid = -1) +{ + HILOG_DEBUG("%{public}s begin", __func__); + if (!abilityInfo.visible) { + HILOG_ERROR("ability visible is false"); + if (callerUid == -1) { + callerUid = IPCSkeleton::GetCallingUid(); + } + if (ROOT_UID == callerUid) { + HILOG_ERROR("uid is root"); + return ABILITY_VISIBLE_FALSE_DENY_REQUEST; + } + auto bms = GetBundleManager(); + CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED); + auto isSystemApp = bms->CheckIsSystemAppByUid(callerUid); + if (callerUid != SYSTEM_UID && !isSystemApp) { + HILOG_ERROR("caller is not systemAp or system"); + std::string bundleName; + bool result = bms->GetBundleNameForUid(callerUid, bundleName); + if (!result) { + HILOG_ERROR("GetBundleNameForUid fail"); + return ABILITY_VISIBLE_FALSE_DENY_REQUEST; + } + if (bundleName != abilityInfo.bundleName) { + HILOG_ERROR("caller ability bundlename not equal abilityInfo.bundleName bundleName: %{public}s " + "abilityInfo.bundleName: %{public}s", + bundleName.c_str(), + abilityInfo.bundleName.c_str()); + return ABILITY_VISIBLE_FALSE_DENY_REQUEST; + } + } + } + HILOG_DEBUG("%{public}s end", __func__); + return ERR_OK; +} +} // namespace AbilityUtil } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/app_scheduler.h b/services/abilitymgr/include/app_scheduler.h index 5e6872cbde8..aa2ec14b398 100644 --- a/services/abilitymgr/include/app_scheduler.h +++ b/services/abilitymgr/include/app_scheduler.h @@ -20,6 +20,7 @@ #include #include "ability_info.h" +// #include "app_process_data.h" #include "appmgr/app_mgr_client.h" #include "appmgr/app_state_callback_host.h" #include "application_info.h" @@ -40,6 +41,23 @@ enum class AppAbilityState { ABILITY_STATE_END, }; +enum class AppState { + BEGIN = 0, + READY, + FOREGROUND, + BACKGROUND, + SUSPENDED, + TERMINATED, + END, +}; + +struct AppInfo { + std::string appName; + std::string processName; + int32_t uid; + AppState state; +}; + /** * @class AppStateCallback * AppStateCallback. @@ -52,6 +70,8 @@ public: {} virtual void OnAbilityRequestDone(const sptr &token, const int32_t state) = 0; + + virtual void OnAppStateChanged(const AppInfo &info) = 0; }; /** @@ -168,6 +188,13 @@ protected: */ virtual void OnAbilityRequestDone(const sptr &token, const AppExecFwk::AbilityState state) override; + /** + * Application state changed callback. + * + * @param appProcessData Process data + */ + virtual void OnAppStateChanged(const AppExecFwk::AppProcessData &appData) override; + private: std::weak_ptr callback_; std::unique_ptr appMgrClient_; diff --git a/services/abilitymgr/include/configuration_holder.h b/services/abilitymgr/include/configuration_holder.h new file mode 100644 index 00000000000..35aed5e3726 --- /dev/null +++ b/services/abilitymgr/include/configuration_holder.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_AAFWK_CONFIGURATION_HOLDER_H +#define OHOS_AAFWK_CONFIGURATION_HOLDER_H + +#include "aafwk_dummy_configuration.h" + +#include + +namespace OHOS { +namespace AAFwk { +/** + * @class AbilityRecord + * AbilityRecord records ability info and states and used to schedule ability life. + */ +class ConfigurationHolder { +public: + ConfigurationHolder() = default; + virtual ~ConfigurationHolder() = default; + + void UpdateConfiguration(const std::shared_ptr config); + std::shared_ptr GetConfiguration() const; + bool ProcessConfigurationChange(); + bool ForceProcessConfigurationChange(const std::shared_ptr &config); + +protected: + virtual bool OnConfigurationChanged(const DummyConfiguration &config, unsigned int configChanges); + virtual std::shared_ptr GetParent() = 0; + virtual unsigned int GetChildSize() = 0; + virtual std::shared_ptr FindChild(unsigned int index) = 0; + + static constexpr unsigned int CHANGE_CONFIG_ALL_CHANGED = 0xFFFFFFFF; + static constexpr unsigned int CHANGE_CONFIG_NONE = 0x00000000; + static constexpr unsigned int CHANGE_CONFIG_LOCALE = 0x00000001; + static constexpr unsigned int CHANGE_CONFIG_LAYOUT = 0x00000002; + static constexpr unsigned int CHANGE_CONFIG_FONTSIZE = 0x00000004; + static constexpr unsigned int CHANGE_CONFIG_ORIENTATION = 0x00000008; + static constexpr unsigned int CHANGE_CONFIG_DENSITY = 0x00000010; + +private: + void DealUpdateConfiguration(); + bool ProcessConfigurationChangeInner(const std::shared_ptr &config); + +private: + std::shared_ptr baseConfiguration_ = nullptr; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_CONFIGURATION_HOLDER_H \ No newline at end of file diff --git a/services/abilitymgr/include/data_ability_caller_recipient.h b/services/abilitymgr/include/data_ability_caller_recipient.h new file mode 100644 index 00000000000..2c148815e4b --- /dev/null +++ b/services/abilitymgr/include/data_ability_caller_recipient.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_OS_AAFWK_DATAABILITY_CALLER_RECIPIENT_H +#define OHOS_OS_AAFWK_DATAABILITY_CALLER_RECIPIENT_H + +#include +#include +#include + +namespace OHOS { +namespace AAFwk { + +class DataAbilityCallerRecipient : public IRemoteObject::DeathRecipient { +public: + using RemoteDiedHandler = std::function &)>; + + explicit DataAbilityCallerRecipient(RemoteDiedHandler handler); + + virtual ~DataAbilityCallerRecipient(); + + virtual void OnRemoteDied(const wptr &remote); + +private: + RemoteDiedHandler handler_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_OS_AAFWK_DATAABILITY_CALLER_RECIPIENT_H \ No newline at end of file diff --git a/services/abilitymgr/include/data_ability_manager.h b/services/abilitymgr/include/data_ability_manager.h index 911c06a7446..b3286f03df1 100644 --- a/services/abilitymgr/include/data_ability_manager.h +++ b/services/abilitymgr/include/data_ability_manager.h @@ -34,11 +34,12 @@ public: public: sptr Acquire( - const AbilityRequest &abilityRequest, bool tryBind, const sptr &client); - int Release(const sptr &scheduler, const sptr &client); + const AbilityRequest &abilityRequest, bool tryBind, const sptr &client, bool isSystem); + int Release(const sptr &scheduler, const sptr &client, bool isSystem); int AttachAbilityThread(const sptr &scheduler, const sptr &token); int AbilityTransitionDone(const sptr &token, int state); void OnAbilityRequestDone(const sptr &token, const int32_t state); + void OnAppStateChanged(const AppInfo &info); void OnAbilityDied(const std::shared_ptr &abilityRecord); std::shared_ptr GetAbilityRecordById(int64_t id); std::shared_ptr GetAbilityRecordByToken(const sptr &token); diff --git a/services/abilitymgr/include/data_ability_record.h b/services/abilitymgr/include/data_ability_record.h index 1af5cd224a2..76673d73d64 100644 --- a/services/abilitymgr/include/data_ability_record.h +++ b/services/abilitymgr/include/data_ability_record.h @@ -24,6 +24,7 @@ #include #include "ability_record.h" +#include "data_ability_caller_recipient.h" namespace OHOS { namespace AAFwk { @@ -38,10 +39,10 @@ public: sptr GetScheduler(); int Attach(const sptr &scheduler); int OnTransitionDone(int state); - int AddClient(const std::shared_ptr &client, bool tryBind); - int RemoveClient(const std::shared_ptr &client); + int AddClient(const sptr &client, bool tryBind, bool isSystem); + int RemoveClient(const sptr &client, bool isSystem); int RemoveClients(const std::shared_ptr &client = nullptr); - size_t GetClientCount(const std::shared_ptr &client = nullptr) const; + size_t GetClientCount(const sptr &client = nullptr) const; int KillBoundClientProcesses(); const AbilityRequest &GetRequest() const; std::shared_ptr GetAbilityRecord(); @@ -50,12 +51,15 @@ public: void Dump(std::vector &info) const; private: + using IRemoteObjectPtr = sptr; using AbilityRecordPtr = std::shared_ptr; struct ClientInfo { - AbilityRecordPtr ability; + IRemoteObjectPtr client; bool tryBind; + bool isSystem; }; + void OnSchedulerDied(const wptr &remote); private: std::condition_variable_any loadedCond_{}; @@ -63,6 +67,7 @@ private: AbilityRecordPtr ability_{}; sptr scheduler_{}; std::list clients_{}; + sptr callerDeathRecipient_; // caller binderDied Recipient }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/kernal_system_app_manager.h b/services/abilitymgr/include/kernal_system_app_manager.h index 1c676249317..fac62154f33 100644 --- a/services/abilitymgr/include/kernal_system_app_manager.h +++ b/services/abilitymgr/include/kernal_system_app_manager.h @@ -69,6 +69,9 @@ public: * @param state,the state of ability lift cycle. */ void OnAbilityRequestDone(const sptr &token, const int32_t state); + + void OnAppStateChanged(const AppInfo &info); + /** * get manager's user id. */ @@ -87,6 +90,9 @@ public: */ std::shared_ptr GetAbilityRecordByToken(const sptr &token); + int UpdateConfiguration(const DummyConfiguration &config); + void RestartAbility(const std::shared_ptr abilityRecord); + private: /** * StartAbilityLocked. diff --git a/services/abilitymgr/include/lifecycle_deal.h b/services/abilitymgr/include/lifecycle_deal.h index b5b418eef10..3113640d4bd 100644 --- a/services/abilitymgr/include/lifecycle_deal.h +++ b/services/abilitymgr/include/lifecycle_deal.h @@ -51,6 +51,9 @@ public: void DisconnectAbility(const Want &want); void Terminate(const Want &want, LifeCycleStateInfo &stateInfo); void CommandAbility(const Want &want, bool reStart, int startId); + void SaveAbilityState(PacMap &outState); + void RestoreAbilityState(const PacMap &inState); + void UpdateConfiguration(const DummyConfiguration &config); private: sptr abilityScheduler_; // kit interface used to schedule ability life diff --git a/services/abilitymgr/include/mission_record.h b/services/abilitymgr/include/mission_record.h index 0b0470c5323..1e4ce4aab5d 100644 --- a/services/abilitymgr/include/mission_record.h +++ b/services/abilitymgr/include/mission_record.h @@ -21,6 +21,7 @@ #include "ability_record.h" #include "mission_stack.h" #include "mission_description_info.h" +#include "mission_option.h" namespace OHOS { namespace AAFwk { @@ -29,9 +30,10 @@ class MissionStack; * @class MissionRecord * MissionRecord records mission info and ability records. */ -class MissionRecord { +class MissionRecord : public ConfigurationHolder { public: MissionRecord(const std::string &bundleName = ""); + MissionRecord(const std::shared_ptr &mission); virtual ~MissionRecord(); /** @@ -69,6 +71,13 @@ public: */ std::shared_ptr GetTopAbilityRecord() const; + /** + * get the last top ability of this mission + * + * @return AbilityRecord. + */ + std::shared_ptr GetLastTopAbility() const; + /** * get the ability by token * @@ -185,10 +194,10 @@ public: /** * set parent mission stack. * - * @param parentStack: the parent mission stack + * @param missionStack: the parent mission stack */ - void SetParentStack(const std::shared_ptr &parent, int stackId); - std::shared_ptr GetParentStack() const; + void SetMissionStack(const std::shared_ptr &missionStack, int stackId); + std::shared_ptr GetMissionStack() const; std::string GetName() const { @@ -199,11 +208,25 @@ public: { missionDescriptionInfo_ = missionDescriptionInfo; }; + std::shared_ptr GetMissionDescriptionInfo() const { return missionDescriptionInfo_; }; + bool SupportMultWindow() const; + + void SetMissionOption(const MissionOption &option); + const MissionOption &GetMissionOption() const; + + bool IsEmpty(); + void Resume(const std::shared_ptr &backup); + +protected: + virtual std::shared_ptr GetParent() override; + virtual unsigned int GetChildSize() override; + virtual std::shared_ptr FindChild(unsigned int index) override; + private: static int nextMissionId_; int missionId_; @@ -214,7 +237,8 @@ private: std::weak_ptr parentMissionStack_; std::shared_ptr missionDescriptionInfo_ = nullptr; -}; // namespace AAFwk + MissionOption option_; +}; } // namespace AAFwk } // namespace OHOS #endif // OHOS_AAFWK_MISSION_RECORD_H \ No newline at end of file diff --git a/services/abilitymgr/include/mission_stack.h b/services/abilitymgr/include/mission_stack.h index e8b4d9478b1..1d402bc4243 100644 --- a/services/abilitymgr/include/mission_stack.h +++ b/services/abilitymgr/include/mission_stack.h @@ -24,6 +24,7 @@ #include "mission_record.h" #include "mission_record_info.h" #include "want.h" +#include "stack_setting.h" namespace OHOS { namespace AAFwk { @@ -31,7 +32,7 @@ namespace AAFwk { * @class MissionStack * MissionStack records mission info. */ -class MissionStack { +class MissionStack : public ConfigurationHolder { public: MissionStack(int id, int userId); virtual ~MissionStack(); @@ -157,6 +158,17 @@ public: */ bool IsExistMissionRecord(int missionId); + bool IsTopMissionRecord(std::shared_ptr &missionRecord) const; + + bool IsEqualStackId(int stackId); + + bool IsEmpty(); + +protected: + virtual std::shared_ptr GetParent() override; + virtual unsigned int GetChildSize() override; + virtual std::shared_ptr FindChild(unsigned int index) override; + private: int missionStackId_; int userId_; diff --git a/services/abilitymgr/include/pending_want_key.h b/services/abilitymgr/include/pending_want_key.h index 66848cc68a9..fd926b267db 100644 --- a/services/abilitymgr/include/pending_want_key.h +++ b/services/abilitymgr/include/pending_want_key.h @@ -44,12 +44,12 @@ public: void SetUserId(int32_t userId); int32_t GetType(); - std::string &GetBundleName(); - std::string &GetRequestWho(); + std::string GetBundleName(); + std::string GetRequestWho(); int32_t GetRequestCode(); - Want &GetRequestWant(); - std::string &GetRequestResolvedType(); - std::vector &GetAllWantsInfos(); + Want GetRequestWant(); + std::string GetRequestResolvedType(); + std::vector GetAllWantsInfos(); int32_t GetFlags(); int32_t GetCode(); int32_t GetUserId(); diff --git a/services/abilitymgr/include/pending_want_manager.h b/services/abilitymgr/include/pending_want_manager.h index 97e9fa9bb49..d3ba84face3 100644 --- a/services/abilitymgr/include/pending_want_manager.h +++ b/services/abilitymgr/include/pending_want_manager.h @@ -133,10 +133,11 @@ public: virtual ~PendingWantManager(); public: - sptr GetWantSender(const int32_t callingUid, const int32_t uid, const WantSenderInfo &wantSenderInfo, - const sptr &callerToken); + sptr GetWantSender(const int32_t callingUid, const int32_t uid, const bool isSystemApp, + const WantSenderInfo &wantSenderInfo, const sptr &callerToken); int32_t SendWantSender(const sptr &target, const SenderInfo &senderInfo); - void CancelWantSender(const int32_t callingUid, const int32_t uid, const sptr &sender); + void CancelWantSender( + const int32_t callingUid, const int32_t uid, const bool isSystemApp, const sptr &sender); int32_t GetPendingWantUid(const sptr &target); int32_t GetPendingWantUserId(const sptr &target); @@ -148,9 +149,10 @@ public: int32_t GetPendingRequestWant(const sptr &target, std::shared_ptr &want); void CancelWantSenderLocked(PendingWantRecord &record, bool cleanAbility); - int32_t PendingWantStartAbility(const Want &want, const sptr &callerToken, int32_t requestCode); - int32_t PendingWantStartAbilitys( - const std::vector wnatsInfo, const sptr &callerToken, int32_t requestCode); + int32_t PendingWantStartAbility( + const Want &want, const sptr &callerToken, int32_t requestCode, int32_t callerUid); + int32_t PendingWantStartAbilitys(const std::vector wnatsInfo, const sptr &callerToken, + int32_t requestCode, int32_t callerUid); int32_t PendingWantPublishCommonEvent(const Want &want, const SenderInfo &senderInfo, int32_t callerUid); private: diff --git a/services/abilitymgr/include/power_storage.h b/services/abilitymgr/include/power_storage.h index 14c3602a64a..fd7c6ddd2c1 100644 --- a/services/abilitymgr/include/power_storage.h +++ b/services/abilitymgr/include/power_storage.h @@ -33,11 +33,14 @@ public: PowerStorage() = default; virtual ~PowerStorage() = default; - void SetPowerOffRecord(const std::shared_ptr &ability); - std::vector GetPowerOffRecord() const; + void SetPowerOffInActiveRecord(const std::shared_ptr &ability); + std::vector GetPowerOffInActiveRecord() const; + void SetPowerOffActiveRecord(const std::shared_ptr &ability); + std::vector GetPowerOffActiveRecord() const; private: - std::vector record_; + std::vector inActiveRecord_; + std::vector activeRecord_; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/resume_mission_container.h b/services/abilitymgr/include/resume_mission_container.h new file mode 100644 index 00000000000..682578c4940 --- /dev/null +++ b/services/abilitymgr/include/resume_mission_container.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_AAFWK_RESUME_MISSION_CONTAINER_H +#define OHOS_AAFWK_RESUME_MISSION_CONTAINER_H + +#include "mission_record.h" +#include "ability_event_handler.h" + +namespace OHOS { +namespace AAFwk { + +class ResumeMissionContainer { +public: + explicit ResumeMissionContainer(const std::shared_ptr &handler); + virtual ~ResumeMissionContainer() = default; + + void Save(const std::shared_ptr &mission); + void Resume(const std::shared_ptr &mission); + bool IsResume(int missionId); + void Remove(int missionId); + +private: + const std::string taskName_ = "ResumeMission#"; + static constexpr int64_t recordSaveTime_ = 24 * 60 * 60 * 1000; + std::map> missionMaps_; + std::shared_ptr handler_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_RESUME_MISSION_CONTAINER_H \ No newline at end of file diff --git a/services/abilitymgr/src/aafwk_dummy_configuration.cpp b/services/abilitymgr/src/aafwk_dummy_configuration.cpp new file mode 100644 index 00000000000..89b2e8879c7 --- /dev/null +++ b/services/abilitymgr/src/aafwk_dummy_configuration.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 "aafwk_dummy_configuration.h" + +#include "string_ex.h" + +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AAFwk { + +DummyConfiguration::DummyConfiguration(const std::string &name) : testInfostr_(name) +{} + +bool DummyConfiguration::ReadFromParcel(Parcel &parcel) +{ + testInfostr_ = Str16ToStr8(parcel.ReadString16()); + return true; +} + +DummyConfiguration *DummyConfiguration::Unmarshalling(Parcel &parcel) +{ + DummyConfiguration *dummyConfiguration = new (std::nothrow) DummyConfiguration(); + if (dummyConfiguration && !dummyConfiguration->ReadFromParcel(parcel)) { + delete dummyConfiguration; + dummyConfiguration = nullptr; + } + return dummyConfiguration; +} + +bool DummyConfiguration::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString16(Str8ToStr16(testInfostr_))) { + return false; + } + return true; +} + +unsigned int DummyConfiguration::Differ(const std::shared_ptr config) const +{ + // temp test code + if (config == nullptr || config->GetName() == "none") { + return 0x00000000; + } + + std::vector changes; + std::string name = config->GetName(); + std::string::size_type nbegin = 0; + std::string::size_type nend = 0; + while (true) { + nend = name.find_first_of("#", nbegin); + if (nend == std::string::npos) { + changes.push_back(name.substr(nbegin, name.length())); + break; + } + changes.push_back(name.substr(nbegin, nend - nbegin)); + nbegin = nend + 1; + } + + HILOG_ERROR("fail to get AbilityEventHandler"); + + unsigned int flag = 0x00000000; + for (auto item : changes) { + if (item == "locale") { + flag |= 0x00000001; + } else if (item == "layout") { + flag |= 0x00000002; + } else if (item == "fontSize") { + flag |= 0x00000004; + } else if (item == "orientation") { + flag |= 0x00000008; + } else if (item == "density") { + flag |= 0x00000010; + } else { + ; + } + } + return flag; +} + +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/ability_connect_callback_stub.cpp b/services/abilitymgr/src/ability_connect_callback_stub.cpp index 397e412bd59..546007f44a0 100644 --- a/services/abilitymgr/src/ability_connect_callback_stub.cpp +++ b/services/abilitymgr/src/ability_connect_callback_stub.cpp @@ -27,7 +27,7 @@ namespace AAFwk { bool AbilityConnectionProxy::WriteInterfaceToken(MessageParcel &data) { if (!data.WriteInterfaceToken(AbilityConnectionProxy::GetDescriptor())) { - HILOG_ERROR("write interface token failed"); + HILOG_ERROR("Write interface token failed."); return false; } return true; @@ -36,8 +36,6 @@ bool AbilityConnectionProxy::WriteInterfaceToken(MessageParcel &data) void AbilityConnectionProxy::OnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) { - HILOG_DEBUG("%s, abilityName:%s,resultCode:%d", __func__, element.GetAbilityName().c_str(), resultCode); - int error; MessageParcel data; MessageParcel reply; @@ -48,30 +46,29 @@ void AbilityConnectionProxy::OnAbilityConnectDone( } if (!data.WriteParcelable(&element)) { - HILOG_ERROR("connect done element error"); + HILOG_ERROR("Connect done element error."); return; } if (!data.WriteParcelable(remoteObject)) { - HILOG_ERROR("connect done remote object error"); + HILOG_ERROR("Connect done remote object error."); return; } if (!data.WriteInt32(resultCode)) { - HILOG_ERROR("connect done result code error"); + HILOG_ERROR("Connect done result code error."); return; } error = Remote()->SendRequest(IAbilityConnection::ON_ABILITY_CONNECT_DONE, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("connect done fail, error: %d", error); + HILOG_ERROR("Connect done fail, error: %{public}d", error); return; } } void AbilityConnectionProxy::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) { - HILOG_DEBUG("%s, element:%s, resultCode:%d", __func__, element.GetURI().c_str(), resultCode); int error; MessageParcel data; MessageParcel reply; @@ -81,13 +78,13 @@ void AbilityConnectionProxy::OnAbilityDisconnectDone(const AppExecFwk::ElementNa return; } if (!data.WriteParcelable(&element) || !data.WriteInt32(resultCode)) { - HILOG_ERROR("disconnect done data write error"); + HILOG_ERROR("Disconnect done data write error."); return; } error = Remote()->SendRequest(IAbilityConnection::ON_ABILITY_DISCONNECT_DONE, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("disconnect done fail, error: %d", error); + HILOG_ERROR("Disconnect done fail, error: %d", error); return; } } @@ -104,7 +101,7 @@ int AbilityConnectionStub::OnRemoteRequest( std::u16string descriptor = AbilityConnectionStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { - HILOG_INFO("local descriptor is not equal to remote"); + HILOG_INFO("Local descriptor is not equal to remote"); return ERR_INVALID_STATE; } @@ -142,7 +139,7 @@ int AbilityConnectionStub::OnRemoteRequest( void AbilityConnectCallbackRecipient::OnRemoteDied(const wptr &__attribute__((unused)) remote) { - HILOG_ERROR("recv AbilityConnectCallbackRecipient death notice"); + HILOG_ERROR("On remote died."); if (handler_) { handler_(remote); } diff --git a/services/abilitymgr/src/ability_connect_manager.cpp b/services/abilitymgr/src/ability_connect_manager.cpp index 94a31693b62..ff9c45246f4 100644 --- a/services/abilitymgr/src/ability_connect_manager.cpp +++ b/services/abilitymgr/src/ability_connect_manager.cpp @@ -34,38 +34,44 @@ AbilityConnectManager::~AbilityConnectManager() int AbilityConnectManager::StartAbility(const AbilityRequest &abilityRequest) { - HILOG_INFO("%{public}s,called", __func__); std::lock_guard guard(Lock_); return StartAbilityLocked(abilityRequest); } int AbilityConnectManager::TerminateAbility(const sptr &token) { - HILOG_INFO("%{public}s,called", __func__); std::lock_guard guard(Lock_); return TerminateAbilityLocked(token); } int AbilityConnectManager::TerminateAbility(const std::shared_ptr &caller, int requestCode) { - HILOG_INFO("%{public}s called, %{public}d", __func__, __LINE__); + HILOG_INFO("Terminate ability."); std::lock_guard guard(Lock_); std::shared_ptr targetAbility = nullptr; + int result = static_cast(ABILITY_VISIBLE_FALSE_DENY_REQUEST); std::for_each(serviceMap_.begin(), serviceMap_.end(), - [&targetAbility, &caller, requestCode](ServiceMapType::reference service) { + [&targetAbility, &caller, requestCode, &result](ServiceMapType::reference service) { auto callerList = service.second->GetCallerRecordList(); for (auto &it : callerList) { if (it->GetCaller() == caller && it->GetRequestCode() == requestCode) { targetAbility = service.second; + if (targetAbility) { + result = AbilityUtil::JudgeAbilityVisibleControl(targetAbility->GetAbilityInfo()); + } break; } } }); if (!targetAbility) { - return ERR_INVALID_VALUE; + return NO_FOUND_ABILITY_BY_CALLER; + } + if (result != ERR_OK) { + HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); + return result; } return TerminateAbilityLocked(targetAbility->GetToken()); @@ -73,21 +79,21 @@ int AbilityConnectManager::TerminateAbility(const std::shared_ptr int AbilityConnectManager::StopServiceAbility(const AbilityRequest &abilityRequest) { - HILOG_INFO("%{public}s,called", __func__); + HILOG_INFO("Stop Service ability."); std::lock_guard guard(Lock_); return StopServiceAbilityLocked(abilityRequest); } int AbilityConnectManager::TerminateAbilityResult(const sptr &token, int startId) { - HILOG_INFO("%{public}s called, startId:%{public}d", __func__, startId); + HILOG_INFO("Terminate ability result."); std::lock_guard guard(Lock_); return TerminateAbilityResultLocked(token, startId); } int AbilityConnectManager::StartAbilityLocked(const AbilityRequest &abilityRequest) { - HILOG_INFO("%{public}s, ability_name:%{public}s", __func__, abilityRequest.want.GetElement().GetURI().c_str()); + HILOG_INFO("Start ability locked, ability_name: %{public}s", abilityRequest.want.GetElement().GetURI().c_str()); std::shared_ptr targetService; bool isLoadedAbility = false; @@ -102,7 +108,7 @@ int AbilityConnectManager::StartAbilityLocked(const AbilityRequest &abilityReque // It may have been started through connect CommandAbility(targetService); } else { - HILOG_ERROR("%{public}s,target service is already activing", __func__); + HILOG_ERROR("Target service is already activing."); return START_SERVICE_ABILITY_ACTIVING; } @@ -117,24 +123,24 @@ int AbilityConnectManager::StartAbilityLocked(const AbilityRequest &abilityReque int AbilityConnectManager::TerminateAbilityLocked(const sptr &token) { - HILOG_INFO("%{public}s,called", __func__); + HILOG_INFO("Terminate ability locked."); auto abilityRecord = GetServiceRecordByToken(token); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); if (abilityRecord->IsTerminating()) { - HILOG_INFO("ability is on terminating"); + HILOG_INFO("Ability is on terminating."); return ERR_OK; } if (abilityRecord->GetConnectRecordList().empty()) { - HILOG_INFO("service ability has no any connection, and not started , need terminate."); + HILOG_INFO("Service ability has no any connection, and not started , need terminate."); auto timeoutTask = [abilityRecord, connectManager = shared_from_this()]() { - HILOG_WARN("disconnect ability terminate timeout."); + HILOG_WARN("Disconnect ability terminate timeout."); connectManager->HandleStopTimeoutTask(abilityRecord); }; abilityRecord->Terminate(timeoutTask); } else { - HILOG_WARN("%{public}s, target service has been connected. It cannot be stopped", __func__); + HILOG_WARN("Target service has been connected. It cannot be stopped."); return TERMINATE_SERVICE_IS_CONNECTED; } @@ -143,14 +149,14 @@ int AbilityConnectManager::TerminateAbilityLocked(const sptr &tok int AbilityConnectManager::TerminateAbilityResultLocked(const sptr &token, int startId) { - HILOG_INFO("%{public}s called, startId:%{public}d", __func__, startId); + HILOG_INFO("Terminate ability result locked, startId: %{public}d", startId); CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE); auto abilityRecord = Token::GetAbilityRecordByToken(token); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); if (abilityRecord->GetStartId() != startId) { - HILOG_ERROR("%{public}s, Start id not equal", __func__); + HILOG_ERROR("Start id not equal."); return TERMINATE_ABILITY_RESULT_FAILED; } @@ -159,26 +165,26 @@ int AbilityConnectManager::TerminateAbilityResultLocked(const sptrIsTerminating()) { - HILOG_INFO("ability is on terminating"); + HILOG_INFO("Ability is on terminating."); return ERR_OK; } if (abilityRecord->GetConnectRecordList().empty()) { - HILOG_INFO("service ability has no any connection, and no started , need terminate."); + HILOG_INFO("Service ability has no any connection, and no started , need terminate."); auto timeoutTask = [abilityRecord, connectManager = shared_from_this()]() { - HILOG_WARN("disconnect ability terminate timeout."); + HILOG_WARN("Disconnect ability terminate timeout."); connectManager->HandleStopTimeoutTask(abilityRecord); }; abilityRecord->Terminate(timeoutTask); } else { - HILOG_WARN("%{public}s, target service has been connected. It cannot be stopped", __func__); + HILOG_WARN("Target service has been connected. It cannot be stopped."); return TERMINATE_SERVICE_IS_CONNECTED; } @@ -235,7 +241,7 @@ int AbilityConnectManager::ConnectAbilityLocked(const AbilityRequest &abilityReq // 3. If this service ability and callback has been connected, There is no need to connect repeatedly if (isLoadedAbility && (isCallbackConnected) && IsAbilityConnected(targetService, connectRecordList)) { - HILOG_ERROR("%{public}s, service and callback was connected", __func__); + HILOG_ERROR("Service and callback was connected."); return ERR_OK; } @@ -266,7 +272,7 @@ int AbilityConnectManager::ConnectAbilityLocked(const AbilityRequest &abilityReq ConnectAbility(targetService); } } else { - HILOG_ERROR("%{public}s,target service is already activing", __func__); + HILOG_ERROR("Target service is already activing."); } auto token = targetService->GetToken(); @@ -277,26 +283,33 @@ int AbilityConnectManager::ConnectAbilityLocked(const AbilityRequest &abilityReq int AbilityConnectManager::DisconnectAbilityLocked(const sptr &connect) { - HILOG_INFO("disconnect ability with connect"); + HILOG_INFO("Disconnect ability locked."); std::lock_guard guard(Lock_); // 1. check whether callback was connected. ConnectListType connectRecordList; GetConnectRecordListFromMap(connect, connectRecordList); if (connectRecordList.empty()) { - HILOG_ERROR("can't find the connect list from connect map by callback."); + HILOG_ERROR("Can't find the connect list from connect map by callback."); return CONNECTION_NOT_EXIST; } // 2. schedule disconnect to target service for (auto &connectRecord : connectRecordList) { if (connectRecord) { + auto abilityRecord = connectRecord->GetAbilityRecord(); + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + int result = AbilityUtil::JudgeAbilityVisibleControl(abilityRecord->GetAbilityInfo()); + if (result != ERR_OK) { + HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); + return result; + } int ret = connectRecord->DisconnectAbility(); if (ret != ERR_OK) { - HILOG_ERROR("disconnect ability fail , ret = %{public}d.", ret); + HILOG_ERROR("Disconnect ability fail , ret = %{public}d.", ret); return ret; } - HILOG_INFO("disconnect ability ,connect record id %{public}d", connectRecord->GetRecordId()); + HILOG_INFO("Disconnect ability ,connect record id %{public}d", connectRecord->GetRecordId()); } } @@ -324,7 +337,7 @@ int AbilityConnectManager::AttachAbilityThreadLocked( eventHandler_->RemoveEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecord->GetEventId()); } std::string element = abilityRecord->GetWant().GetElement().GetURI(); - HILOG_INFO("%{public}s, ability: %{public}s", __func__, element.c_str()); + HILOG_INFO("Ability: %{public}s", element.c_str()); abilityRecord->SetScheduler(scheduler); DelayedSingleton::GetInstance()->MoveToForground(token); @@ -338,7 +351,7 @@ void AbilityConnectManager::OnAbilityRequestDone(const sptr &toke auto abilityRecord = GetServiceRecordByToken(token); CHECK_POINTER(abilityRecord); std::string element = abilityRecord->GetWant().GetElement().GetURI(); - HILOG_INFO("%{public}s, ability: %{public}s", __func__, element.c_str()); + HILOG_INFO("Ability: %{public}s", element.c_str()); if (abilitState == AppAbilityState::ABILITY_STATE_FOREGROUND) { abilityRecord->Inactivate(); @@ -348,6 +361,18 @@ void AbilityConnectManager::OnAbilityRequestDone(const sptr &toke } } +void AbilityConnectManager::OnAppStateChanged(const AppInfo &info) +{ + std::lock_guard guard(Lock_); + std::for_each(serviceMap_.begin(), serviceMap_.end(), [&info](ServiceMapType::reference service) { + if (service.second && service.second->GetApplicationInfo().name == info.appName && + (info.processName == service.second->GetAbilityInfo().process || + info.processName == service.second->GetApplicationInfo().bundleName)) { + service.second->SetAppState(info.state); + } + }); +} + int AbilityConnectManager::AbilityTransitionDone(const sptr &token, int state) { std::lock_guard guard(Lock_); @@ -357,7 +382,7 @@ int AbilityConnectManager::AbilityTransitionDone(const sptr &toke std::string element = abilityRecord->GetWant().GetElement().GetURI(); int targetState = AbilityRecord::ConvertLifeCycleToAbilityState(static_cast(state)); std::string abilityState = AbilityRecord::ConvertAbilityState(static_cast(targetState)); - HILOG_INFO("%{public}s, ability: %{public}s, state: %{public}s", __func__, element.c_str(), abilityState.c_str()); + HILOG_INFO("Ability: %{public}s, state: %{public}s", element.c_str(), abilityState.c_str()); switch (state) { case AbilityState::INACTIVE: { @@ -367,7 +392,7 @@ int AbilityConnectManager::AbilityTransitionDone(const sptr &toke return DispatchTerminate(abilityRecord); } default: { - HILOG_WARN("don't support transiting state: %{public}d", state); + HILOG_WARN("Don't support transiting state: %{public}d", state); return ERR_INVALID_VALUE; } } @@ -383,13 +408,11 @@ int AbilityConnectManager::ScheduleConnectAbilityDoneLocked( CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); std::string element = abilityRecord->GetWant().GetElement().GetURI(); - HILOG_DEBUG("%{public}s, ability: %{public}s", __func__, element.c_str()); + HILOG_DEBUG("Ability: %{public}s", element.c_str()); if ((!abilityRecord->IsAbilityState(AbilityState::INACTIVE)) && (!abilityRecord->IsAbilityState(AbilityState::ACTIVE))) { - HILOG_ERROR("%{public}s, ability record state is not inactive ,state:%{public}d", - __func__, - abilityRecord->GetAbilityState()); + HILOG_ERROR("Ability record state is not inactive ,state:%{public}d", abilityRecord->GetAbilityState()); return INVALID_CONNECTION_STATE; } @@ -413,9 +436,7 @@ int AbilityConnectManager::ScheduleDisconnectAbilityDoneLocked(const sptrIsAbilityState(AbilityState::ACTIVE)) { - HILOG_ERROR("%{public}s, the service ability state is not active ,state:%{public}d", - __func__, - abilityRecord->GetAbilityState()); + HILOG_ERROR("The service ability state is not active ,state:%{public}d", abilityRecord->GetAbilityState()); return INVALID_CONNECTION_STATE; } @@ -426,9 +447,9 @@ int AbilityConnectManager::ScheduleDisconnectAbilityDoneLocked(const sptrScheduleDisconnectAbilityDone(); abilityRecord->RemoveConnectRecordFromList(connect); if (abilityRecord->IsConnectListEmpty() && abilityRecord->GetStartId() == 0) { - HILOG_INFO("service ability has no any connection, and not started , need terminate."); + HILOG_INFO("Service ability has no any connection, and not started , need terminate."); auto timeoutTask = [abilityRecord, connectManager = shared_from_this()]() { - HILOG_WARN("disconnect ability terminate timeout."); + HILOG_WARN("Disconnect ability terminate timeout."); connectManager->HandleStopTimeoutTask(abilityRecord); }; abilityRecord->Terminate(timeoutTask); @@ -445,13 +466,11 @@ int AbilityConnectManager::ScheduleCommandAbilityDoneLocked(const sptrGetWant().GetElement().GetURI(); - HILOG_DEBUG("%{public}s, ability: %{public}s", __func__, element.c_str()); + HILOG_DEBUG("Ability: %{public}s", element.c_str()); if ((!abilityRecord->IsAbilityState(AbilityState::INACTIVE)) && (!abilityRecord->IsAbilityState(AbilityState::ACTIVE))) { - HILOG_ERROR("%{public}s, ability record state is not inactive ,state:%{public}d", - __func__, - abilityRecord->GetAbilityState()); + HILOG_ERROR("Ability record state is not inactive ,state:%{public}d", abilityRecord->GetAbilityState()); return INVALID_CONNECTION_STATE; } // complete command and pop waiting start ability from queue. @@ -544,7 +563,7 @@ void AbilityConnectManager::PostTimeOutTask(const std::shared_ptr CHECK_POINTER(eventHandler_); if (messageId != AbilityConnectManager::LOAD_TIMEOUT_MSG && messageId != AbilityConnectManager::CONNECT_TIMEOUT_MSG) { - HILOG_ERROR("timeout task messageId is error."); + HILOG_ERROR("Timeout task messageId is error."); return; } @@ -568,7 +587,7 @@ void AbilityConnectManager::PostTimeOutTask(const std::shared_ptr } auto timeoutTask = [abilityRecord, connectManager = shared_from_this(), resultCode]() { - HILOG_WARN("connect or load ability timeout."); + HILOG_WARN("Connect or load ability timeout."); connectManager->HandleStartTimeoutTask(abilityRecord, resultCode); }; @@ -577,13 +596,13 @@ void AbilityConnectManager::PostTimeOutTask(const std::shared_ptr void AbilityConnectManager::HandleStartTimeoutTask(const std::shared_ptr &abilityRecord, int resultCode) { - HILOG_DEBUG("complete connect or load ability timeout."); + HILOG_DEBUG("Complete connect or load ability timeout."); std::lock_guard guard(Lock_); CHECK_POINTER(abilityRecord); auto connectingList = abilityRecord->GetConnectingRecordList(); for (auto &connectRecord : connectingList) { if (connectRecord == nullptr) { - HILOG_WARN("connectRecord is nullptr."); + HILOG_WARN("ConnectRecord is nullptr."); continue; } connectRecord->CompleteConnect(resultCode); @@ -591,23 +610,22 @@ void AbilityConnectManager::HandleStartTimeoutTask(const std::shared_ptr &abilityRecord) { - HILOG_DEBUG("complete stop ability timeout start."); + HILOG_DEBUG("Complete stop ability timeout start."); std::lock_guard guard(Lock_); CHECK_POINTER(abilityRecord); TerminateDone(abilityRecord); - HILOG_DEBUG("complete stop ability timeout end."); } void AbilityConnectManager::HandleDisconnectTask(const ConnectListType &connectlist) { - HILOG_DEBUG("complete disconnect ability."); + HILOG_DEBUG("Complete disconnect ability."); std::lock_guard guard(Lock_); for (auto &connectRecord : connectlist) { if (!connectRecord) { @@ -616,7 +634,7 @@ void AbilityConnectManager::HandleDisconnectTask(const ConnectListType &connectl auto targetService = connectRecord->GetAbilityRecord(); if (targetService && connectRecord->GetConnectState() == ConnectionState::DISCONNECTED && targetService->GetConnectRecordList().size() > 1) { - HILOG_WARN("this record complete disconnect directly. recordId:%{public}d", connectRecord->GetRecordId()); + HILOG_WARN("This record complete disconnect directly. recordId:%{public}d", connectRecord->GetRecordId()); connectRecord->CompleteDisconnect(ERR_OK); targetService->RemoveConnectRecordFromList(connectRecord); RemoveConnectionRecordFromMap(connectRecord); @@ -628,7 +646,7 @@ int AbilityConnectManager::DispatchInactive(const std::shared_ptr { CHECK_POINTER_AND_RETURN(eventHandler_, ERR_INVALID_VALUE); if (!abilityRecord->IsAbilityState(AbilityState::INACTIVATING)) { - HILOG_ERROR("ability transition life state error. expect %{public}d, actual %{public}d callback %{public}d", + HILOG_ERROR("Ability transition life state error. expect %{public}d, actual %{public}d callback %{public}d", AbilityState::INACTIVATING, abilityRecord->GetAbilityState(), state); @@ -674,7 +692,7 @@ void AbilityConnectManager::CommandAbility(const std::shared_ptr std::string taskName = std::string("CommandTimeout_") + std::to_string(recordId) + std::string("_") + std::to_string(abilityRecord->GetStartId()); auto timeoutTask = [abilityRecord, connectManager = shared_from_this()]() { - HILOG_ERROR("command ability timeout. %{public}s", abilityRecord->GetAbilityInfo().name.c_str()); + HILOG_ERROR("Command ability timeout. %{public}s", abilityRecord->GetAbilityInfo().name.c_str()); }; eventHandler_->PostTask(timeoutTask, taskName, AbilityManagerService::COMMAND_TIMEOUT); // scheduling command ability @@ -688,7 +706,7 @@ void AbilityConnectManager::TerminateDone(const std::shared_ptr & std::string expect = AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING); std::string actual = AbilityRecord::ConvertAbilityState(abilityRecord->GetAbilityState()); HILOG_ERROR( - "transition life state error. expect %{public}s, actual %{public}s", expect.c_str(), actual.c_str()); + "Transition life state error. expect %{public}s, actual %{public}s", expect.c_str(), actual.c_str()); return; } DelayedSingleton::GetInstance()->MoveToBackground(abilityRecord->GetToken()); @@ -715,11 +733,10 @@ void AbilityConnectManager::RemoveConnectionRecordFromMap(const std::shared_ptr< auto &connectList = connectCallback.second; auto connectRecord = std::find(connectList.begin(), connectList.end(), connection); if (connectRecord != connectList.end()) { - HILOG_INFO( - "%{public}s: remove connrecord(%{public}d) from maplist", __func__, (*connectRecord)->GetRecordId()); + HILOG_INFO("Remove connrecord(%{public}d) from maplist.", (*connectRecord)->GetRecordId()); connectList.remove(connection); if (connectList.empty()) { - HILOG_INFO("%{public}s: remove connlist from map ", __func__); + HILOG_INFO("Remove connlist from map."); sptr connect = iface_cast(connectCallback.first); RemoveConnectDeathRecipient(connect); connectMap_.erase(connectCallback.first); @@ -734,10 +751,10 @@ void AbilityConnectManager::RemoveServiceAbility(const std::shared_ptrGetAbilityInfo(); std::string element = abilityInfo.deviceId + "/" + abilityInfo.bundleName + "/" + abilityInfo.name; - HILOG_INFO("%{public}s: remove service(%{public}s) from map ", __func__, element.c_str()); + HILOG_INFO("Remove service(%{public}s) from map.", element.c_str()); auto it = serviceMap_.find(element); if (it != serviceMap_.end()) { - HILOG_INFO("%{public}s: remove service(%{public}s) from map ", __func__, element.c_str()); + HILOG_INFO("Remove service(%{public}s) from map.", element.c_str()); serviceMap_.erase(it); } } @@ -748,7 +765,7 @@ void AbilityConnectManager::AddConnectDeathRecipient(const sptrAsObject()); auto it = recipientMap_.find(connect->AsObject()); if (it != recipientMap_.end()) { - HILOG_ERROR("%{public}s this death recipient has been added.", __func__); + HILOG_ERROR("This death recipient has been added."); return; } else { sptr deathRecipient = new AbilityConnectCallbackRecipient( @@ -782,7 +799,7 @@ void AbilityConnectManager::OnCallBackDied(const wptr &remote) void AbilityConnectManager::HandleCallBackDiedTask(const sptr &connect) { - HILOG_INFO("%{public}s,called", __func__); + HILOG_INFO("Handle call back died task."); std::lock_guard guard(Lock_); CHECK_POINTER(connect); auto it = connectMap_.find(connect); @@ -792,7 +809,7 @@ void AbilityConnectManager::HandleCallBackDiedTask(const sptr &co connRecord->ClearConnCallBack(); } } else { - HILOG_INFO("%{public}s died object can't find from conn map.", __func__); + HILOG_INFO("Died object can't find from conn map."); return; } sptr object = iface_cast(connect); @@ -801,10 +818,10 @@ void AbilityConnectManager::HandleCallBackDiedTask(const sptr &co void AbilityConnectManager::OnAbilityDied(const std::shared_ptr &abilityRecord) { - HILOG_INFO("%{public}s,called", __func__); + HILOG_INFO("On ability died."); CHECK_POINTER(abilityRecord); if (abilityRecord->GetAbilityInfo().type != AbilityType::SERVICE) { - HILOG_DEBUG("ability type is not service"); + HILOG_DEBUG("Ability type is not service."); return; } if (eventHandler_) { @@ -817,16 +834,16 @@ void AbilityConnectManager::OnAbilityDied(const std::shared_ptr & void AbilityConnectManager::HandleAbilityDiedTask(const std::shared_ptr &abilityRecord) { - HILOG_INFO("%{public}s,called", __func__); + HILOG_INFO("Handle ability died task."); std::lock_guard guard(Lock_); CHECK_POINTER(abilityRecord); if (!GetServiceRecordByToken(abilityRecord->GetToken())) { - HILOG_ERROR("%{public}s died ability record is not exist in service map", __func__); + HILOG_ERROR("Died ability record is not exist in service map."); return; } ConnectListType connlist = abilityRecord->GetConnectRecordList(); for (auto &connectRecord : connlist) { - HILOG_WARN("this record complete disconnect directly. recordId:%{public}d", connectRecord->GetRecordId()); + HILOG_WARN("This record complete disconnect directly. recordId:%{public}d", connectRecord->GetRecordId()); connectRecord->CompleteDisconnect(ERR_OK); abilityRecord->RemoveConnectRecordFromList(connectRecord); RemoveConnectionRecordFromMap(connectRecord); diff --git a/services/abilitymgr/src/ability_event_handler.cpp b/services/abilitymgr/src/ability_event_handler.cpp index 4e59060595c..aa259478921 100644 --- a/services/abilitymgr/src/ability_event_handler.cpp +++ b/services/abilitymgr/src/ability_event_handler.cpp @@ -25,13 +25,13 @@ AbilityEventHandler::AbilityEventHandler( const std::shared_ptr &runner, const std::weak_ptr &server) : AppExecFwk::EventHandler(runner), server_(server) { - HILOG_INFO("AbilityEventHandler::AbilityEventHandler::instance created."); + HILOG_INFO("Constructors."); } void AbilityEventHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) { CHECK_POINTER(event); - HILOG_DEBUG("AMSEventHandler::ProcessEvent::inner event id obtained: %u.", event->GetInnerEventId()); + HILOG_DEBUG("Event id obtained: %{public}u.", event->GetInnerEventId()); switch (event->GetInnerEventId()) { case AbilityManagerService::LOAD_TIMEOUT_MSG: { ProcessLoadTimeOut(event->GetParam()); @@ -42,13 +42,13 @@ void AbilityEventHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &ev break; } case AbilityManagerService::INACTIVE_TIMEOUT_MSG: { - HILOG_INFO("inactive timeout."); + HILOG_INFO("Inactive timeout."); // inactivate pre ability immediately in case blocking next ability start ProcessInactiveTimeOut(event->GetParam()); break; } default: { - HILOG_WARN("unsupported timeout message."); + HILOG_WARN("Unsupported timeout message."); break; } } @@ -56,7 +56,7 @@ void AbilityEventHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &ev void AbilityEventHandler::ProcessLoadTimeOut(int64_t eventId) { - HILOG_INFO("attach timeout."); + HILOG_INFO("Attach timeout."); auto server = server_.lock(); CHECK_POINTER(server); server->HandleLoadTimeOut(eventId); @@ -64,14 +64,14 @@ void AbilityEventHandler::ProcessLoadTimeOut(int64_t eventId) void AbilityEventHandler::ProcessActiveTimeOut(int64_t eventId) { - HILOG_INFO("active timeout."); + HILOG_INFO("Active timeout."); auto server = server_.lock(); CHECK_POINTER(server); server->HandleActiveTimeOut(eventId); } void AbilityEventHandler::ProcessInactiveTimeOut(int64_t eventId) { - HILOG_INFO("inactive timeout."); + HILOG_INFO("Inactive timeout."); auto server = server_.lock(); CHECK_POINTER(server); server->HandleInactiveTimeOut(eventId); diff --git a/services/abilitymgr/src/ability_manager_client.cpp b/services/abilitymgr/src/ability_manager_client.cpp index 54ea6298390..3dbe6bb254a 100644 --- a/services/abilitymgr/src/ability_manager_client.cpp +++ b/services/abilitymgr/src/ability_manager_client.cpp @@ -29,6 +29,22 @@ namespace AAFwk { std::shared_ptr AbilityManagerClient::instance_ = nullptr; std::mutex AbilityManagerClient::mutex_; +#define CHECK_REMOTE_OBJECT(object) \ + if (!object) { \ + if (ERR_OK != Connect()) { \ + HILOG_ERROR("ability service can't connect."); \ + return; \ + } \ + } + +#define CHECK_REMOTE_OBJECT_AND_RETURN(object, value) \ + if (!object) { \ + if (ERR_OK != Connect()) { \ + HILOG_ERROR("ability service can't connect."); \ + return value; \ + } \ + } + std::shared_ptr AbilityManagerClient::GetInstance() { if (instance_ == nullptr) { @@ -49,22 +65,14 @@ AbilityManagerClient::~AbilityManagerClient() ErrCode AbilityManagerClient::AttachAbilityThread( const sptr &scheduler, const sptr &token) { - if (remoteObject_ == nullptr) { - ErrCode err = Connect(); - if (err != ERR_OK) { - return ABILITY_SERVICE_NOT_CONNECTED; - } - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->AttachAbilityThread(scheduler, token); } ErrCode AbilityManagerClient::AbilityTransitionDone(const sptr &token, int state) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->AbilityTransitionDone(token, state); } @@ -72,90 +80,71 @@ ErrCode AbilityManagerClient::AbilityTransitionDone(const sptr &t ErrCode AbilityManagerClient::ScheduleConnectAbilityDone( const sptr &token, const sptr &remoteObject) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->ScheduleConnectAbilityDone(token, remoteObject); } ErrCode AbilityManagerClient::ScheduleDisconnectAbilityDone(const sptr &token) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->ScheduleDisconnectAbilityDone(token); } ErrCode AbilityManagerClient::ScheduleCommandAbilityDone(const sptr &token) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not command", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->ScheduleCommandAbilityDone(token); } void AbilityManagerClient::AddWindowInfo(const sptr &token, int32_t windowToken) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return; - } + CHECK_REMOTE_OBJECT(remoteObject_); sptr abms = iface_cast(remoteObject_); abms->AddWindowInfo(token, windowToken); } ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->StartAbility(want, requestCode); } ErrCode AbilityManagerClient::StartAbility(const Want &want, const sptr &callerToken, int requestCode) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->StartAbility(want, callerToken, requestCode); } +ErrCode AbilityManagerClient::StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->StartAbility(want, abilityStartSetting, callerToken, requestCode); +} + ErrCode AbilityManagerClient::TerminateAbility(const sptr &token, int resultCode, const Want *resultWant) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->TerminateAbility(token, resultCode, resultWant); } ErrCode AbilityManagerClient::TerminateAbility(const sptr &callerToken, int requestCode) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); - return abms->TerminateAbility(callerToken, requestCode); + return abms->TerminateAbilityByCaller(callerToken, requestCode); } ErrCode AbilityManagerClient::TerminateAbilityResult(const sptr &token, int startId) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->TerminateAbilityResult(token, startId); } @@ -163,20 +152,14 @@ ErrCode AbilityManagerClient::TerminateAbilityResult(const sptr & ErrCode AbilityManagerClient::ConnectAbility( const Want &want, const sptr &connect, const sptr &callerToken) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->ConnectAbility(want, connect, callerToken); } ErrCode AbilityManagerClient::DisconnectAbility(const sptr &connect) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->DisconnectAbility(connect); } @@ -184,10 +167,7 @@ ErrCode AbilityManagerClient::DisconnectAbility(const sptr & sptr AbilityManagerClient::AcquireDataAbility( const Uri &uri, bool tryBind, const sptr &callerToken) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return nullptr; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, nullptr); sptr abms = iface_cast(remoteObject_); return abms->AcquireDataAbility(uri, tryBind, callerToken); } @@ -195,20 +175,14 @@ sptr AbilityManagerClient::AcquireDataAbility( ErrCode AbilityManagerClient::ReleaseDataAbility( sptr dataAbilityScheduler, const sptr &callerToken) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->ReleaseDataAbility(dataAbilityScheduler, callerToken); } ErrCode AbilityManagerClient::DumpState(const std::string &args, std::vector &state) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); abms->DumpState(args, state); return ERR_OK; @@ -222,35 +196,28 @@ ErrCode AbilityManagerClient::Connect() } sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (systemManager == nullptr) { - HILOG_ERROR("%{private}s:fail to get Registry", __func__); + HILOG_ERROR("Fail to get registry."); return GET_ABILITY_SERVICE_FAILED; } remoteObject_ = systemManager->GetSystemAbility(ABILITY_MGR_SERVICE_ID); if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:fail to connect AbilityManagerService", __func__); + HILOG_ERROR("Fail to connect ability manager service."); return GET_ABILITY_SERVICE_FAILED; } - HILOG_DEBUG("connect AbilityManagerService success"); + HILOG_DEBUG("Connect ability manager service success."); return ERR_OK; } ErrCode AbilityManagerClient::GetAllStackInfo(StackInfo &stackInfo) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } - + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->GetAllStackInfo(stackInfo); } ErrCode AbilityManagerClient::StopServiceAbility(const Want &want) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->StopServiceAbility(want); } @@ -258,57 +225,41 @@ ErrCode AbilityManagerClient::StopServiceAbility(const Want &want) ErrCode AbilityManagerClient::GetRecentMissions( const int32_t numMax, const int32_t flags, std::vector &recentList) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->GetRecentMissions(numMax, flags, recentList); } ErrCode AbilityManagerClient::GetMissionSnapshot(const int32_t missionId, MissionSnapshotInfo &snapshot) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->GetMissionSnapshot(missionId, snapshot); } ErrCode AbilityManagerClient::MoveMissionToTop(int32_t missionId) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->MoveMissionToTop(missionId); } ErrCode AbilityManagerClient::MoveMissionToEnd(const sptr &token, const bool nonFirst) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->MoveMissionToEnd(token, nonFirst); } ErrCode AbilityManagerClient::RemoveMissions(std::vector missionId) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } - + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); int error = ERR_OK; for (auto it : missionId) { error = abms->RemoveMission(it); if (error != ERR_OK) { - HILOG_ERROR("%{private}s failed, error:%{private}d", __func__, error); + HILOG_ERROR("Failed, error:%{private}d", error); break; } } @@ -318,20 +269,14 @@ ErrCode AbilityManagerClient::RemoveMissions(std::vector missionId) ErrCode AbilityManagerClient::RemoveStack(int id) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->RemoveStack(id); } ErrCode AbilityManagerClient::KillProcess(const std::string &bundleName) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->KillProcess(bundleName); } @@ -339,13 +284,10 @@ ErrCode AbilityManagerClient::KillProcess(const std::string &bundleName) ErrCode AbilityManagerClient::IsFirstInMission(const sptr &token) { if (token == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); + HILOG_ERROR("token is nullptr"); return ERR_NULL_OBJECT; } - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); if (!(abms->IsFirstInMission(token))) { return NO_FIRST_IN_MISSION; @@ -356,50 +298,92 @@ ErrCode AbilityManagerClient::IsFirstInMission(const sptr &token) ErrCode AbilityManagerClient::CompelVerifyPermission( const std::string &permission, int pid, int uid, std::string &message) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->CompelVerifyPermission(permission, pid, uid, message); } +ErrCode AbilityManagerClient::MoveMissionToFloatingStack(const MissionOption &missionOption) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->MoveMissionToFloatingStack(missionOption); +} + +ErrCode AbilityManagerClient::MoveMissionToSplitScreenStack(const MissionOption &missionOption) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->MoveMissionToSplitScreenStack(missionOption); +} + +ErrCode AbilityManagerClient::MinimizeMultiWindow(int missionId) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->MinimizeMultiWindow(missionId); +} + +ErrCode AbilityManagerClient::MaximizeMultiWindow(int missionId) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->MaximizeMultiWindow(missionId); +} + +ErrCode AbilityManagerClient::ChangeFocusAbility( + const sptr &lostFocusToken, const sptr &getFocusToken) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->ChangeFocusAbility(lostFocusToken, getFocusToken); +} + +ErrCode AbilityManagerClient::GetFloatingMissions(std::vector &list) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->GetFloatingMissions(list); +} + +ErrCode AbilityManagerClient::CloseMultiWindow(int missionId) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->CloseMultiWindow(missionId); +} + +ErrCode AbilityManagerClient::SetMissionStackSetting(const StackSetting &stackSetting) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->SetMissionStackSetting(stackSetting); +} + ErrCode AbilityManagerClient::PowerOff() { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->PowerOff(); } ErrCode AbilityManagerClient::PowerOn() { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->PowerOn(); } ErrCode AbilityManagerClient::LockMission(int missionId) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->LockMission(missionId); } ErrCode AbilityManagerClient::UnlockMission(int missionId) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->UnlockMission(missionId); } @@ -407,71 +391,52 @@ ErrCode AbilityManagerClient::UnlockMission(int missionId) ErrCode AbilityManagerClient::SetMissionDescriptionInfo( const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->SetMissionDescriptionInfo(token, missionDescriptionInfo); } -int AbilityManagerClient::GetMissionLockModeState() +ErrCode AbilityManagerClient::GetMissionLockModeState() { - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->GetMissionLockModeState(); } +ErrCode AbilityManagerClient::UpdateConfiguration(const DummyConfiguration &config) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->UpdateConfiguration(config); +} + sptr AbilityManagerClient::GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return nullptr; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, nullptr); sptr abms = iface_cast(remoteObject_); return abms->GetWantSender(wantSenderInfo, callerToken); } ErrCode AbilityManagerClient::SendWantSender(const sptr &target, const SenderInfo &senderInfo) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); sptr abms = iface_cast(remoteObject_); return abms->SendWantSender(target, senderInfo); } void AbilityManagerClient::CancelWantSender(const sptr &sender) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return; - } + CHECK_REMOTE_OBJECT(remoteObject_); sptr abms = iface_cast(remoteObject_); abms->CancelWantSender(sender); } ErrCode AbilityManagerClient::GetPendingWantUid(const sptr &target, int32_t &uid) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); if (target == nullptr) { - HILOG_ERROR("%{private}s:target is nullptr", __func__); + HILOG_ERROR("target is nullptr."); return ABILITY_SERVICE_NOT_CONNECTED; } sptr abms = iface_cast(remoteObject_); @@ -481,14 +446,9 @@ ErrCode AbilityManagerClient::GetPendingWantUid(const sptr &target, ErrCode AbilityManagerClient::GetPendingWantUserId(const sptr &target, int32_t &userId) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); if (target == nullptr) { - HILOG_ERROR("%{private}s:target is nullptr", __func__); + HILOG_ERROR("target is nullptr."); return ABILITY_SERVICE_NOT_CONNECTED; } sptr abms = iface_cast(remoteObject_); @@ -498,14 +458,9 @@ ErrCode AbilityManagerClient::GetPendingWantUserId(const sptr &targ ErrCode AbilityManagerClient::GetPendingWantBundleName(const sptr &target, std::string &bundleName) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); if (target == nullptr) { - HILOG_ERROR("%{private}s:target is nullptr", __func__); + HILOG_ERROR("target is nullptr."); return ABILITY_SERVICE_NOT_CONNECTED; } sptr abms = iface_cast(remoteObject_); @@ -515,14 +470,9 @@ ErrCode AbilityManagerClient::GetPendingWantBundleName(const sptr & ErrCode AbilityManagerClient::GetPendingWantCode(const sptr &target, int32_t &code) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); if (target == nullptr) { - HILOG_ERROR("%{private}s:target is nullptr", __func__); + HILOG_ERROR("target is nullptr."); return ABILITY_SERVICE_NOT_CONNECTED; } sptr abms = iface_cast(remoteObject_); @@ -532,35 +482,26 @@ ErrCode AbilityManagerClient::GetPendingWantCode(const sptr &target ErrCode AbilityManagerClient::GetPendingWantType(const sptr &target, int32_t &type) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); if (target == nullptr) { - HILOG_ERROR("%{private}s:target is nullptr", __func__); + HILOG_ERROR("target is nullptr."); return ABILITY_SERVICE_NOT_CONNECTED; } sptr abms = iface_cast(remoteObject_); type = abms->GetPendingWantType(target); + type < 0 ? type = 0 : type; return ERR_OK; } void AbilityManagerClient::RegisterCancelListener(const sptr &sender, const sptr &recevier) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return; - } + CHECK_REMOTE_OBJECT(remoteObject_); if (sender == nullptr) { - HILOG_ERROR("%{private}s:sender is nullptr", __func__); + HILOG_ERROR("sender is nullptr."); return; } if (recevier == nullptr) { - HILOG_ERROR("%{private}s:recevier is nullptr", __func__); + HILOG_ERROR("recevier is nullptr."); return; } sptr abms = iface_cast(remoteObject_); @@ -570,18 +511,13 @@ void AbilityManagerClient::RegisterCancelListener(const sptr &sende void AbilityManagerClient::UnregisterCancelListener( const sptr &sender, const sptr &recevier) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return; - } + CHECK_REMOTE_OBJECT(remoteObject_); if (sender == nullptr) { - HILOG_ERROR("%{private}s:sender is nullptr", __func__); + HILOG_ERROR("sender is nullptr."); return; } if (recevier == nullptr) { - HILOG_ERROR("%{private}s:recevier is nullptr", __func__); + HILOG_ERROR("recevier is nullptr."); return; } sptr abms = iface_cast(remoteObject_); @@ -590,18 +526,13 @@ void AbilityManagerClient::UnregisterCancelListener( ErrCode AbilityManagerClient::GetPendingRequestWant(const sptr &target, std::shared_ptr &want) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (remoteObject_ == nullptr) { - HILOG_ERROR("%{private}s:ability service not connect", __func__); - return ABILITY_SERVICE_NOT_CONNECTED; - } + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); if (target == nullptr) { - HILOG_ERROR("%{private}s:target is nullptr", __func__); + HILOG_ERROR("target is nullptr."); return ABILITY_SERVICE_NOT_CONNECTED; } if (want == nullptr) { - HILOG_ERROR("%{private}s:want is nullptr", __func__); + HILOG_ERROR("want is nullptr."); return ABILITY_SERVICE_NOT_CONNECTED; } sptr abms = iface_cast(remoteObject_); diff --git a/services/abilitymgr/src/ability_manager_proxy.cpp b/services/abilitymgr/src/ability_manager_proxy.cpp index dca43305a1c..c41736d1cdc 100644 --- a/services/abilitymgr/src/ability_manager_proxy.cpp +++ b/services/abilitymgr/src/ability_manager_proxy.cpp @@ -30,7 +30,7 @@ namespace AAFwk { bool AbilityManagerProxy::WriteInterfaceToken(MessageParcel &data) { if (!data.WriteInterfaceToken(AbilityManagerProxy::GetDescriptor())) { - HILOG_ERROR("write interface token failed"); + HILOG_ERROR("write interface token failed."); return false; } return true; @@ -47,17 +47,51 @@ int AbilityManagerProxy::StartAbility(const Want &want, int requestCode) return INNER_ERR; } if (!data.WriteParcelable(&want)) { - HILOG_ERROR("%{public}s fail, want write parcelable error", __func__); + HILOG_ERROR("want write failed."); return INNER_ERR; } if (!data.WriteInt32(requestCode)) { - HILOG_ERROR("%{public}s fail, requestCode write int32 error", __func__); + HILOG_ERROR("requestCode write failed."); return INNER_ERR; } error = Remote()->SendRequest(IAbilityManager::START_ABILITY, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("start ability fail, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteParcelable(&want)) { + HILOG_ERROR("want write failed."); + return INNER_ERR; + } + if (!data.WriteParcelable(&abilityStartSetting)) { + HILOG_ERROR("abilityStartSetting write failed."); + return INNER_ERR; + } + if (!data.WriteParcelable(callerToken)) { + HILOG_ERROR("callerToken write failed."); + return INNER_ERR; + } + if (!data.WriteInt32(requestCode)) { + HILOG_ERROR("requestCode write failed."); + return INNER_ERR; + } + error = Remote()->SendRequest(IAbilityManager::START_ABILITY_FOR_SETTINGS, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -74,21 +108,21 @@ int AbilityManagerProxy::StartAbility(const Want &want, const sptrSendRequest(IAbilityManager::START_ABILITY_ADD_CALLER, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("start ability fail, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -105,12 +139,12 @@ int AbilityManagerProxy::TerminateAbility(const sptr &token, int return INNER_ERR; } if (!data.WriteParcelable(token) || !data.WriteInt32(resultCode) || !data.WriteParcelable(resultWant)) { - HILOG_ERROR("terminate ability. fail to write to parcel."); + HILOG_ERROR("data write failed."); return INNER_ERR; } error = Remote()->SendRequest(IAbilityManager::TERMINATE_ABILITY, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("terminate ability fail, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -127,12 +161,12 @@ int AbilityManagerProxy::TerminateAbilityByCaller(const sptr &cal return INNER_ERR; } if (!data.WriteParcelable(callerToken) || !data.WriteInt32(requestCode)) { - HILOG_ERROR("%{public}s. fail to write to parcel.", __func__); + HILOG_ERROR("data write failed."); return INNER_ERR; } error = Remote()->SendRequest(IAbilityManager::TERMINATE_ABILITY_BY_CALLER, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("terminate ability fail, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -150,7 +184,7 @@ int AbilityManagerProxy::ConnectAbility( return INNER_ERR; } if (!data.WriteParcelable(&want)) { - HILOG_ERROR("connect ability fail, want error"); + HILOG_ERROR("want write failed."); return ERR_INVALID_VALUE; } if (connect == nullptr) { @@ -158,17 +192,17 @@ int AbilityManagerProxy::ConnectAbility( return ERR_INVALID_VALUE; } if (!data.WriteParcelable(connect->AsObject())) { - HILOG_ERROR("connect ability fail, connect error"); + HILOG_ERROR("connect write failed."); return ERR_INVALID_VALUE; } if (!data.WriteParcelable(callerToken)) { - HILOG_ERROR("connect ability fail, callerToken error"); + HILOG_ERROR("callerToken write failed."); return ERR_INVALID_VALUE; } error = Remote()->SendRequest(IAbilityManager::CONNECT_ABILITY, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("connect ability fail, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -188,13 +222,13 @@ int AbilityManagerProxy::DisconnectAbility(const sptr &conne return INNER_ERR; } if (!data.WriteParcelable(connect->AsObject())) { - HILOG_ERROR("disconnect ability fail, connect error"); + HILOG_ERROR("connect write failed."); return ERR_INVALID_VALUE; } error = Remote()->SendRequest(IAbilityManager::DISCONNECT_ABILITY, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("disconnect ability fail, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -216,12 +250,12 @@ sptr AbilityManagerProxy::AcquireDataAbility( return nullptr; } if (!data.WriteString(uri.ToString()) || !data.WriteBool(tryBind) || !data.WriteParcelable(callerToken)) { - HILOG_ERROR("failed to mashalling the acquires data ability."); + HILOG_ERROR("data write failed."); return nullptr; } error = Remote()->SendRequest(IAbilityManager::ACQUIRE_DATA_ABILITY, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("failed to send acquire data ability request, error: %{public}d", error); + HILOG_ERROR("Send request error: %{public}d", error); return nullptr; } @@ -243,12 +277,12 @@ int AbilityManagerProxy::ReleaseDataAbility( return INNER_ERR; } if (!data.WriteParcelable(dataAbilityScheduler->AsObject()) || !data.WriteParcelable(callerToken)) { - HILOG_ERROR("failed to mashalling the release data ability."); + HILOG_ERROR("data write failed."); return INNER_ERR; } error = Remote()->SendRequest(IAbilityManager::RELEASE_DATA_ABILITY, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("failed to send release data ability request, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -267,12 +301,12 @@ int AbilityManagerProxy::AttachAbilityThread(const sptr &sche return INNER_ERR; } if (!data.WriteParcelable(scheduler->AsObject()) || !data.WriteParcelable(token)) { - HILOG_ERROR("attach ability. fail to write to parcel."); + HILOG_ERROR("data write failed."); return INNER_ERR; } error = Remote()->SendRequest(IAbilityManager::ATTACH_ABILITY_THREAD, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("attach ability fail, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -289,12 +323,12 @@ int AbilityManagerProxy::AbilityTransitionDone(const sptr &token, return INNER_ERR; } if (!data.WriteParcelable(token) || !data.WriteInt32(state)) { - HILOG_ERROR("ability transaction done. fail to write to parcel."); + HILOG_ERROR("data write failed."); return INNER_ERR; } error = Remote()->SendRequest(IAbilityManager::ABILITY_TRANSITION_DONE, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("ability transaction done fail, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -312,17 +346,17 @@ int AbilityManagerProxy::ScheduleConnectAbilityDone( return INNER_ERR; } if (!data.WriteParcelable(token)) { - HILOG_ERROR("schedule connect done fail, token error"); + HILOG_ERROR("token write failed."); return ERR_INVALID_VALUE; } if (!data.WriteParcelable(remoteObject)) { - HILOG_ERROR("schedule connect done fail, remoteObject error"); + HILOG_ERROR("remoteObject write failed."); return ERR_INVALID_VALUE; } error = Remote()->SendRequest(IAbilityManager::CONNECT_ABILITY_DONE, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("schedule connect done fail, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -339,13 +373,13 @@ int AbilityManagerProxy::ScheduleDisconnectAbilityDone(const sptr return INNER_ERR; } if (!data.WriteParcelable(token)) { - HILOG_ERROR("schedule disconnect done fail, token error"); + HILOG_ERROR("token write failed."); return ERR_INVALID_VALUE; } error = Remote()->SendRequest(IAbilityManager::DISCONNECT_ABILITY_DONE, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("schedule disconnect done fail, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -362,13 +396,13 @@ int AbilityManagerProxy::ScheduleCommandAbilityDone(const sptr &t return INNER_ERR; } if (!data.WriteParcelable(token)) { - HILOG_ERROR("schedule command done fail, token error"); + HILOG_ERROR("token write failed."); return ERR_INVALID_VALUE; } error = Remote()->SendRequest(IAbilityManager::COMMAND_ABILITY_DONE, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("schedule command done fail, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -385,12 +419,12 @@ void AbilityManagerProxy::AddWindowInfo(const sptr &token, int32_ return; } if (!data.WriteParcelable(token) || !data.WriteInt32(windowToken)) { - HILOG_ERROR("add window info write to parce fail."); + HILOG_ERROR("data write failed."); return; } error = Remote()->SendRequest(ADD_WINDOW_INFO, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("add window info fail, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); } } @@ -407,7 +441,7 @@ void AbilityManagerProxy::DumpState(const std::string &args, std::vectorSendRequest(IAbilityManager::DUMP_STATE, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("AbilityManagerProxy: SendRequest err %d", error); + HILOG_ERROR("AbilityManagerProxy: SendRequest err %{public}d", error); return; } int32_t stackNum = reply.ReadInt32(); @@ -428,12 +462,12 @@ int AbilityManagerProxy::TerminateAbilityResult(const sptr &token return INNER_ERR; } if (!data.WriteParcelable(token) || !data.WriteInt32(startId)) { - HILOG_ERROR("terminate ability for result fail"); + HILOG_ERROR("data write failed."); return ERR_INVALID_VALUE; } error = Remote()->SendRequest(IAbilityManager::TERMINATE_ABILITY_RESULT, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("terminate ability for result fail, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -450,12 +484,12 @@ int AbilityManagerProxy::StopServiceAbility(const Want &want) return INNER_ERR; } if (!data.WriteParcelable(&want)) { - HILOG_ERROR("stop service ability. fail to write to parcel."); + HILOG_ERROR("want write failed."); return INNER_ERR; } error = Remote()->SendRequest(IAbilityManager::STOP_SERVICE_ABILITY, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("stop service ability, error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -473,22 +507,22 @@ int AbilityManagerProxy::GetAllStackInfo(StackInfo &stackInfo) } sptr remote = Remote(); if (remote == nullptr) { - HILOG_ERROR("GetAllStackInfo: remote is nullptr"); + HILOG_ERROR("remote is nullptr."); return ERR_UNKNOWN_OBJECT; } error = remote->SendRequest(IAbilityManager::LIST_STACK_INFO, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("GetAllStackInfo: SendRequest err %{public}d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } int32_t result = reply.ReadInt32(); if (result != ERR_OK) { - HILOG_ERROR("GetAllStackInfo: ReadInt32 err %{public}d", result); + HILOG_ERROR("Read info failed, err %{public}d", result); return result; } std::unique_ptr info(reply.ReadParcelable()); if (!info) { - HILOG_ERROR("readParcelableInfo failed"); + HILOG_ERROR("Read info failed."); return ERR_UNKNOWN_OBJECT; } stackInfo = *info; @@ -502,12 +536,11 @@ int AbilityManagerProxy::GetParcelableInfos(MessageParcel &reply, std::vector for (int32_t i = 0; i < infoSize; i++) { std::unique_ptr info(reply.ReadParcelable()); if (!info) { - HILOG_ERROR("Read Parcelable infos failed"); + HILOG_ERROR("Read Parcelable infos failed."); return ERR_INVALID_VALUE; } parcelableInfos.emplace_back(*info); } - HILOG_INFO("get parcelable infos success"); return NO_ERROR; } @@ -522,21 +555,21 @@ int AbilityManagerProxy::GetRecentMissions( return INNER_ERR; } if (!data.WriteInt32(numMax)) { - HILOG_ERROR("get recent missions by numMax , WriteInt32 fail."); + HILOG_ERROR("numMax write failed."); return ERR_INVALID_VALUE; } if (!data.WriteInt32(flags)) { - HILOG_ERROR("get recent missions by flags , WriteInt32 fail."); + HILOG_ERROR("flags write failed."); return ERR_INVALID_VALUE; } error = Remote()->SendRequest(IAbilityManager::GET_RECENT_MISSION, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("get recent mission fail, error: %{public}d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } error = GetParcelableInfos(reply, recentList); if (error != NO_ERROR) { - HILOG_ERROR("GetParcelableInfos fail, error: %{public}d", error); + HILOG_ERROR("Get info error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -553,17 +586,17 @@ int AbilityManagerProxy::GetMissionSnapshot(const int32_t missionId, MissionSnap return INNER_ERR; } if (!data.WriteInt32(missionId)) { - HILOG_ERROR("get recent missions by missionId , WriteInt32 fail."); + HILOG_ERROR("missionId write failed."); return ERR_INVALID_VALUE; } error = Remote()->SendRequest(IAbilityManager::GET_MISSION_SNAPSHOT, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("get mission snapshot fail, error: %{public}d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } std::unique_ptr info(reply.ReadParcelable()); if (!info) { - HILOG_ERROR("readParcelableInfo failed"); + HILOG_ERROR("readParcelableInfo failed."); return ERR_UNKNOWN_OBJECT; } snapshot = *info; @@ -581,12 +614,12 @@ int AbilityManagerProxy::MoveMissionToTop(int32_t missionId) return INNER_ERR; } if (!data.WriteInt32(missionId)) { - HILOG_ERROR("move mission to top by missionId , WriteInt32 fail."); + HILOG_ERROR("missionId write failed."); return ERR_INVALID_VALUE; } error = Remote()->SendRequest(IAbilityManager::MOVE_MISSION_TO_TOP, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("move mission to top fail, error: %{public}d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -602,13 +635,13 @@ int AbilityManagerProxy::MoveMissionToEnd(const sptr &token, cons if (!WriteInterfaceToken(data)) { return INNER_ERR; } - if (!data.WriteParcelable(token) || data.WriteBool(nonFirst)) { - HILOG_ERROR("move mission to end failed"); + if (!data.WriteParcelable(token) || !data.WriteBool(nonFirst)) { + HILOG_ERROR("data write failed."); return ERR_INVALID_VALUE; } error = Remote()->SendRequest(IAbilityManager::MOVE_MISSION_TO_END, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("move mission to end fail, error: %{public}d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -625,12 +658,12 @@ int AbilityManagerProxy::RemoveMission(int id) return INNER_ERR; } if (!data.WriteInt32(id)) { - HILOG_ERROR("remove mission by id , WriteInt32 fail."); + HILOG_ERROR("id write failed."); return ERR_INVALID_VALUE; } error = Remote()->SendRequest(IAbilityManager::REMOVE_MISSION, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("remove mission by id , error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -647,12 +680,12 @@ int AbilityManagerProxy::RemoveStack(int id) return INNER_ERR; } if (!data.WriteInt32(id)) { - HILOG_ERROR("remove stack by id , WriteInt32 fail."); + HILOG_ERROR("id write failed."); return ERR_INVALID_VALUE; } error = Remote()->SendRequest(IAbilityManager::REMOVE_STACK, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("remove stack by id , error: %d", error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -668,12 +701,12 @@ int AbilityManagerProxy::KillProcess(const std::string &bundleName) return INNER_ERR; } if (!data.WriteString16(Str8ToStr16(bundleName))) { - HILOG_ERROR("%{public}s , WriteString16 fail.", __func__); + HILOG_ERROR("bundleName write failed."); return ERR_INVALID_VALUE; } int error = Remote()->SendRequest(IAbilityManager::KILL_PROCESS, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%s, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -689,10 +722,51 @@ int AbilityManagerProxy::UninstallApp(const std::string &bundleName) return INNER_ERR; } if (!data.WriteString16(Str8ToStr16(bundleName))) { - HILOG_ERROR("%{public}s , WriteString16 fail.", __func__); + HILOG_ERROR("bundleName write failed."); return ERR_INVALID_VALUE; } int error = Remote()->SendRequest(IAbilityManager::UNINSTALL_APP, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::MoveMissionToFloatingStack(const MissionOption &missionOption) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteParcelable(&missionOption)) { + HILOG_ERROR("fail to write to parcel."); + return INNER_ERR; + } + int error = Remote()->SendRequest(IAbilityManager::MOVE_MISSION_TO_FLOATING_STACK, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("%s, error: %d", __func__, error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::MoveMissionToSplitScreenStack(const MissionOption &missionOption) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteParcelable(&missionOption)) { + HILOG_ERROR("fail to write to parcel."); + return INNER_ERR; + } + int error = Remote()->SendRequest(IAbilityManager::MOVE_MISSION_TO_SPLITSCREEN_STACK, data, reply, option); if (error != NO_ERROR) { HILOG_ERROR("%s, error: %d", __func__, error); return error; @@ -700,6 +774,134 @@ int AbilityManagerProxy::UninstallApp(const std::string &bundleName) return reply.ReadInt32(); } +int AbilityManagerProxy::ChangeFocusAbility( + const sptr &lostFocusToken, const sptr &getFocusToken) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteParcelable(lostFocusToken) || !data.WriteParcelable(getFocusToken)) { + HILOG_ERROR("change focus ability failed"); + return ERR_INVALID_VALUE; + } + auto error = Remote()->SendRequest(IAbilityManager::CHANGE_FOCUS_ABILITY, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("change focus ability error: %d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::MinimizeMultiWindow(int missionId) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteInt32(missionId)) { + HILOG_ERROR("WriteInt32 fail."); + return ERR_INVALID_VALUE; + } + auto error = Remote()->SendRequest(IAbilityManager::MINIMIZE_MULTI_WINDOW, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("minimize multi window error: %d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::MaximizeMultiWindow(int missionId) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteInt32(missionId)) { + HILOG_ERROR("WriteInt32 fail."); + return ERR_INVALID_VALUE; + } + auto error = Remote()->SendRequest(IAbilityManager::MAXIMIZE_MULTI_WINDOW, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("maximize multi window error: %d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::GetFloatingMissions(std::vector &list) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + auto error = Remote()->SendRequest(IAbilityManager::GET_FLOATING_MISSIONS, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("get floating mission fail, error: %{public}d", error); + return error; + } + error = GetParcelableInfos(reply, list); + if (error != NO_ERROR) { + HILOG_ERROR("GetParcelableInfos fail, error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::CloseMultiWindow(int missionId) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteInt32(missionId)) { + HILOG_ERROR("WriteInt32 fail."); + return ERR_INVALID_VALUE; + } + auto error = Remote()->SendRequest(IAbilityManager::CLOSE_MULTI_WINDOW, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("close multi window error: %d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::SetMissionStackSetting(const StackSetting &stackSetting) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteParcelable(&stackSetting)) { + HILOG_ERROR("%{public}s WriteParcelable", __func__); + return INNER_ERR; + } + auto error = Remote()->SendRequest(IAbilityManager::SET_STACK_SETTING, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("%{public}s for result fail, error: %d", __func__, error); + return error; + } + return reply.ReadInt32(); +} + bool AbilityManagerProxy::IsFirstInMission(const sptr &token) { MessageParcel data; @@ -710,12 +912,12 @@ bool AbilityManagerProxy::IsFirstInMission(const sptr &token) return INNER_ERR; } if (!data.WriteParcelable(token)) { - HILOG_ERROR("%{public}s for result fail", __func__); + HILOG_ERROR("token write failed."); return false; } auto error = Remote()->SendRequest(IAbilityManager::IS_FIRST_IN_MISSION, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s for result fail, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return false; } return reply.ReadBool(); @@ -730,12 +932,12 @@ int AbilityManagerProxy::CompelVerifyPermission(const std::string &permission, i return INNER_ERR; } if (!data.WriteString16(Str8ToStr16(permission)) || !data.WriteInt32(pid) || !data.WriteInt32(uid)) { - HILOG_ERROR("%{public}s, write failed", __func__); + HILOG_ERROR("data write failed."); return INNER_ERR; } auto error = Remote()->SendRequest(IAbilityManager::COMPEL_VERIFY_PERMISSION, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } message = Str16ToStr8(reply.ReadString16()); @@ -752,7 +954,7 @@ int AbilityManagerProxy::PowerOff() } auto error = Remote()->SendRequest(IAbilityManager::POWER_OFF, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -768,7 +970,7 @@ int AbilityManagerProxy::PowerOn() } auto error = Remote()->SendRequest(IAbilityManager::POWER_ON, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -863,11 +1065,30 @@ int AbilityManagerProxy::GetMissionLockModeState() return reply.ReadInt32(); } +int AbilityManagerProxy::UpdateConfiguration(const DummyConfiguration &config) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteParcelable(&config)) { + return INNER_ERR; + } + error = Remote()->SendRequest(IAbilityManager::UPDATE_CONFIGURATION, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("update configuration, error: %d", error); + return error; + } + return reply.ReadInt32(); +} + sptr AbilityManagerProxy::GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) { - HILOG_INFO("%{public}s:begin.", __func__); - MessageParcel data; MessageParcel reply; MessageOption option; @@ -875,16 +1096,16 @@ sptr AbilityManagerProxy::GetWantSender( return nullptr; } if (!data.WriteParcelable(&wantSenderInfo)) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("wantSenderInfo write failed."); return nullptr; } if (!data.WriteParcelable(callerToken)) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("callerToken write failed."); return nullptr; } auto error = Remote()->SendRequest(IAbilityManager::GET_PENDING_WANT_SENDER, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return nullptr; } sptr wantSender = iface_cast(reply.ReadParcelable()); @@ -896,8 +1117,6 @@ sptr AbilityManagerProxy::GetWantSender( int AbilityManagerProxy::SendWantSender(const sptr &target, const SenderInfo &senderInfo) { - HILOG_INFO("%{public}s:begin.", __func__); - MessageParcel data; MessageParcel reply; MessageOption option; @@ -905,17 +1124,17 @@ int AbilityManagerProxy::SendWantSender(const sptr &target, const S return INNER_ERR; } if (target == nullptr || !data.WriteParcelable(target->AsObject())) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("target write failed."); return INNER_ERR; } if (!data.WriteParcelable(&senderInfo)) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("senderInfo write failed."); return INNER_ERR; } auto error = Remote()->SendRequest(IAbilityManager::SEND_PENDING_WANT_SENDER, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } return reply.ReadInt32(); @@ -923,8 +1142,6 @@ int AbilityManagerProxy::SendWantSender(const sptr &target, const S void AbilityManagerProxy::CancelWantSender(const sptr &sender) { - HILOG_INFO("%{public}s:begin.", __func__); - MessageParcel data; MessageParcel reply; MessageOption option; @@ -932,22 +1149,18 @@ void AbilityManagerProxy::CancelWantSender(const sptr &sender) return; } if (sender == nullptr || !data.WriteParcelable(sender->AsObject())) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("sender write failed."); return; } - // data.WriteString16(Str8ToStr16(bundleName)); - // data.WriteInt32(userId); auto error = Remote()->SendRequest(IAbilityManager::CANCEL_PENDING_WANT_SENDER, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return; } } int AbilityManagerProxy::GetPendingWantUid(const sptr &target) { - HILOG_INFO("%{public}s:begin.", __func__); - MessageParcel data; MessageParcel reply; MessageOption option; @@ -955,12 +1168,12 @@ int AbilityManagerProxy::GetPendingWantUid(const sptr &target) return INNER_ERR; } if (target == nullptr || !data.WriteParcelable(target->AsObject())) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("target write failed."); return ERR_INVALID_VALUE; } auto error = Remote()->SendRequest(IAbilityManager::GET_PENDING_WANT_UID, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return INNER_ERR; } return reply.ReadInt32(); @@ -968,8 +1181,6 @@ int AbilityManagerProxy::GetPendingWantUid(const sptr &target) int AbilityManagerProxy::GetPendingWantUserId(const sptr &target) { - HILOG_INFO("%{public}s:begin.", __func__); - MessageParcel data; MessageParcel reply; MessageOption option; @@ -977,12 +1188,12 @@ int AbilityManagerProxy::GetPendingWantUserId(const sptr &target) return INNER_ERR; } if (target == nullptr || !data.WriteParcelable(target->AsObject())) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("target write failed."); return ERR_INVALID_VALUE; } auto error = Remote()->SendRequest(IAbilityManager::GET_PENDING_WANT_USERID, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return INNER_ERR; } return reply.ReadInt32(); @@ -990,8 +1201,6 @@ int AbilityManagerProxy::GetPendingWantUserId(const sptr &target) std::string AbilityManagerProxy::GetPendingWantBundleName(const sptr &target) { - HILOG_INFO("%{public}s:begin.", __func__); - MessageParcel data; MessageParcel reply; MessageOption option; @@ -999,12 +1208,12 @@ std::string AbilityManagerProxy::GetPendingWantBundleName(const sptrAsObject())) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("target write failed."); return ""; } auto error = Remote()->SendRequest(IAbilityManager::GET_PENDING_WANT_BUNDLENAME, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return ""; } return Str16ToStr8(reply.ReadString16()); @@ -1012,8 +1221,6 @@ std::string AbilityManagerProxy::GetPendingWantBundleName(const sptr &target) { - HILOG_INFO("%{public}s:begin.", __func__); - MessageParcel data; MessageParcel reply; MessageOption option; @@ -1021,12 +1228,12 @@ int AbilityManagerProxy::GetPendingWantCode(const sptr &target) return INNER_ERR; } if (target == nullptr || !data.WriteParcelable(target->AsObject())) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("target write failed."); return ERR_INVALID_VALUE; } auto error = Remote()->SendRequest(IAbilityManager::GET_PENDING_WANT_CODE, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return INNER_ERR; } return reply.ReadInt32(); @@ -1034,8 +1241,6 @@ int AbilityManagerProxy::GetPendingWantCode(const sptr &target) int AbilityManagerProxy::GetPendingWantType(const sptr &target) { - HILOG_INFO("%{public}s:begin.", __func__); - MessageParcel data; MessageParcel reply; MessageOption option; @@ -1043,12 +1248,12 @@ int AbilityManagerProxy::GetPendingWantType(const sptr &target) return INNER_ERR; } if (target == nullptr || !data.WriteParcelable(target->AsObject())) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("target write failed."); return ERR_INVALID_VALUE; } auto error = Remote()->SendRequest(IAbilityManager::GET_PENDING_WANT_TYPE, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return INNER_ERR; } return reply.ReadInt32(); @@ -1056,8 +1261,6 @@ int AbilityManagerProxy::GetPendingWantType(const sptr &target) void AbilityManagerProxy::RegisterCancelListener(const sptr &sender, const sptr &receiver) { - HILOG_INFO("%{public}s:begin.", __func__); - MessageParcel data; MessageParcel reply; MessageOption option; @@ -1065,24 +1268,22 @@ void AbilityManagerProxy::RegisterCancelListener(const sptr &sender return; } if (sender == nullptr || !data.WriteParcelable(sender->AsObject())) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("sender write failed."); return; } if (receiver == nullptr || !data.WriteParcelable(receiver->AsObject())) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("receiver write failed."); return; } auto error = Remote()->SendRequest(IAbilityManager::REGISTER_CANCEL_LISTENER, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return; } } void AbilityManagerProxy::UnregisterCancelListener(const sptr &sender, const sptr &receiver) { - HILOG_INFO("%{public}s:begin.", __func__); - MessageParcel data; MessageParcel reply; MessageOption option; @@ -1090,24 +1291,22 @@ void AbilityManagerProxy::UnregisterCancelListener(const sptr &send return; } if (sender == nullptr || !data.WriteParcelable(sender->AsObject())) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("sender write failed."); return; } if (receiver == nullptr || !data.WriteParcelable(receiver->AsObject())) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("receiver write failed."); return; } auto error = Remote()->SendRequest(IAbilityManager::UNREGISTER_CANCEL_LISTENER, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return; } } int AbilityManagerProxy::GetPendingRequestWant(const sptr &target, std::shared_ptr &want) { - HILOG_INFO("%{public}s:begin.", __func__); - MessageParcel data; MessageParcel reply; MessageOption option; @@ -1115,16 +1314,16 @@ int AbilityManagerProxy::GetPendingRequestWant(const sptr &target, return INNER_ERR; } if (target == nullptr || !data.WriteParcelable(target->AsObject())) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("target write failed."); return INNER_ERR; } if (want == nullptr || !data.WriteParcelable(want.get())) { - HILOG_ERROR("%{public}s WriteParcelable", __func__); + HILOG_ERROR("want write failed."); return INNER_ERR; } auto error = Remote()->SendRequest(IAbilityManager::GET_PENDING_REQUEST_WANT, data, reply, option); if (error != NO_ERROR) { - HILOG_ERROR("%{public}s send request error, error: %d", __func__, error); + HILOG_ERROR("Send request error: %{public}d", error); return error; } std::unique_ptr wantInfo(reply.ReadParcelable()); diff --git a/services/abilitymgr/src/ability_manager_service.cpp b/services/abilitymgr/src/ability_manager_service.cpp index 09b92eebb60..efb99dd6145 100644 --- a/services/abilitymgr/src/ability_manager_service.cpp +++ b/services/abilitymgr/src/ability_manager_service.cpp @@ -55,6 +55,8 @@ const std::map AbilityManagerServic std::map::value_type("-d", KEY_DUMP_DATA), std::map::value_type("--ui", KEY_DUMP_SYSTEM_UI), std::map::value_type("-u", KEY_DUMP_SYSTEM_UI), + std::map::value_type("-focus", KEY_DUMP_FOCUS_ABILITY), + std::map::value_type("-f", KEY_DUMP_FOCUS_ABILITY), }; const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); @@ -79,12 +81,12 @@ AbilityManagerService::~AbilityManagerService() void AbilityManagerService::OnStart() { if (state_ == ServiceRunningState::STATE_RUNNING) { - HILOG_INFO("Ability Manager Service has already started."); + HILOG_INFO("Ability manager service has already started."); return; } - HILOG_INFO("Ability Manager Service started."); + HILOG_INFO("Ability manager service started."); if (!Init()) { - HILOG_ERROR("failed to init service."); + HILOG_ERROR("Failed to init service."); return; } state_ = ServiceRunningState::STATE_RUNNING; @@ -93,11 +95,11 @@ void AbilityManagerService::OnStart() * so it can't affect the TDD test program */ bool ret = Publish(DelayedSingleton::GetInstance().get()); if (!ret) { - HILOG_ERROR("AbilityManagerService::Init Publish failed!"); + HILOG_ERROR("Init publish failed!"); return; } - HILOG_INFO("Ability Manager Service start success."); + HILOG_INFO("Ability manager service start success."); } bool AbilityManagerService::Init() @@ -132,13 +134,13 @@ bool AbilityManagerService::Init() handler_->PostTask(startLauncherAbilityTask, "startLauncherAbility"); dataAbilityManager_ = dataAbilityManager; pendingWantManager_ = pendingWantManager; - HILOG_INFO("init success"); + HILOG_INFO("Init success."); return true; } void AbilityManagerService::OnStop() { - HILOG_INFO("stop service"); + HILOG_INFO("Stop service."); eventLoop_.reset(); handler_.reset(); state_ = ServiceRunningState::STATE_NOT_START; @@ -152,10 +154,17 @@ ServiceRunningState AbilityManagerService::QueryServiceState() const int AbilityManagerService::StartAbility(const Want &want, int requestCode) { HILOG_INFO("%{public}s", __func__); - return StartAbility(want, nullptr, requestCode); + return StartAbility(want, nullptr, requestCode, -1); } int AbilityManagerService::StartAbility(const Want &want, const sptr &callerToken, int requestCode) +{ + HILOG_INFO("%{public}s", __func__); + return StartAbility(want, callerToken, requestCode, -1); +} + +int AbilityManagerService::StartAbility( + const Want &want, const sptr &callerToken, int requestCode, int callerUid) { HILOG_INFO("%{public}s", __func__); @@ -166,17 +175,22 @@ int AbilityManagerService::StartAbility(const Want &want, const sptrStartAbility(abilityRequest); } +int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode) +{ + HILOG_INFO("Start ability setting."); + if (callerToken != nullptr && !VerificationToken(callerToken)) { + return ERR_INVALID_VALUE; + } + + AbilityRequest abilityRequest; + int result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken); + if (result != ERR_OK) { + HILOG_ERROR("Generate ability request error."); + return result; + } + + abilityRequest.startSetting = std::make_shared(abilityStartSetting); + + auto abilityInfo = abilityRequest.abilityInfo; + if (abilityInfo.type == AppExecFwk::AbilityType::DATA) { + HILOG_ERROR("Cannot start data ability, use 'AcquireDataAbility()' instead."); + return ERR_INVALID_VALUE; + } + + if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) { + result = PreLoadAppDataAbilities(abilityInfo.bundleName); + if (result != ERR_OK) { + HILOG_ERROR("StartAbility: App data ability preloading failed, '%{public}s', %{public}d", + abilityInfo.bundleName.c_str(), + result); + return result; + } + } + + if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) { + HILOG_ERROR("Only support for page type ability."); + return ERR_INVALID_VALUE; + } + if (IsSystemUiApp(abilityRequest.abilityInfo)) { + return systemAppManager_->StartAbility(abilityRequest); + } + return currentStackManager_->StartAbility(abilityRequest); +} + int AbilityManagerService::TerminateAbility(const sptr &token, int resultCode, const Want *resultWant) { - HILOG_INFO("%{public}s. for result: %{public}d", __func__, (resultWant != nullptr)); + HILOG_INFO("Terminate ability for result: %{public}d", (resultWant != nullptr)); if (!VerificationToken(token)) { return ERR_INVALID_VALUE; } auto abilityRecord = Token::GetAbilityRecordByToken(token); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + int result = AbilityUtil::JudgeAbilityVisibleControl(abilityRecord->GetAbilityInfo()); + if (result != ERR_OK) { + HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); + return result; + } if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) { - HILOG_ERROR("system ui not allow terminate."); + HILOG_ERROR("System ui not allow terminate."); return ERR_INVALID_VALUE; } @@ -223,7 +285,7 @@ int AbilityManagerService::TerminateAbility(const sptr &token, in } if ((resultWant != nullptr) && - AbilitUtil::IsSystemDialogAbility( + AbilityUtil::IsSystemDialogAbility( abilityRecord->GetAbilityInfo().bundleName, abilityRecord->GetAbilityInfo().name) && resultWant->HasParameter(AbilityConfig::SYSTEM_DIALOG_KEY) && resultWant->HasParameter(AbilityConfig::SYSTEM_DIALOG_CALLER_BUNDLENAME) && @@ -236,23 +298,22 @@ int AbilityManagerService::TerminateAbility(const sptr &token, in void AbilityManagerService::RequestPermission(const Want *resultWant) { - if (iBundleManager_ == nullptr || resultWant == nullptr) { - HILOG_ERROR("iBundleManager or resultWant is nullptr."); - return; - } - std::string callerBundleName = resultWant->GetStringParam(AbilityConfig::SYSTEM_DIALOG_CALLER_BUNDLENAME); - std::vector permissions = - resultWant->GetStringArrayParam(AbilityConfig::SYSTEM_DIALOG_REQUEST_PERMISSIONS); + HILOG_INFO("Request permission."); + CHECK_POINTER(iBundleManager_); + CHECK_POINTER_IS_NULLPTR(resultWant); + + auto callerBundleName = resultWant->GetStringParam(AbilityConfig::SYSTEM_DIALOG_CALLER_BUNDLENAME); + auto permissions = resultWant->GetStringArrayParam(AbilityConfig::SYSTEM_DIALOG_REQUEST_PERMISSIONS); for (auto &it : permissions) { auto ret = iBundleManager_->RequestPermissionFromUser(callerBundleName, it, GetUserId()); - HILOG_INFO("request permission from user result :%{public}d, permission:%{public}s.", ret, it.c_str()); + HILOG_INFO("Request permission from user result :%{public}d, permission:%{public}s.", ret, it.c_str()); } } int AbilityManagerService::TerminateAbilityByCaller(const sptr &callerToken, int requestCode) { - HILOG_INFO("%{public}s %{public}d", __func__, __LINE__); + HILOG_INFO("Terminate ability by caller."); if (!VerificationToken(callerToken)) { return ERR_INVALID_VALUE; } @@ -261,30 +322,37 @@ int AbilityManagerService::TerminateAbilityByCaller(const sptr &c CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) { - HILOG_ERROR("system ui not allow terminate."); + HILOG_ERROR("System ui not allow terminate."); return ERR_INVALID_VALUE; } auto type = abilityRecord->GetAbilityInfo().type; switch (type) { - case AppExecFwk::AbilityType::SERVICE: - return connectManager_->TerminateAbility(abilityRecord, requestCode); - break; - case AppExecFwk::AbilityType::PAGE: - return currentStackManager_->TerminateAbility(abilityRecord, requestCode); - break; + case AppExecFwk::AbilityType::SERVICE: { + auto result = connectManager_->TerminateAbility(abilityRecord, requestCode); + if (result == NO_FOUND_ABILITY_BY_CALLER) { + return currentStackManager_->TerminateAbility(abilityRecord, requestCode); + } + return result; + } + case AppExecFwk::AbilityType::PAGE: { + auto result = currentStackManager_->TerminateAbility(abilityRecord, requestCode); + if (result == NO_FOUND_ABILITY_BY_CALLER) { + return connectManager_->TerminateAbility(abilityRecord, requestCode); + } + return result; + } default: return ERR_INVALID_VALUE; - break; } } int AbilityManagerService::GetRecentMissions( const int32_t numMax, const int32_t flags, std::vector &recentList) { - HILOG_INFO("%{public}s numMax %{public}d, flags: %{public}d", __func__, numMax, flags); + HILOG_INFO("numMax: %{public}d, flags: %{public}d", numMax, flags); if (numMax < 0 || flags < 0) { - HILOG_ERROR("get recent missions, numMax or flags is invalid"); + HILOG_ERROR("numMax or flags is invalid."); return ERR_INVALID_VALUE; } @@ -316,11 +384,22 @@ int AbilityManagerService::GetMissionLockModeState() return currentStackManager_->GetMissionLockModeState(); } +int AbilityManagerService::UpdateConfiguration(const DummyConfiguration &config) +{ + HILOG_INFO("%{public}s called", __func__); + CHECK_POINTER_AND_RETURN(currentStackManager_, ERR_INVALID_VALUE); + CHECK_POINTER_AND_RETURN(systemAppManager_, ERR_INVALID_VALUE); + + systemAppManager_->UpdateConfiguration(config); + + return currentStackManager_->UpdateConfiguration(config); +} + int AbilityManagerService::MoveMissionToTop(int32_t missionId) { - HILOG_INFO("%{public}s mission id: %d", __func__, missionId); + HILOG_INFO("Move mission to top."); if (missionId < 0) { - HILOG_ERROR("%{public}s, mission id is invalid", __func__); + HILOG_ERROR("Mission id is invalid."); return ERR_INVALID_VALUE; } @@ -329,7 +408,7 @@ int AbilityManagerService::MoveMissionToTop(int32_t missionId) int AbilityManagerService::MoveMissionToEnd(const sptr &token, const bool nonFirst) { - HILOG_INFO("%{public}s called", __func__); + HILOG_INFO("Move mission to end."); CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE); if (!VerificationToken(token)) { return ERR_INVALID_VALUE; @@ -339,9 +418,9 @@ int AbilityManagerService::MoveMissionToEnd(const sptr &token, co int AbilityManagerService::RemoveMission(int id) { - HILOG_DEBUG("remove mission called"); + HILOG_INFO("Remove mission."); if (id < 0) { - HILOG_ERROR("remove mission, id is invalid"); + HILOG_ERROR("Mission id is invalid."); return ERR_INVALID_VALUE; } return currentStackManager_->RemoveMissionById(id); @@ -349,9 +428,9 @@ int AbilityManagerService::RemoveMission(int id) int AbilityManagerService::RemoveStack(int id) { - HILOG_DEBUG("remove stack called"); + HILOG_INFO("Remove stack."); if (id < 0) { - HILOG_ERROR("remove stack, id is invalid"); + HILOG_ERROR("Stack id is invalid."); return ERR_INVALID_VALUE; } return currentStackManager_->RemoveStack(id); @@ -360,16 +439,21 @@ int AbilityManagerService::RemoveStack(int id) int AbilityManagerService::ConnectAbility( const Want &want, const sptr &connect, const sptr &callerToken) { - HILOG_INFO("%{public}s", __func__); + HILOG_INFO("Connect ability."); CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE); CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE); AbilityRequest abilityRequest; - int result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken); + int result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, callerToken); if (result != ERR_OK) { - HILOG_ERROR("%{public}s generate ability request error.", __func__); + HILOG_ERROR("Generate ability request error."); return result; } auto abilityInfo = abilityRequest.abilityInfo; + result = AbilityUtil::JudgeAbilityVisibleControl(abilityInfo); + if (result != ERR_OK) { + HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); + return result; + } auto type = abilityInfo.type; if (type != AppExecFwk::AbilityType::SERVICE) { HILOG_ERROR("Connect Ability failed, target Ability is not Service."); @@ -387,7 +471,7 @@ int AbilityManagerService::ConnectAbility( int AbilityManagerService::DisconnectAbility(const sptr &connect) { - HILOG_DEBUG("%{public}s", __func__); + HILOG_DEBUG("Disconnect ability."); CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE); CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE); return connectManager_->DisconnectAbilityLocked(connect); @@ -401,63 +485,43 @@ void AbilityManagerService::RemoveAllServiceRecord() sptr AbilityManagerService::GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) { - HILOG_INFO("%{public}s:begin.", __func__); + HILOG_INFO("Get want Sender."); + CHECK_POINTER_AND_RETURN(pendingWantManager_, nullptr); - if (pendingWantManager_ == nullptr) { - HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__); - return nullptr; - } auto bms = GetBundleManager(); - if (bms == nullptr) { - HILOG_ERROR("%s, bms is nullptr", __func__); - return nullptr; - } + CHECK_POINTER_AND_RETURN(bms, nullptr); + int32_t callerUid = IPCSkeleton::GetCallingUid(); AppExecFwk::BundleInfo bundleInfo; bool bundleMgrResult = bms->GetBundleInfo(wantSenderInfo.bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); if (!bundleMgrResult) { - HILOG_ERROR("GetBundleInfo is fail"); + HILOG_ERROR("GetBundleInfo is fail."); return nullptr; } HILOG_INFO("AbilityManagerService::GetWantSender: bundleName = %{public}s", wantSenderInfo.bundleName.c_str()); - return pendingWantManager_->GetWantSender(callerUid, bundleInfo.uid, wantSenderInfo, callerToken); + return pendingWantManager_->GetWantSender( + callerUid, bundleInfo.uid, bms->CheckIsSystemAppByUid(callerUid), wantSenderInfo, callerToken); } int AbilityManagerService::SendWantSender(const sptr &target, const SenderInfo &senderInfo) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (pendingWantManager_ == nullptr) { - HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__); - return ERR_INVALID_VALUE; - } - if (target == nullptr) { - HILOG_ERROR("%s, target is nullptr", __func__); - return ERR_INVALID_VALUE; - } - + HILOG_INFO("Send want sender."); + CHECK_POINTER_AND_RETURN(pendingWantManager_, ERR_INVALID_VALUE); + CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE); return pendingWantManager_->SendWantSender(target, senderInfo); } void AbilityManagerService::CancelWantSender(const sptr &sender) { - HILOG_INFO("%{public}s:begin.", __func__); + HILOG_INFO("Cancel want sender."); + CHECK_POINTER(pendingWantManager_); + CHECK_POINTER(sender); - if (pendingWantManager_ == nullptr) { - HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__); - return; - } - if (sender == nullptr) { - HILOG_ERROR("%s, sender is nullptr", __func__); - return; - } auto bms = GetBundleManager(); - if (bms == nullptr) { - HILOG_ERROR("%s, bms is nullptr", __func__); - return; - } + CHECK_POINTER(bms); + int32_t callerUid = IPCSkeleton::GetCallingUid(); sptr record = iface_cast(sender->AsObject()); @@ -465,11 +529,11 @@ void AbilityManagerService::CancelWantSender(const sptr &sender) bool bundleMgrResult = bms->GetBundleInfo(record->GetKey()->GetBundleName(), AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); if (!bundleMgrResult) { - HILOG_ERROR("GetBundleInfo is fail"); + HILOG_ERROR("GetBundleInfo is fail."); return; } - pendingWantManager_->CancelWantSender(callerUid, bundleInfo.uid, sender); + pendingWantManager_->CancelWantSender(callerUid, bundleInfo.uid, bms->CheckIsSystemAppByUid(callerUid), sender); } int AbilityManagerService::GetPendingWantUid(const sptr &target) @@ -478,11 +542,11 @@ int AbilityManagerService::GetPendingWantUid(const sptr &target) if (pendingWantManager_ == nullptr) { HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__); - return ERR_INVALID_VALUE; + return -1; } if (target == nullptr) { HILOG_ERROR("%s, target is nullptr", __func__); - return ERR_INVALID_VALUE; + return -1; } return pendingWantManager_->GetPendingWantUid(target); } @@ -493,27 +557,20 @@ int AbilityManagerService::GetPendingWantUserId(const sptr &target) if (pendingWantManager_ == nullptr) { HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__); - return ERR_INVALID_VALUE; + return -1; } if (target == nullptr) { HILOG_ERROR("%s, target is nullptr", __func__); - return ERR_INVALID_VALUE; + return -1; } return pendingWantManager_->GetPendingWantUserId(target); } std::string AbilityManagerService::GetPendingWantBundleName(const sptr &target) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (pendingWantManager_ == nullptr) { - HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__); - return ""; - } - if (target == nullptr) { - HILOG_ERROR("%s, target is nullptr", __func__); - return ""; - } + HILOG_INFO("Get pending want bundle name."); + CHECK_POINTER_AND_RETURN(pendingWantManager_, ""); + CHECK_POINTER_AND_RETURN(target, ""); return pendingWantManager_->GetPendingWantBundleName(target); } @@ -523,11 +580,11 @@ int AbilityManagerService::GetPendingWantCode(const sptr &target) if (pendingWantManager_ == nullptr) { HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__); - return ERR_INVALID_VALUE; + return -1; } if (target == nullptr) { HILOG_ERROR("%s, target is nullptr", __func__); - return ERR_INVALID_VALUE; + return -1; } return pendingWantManager_->GetPendingWantCode(target); } @@ -538,70 +595,40 @@ int AbilityManagerService::GetPendingWantType(const sptr &target) if (pendingWantManager_ == nullptr) { HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__); - return ERR_INVALID_VALUE; + return -1; } if (target == nullptr) { HILOG_ERROR("%s, target is nullptr", __func__); - return ERR_INVALID_VALUE; + return -1; } return pendingWantManager_->GetPendingWantType(target); } void AbilityManagerService::RegisterCancelListener(const sptr &sender, const sptr &receiver) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (pendingWantManager_ == nullptr) { - HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__); - return; - } - if (sender == nullptr) { - HILOG_ERROR("%s, sender is nullptr", __func__); - return; - } - if (receiver == nullptr) { - HILOG_ERROR("%s, receiver is nullptr", __func__); - return; - } + HILOG_INFO("Register cancel listener."); + CHECK_POINTER(pendingWantManager_); + CHECK_POINTER(sender); + CHECK_POINTER(receiver); pendingWantManager_->RegisterCancelListener(sender, receiver); } void AbilityManagerService::UnregisterCancelListener( const sptr &sender, const sptr &receiver) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (pendingWantManager_ == nullptr) { - HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__); - return; - } - if (sender == nullptr) { - HILOG_ERROR("%s, sender is nullptr", __func__); - return; - } - if (receiver == nullptr) { - HILOG_ERROR("%s, receiver is nullptr", __func__); - return; - } + HILOG_INFO("Unregister cancel listener."); + CHECK_POINTER(pendingWantManager_); + CHECK_POINTER(sender); + CHECK_POINTER(receiver); pendingWantManager_->UnregisterCancelListener(sender, receiver); } int AbilityManagerService::GetPendingRequestWant(const sptr &target, std::shared_ptr &want) { - HILOG_INFO("%{public}s:begin.", __func__); - - if (pendingWantManager_ == nullptr) { - HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__); - return ERR_INVALID_VALUE; - } - if (target == nullptr) { - HILOG_ERROR("%s, target is nullptr", __func__); - return ERR_INVALID_VALUE; - } - if (want == nullptr) { - HILOG_ERROR("%s, want is nullptr", __func__); - return ERR_INVALID_VALUE; - } + HILOG_INFO("Get pending request want."); + CHECK_POINTER_AND_RETURN(pendingWantManager_, ERR_INVALID_VALUE); + CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE); + CHECK_POINTER_AND_RETURN(want, ERR_INVALID_VALUE); return pendingWantManager_->GetPendingRequestWant(target, want); } @@ -619,9 +646,14 @@ std::list> AbilityManagerService::GetConnectRe sptr AbilityManagerService::AcquireDataAbility( const Uri &uri, bool tryBind, const sptr &callerToken) { - HILOG_INFO("%{public}s, called.", __func__); - if (!VerificationToken(callerToken)) { - return nullptr; + HILOG_INFO("%{public}s, called. uid %{public}d", __func__, IPCSkeleton::GetCallingUid()); + bool isSystem = (IPCSkeleton::GetCallingUid() == AbilityUtil::SYSTEM_UID); + if (!isSystem) { + HILOG_INFO("callerToken not system %{public}s", __func__); + if (!VerificationToken(callerToken)) { + HILOG_INFO("VerificationToken fail"); + return nullptr; + } } auto bms = GetBundleManager(); @@ -640,12 +672,17 @@ sptr AbilityManagerService::AcquireDataAbility( } AbilityRequest abilityRequest; - std::string dataAbilityUri = AbilityConfig::SCHEME_DATA_ABILITY + "://" + pathSegments[0]; + std::string dataAbilityUri = localUri.ToString(); bool queryResult = iBundleManager_->QueryAbilityInfoByUri(dataAbilityUri, abilityRequest.abilityInfo); if (!queryResult || abilityRequest.abilityInfo.name.empty() || abilityRequest.abilityInfo.bundleName.empty()) { HILOG_ERROR("Invalid ability info for data ability acquiring."); return nullptr; } + int result = AbilityUtil::JudgeAbilityVisibleControl(abilityRequest.abilityInfo); + if (result != ERR_OK) { + HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); + return nullptr; + } abilityRequest.appInfo = abilityRequest.abilityInfo.applicationInfo; if (abilityRequest.appInfo.name.empty() || abilityRequest.appInfo.bundleName.empty()) { HILOG_ERROR("Invalid app info for data ability acquiring."); @@ -660,24 +697,29 @@ sptr AbilityManagerService::AcquireDataAbility( abilityRequest.appInfo.bundleName.c_str(), abilityRequest.abilityInfo.name.c_str()); - return dataAbilityManager_->Acquire(abilityRequest, tryBind, callerToken); + return dataAbilityManager_->Acquire(abilityRequest, tryBind, callerToken, isSystem); } int AbilityManagerService::ReleaseDataAbility( sptr dataAbilityScheduler, const sptr &callerToken) { HILOG_INFO("%{public}s, called.", __func__); - if (!VerificationToken(callerToken)) { - return ERR_INVALID_STATE; + bool isSystem = (IPCSkeleton::GetCallingUid() == AbilityUtil::SYSTEM_UID); + if (!isSystem) { + HILOG_INFO("callerToken not system %{public}s", __func__); + if (!VerificationToken(callerToken)) { + HILOG_INFO("VerificationToken fail"); + return ERR_INVALID_STATE; + } } - return dataAbilityManager_->Release(dataAbilityScheduler, callerToken); + return dataAbilityManager_->Release(dataAbilityScheduler, callerToken, isSystem); } int AbilityManagerService::AttachAbilityThread( const sptr &scheduler, const sptr &token) { - HILOG_INFO("%{public}s, called.", __func__); + HILOG_INFO("Attach ability thread."); CHECK_POINTER_AND_RETURN(scheduler, ERR_INVALID_VALUE); if (!VerificationToken(token)) { @@ -712,6 +754,7 @@ void AbilityManagerService::DumpFuncInit() dumpFuncMap_[KEY_DUMP_SERVICE] = &AbilityManagerService::DumpStateInner; dumpFuncMap_[KEY_DUMP_DATA] = &AbilityManagerService::DataDumpStateInner; dumpFuncMap_[KEY_DUMP_SYSTEM_UI] = &AbilityManagerService::SystemDumpStateInner; + dumpFuncMap_[KEY_DUMP_FOCUS_ABILITY] = &AbilityManagerService::DumpFocusMapInner; } void AbilityManagerService::DumpInner(const std::string &args, std::vector &info) @@ -724,6 +767,11 @@ void AbilityManagerService::DumpStackListInner(const std::string &args, std::vec currentStackManager_->DumpStackList(info); } +void AbilityManagerService::DumpFocusMapInner(const std::string &args, std::vector &info) +{ + currentStackManager_->DumpFocusMap(info); +} + void AbilityManagerService::DumpStackInner(const std::string &args, std::vector &info) { std::vector argList; @@ -735,7 +783,7 @@ void AbilityManagerService::DumpStackInner(const std::string &args, std::vector< info.push_back("error: invalid argument, please see 'ability dump -h'."); return; } - int stackId = -1; + int stackId = DEFAULT_INVAL_VALUE; (void)StrToInt(argList[1], stackId); currentStackManager_->DumpStack(stackId, info); } @@ -751,7 +799,7 @@ void AbilityManagerService::DumpMissionInner(const std::string &args, std::vecto info.push_back("error: invalid argument, please see 'ability dump -h'."); return; } - int missionId = -1; + int missionId = DEFAULT_INVAL_VALUE; (void)StrToInt(argList[1], missionId); currentStackManager_->DumpMission(missionId, info); } @@ -830,18 +878,16 @@ void AbilityManagerService::DumpState(const std::string &args, std::vector &token, int state) { - HILOG_INFO("%{public}s, state:%{public}d", __func__, state); + HILOG_INFO("Ability transition done, state:%{public}d", state); if (!VerificationToken(token)) { return ERR_INVALID_VALUE; } auto abilityRecord = Token::GetAbilityRecordByToken(token); - if (abilityRecord == nullptr) { - HILOG_ERROR("%s, ability record is nullptr", __func__); - return ERR_INVALID_VALUE; - } + CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr."); + auto abilityInfo = abilityRecord->GetAbilityInfo(); - HILOG_DEBUG("%{public}s, state:%{public}d name:%{public}s", __func__, state, abilityInfo.name.c_str()); + HILOG_DEBUG("state:%{public}d name:%{public}s", state, abilityInfo.name.c_str()); auto type = abilityInfo.type; if (type == AppExecFwk::AbilityType::SERVICE) { return connectManager_->AbilityTransitionDone(token, state); @@ -859,7 +905,7 @@ int AbilityManagerService::AbilityTransitionDone(const sptr &toke int AbilityManagerService::ScheduleConnectAbilityDone( const sptr &token, const sptr &remoteObject) { - HILOG_INFO("%{public}s, called.", __func__); + HILOG_INFO("Schedule connect ability done."); if (!VerificationToken(token)) { return ERR_INVALID_VALUE; } @@ -869,7 +915,7 @@ int AbilityManagerService::ScheduleConnectAbilityDone( auto type = abilityRecord->GetAbilityInfo().type; if (type != AppExecFwk::AbilityType::SERVICE) { - HILOG_ERROR("Connect Ability failed, target Ability is not Service."); + HILOG_ERROR("Connect ability failed, target ability is not service."); return TARGET_ABILITY_NOT_SERVICE; } @@ -878,7 +924,7 @@ int AbilityManagerService::ScheduleConnectAbilityDone( int AbilityManagerService::ScheduleDisconnectAbilityDone(const sptr &token) { - HILOG_INFO("%{public}s, called.", __func__); + HILOG_INFO("Schedule disconnect ability done."); if (!VerificationToken(token)) { return ERR_INVALID_VALUE; } @@ -888,7 +934,7 @@ int AbilityManagerService::ScheduleDisconnectAbilityDone(const sptrGetAbilityInfo().type; if (type != AppExecFwk::AbilityType::SERVICE) { - HILOG_ERROR("Connect Ability failed, target Ability is not Service."); + HILOG_ERROR("Connect ability failed, target ability is not service."); return TARGET_ABILITY_NOT_SERVICE; } @@ -897,7 +943,7 @@ int AbilityManagerService::ScheduleDisconnectAbilityDone(const sptr &token) { - HILOG_INFO("%{public}s, called.", __func__); + HILOG_INFO("Schedule command ability done."); if (!VerificationToken(token)) { return ERR_INVALID_VALUE; } @@ -907,7 +953,7 @@ int AbilityManagerService::ScheduleCommandAbilityDone(const sptr auto type = abilityRecord->GetAbilityInfo().type; if (type != AppExecFwk::AbilityType::SERVICE) { - HILOG_ERROR("Connect Ability failed, target Ability is not Service."); + HILOG_ERROR("Connect ability failed, target ability is not service."); return TARGET_ABILITY_NOT_SERVICE; } @@ -916,7 +962,7 @@ int AbilityManagerService::ScheduleCommandAbilityDone(const sptr void AbilityManagerService::AddWindowInfo(const sptr &token, int32_t windowToken) { - HILOG_DEBUG("add window id."); + HILOG_DEBUG("Add window id."); if (!VerificationToken(token)) { return; } @@ -925,7 +971,7 @@ void AbilityManagerService::AddWindowInfo(const sptr &token, int3 void AbilityManagerService::OnAbilityRequestDone(const sptr &token, const int32_t state) { - HILOG_INFO("%{public}s, called.", __func__); + HILOG_INFO("On ability request done."); if (!VerificationToken(token)) { return; } @@ -952,6 +998,15 @@ void AbilityManagerService::OnAbilityRequestDone(const sptr &toke } } +void AbilityManagerService::OnAppStateChanged(const AppInfo &info) +{ + HILOG_INFO("On app state changed."); + currentStackManager_->OnAppStateChanged(info); + connectManager_->OnAppStateChanged(info); + systemAppManager_->OnAppStateChanged(info); + dataAbilityManager_->OnAppStateChanged(info); +} + std::shared_ptr AbilityManagerService::GetEventHandler() { return handler_; @@ -983,14 +1038,14 @@ void AbilityManagerService::DumpWaittingAbilityQueue(std::string &result) // multi user scene int AbilityManagerService::GetUserId() { - return 0; + return DEFAULT_USER_ID; } void AbilityManagerService::WaitForStartingLauncherAbility() { HILOG_INFO("Waiting AppMgr Service run completed."); while (!appScheduler_->Init(shared_from_this())) { - HILOG_ERROR("failed to init appScheduler_"); + HILOG_ERROR("Failed to init appScheduler_"); usleep(REPOLL_TIME_MICRO_SECONDS); } @@ -1000,7 +1055,7 @@ void AbilityManagerService::WaitForStartingLauncherAbility() sptr bundle_obj = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); if (bundle_obj == nullptr) { - HILOG_ERROR("failed to get bundle manager service"); + HILOG_ERROR("Failed to get bundle manager service"); usleep(REPOLL_TIME_MICRO_SECONDS); continue; } @@ -1034,21 +1089,21 @@ void AbilityManagerService::WaitForStartingLauncherAbility() usleep(REPOLL_TIME_MICRO_SECONDS); waitCnt++; } - HILOG_INFO("waiting boot animation for 5 seconds."); + HILOG_INFO("Waiting boot animation for 5 seconds."); usleep(REPOLL_TIME_MICRO_SECONDS * 5); - HILOG_INFO("start Home Launcher Ability."); + HILOG_INFO("Start Home Launcher Ability."); /* start launch ability */ - (void)StartAbility(want, -1); + (void)StartAbility(want, DEFAULT_INVAL_VALUE); return; } void AbilityManagerService::StartSystemUi(const std::string abilityName) { - HILOG_INFO("starting system ui app."); + HILOG_INFO("Starting system ui app."); Want want; want.SetElementName(AbilityConfig::SYSTEM_UI_BUNDLE_NAME, abilityName); - HILOG_INFO("starting system ui: %{public}s.", abilityName.c_str()); - (void)StartAbility(want, -1); + HILOG_INFO("Ability name: %{public}s.", abilityName.c_str()); + (void)StartAbility(want, DEFAULT_INVAL_VALUE); return; } @@ -1058,29 +1113,30 @@ int AbilityManagerService::GenerateAbilityRequest( request.want = want; request.requestCode = requestCode; request.callerToken = callerToken; + request.startSetting = nullptr; auto bms = GetBundleManager(); CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED); bms->QueryAbilityInfo(want, request.abilityInfo); if (request.abilityInfo.name.empty() || request.abilityInfo.bundleName.empty()) { - HILOG_ERROR("failed to get ability info"); + HILOG_ERROR("Failed to get ability info."); return RESOLVE_ABILITY_ERR; } - HILOG_DEBUG("query ability name:%s,", request.abilityInfo.name.c_str()); + HILOG_DEBUG("Query ability name: %{public}s,", request.abilityInfo.name.c_str()); request.appInfo = request.abilityInfo.applicationInfo; if (request.appInfo.name.empty() || request.appInfo.bundleName.empty()) { - HILOG_ERROR("failed to get app info"); + HILOG_ERROR("Failed to get app info"); return RESOLVE_APP_ERR; } - HILOG_DEBUG("query app name:%s,", request.appInfo.name.c_str()); + HILOG_DEBUG("Query app name: %{public}s,", request.appInfo.name.c_str()); return ERR_OK; } int AbilityManagerService::GetAllStackInfo(StackInfo &stackInfo) { - HILOG_DEBUG("get all stack info start"); + HILOG_DEBUG("Get all stack info."); CHECK_POINTER_AND_RETURN(currentStackManager_, ERR_NO_INIT); currentStackManager_->GetAllStackInfo(stackInfo); return ERR_OK; @@ -1088,17 +1144,22 @@ int AbilityManagerService::GetAllStackInfo(StackInfo &stackInfo) int AbilityManagerService::TerminateAbilityResult(const sptr &token, int startId) { - HILOG_INFO("%{public}s, startId:%{public}d", __func__, startId); + HILOG_INFO("Terminate ability result, startId: %{public}d", startId); if (!VerificationToken(token)) { return ERR_INVALID_VALUE; } auto abilityRecord = Token::GetAbilityRecordByToken(token); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + int result = AbilityUtil::JudgeAbilityVisibleControl(abilityRecord->GetAbilityInfo()); + if (result != ERR_OK) { + HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); + return result; + } auto type = abilityRecord->GetAbilityInfo().type; if (type != AppExecFwk::AbilityType::SERVICE) { - HILOG_ERROR("%{public}s failed, target Ability is not Service.", __func__); + HILOG_ERROR("target ability is not service."); return TARGET_ABILITY_NOT_SERVICE; } @@ -1107,17 +1168,17 @@ int AbilityManagerService::TerminateAbilityResult(const sptr &tok int AbilityManagerService::StopServiceAbility(const Want &want) { - HILOG_DEBUG("%{public}s", __func__); + HILOG_DEBUG("Stop service ability."); AbilityRequest abilityRequest; - int result = GenerateAbilityRequest(want, -1, abilityRequest, nullptr); + int result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr); if (result != ERR_OK) { - HILOG_ERROR("%{public}s generate ability request error.", __func__); + HILOG_ERROR("Generate ability request error."); return result; } auto abilityInfo = abilityRequest.abilityInfo; auto type = abilityInfo.type; if (type != AppExecFwk::AbilityType::SERVICE) { - HILOG_ERROR("%{public}s target ability is not service type", __func__); + HILOG_ERROR("Target ability is not service type."); return TARGET_ABILITY_NOT_SERVICE; } return connectManager_->StopServiceAbility(abilityRequest); @@ -1147,7 +1208,7 @@ void AbilityManagerService::OnAbilityDied(std::shared_ptr ability int AbilityManagerService::KillProcess(const std::string &bundleName) { - HILOG_DEBUG("%{public}s, bundleName: %{public}s %{public}d", __func__, bundleName.c_str(), __LINE__); + HILOG_DEBUG("Kill process, bundleName: %{public}s", bundleName.c_str()); int ret = DelayedSingleton::GetInstance()->KillApplication(bundleName); if (ret != ERR_OK) { return KILL_PROCESS_FAILED; @@ -1157,7 +1218,7 @@ int AbilityManagerService::KillProcess(const std::string &bundleName) int AbilityManagerService::UninstallApp(const std::string &bundleName) { - HILOG_DEBUG("%{public}s, bundleName: %{public}s %{public}d", __func__, bundleName.c_str(), __LINE__); + HILOG_DEBUG("Uninstall app, bundleName: %{public}s", bundleName.c_str()); CHECK_POINTER_AND_RETURN(currentStackManager_, ERR_NO_INIT); currentStackManager_->UninstallApp(bundleName); int ret = DelayedSingleton::GetInstance()->KillApplication(bundleName); @@ -1173,7 +1234,7 @@ sptr AbilityManagerService::GetBundleManager() auto bundleObj = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); if (bundleObj == nullptr) { - HILOG_ERROR("failed to get bundle manager service"); + HILOG_ERROR("Failed to get bundle manager service."); return nullptr; } iBundleManager_ = iface_cast(bundleObj); @@ -1220,7 +1281,7 @@ int AbilityManagerService::PreLoadAppDataAbilities(const std::string &bundleName dataAbilityRequest.abilityInfo = *it; HILOG_INFO("App data ability preloading: '%{public}s.%{public}s'...", it->bundleName.c_str(), it->name.c_str()); - auto dataAbility = dataAbilityManager_->Acquire(dataAbilityRequest, false, nullptr); + auto dataAbility = dataAbilityManager_->Acquire(dataAbilityRequest, false, nullptr, false); if (dataAbility == nullptr) { HILOG_ERROR( "Failed to preload data ability '%{public}s.%{public}s'.", it->bundleName.c_str(), it->name.c_str()); @@ -1243,7 +1304,7 @@ bool AbilityManagerService::IsSystemUiApp(const AppExecFwk::AbilityInfo &info) c void AbilityManagerService::HandleLoadTimeOut(int64_t eventId) { - HILOG_DEBUG("%{public}s", __func__); + HILOG_DEBUG("Handle load timeout."); if (systemAppManager_) { systemAppManager_->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, eventId); } @@ -1254,7 +1315,7 @@ void AbilityManagerService::HandleLoadTimeOut(int64_t eventId) void AbilityManagerService::HandleActiveTimeOut(int64_t eventId) { - HILOG_DEBUG("%{public}s", __func__); + HILOG_DEBUG("Handle active timeout."); if (systemAppManager_) { systemAppManager_->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, eventId); } @@ -1265,7 +1326,7 @@ void AbilityManagerService::HandleActiveTimeOut(int64_t eventId) void AbilityManagerService::HandleInactiveTimeOut(int64_t eventId) { - HILOG_DEBUG("%{public}s", __func__); + HILOG_DEBUG("Handle inactive timeout."); if (currentStackManager_) { currentStackManager_->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, eventId); } @@ -1273,7 +1334,7 @@ void AbilityManagerService::HandleInactiveTimeOut(int64_t eventId) bool AbilityManagerService::VerificationToken(const sptr &token) { - HILOG_INFO("%{public}s, called.", __func__); + HILOG_INFO("Verification token."); CHECK_POINTER_RETURN_BOOL(currentStackManager_); CHECK_POINTER_RETURN_BOOL(dataAbilityManager_); CHECK_POINTER_RETURN_BOOL(connectManager_); @@ -1298,13 +1359,76 @@ bool AbilityManagerService::VerificationToken(const sptr &token) return true; } - HILOG_ERROR("%{public}s, Failed to verify token", __func__); + HILOG_ERROR("Failed to verify token."); return false; } +int AbilityManagerService::MoveMissionToFloatingStack(const MissionOption &missionOption) +{ + HILOG_INFO("Move mission to floating stack."); + return currentStackManager_->MoveMissionToFloatingStack(missionOption); +} + +int AbilityManagerService::MoveMissionToSplitScreenStack(const MissionOption &missionOption) +{ + HILOG_INFO("Move mission to split screen stack."); + return currentStackManager_->MoveMissionToSplitScreenStack(missionOption); +} + +int AbilityManagerService::ChangeFocusAbility( + const sptr &lostFocusToken, const sptr &getFocusToken) +{ + HILOG_INFO("Change focus ability."); + CHECK_POINTER_AND_RETURN(lostFocusToken, ERR_INVALID_VALUE); + CHECK_POINTER_AND_RETURN(getFocusToken, ERR_INVALID_VALUE); + CHECK_POINTER_AND_RETURN(currentStackManager_, ERR_INVALID_VALUE); + + if (!VerificationToken(lostFocusToken)) { + return ERR_INVALID_VALUE; + } + + if (!VerificationToken(getFocusToken)) { + return ERR_INVALID_VALUE; + } + + return currentStackManager_->ChangeFocusAbility(lostFocusToken, getFocusToken); +} + +int AbilityManagerService::MinimizeMultiWindow(int missionId) +{ + HILOG_INFO("Minimize multi window."); + return currentStackManager_->MinimizeMultiWindow(missionId); +} + +int AbilityManagerService::MaximizeMultiWindow(int missionId) +{ + HILOG_INFO("Maximize multi window."); + return currentStackManager_->MaximizeMultiWindow(missionId); +} + +int AbilityManagerService::GetFloatingMissions(std::vector &list) +{ + HILOG_INFO("Get floating missions."); + return currentStackManager_->GetFloatingMissions(list); +} + +int AbilityManagerService::CloseMultiWindow(int missionId) +{ + HILOG_INFO("Close multi window."); + CHECK_POINTER_AND_RETURN(currentStackManager_, ERR_INVALID_VALUE); + return currentStackManager_->CloseMultiWindow(missionId); +} + +int AbilityManagerService::SetMissionStackSetting(const StackSetting &stackSetting) +{ + HILOG_INFO("Set mission stack setting."); + currentStackManager_->SetMissionStackSetting(stackSetting); + return ERR_OK; +} + bool AbilityManagerService::IsFirstInMission(const sptr &token) { - HILOG_INFO("%{public}s,%{public}d", __PRETTY_FUNCTION__, __LINE__); + HILOG_INFO("Is first in mission."); CHECK_POINTER_RETURN_BOOL(token); CHECK_POINTER_RETURN_BOOL(currentStackManager_); @@ -1317,20 +1441,20 @@ bool AbilityManagerService::IsFirstInMission(const sptr &token) int AbilityManagerService::CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) { - HILOG_INFO("%{public}s,%{public}d", __PRETTY_FUNCTION__, __LINE__); + HILOG_INFO("Compel verify permission."); return DelayedSingleton::GetInstance()->CompelVerifyPermission(permission, pid, uid, message); } int AbilityManagerService::PowerOff() { - HILOG_INFO("%{public}s,%{public}d", __PRETTY_FUNCTION__, __LINE__); + HILOG_INFO("Power off."); CHECK_POINTER_AND_RETURN(currentStackManager_, ERR_NO_INIT); return currentStackManager_->PowerOff(); } int AbilityManagerService::PowerOn() { - HILOG_INFO("%{public}s,%{public}d", __PRETTY_FUNCTION__, __LINE__); + HILOG_INFO("Power on."); CHECK_POINTER_AND_RETURN(currentStackManager_, ERR_NO_INIT); return currentStackManager_->PowerOn(); } @@ -1367,5 +1491,39 @@ int AbilityManagerService::GetUidByBundleName(std::string bundleName) return iBundleManager_->GetUidByBundleName(bundleName, GetUserId()); } +void AbilityManagerService::RestartAbility(const sptr &token) +{ + HILOG_INFO("%{public}s called", __func__); + CHECK_POINTER(currentStackManager_); + CHECK_POINTER(systemAppManager_); + if (!VerificationToken(token)) { + return; + } + + auto abilityRecord = Token::GetAbilityRecordByToken(token); + CHECK_POINTER(abilityRecord); + + if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) { + systemAppManager_->RestartAbility(abilityRecord); + return; + } + + currentStackManager_->RestartAbility(abilityRecord); +} + +void AbilityManagerService::NotifyBmsAbilityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) +{ + auto bundleManager = GetBundleManager(); + CHECK_POINTER(bundleManager); + bundleManager->NotifyActivityLifeStatus(bundleName, abilityName, launchTime); +} + +int AbilityManagerService::CheckPermission(const std::string &bundleName, const std::string &permission) +{ + auto bundleManager = GetBundleManager(); + CHECK_POINTER_AND_RETURN(bundleManager, INNER_ERR); + return bundleManager->CheckPermission(bundleName, permission); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp index 9281226edb7..e63370368d6 100644 --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -55,6 +55,15 @@ AbilityManagerStub::AbilityManagerStub() requestFuncMap_[DISCONNECT_ABILITY] = &AbilityManagerStub::DisconnectAbilityInner; requestFuncMap_[STOP_SERVICE_ABILITY] = &AbilityManagerStub::StopServiceAbilityInner; requestFuncMap_[DUMP_STATE] = &AbilityManagerStub::DumpStateInner; + requestFuncMap_[START_ABILITY_FOR_SETTINGS] = &AbilityManagerStub::StartAbilityForSettingsInner; + requestFuncMap_[MOVE_MISSION_TO_FLOATING_STACK] = &AbilityManagerStub::MoveMissionToFloatingStackInner; + requestFuncMap_[MOVE_MISSION_TO_SPLITSCREEN_STACK] = &AbilityManagerStub::MoveMissionToSplitScreenStackInner; + requestFuncMap_[CHANGE_FOCUS_ABILITY] = &AbilityManagerStub::ChangeFocusAbilityInner; + requestFuncMap_[MINIMIZE_MULTI_WINDOW] = &AbilityManagerStub::MinimizeMultiWindowInner; + requestFuncMap_[MAXIMIZE_MULTI_WINDOW] = &AbilityManagerStub::MaximizeMultiWindowInner; + requestFuncMap_[GET_FLOATING_MISSIONS] = &AbilityManagerStub::GetFloatingMissionsInner; + requestFuncMap_[CLOSE_MULTI_WINDOW] = &AbilityManagerStub::CloseMultiWindowInner; + requestFuncMap_[SET_STACK_SETTING] = &AbilityManagerStub::SetMissionStackSettingInner; requestFuncMap_[IS_FIRST_IN_MISSION] = &AbilityManagerStub::IsFirstInMissionInner; requestFuncMap_[COMPEL_VERIFY_PERMISSION] = &AbilityManagerStub::CompelVerifyPermissionInner; requestFuncMap_[POWER_OFF] = &AbilityManagerStub::PowerOffInner; @@ -74,6 +83,7 @@ AbilityManagerStub::AbilityManagerStub() requestFuncMap_[GET_PENDING_REQUEST_WANT] = &AbilityManagerStub::GetPendingRequestWantInner; requestFuncMap_[SET_MISSION_INFO] = &AbilityManagerStub::SetMissionDescriptionInfoInner; requestFuncMap_[GET_MISSION_LOCK_MODE_STATE] = &AbilityManagerStub::GetMissionLockModeStateInner; + requestFuncMap_[UPDATE_CONFIGURATION] = &AbilityManagerStub::UpdateConfigurationInner; } AbilityManagerStub::~AbilityManagerStub() @@ -83,7 +93,7 @@ AbilityManagerStub::~AbilityManagerStub() int AbilityManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - HILOG_DEBUG("AbilityManagerStub::OnRemoteRequest, cmd = %d, flags= %d", code, option.GetFlags()); + HILOG_DEBUG("cmd = %{public}d, flags= %{public}d", code, option.GetFlags()); std::u16string descriptor = AbilityManagerStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { @@ -98,7 +108,7 @@ int AbilityManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess return (this->*requestFunc)(data, reply); } } - HILOG_WARN("AbilityManagerStub::OnRemoteRequest, default case, need check."); + HILOG_WARN("default case, need check."); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } @@ -119,7 +129,7 @@ int AbilityManagerStub::TerminateAbilityByCallerInner(MessageParcel &data, Messa { auto callerToken = data.ReadParcelable(); int requestCode = data.ReadInt32(); - int32_t result = TerminateAbility(callerToken, requestCode); + int32_t result = TerminateAbilityByCaller(callerToken, requestCode); reply.WriteInt32(result); return NO_ERROR; } @@ -181,11 +191,11 @@ int AbilityManagerStub::GetAllStackInfoInner(MessageParcel &data, MessageParcel StackInfo stackInfo; int32_t result = GetAllStackInfo(stackInfo); if (!reply.WriteInt32(result)) { - HILOG_ERROR("AbilityManagerStub: GetAllStackInfo result error"); + HILOG_ERROR("GetAllStackInfo result error"); return ERR_INVALID_VALUE; } if (!reply.WriteParcelable(&stackInfo)) { - HILOG_ERROR("AbilityManagerStub: GetAllStackInfo error"); + HILOG_ERROR("GetAllStackInfo error"); return ERR_INVALID_VALUE; } return NO_ERROR; @@ -214,7 +224,7 @@ int AbilityManagerStub::RemoveMissionInner(MessageParcel &data, MessageParcel &r int id = data.ReadInt32(); int32_t result = RemoveMission(id); if (!reply.WriteInt32(result)) { - HILOG_ERROR("AbilityManagerStub: remove mission error"); + HILOG_ERROR("remove mission error."); return ERR_INVALID_VALUE; } return NO_ERROR; @@ -225,7 +235,7 @@ int AbilityManagerStub::RemoveStackInner(MessageParcel &data, MessageParcel &rep int id = data.ReadInt32(); int32_t result = RemoveStack(id); if (!reply.WriteInt32(result)) { - HILOG_ERROR("AbilityManagerStub: remove stack error"); + HILOG_ERROR("remove stack error"); return ERR_INVALID_VALUE; } return NO_ERROR; @@ -245,12 +255,12 @@ int AbilityManagerStub::GetMissionSnapshotInner(MessageParcel &data, MessageParc int32_t missionId = data.ReadInt32(); int32_t result = GetMissionSnapshot(missionId, snapshot); if (!reply.WriteParcelable(&snapshot)) { - HILOG_ERROR("AbilityManagerStub: GetMissionSnapshot error"); + HILOG_ERROR("GetMissionSnapshot error"); return ERR_INVALID_VALUE; } if (!reply.WriteInt32(result)) { - HILOG_ERROR("AbilityManagerStub: GetMissionSnapshot result error"); + HILOG_ERROR("GetMissionSnapshot result error"); return ERR_INVALID_VALUE; } return NO_ERROR; @@ -286,7 +296,7 @@ int AbilityManagerStub::MoveMissionToTopInner(MessageParcel &data, MessageParcel int32_t id = data.ReadInt32(); int result = MoveMissionToTop(id); if (!reply.WriteInt32(result)) { - HILOG_ERROR("AbilityManagerStub: move mission to top error"); + HILOG_ERROR("move mission to top error"); return ERR_INVALID_VALUE; } return NO_ERROR; @@ -298,7 +308,7 @@ int AbilityManagerStub::MoveMissionToEndInner(MessageParcel &data, MessageParcel auto nonFirst = data.ReadBool(); int result = MoveMissionToEnd(token, nonFirst); if (!reply.WriteInt32(result)) { - HILOG_ERROR("AbilityManagerStub: move mission to top error"); + HILOG_ERROR("move mission to top error"); return ERR_INVALID_VALUE; } return NO_ERROR; @@ -309,7 +319,7 @@ int AbilityManagerStub::KillProcessInner(MessageParcel &data, MessageParcel &rep std::string bundleName = Str16ToStr8(data.ReadString16()); int result = KillProcess(bundleName); if (!reply.WriteInt32(result)) { - HILOG_ERROR("AbilityManagerStub: remove stack error"); + HILOG_ERROR("remove stack error"); return ERR_INVALID_VALUE; } return NO_ERROR; @@ -320,7 +330,7 @@ int AbilityManagerStub::UninstallAppInner(MessageParcel &data, MessageParcel &re std::string bundleName = Str16ToStr8(data.ReadString16()); int result = UninstallApp(bundleName); if (!reply.WriteInt32(result)) { - HILOG_ERROR("AbilityManagerStub: remove stack error"); + HILOG_ERROR("remove stack error"); return ERR_INVALID_VALUE; } return NO_ERROR; @@ -330,7 +340,7 @@ int AbilityManagerStub::StartAbilityInner(MessageParcel &data, MessageParcel &re { Want *want = data.ReadParcelable(); if (want == nullptr) { - HILOG_ERROR("AbilityManagerStub: want is nullptr"); + HILOG_ERROR("want is nullptr"); return ERR_INVALID_VALUE; } int requestCode = data.ReadInt32(); @@ -344,7 +354,7 @@ int AbilityManagerStub::StartAbilityAddCallerInner(MessageParcel &data, MessageP { Want *want = data.ReadParcelable(); if (want == nullptr) { - HILOG_ERROR("AbilityManagerStub: want is nullptr"); + HILOG_ERROR("want is nullptr"); return ERR_INVALID_VALUE; } auto callerToken = data.ReadParcelable(); @@ -359,7 +369,7 @@ int AbilityManagerStub::ConnectAbilityInner(MessageParcel &data, MessageParcel & { Want *want = data.ReadParcelable(); if (want == nullptr) { - HILOG_ERROR("AbilityManagerStub: want is nullptr"); + HILOG_ERROR("want is nullptr"); return ERR_INVALID_VALUE; } auto callback = iface_cast(data.ReadParcelable()); @@ -383,7 +393,7 @@ int AbilityManagerStub::StopServiceAbilityInner(MessageParcel &data, MessageParc { Want *want = data.ReadParcelable(); if (want == nullptr) { - HILOG_ERROR("AbilityManagerStub: want is nullptr"); + HILOG_ERROR("want is nullptr"); return ERR_INVALID_VALUE; } int32_t result = StopServiceAbility(*want); @@ -409,12 +419,118 @@ int AbilityManagerStub::DumpStateInner(MessageParcel &data, MessageParcel &reply return NO_ERROR; } +int AbilityManagerStub::StartAbilityForSettingsInner(MessageParcel &data, MessageParcel &reply) +{ + Want *want = data.ReadParcelable(); + if (want == nullptr) { + HILOG_ERROR("want is nullptr"); + return ERR_INVALID_VALUE; + } + AbilityStartSetting *abilityStartSetting = data.ReadParcelable(); + auto callerToken = data.ReadParcelable(); + int requestCode = data.ReadInt32(); + int32_t result = StartAbility(*want, *abilityStartSetting, callerToken, requestCode); + reply.WriteInt32(result); + delete want; + delete abilityStartSetting; + return NO_ERROR; +} + +int AbilityManagerStub::MoveMissionToFloatingStackInner(MessageParcel &data, MessageParcel &reply) +{ + MissionOption *missionOption = data.ReadParcelable(); + if (missionOption == nullptr) { + HILOG_ERROR("missionOption is nullptr"); + return ERR_INVALID_VALUE; + } + + auto result = MoveMissionToFloatingStack(*missionOption); + reply.WriteInt32(result); + delete missionOption; + return NO_ERROR; +} + +int AbilityManagerStub::MoveMissionToSplitScreenStackInner(MessageParcel &data, MessageParcel &reply) +{ + MissionOption *missionOption = data.ReadParcelable(); + if (missionOption == nullptr) { + HILOG_ERROR("missionOption is nullptr"); + return ERR_INVALID_VALUE; + } + auto result = MoveMissionToSplitScreenStack(*missionOption); + reply.WriteInt32(result); + delete missionOption; + return NO_ERROR; +} + +int AbilityManagerStub::ChangeFocusAbilityInner(MessageParcel &data, MessageParcel &reply) +{ + auto loseToken = data.ReadParcelable(); + auto getToken = data.ReadParcelable(); + auto result = ChangeFocusAbility(loseToken, getToken); + reply.WriteInt32(result); + return NO_ERROR; +} + +int AbilityManagerStub::MinimizeMultiWindowInner(MessageParcel &data, MessageParcel &reply) +{ + auto missionId = data.ReadInt32(); + auto result = MinimizeMultiWindow(missionId); + reply.WriteInt32(result); + return NO_ERROR; +} + +int AbilityManagerStub::MaximizeMultiWindowInner(MessageParcel &data, MessageParcel &reply) +{ + auto missionId = data.ReadInt32(); + auto result = MaximizeMultiWindow(missionId); + reply.WriteInt32(result); + return NO_ERROR; +} + +int AbilityManagerStub::GetFloatingMissionsInner(MessageParcel &data, MessageParcel &reply) +{ + std::vector missionInfos; + auto result = GetFloatingMissions(missionInfos); + reply.WriteInt32(missionInfos.size()); + for (auto &it : missionInfos) { + if (!reply.WriteParcelable(&it)) { + return ERR_INVALID_VALUE; + } + } + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +int AbilityManagerStub::CloseMultiWindowInner(MessageParcel &data, MessageParcel &reply) +{ + auto missionId = data.ReadInt32(); + auto result = CloseMultiWindow(missionId); + reply.WriteInt32(result); + return NO_ERROR; +} + +int AbilityManagerStub::SetMissionStackSettingInner(MessageParcel &data, MessageParcel &reply) +{ + StackSetting *stackSetting = data.ReadParcelable(); + if (stackSetting == nullptr) { + HILOG_ERROR("stackSetting is nullptr"); + return ERR_INVALID_VALUE; + } + auto result = SetMissionStackSetting(*stackSetting); + reply.WriteInt32(result); + delete stackSetting; + return NO_ERROR; +} + int AbilityManagerStub::IsFirstInMissionInner(MessageParcel &data, MessageParcel &reply) { auto token = data.ReadParcelable(); auto result = IsFirstInMission(token); if (!reply.WriteBool(result)) { - HILOG_ERROR("%{public}s: error", __func__); + HILOG_ERROR("reply write failed."); return ERR_INVALID_VALUE; } return NO_ERROR; @@ -471,7 +587,7 @@ int AbilityManagerStub::UnlockMissionInner(MessageParcel &data, MessageParcel &r int AbilityManagerStub::SetMissionDescriptionInfoInner(MessageParcel &data, MessageParcel &reply) { auto token = data.ReadParcelable(); - auto missionInfo = data.ReadParcelable(); + std::unique_ptr missionInfo(data.ReadParcelable()); int result = SetMissionDescriptionInfo(token, *missionInfo); if (!reply.WriteInt32(result)) { HILOG_ERROR("AbilityManagerStub: set mission info failed."); @@ -490,13 +606,26 @@ int AbilityManagerStub::GetMissionLockModeStateInner(MessageParcel &data, Messag return NO_ERROR; } -int AbilityManagerStub::GetWantSenderInner(MessageParcel &data, MessageParcel &reply) +int AbilityManagerStub::UpdateConfigurationInner(MessageParcel &data, MessageParcel &reply) { - HILOG_INFO("%{public}s:begin.", __func__); + std::unique_ptr config(data.ReadParcelable()); + if (config == nullptr) { + HILOG_ERROR("AbilityManagerStub: config is nullptr"); + return ERR_INVALID_VALUE; + } + int result = UpdateConfiguration(*config); + if (!reply.WriteInt32(result)) { + HILOG_ERROR("AbilityManagerStub: update configuration failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} +int AbilityManagerStub::GetWantSenderInner(MessageParcel &data, MessageParcel &reply) +{ WantSenderInfo *wantSenderInfo = data.ReadParcelable(); if (wantSenderInfo == nullptr) { - HILOG_ERROR("AbilityManagerStub: wantSenderInfo is nullptr"); + HILOG_ERROR("wantSenderInfo is nullptr"); return ERR_INVALID_VALUE; } sptr callerToken = data.ReadParcelable(); @@ -510,16 +639,14 @@ int AbilityManagerStub::GetWantSenderInner(MessageParcel &data, MessageParcel &r int AbilityManagerStub::SendWantSenderInner(MessageParcel &data, MessageParcel &reply) { - HILOG_INFO("%{public}s:begin.", __func__); - sptr wantSender = iface_cast(data.ReadParcelable()); if (wantSender == nullptr) { - HILOG_ERROR("AbilityManagerStub: wantSender is nullptr"); + HILOG_ERROR("wantSender is nullptr"); return ERR_INVALID_VALUE; } SenderInfo *senderInfo = data.ReadParcelable(); if (senderInfo == nullptr) { - HILOG_ERROR("AbilityManagerStub: senderInfo is nullptr"); + HILOG_ERROR("senderInfo is nullptr"); return ERR_INVALID_VALUE; } int32_t result = SendWantSender(wantSender, *senderInfo); @@ -529,11 +656,9 @@ int AbilityManagerStub::SendWantSenderInner(MessageParcel &data, MessageParcel & int AbilityManagerStub::CancelWantSenderInner(MessageParcel &data, MessageParcel &reply) { - HILOG_INFO("%{public}s:begin.", __func__); - sptr wantSender = iface_cast(data.ReadParcelable()); if (wantSender == nullptr) { - HILOG_ERROR("AbilityManagerStub: wantSender is nullptr"); + HILOG_ERROR("wantSender is nullptr"); return ERR_INVALID_VALUE; } CancelWantSender(wantSender); @@ -542,11 +667,9 @@ int AbilityManagerStub::CancelWantSenderInner(MessageParcel &data, MessageParcel int AbilityManagerStub::GetPendingWantUidInner(MessageParcel &data, MessageParcel &reply) { - HILOG_INFO("%{public}s:begin.", __func__); - sptr wantSender = iface_cast(data.ReadParcelable()); if (wantSender == nullptr) { - HILOG_ERROR("AbilityManagerStub: wantSender is nullptr"); + HILOG_ERROR("wantSender is nullptr"); return ERR_INVALID_VALUE; } @@ -557,11 +680,9 @@ int AbilityManagerStub::GetPendingWantUidInner(MessageParcel &data, MessageParce int AbilityManagerStub::GetPendingWantUserIdInner(MessageParcel &data, MessageParcel &reply) { - HILOG_INFO("%{public}s:begin.", __func__); - sptr wantSender = iface_cast(data.ReadParcelable()); if (wantSender == nullptr) { - HILOG_ERROR("AbilityManagerStub: wantSender is nullptr"); + HILOG_ERROR("wantSender is nullptr"); return ERR_INVALID_VALUE; } @@ -572,11 +693,9 @@ int AbilityManagerStub::GetPendingWantUserIdInner(MessageParcel &data, MessagePa int AbilityManagerStub::GetPendingWantBundleNameInner(MessageParcel &data, MessageParcel &reply) { - HILOG_INFO("%{public}s:begin.", __func__); - sptr wantSender = iface_cast(data.ReadParcelable()); if (wantSender == nullptr) { - HILOG_ERROR("AbilityManagerStub: wantSender is nullptr"); + HILOG_ERROR("wantSender is nullptr"); return ERR_INVALID_VALUE; } @@ -587,11 +706,9 @@ int AbilityManagerStub::GetPendingWantBundleNameInner(MessageParcel &data, Messa int AbilityManagerStub::GetPendingWantCodeInner(MessageParcel &data, MessageParcel &reply) { - HILOG_INFO("%{public}s:begin.", __func__); - sptr wantSender = iface_cast(data.ReadParcelable()); if (wantSender == nullptr) { - HILOG_ERROR("AbilityManagerStub: wantSender is nullptr"); + HILOG_ERROR("wantSender is nullptr"); return ERR_INVALID_VALUE; } @@ -602,11 +719,9 @@ int AbilityManagerStub::GetPendingWantCodeInner(MessageParcel &data, MessageParc int AbilityManagerStub::GetPendingWantTypeInner(MessageParcel &data, MessageParcel &reply) { - HILOG_INFO("%{public}s:begin.", __func__); - sptr wantSender = iface_cast(data.ReadParcelable()); if (wantSender == nullptr) { - HILOG_ERROR("AbilityManagerStub: wantSender is nullptr"); + HILOG_ERROR("wantSender is nullptr"); return ERR_INVALID_VALUE; } @@ -617,16 +732,14 @@ int AbilityManagerStub::GetPendingWantTypeInner(MessageParcel &data, MessageParc int AbilityManagerStub::RegisterCancelListenerInner(MessageParcel &data, MessageParcel &reply) { - HILOG_INFO("%{public}s:begin.", __func__); - sptr sender = iface_cast(data.ReadParcelable()); if (sender == nullptr) { - HILOG_ERROR("AbilityManagerStub: sender is nullptr"); + HILOG_ERROR("sender is nullptr"); return ERR_INVALID_VALUE; } sptr receiver = iface_cast(data.ReadParcelable()); if (receiver == nullptr) { - HILOG_ERROR("AbilityManagerStub: receiver is nullptr"); + HILOG_ERROR("receiver is nullptr"); return ERR_INVALID_VALUE; } RegisterCancelListener(sender, receiver); @@ -635,16 +748,14 @@ int AbilityManagerStub::RegisterCancelListenerInner(MessageParcel &data, Message int AbilityManagerStub::UnregisterCancelListenerInner(MessageParcel &data, MessageParcel &reply) { - HILOG_INFO("%{public}s:begin.", __func__); - sptr sender = iface_cast(data.ReadParcelable()); if (sender == nullptr) { - HILOG_ERROR("AbilityManagerStub: sender is nullptr"); + HILOG_ERROR("sender is nullptr"); return ERR_INVALID_VALUE; } sptr receiver = iface_cast(data.ReadParcelable()); if (receiver == nullptr) { - HILOG_ERROR("AbilityManagerStub: receiver is nullptr"); + HILOG_ERROR("receiver is nullptr"); return ERR_INVALID_VALUE; } UnregisterCancelListener(sender, receiver); @@ -653,23 +764,20 @@ int AbilityManagerStub::UnregisterCancelListenerInner(MessageParcel &data, Messa int AbilityManagerStub::GetPendingRequestWantInner(MessageParcel &data, MessageParcel &reply) { - HILOG_INFO("%{public}s:begin.", __func__); - sptr wantSender = iface_cast(data.ReadParcelable()); if (wantSender == nullptr) { - HILOG_ERROR("AbilityManagerStub: wantSender is nullptr"); + HILOG_ERROR("wantSender is nullptr"); return ERR_INVALID_VALUE; } std::shared_ptr want(data.ReadParcelable()); int32_t result = GetPendingRequestWant(wantSender, want); if (result != NO_ERROR) { - HILOG_ERROR("AbilityManagerStub: GetPendingRequestWant is failed"); + HILOG_ERROR("GetPendingRequestWant is failed"); return ERR_INVALID_VALUE; } reply.WriteParcelable(want.get()); return NO_ERROR; } - } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_record.cpp b/services/abilitymgr/src/ability_record.cpp index 1240817fadd..2f5a4f8c7df 100644 --- a/services/abilitymgr/src/ability_record.cpp +++ b/services/abilitymgr/src/ability_record.cpp @@ -40,6 +40,15 @@ const std::map AbilityRecord::stateToStrMap = { std::map::value_type(MOVING_BACKGROUND, "MOVING_BACKGROUND"), std::map::value_type(TERMINATING, "TERMINATING"), }; +const std::map AbilityRecord::appStateToStrMap_ = { + std::map::value_type(AppState::BEGIN, "BEGIN"), + std::map::value_type(AppState::READY, "READY"), + std::map::value_type(AppState::FOREGROUND, "FOREGROUND"), + std::map::value_type(AppState::BACKGROUND, "BACKGROUND"), + std::map::value_type(AppState::SUSPENDED, "SUSPENDED"), + std::map::value_type(AppState::TERMINATED, "TERMINATED"), + std::map::value_type(AppState::END, "END"), +}; const std::map AbilityRecord::convertStateMap = { std::map::value_type(ABILITY_STATE_INITIAL, INITIAL), std::map::value_type(ABILITY_STATE_INACTIVE, INACTIVE), @@ -92,6 +101,10 @@ std::shared_ptr AbilityRecord::CreateAbilityRecord(const AbilityR HILOG_ERROR("failed to init new ability record"); return nullptr; } + if (abilityRequest.startSetting != nullptr) { + HILOG_INFO("abilityRequest.startSetting..."); + abilityRecord->SetStartSetting(abilityRequest.startSetting); + } return abilityRecord; } @@ -112,7 +125,7 @@ bool AbilityRecord::Init() int AbilityRecord::LoadAbility() { HILOG_INFO("%s", __func__); - startTime_ = SystemTimeMillis(); + startTime_ = AbilityUtil::SystemTimeMillis(); CHECK_POINTER_AND_RETURN(token_, ERR_INVALID_VALUE); std::string appName = applicationInfo_.name; if (appName.empty()) { @@ -121,7 +134,7 @@ int AbilityRecord::LoadAbility() } if (abilityInfo_.type != AppExecFwk::AbilityType::DATA) { - if (isKernalSystemAbility) { + if (isKernalSystemAbility_) { SendEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, AbilityManagerService::SYSTEM_UI_TIMEOUT); } else { SendEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, AbilityManagerService::LOAD_TIMEOUT); @@ -137,7 +150,7 @@ int AbilityRecord::LoadAbility() int AbilityRecord::TerminateAbility() { - HILOG_INFO("%s", __func__); + HILOG_INFO("%{public}s", __func__); return DelayedSingleton::GetInstance()->TerminateAbility(token_); } @@ -154,11 +167,24 @@ void AbilityRecord::SetMissionStackId(const int stackId) lifeCycleStateInfo_.stackId = stackId; } +int AbilityRecord::GetMissionStackId() const +{ + return lifeCycleStateInfo_.stackId; +} + std::shared_ptr AbilityRecord::GetMissionRecord() const { return missionRecord_.lock(); } +int AbilityRecord::GetMissionRecordId() const +{ + if (missionRecord_.lock()) { + return missionRecord_.lock()->GetMissionRecordId(); + } + return DEFAULT_INVAL_VALUE; +} + const AppExecFwk::AbilityInfo &AbilityRecord::GetAbilityInfo() const { return abilityInfo_; @@ -181,7 +207,7 @@ void AbilityRecord::SetAbilityState(AbilityState state) void AbilityRecord::SetScheduler(const sptr &scheduler) { - HILOG_INFO("%s", __func__); + HILOG_INFO("%{public}s", __func__); CHECK_POINTER(lifecycleDeal_); if (scheduler != nullptr) { if (scheduler_ != nullptr && schedulerDeathRecipient_ != nullptr) { @@ -204,6 +230,15 @@ void AbilityRecord::SetScheduler(const sptr &scheduler) } else { HILOG_ERROR("scheduler is nullptr"); isReady_ = false; + isWindowAttached_ = false; + SetIsNewWant(false); + if (scheduler_ != nullptr && schedulerDeathRecipient_ != nullptr) { + auto schedulerObject = scheduler_->AsObject(); + if (schedulerObject != nullptr) { + schedulerObject->RemoveDeathRecipient(schedulerDeathRecipient_); + } + } + scheduler_ = scheduler; } } @@ -276,6 +311,7 @@ bool AbilityRecord::IsForceTerminate() const { return isForceTerminate_; } + void AbilityRecord::SetForceTerminate(bool flag) { isForceTerminate_ = flag; @@ -298,17 +334,17 @@ void AbilityRecord::SetIsNewWant(bool isNewWant) bool AbilityRecord::IsCreateByConnect() const { - return isCreateByConnect; + return isCreateByConnect_; } void AbilityRecord::SetCreateByConnectMode() { - isCreateByConnect = true; + isCreateByConnect_ = true; } void AbilityRecord::Activate() { - HILOG_INFO("%{public}s", __func__); + HILOG_INFO("Activate."); CHECK_POINTER(lifecycleDeal_); SendEvent(AbilityManagerService::ACTIVE_TIMEOUT_MSG, AbilityManagerService::ACTIVE_TIMEOUT); @@ -328,6 +364,24 @@ void AbilityRecord::Activate() } } +void AbilityRecord::ProcessActivateInMoving() +{ + HILOG_DEBUG("ProcessActivateInMovingState."); + if (!IsAbilityState(AbilityState::ACTIVE) && !IsAbilityState(AbilityState::ACTIVATING)) { + SetInMovingState(true); + ProcessActivate(); + } +} + +void AbilityRecord::ProcessInactivateInMoving() +{ + HILOG_DEBUG("ProcessActivateInMovingState."); + if (IsAbilityState(AbilityState::ACTIVE) || IsAbilityState(AbilityState::ACTIVATING)) { + SetInMovingState(true); + ProcessInactivate(); + } +} + void AbilityRecord::ProcessActivate() { std::string element = GetWant().GetElement().GetURI(); @@ -335,8 +389,12 @@ void AbilityRecord::ProcessActivate() if (isReady_) { if (IsAbilityState(AbilityState::BACKGROUND)) { - HILOG_DEBUG("MoveToForground, %{public}s", element.c_str()); - DelayedSingleton::GetInstance()->MoveToForground(token_); + // background to activte state + if (!ProcessConfigurationChange()) { + // true: restartability, false: continue activate + HILOG_DEBUG("MoveToForground, %{public}s", element.c_str()); + DelayedSingleton::GetInstance()->MoveToForground(token_); + } } else { HILOG_DEBUG("Activate %{public}s", element.c_str()); Activate(); @@ -353,8 +411,12 @@ void AbilityRecord::ProcessInactivate() if (isReady_) { if (IsAbilityState(AbilityState::BACKGROUND)) { - HILOG_DEBUG("MoveToForground, %{public}s", element.c_str()); - DelayedSingleton::GetInstance()->MoveToForground(token_); + // background to activte state + if (!ProcessConfigurationChange()) { + // true: restartability, false: continue activate + HILOG_DEBUG("MoveToForground, %{public}s", element.c_str()); + DelayedSingleton::GetInstance()->MoveToForground(token_); + } } else if (!IsAbilityState(AbilityState::INACTIVE) && !IsAbilityState(AbilityState::INACTIVATING)) { HILOG_DEBUG("Inactivate %{public}s", element.c_str()); Inactivate(); @@ -366,7 +428,7 @@ void AbilityRecord::ProcessInactivate() void AbilityRecord::Inactivate() { - HILOG_INFO("%{public}s", __func__); + HILOG_INFO("Inactivate."); CHECK_POINTER(lifecycleDeal_); SendEvent(AbilityManagerService::INACTIVE_TIMEOUT_MSG, AbilityManagerService::INACTIVE_TIMEOUT); @@ -379,7 +441,7 @@ void AbilityRecord::Inactivate() void AbilityRecord::MoveToBackground(const Closure &task) { - HILOG_INFO("%{public}s", __func__); + HILOG_INFO("Move to background."); CHECK_POINTER(lifecycleDeal_); auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); if (handler == nullptr || task == nullptr) { @@ -392,6 +454,12 @@ void AbilityRecord::MoveToBackground(const Closure &task) // eventId_ is a unique id of the task. handler->PostTask(task, std::to_string(eventId_), AbilityManagerService::BACKGROUND_TIMEOUT); } + + if (!IsTerminating() || IsRestarting()) { + // schedule save ability state before moving to background. + SaveAbilityState(); + } + // schedule background after updating AbilityState and sending timeout message to avoid ability async callback // earlier than above actions. currentState_ = AbilityState::MOVING_BACKGROUND; @@ -400,7 +468,7 @@ void AbilityRecord::MoveToBackground(const Closure &task) void AbilityRecord::Terminate(const Closure &task) { - HILOG_INFO("terminate ability : %{public}s", __func__); + HILOG_INFO("Terminate ability."); CHECK_POINTER(lifecycleDeal_); auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); if (handler == nullptr || task == nullptr) { @@ -421,21 +489,21 @@ void AbilityRecord::Terminate(const Closure &task) void AbilityRecord::ConnectAbility() { - HILOG_INFO("%{public}s", __func__); + HILOG_INFO("Connect ability."); CHECK_POINTER(lifecycleDeal_); lifecycleDeal_->ConnectAbility(want_); } void AbilityRecord::DisconnectAbility() { - HILOG_INFO("%{public}s", __func__); + HILOG_INFO("Disconnect ability."); CHECK_POINTER(lifecycleDeal_); lifecycleDeal_->DisconnectAbility(want_); } void AbilityRecord::CommandAbility() { - HILOG_INFO("%{public}s", __func__); + HILOG_INFO("Command ability."); CHECK_POINTER(lifecycleDeal_); lifecycleDeal_->CommandAbility(want_, false, startId_); } @@ -443,11 +511,24 @@ void AbilityRecord::CommandAbility() void AbilityRecord::SaveAbilityState() { HILOG_INFO("%{public}s", __func__); + CHECK_POINTER(lifecycleDeal_); + lifecycleDeal_->SaveAbilityState(stateDatas_); } void AbilityRecord::RestoreAbilityState() { HILOG_INFO("%{public}s", __func__); + CHECK_POINTER(lifecycleDeal_); + lifecycleDeal_->RestoreAbilityState(stateDatas_); + stateDatas_.Clear(); + isRestarting_ = false; +} + +void AbilityRecord::TopActiveAbilityChanged(bool flag) +{ + HILOG_INFO("%{public}s called, isTop: %{public}d", __func__, flag); + CHECK_POINTER(scheduler_); + scheduler_->NotifyTopActiveAbilityChanged(flag); } void AbilityRecord::SetWant(const Want &want) @@ -477,7 +558,7 @@ std::shared_ptr AbilityRecord::GetResult() const void AbilityRecord::SendResult() { - HILOG_INFO("%{public}s", __func__); + HILOG_INFO("Send result."); CHECK_POINTER(scheduler_); CHECK_POINTER(result_); scheduler_->SendResult(result_->requestCode_, result_->resultCode_, result_->resultWant_); @@ -512,12 +593,11 @@ void AbilityRecord::AddConnectRecordToList(const std::shared_ptr &callerToken, int requestCode) { - HILOG_INFO("%{public}s", __func__); + HILOG_INFO("Add caller record."); auto abilityRecord = Token::GetAbilityRecordByToken(callerToken); CHECK_POINTER(abilityRecord); @@ -554,8 +633,7 @@ void AbilityRecord::AddCallerRecord(const sptr &callerToken, int lifeCycleStateInfo_.caller.deviceId = abilityRecord->GetAbilityInfo().deviceId; lifeCycleStateInfo_.caller.bundleName = abilityRecord->GetAbilityInfo().bundleName; lifeCycleStateInfo_.caller.abilityName = abilityRecord->GetAbilityInfo().name; - HILOG_INFO("%{public}s, caller %{public}s, %{public}s, %{public}s", - __func__, + HILOG_INFO("caller %{public}s, %{public}s, %{public}s", abilityRecord->GetAbilityInfo().deviceId.c_str(), abilityRecord->GetAbilityInfo().bundleName.c_str(), abilityRecord->GetAbilityInfo().name.c_str()); @@ -569,6 +647,7 @@ std::list> AbilityRecord::GetCallerRecordList() co void AbilityRecord::AddWindowInfo(int windowToken) { windowInfo_ = std::make_shared(windowToken); + isWindowAttached_ = true; } void AbilityRecord::RemoveWindowInfo() @@ -615,15 +694,6 @@ std::shared_ptr AbilityRecord::GetDisconnectingRecord() const return (connect != connRecordList_.end()) ? *connect : nullptr; } -int64_t AbilityRecord::SystemTimeMillis() -{ - struct timespec t; - t.tv_sec = 0; - t.tv_nsec = 0; - clock_gettime(CLOCK_MONOTONIC, &t); - return (int64_t)((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS; -} - void AbilityRecord::GetAbilityTypeString(std::string &typeStr) { AppExecFwk::AbilityType type = GetAbilityInfo().type; @@ -657,13 +727,22 @@ std::string AbilityRecord::ConvertAbilityState(const AbilityState &state) return "INVALIDSTATE"; } +std::string AbilityRecord::ConvertAppState(const AppState &state) +{ + auto it = appStateToStrMap_.find(state); + if (it != appStateToStrMap_.end()) { + return it->second; + } + return "INVALIDSTATE"; +} + int AbilityRecord::ConvertLifeCycleToAbilityState(const AbilityLifeCycleState &state) { auto it = convertStateMap.find(state); if (it != convertStateMap.end()) { return it->second; } - return -1; + return DEFAULT_INVAL_VALUE; } void AbilityRecord::Dump(std::vector &info) @@ -704,6 +783,8 @@ void AbilityRecord::Dump(std::vector &info) dumpInfo = " state #" + AbilityRecord::ConvertAbilityState(GetAbilityState()) + " start time [" + std::to_string(startTime_) + "]"; info.push_back(dumpInfo); + dumpInfo = " app state #" + AbilityRecord::ConvertAppState(appState_); + info.push_back(dumpInfo); dumpInfo = " ready #" + std::to_string(isReady_) + " window attached #" + std::to_string(isWindowAttached_) + " launcher #" + std::to_string(isLauncherAbility_); info.push_back(dumpInfo); @@ -712,7 +793,7 @@ void AbilityRecord::Dump(std::vector &info) void AbilityRecord::SetStartTime() { if (startTime_ == 0) { - startTime_ = SystemTimeMillis(); + startTime_ = AbilityUtil::SystemTimeMillis(); } } @@ -729,6 +810,7 @@ void AbilityRecord::DumpService(std::vector &info) const info.emplace_back(" main name [" + GetAbilityInfo().name + "]"); info.emplace_back(" bundle name [" + GetAbilityInfo().bundleName + "]"); info.emplace_back(" ability type [SERVICE]"); + info.emplace_back(" app state #" + AbilityRecord::ConvertAppState(appState_)); info.emplace_back(" Connections: " + std::to_string(connRecordList_.size())); for (auto &&conn : connRecordList_) { @@ -767,7 +849,7 @@ void AbilityRecord::GetAbilityRecordInfo(AbilityRecordInfo &recordInfo) void AbilityRecord::OnSchedulerDied(const wptr &remote) { - HILOG_DEBUG("%{public}s(%{public}d)", __PRETTY_FUNCTION__, __LINE__); + HILOG_DEBUG("On scheduler died."); CHECK_POINTER(scheduler_); auto object = remote.promote(); @@ -788,6 +870,7 @@ void AbilityRecord::OnSchedulerDied(const wptr &remote) scheduler_.clear(); CHECK_POINTER(lifecycleDeal_); lifecycleDeal_->SetScheduler(nullptr); + isWindowAttached_ = false; auto abilityManagerService = DelayedSingleton::GetInstance(); CHECK_POINTER(abilityManagerService); @@ -823,22 +906,22 @@ int AbilityRecord::GetStartId() const void AbilityRecord::SetIsUninstallAbility() { - isUninstall = true; + isUninstall_ = true; } bool AbilityRecord::IsUninstallAbility() const { - return isUninstall; + return isUninstall_; } void AbilityRecord::SetKernalSystemAbility() { - isKernalSystemAbility = true; + isKernalSystemAbility_ = true; } bool AbilityRecord::IsKernalSystemAbility() const { - return isKernalSystemAbility; + return isKernalSystemAbility_; } void AbilityRecord::SetLauncherRoot() @@ -865,6 +948,54 @@ void AbilityRecord::SendEvent(uint32_t msg, uint32_t timeOut) handler->SendEvent(msg, eventId_, timeOut); } +bool AbilityRecord::SupportMultWindow() const +{ + // LauncherAbility don't support multi window display. + if (isLauncherAbility_) { + return false; + } + + // return (ERR_OK == DelayedSingleton::GetInstance()->CheckPermission( + // abilityInfo_.bundleName, AbilityConfig::FLOATING_WINDOW_PERMISSION)); + return true; +} + +void AbilityRecord::NotifyMultiWinModeChanged(const AbilityWindowConfiguration &winModeKey, bool flag) +{ + HILOG_INFO("Notify multi window mode changed."); + CHECK_POINTER(scheduler_); + scheduler_->NotifyMultiWinModeChanged(static_cast(winModeKey), flag); +} + +void AbilityRecord::SetInMovingState(bool isMoving) +{ + isInMovingState_ = isMoving; +} + +bool AbilityRecord::GetInMovingState() const +{ + return isInMovingState_; +} + +bool AbilityRecord::IsToEnd() const +{ + return isToEnd_; +} +void AbilityRecord::SetToEnd(bool isToEnd) +{ + isToEnd_ = isToEnd; +} + +void AbilityRecord::SetStartSetting(const std::shared_ptr &setting) +{ + lifeCycleStateInfo_.setting = setting; +} + +std::shared_ptr AbilityRecord::GetStartSetting() const +{ + return lifeCycleStateInfo_.setting; +} + void AbilityRecord::SetPowerState(const bool isPower) { isPowerState_ = isPower; @@ -874,5 +1005,108 @@ bool AbilityRecord::GetPowerState() const { return isPowerState_; } + +void AbilityRecord::SetRestarting(const bool isRestart) +{ + isRestarting_ = isRestart; +} + +bool AbilityRecord::IsRestarting() const +{ + return isRestarting_; +} + +void AbilityRecord::SetAppState(const AppState &state) +{ + appState_ = state; +} + +AppState AbilityRecord::GetAppState() const +{ + return appState_; +} + +bool AbilityRecord::OnConfigurationChanged(const DummyConfiguration &config, unsigned int configChanges) +{ + HILOG_INFO("%{public}s called", __FUNCTION__); + + HILOG_INFO("targetConfig: %{public}s, changeTypes:%{public}d", config.GetName().c_str(), configChanges); + + unsigned int focusChanges = GetIntConfigChanges(); + bool isFocused = ((focusChanges & configChanges) > 0); + if (isFocused) { + CHECK_POINTER_RETURN_BOOL(lifecycleDeal_); + if (isReady_) { + lifecycleDeal_->UpdateConfiguration(config); + return false; + } + } + + auto abilityManagerService = DelayedSingleton::GetInstance(); + CHECK_POINTER_RETURN_BOOL(abilityManagerService); + auto handler = abilityManagerService->GetEventHandler(); + g_abilityRecordEventId_++; + eventId_ = g_abilityRecordEventId_; + + CHECK_POINTER_RETURN_BOOL(handler); + auto task = [abilityManagerService, token = token_]() { abilityManagerService->RestartAbility(token); }; + // eventId_ is a unique id of the task. + handler->PostTask(task, std::to_string(eventId_), AbilityManagerService::RESTART_ABILITY_TIMEOUT); + return true; +} + +std::shared_ptr AbilityRecord::GetParent() +{ + return missionRecord_.lock(); +} + +unsigned int AbilityRecord::GetChildSize() +{ + return 0; +} + +std::shared_ptr AbilityRecord::FindChild(unsigned int index) +{ + return nullptr; +} + +unsigned int AbilityRecord::GetIntConfigChanges() +{ + auto changes = abilityInfo_.configChanges; + unsigned int intChangs = CHANGE_CONFIG_NONE; + + for (auto item : changes) { + HILOG_INFO("configChange: %{public}s", item.c_str()); + if (item == "locale") { + intChangs |= CHANGE_CONFIG_LOCALE; + } else if (item == "layout") { + intChangs |= CHANGE_CONFIG_LAYOUT; + } else if (item == "fontSize") { + intChangs |= CHANGE_CONFIG_FONTSIZE; + } else if (item == "orientation") { + intChangs |= CHANGE_CONFIG_ORIENTATION; + } else if (item == "density") { + intChangs |= CHANGE_CONFIG_DENSITY; + } else { + ; + } + } + return intChangs; +} + +void AbilityRecord::ClearFlag() +{ + isRestarting_ = false; + isPowerState_ = false; + isForceTerminate_ = false; + isUninstall_ = false; + isTerminating_ = false; + isInMovingState_ = false; + preAbilityRecord_.reset(); + nextAbilityRecord_.reset(); + backAbilityRecord_.reset(); + startTime_ = 0; + appState_ = AppState::END; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_scheduler_proxy.cpp b/services/abilitymgr/src/ability_scheduler_proxy.cpp index a744a282d40..2e377d49f50 100644 --- a/services/abilitymgr/src/ability_scheduler_proxy.cpp +++ b/services/abilitymgr/src/ability_scheduler_proxy.cpp @@ -135,6 +135,12 @@ void AbilitySchedulerProxy::ScheduleSaveAbilityState(PacMap &outState) if (err != NO_ERROR) { HILOG_ERROR("ScheduleSaveAbilityState fail to SendRequest. err: %d", err); } + std::unique_ptr pacMap(reply.ReadParcelable()); + if (!pacMap) { + HILOG_ERROR("readParcelableInfo failed"); + return; + } + outState = *pacMap; } void AbilitySchedulerProxy::ScheduleRestoreAbilityState(const PacMap &inState) @@ -145,12 +151,34 @@ void AbilitySchedulerProxy::ScheduleRestoreAbilityState(const PacMap &inState) if (!WriteInterfaceToken(data)) { return; } + if (!data.WriteParcelable(&inState)) { + HILOG_ERROR("WriteParcelable error"); + return; + } int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_RESTORE_ABILITY_STATE, data, reply, option); if (err != NO_ERROR) { HILOG_ERROR("ScheduleRestoreAbilityState fail to SendRequest. err: %d", err); } } +void AbilitySchedulerProxy::ScheduleUpdateConfiguration(const DummyConfiguration &config) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return; + } + if (!data.WriteParcelable(&config)) { + HILOG_ERROR("fail to WriteParcelable"); + return; + } + int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_UPDATE_CONFIGURATION, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("ScheduleRestoreAbilityState fail to SendRequest. err: %d", err); + } +} + /** * @brief Obtains the MIME types of files supported. * @@ -612,5 +640,137 @@ int AbilitySchedulerProxy::BatchInsert(const Uri &uri, const std::vectorSendRequest(IAbilityScheduler::MULTI_WIN_CHANGED, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("NotifyMultiWinModeChanged fail to SendRequest. err: %d", err); + } +} + +/** + * @brief notify this ability is top active ability. + * + * @param flag true: Indicates this ability is top active ability + */ +void AbilitySchedulerProxy::NotifyTopActiveAbilityChanged(bool flag) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return; + } + if (!data.WriteBool(flag)) { + HILOG_ERROR("fail to WriteBool"); + return; + } + int32_t err = Remote()->SendRequest(IAbilityScheduler::TOP_ACTIVE_ABILITY_CHANGED, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("NotifyTopActiveAbilityChanged fail to SendRequest. err: %d", err); + } +} + +/** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the + * context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to + * any method that is called on the Data ability must require normalization verification and denormalization. The + * default implementation of this method returns null, indicating that this Data ability does not support URI + * normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ +Uri AbilitySchedulerProxy::NormalizeUri(const Uri &uri) +{ + Uri urivalue(""); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return urivalue; + } + + if (!data.WriteParcelable(&uri)) { + HILOG_ERROR("fail to WriteParcelable uri"); + return urivalue; + } + + int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_NORMALIZEURI, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("NormalizeUri fail to SendRequest. err: %d", err); + } + + Uri *value = reply.ReadParcelable(); + if (value == nullptr) { + HILOG_ERROR("ReadParcelable value is nullptr"); + } + return *value; +} + +/** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed + * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found + * in the current environment. + */ +Uri AbilitySchedulerProxy::DenormalizeUri(const Uri &uri) +{ + Uri urivalue(""); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return urivalue; + } + + if (!data.WriteParcelable(&uri)) { + HILOG_ERROR("fail to WriteParcelable uri"); + return urivalue; + } + + int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_DENORMALIZEURI, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("DenormalizeUri fail to SendRequest. err: %d", err); + } + + auto value = reply.ReadParcelable(); + if (value == nullptr) { + HILOG_ERROR("ReadParcelable value is nullptr"); + } + return *value; +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/ability_scheduler_stub.cpp b/services/abilitymgr/src/ability_scheduler_stub.cpp index ff5d236cb44..1edcdd4265b 100644 --- a/services/abilitymgr/src/ability_scheduler_stub.cpp +++ b/services/abilitymgr/src/ability_scheduler_stub.cpp @@ -41,6 +41,11 @@ AbilitySchedulerStub::AbilitySchedulerStub() requestFuncMap_[SCHEDULE_GETTYPE] = &AbilitySchedulerStub::GetTypeInner; requestFuncMap_[SCHEDULE_RELOAD] = &AbilitySchedulerStub::ReloadInner; requestFuncMap_[SCHEDULE_BATCHINSERT] = &AbilitySchedulerStub::BatchInsertInner; + requestFuncMap_[MULTI_WIN_CHANGED] = &AbilitySchedulerStub::MutiWinModeChangedInner; + requestFuncMap_[SCHEDULE_NORMALIZEURI] = &AbilitySchedulerStub::NormalizeUriInner; + requestFuncMap_[SCHEDULE_DENORMALIZEURI] = &AbilitySchedulerStub::DenormalizeUriInner; + requestFuncMap_[SCHEDULE_UPDATE_CONFIGURATION] = &AbilitySchedulerStub::UpdateConfigurationInner; + requestFuncMap_[TOP_ACTIVE_ABILITY_CHANGED] = &AbilitySchedulerStub::TopActiveAbilityChangedInner; } AbilitySchedulerStub::~AbilitySchedulerStub() @@ -141,12 +146,24 @@ int AbilitySchedulerStub::CommandAbilityInner(MessageParcel &data, MessageParcel int AbilitySchedulerStub::SaveAbilityStateInner(MessageParcel &data, MessageParcel &reply) { + PacMap pacMap; + ScheduleSaveAbilityState(pacMap); + if (!reply.WriteParcelable(&pacMap)) { + HILOG_ERROR("AbilityManagerStub: SaveAbilityState error"); + return ERR_INVALID_VALUE; + } return NO_ERROR; } int AbilitySchedulerStub::RestoreAbilityStateInner(MessageParcel &data, MessageParcel &reply) { - HILOG_INFO("RestoreAbilityStateInner"); + PacMap *pacMap = data.ReadParcelable(); + if (pacMap == nullptr) { + HILOG_ERROR("AbilitySchedulerStub RestoreAbilityState is nullptr"); + return ERR_INVALID_VALUE; + } + ScheduleRestoreAbilityState(*pacMap); + delete pacMap; return NO_ERROR; } @@ -385,6 +402,68 @@ int AbilitySchedulerStub::BatchInsertInner(MessageParcel &data, MessageParcel &r return NO_ERROR; } +int AbilitySchedulerStub::NormalizeUriInner(MessageParcel &data, MessageParcel &reply) +{ + Uri *uri = data.ReadParcelable(); + if (uri == nullptr) { + HILOG_ERROR("AbilitySchedulerStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + + Uri ret(""); + ret = NormalizeUri(*uri); + if (!reply.WriteParcelable(&ret)) { + HILOG_ERROR("fail to WriteParcelable type"); + return ERR_INVALID_VALUE; + } + delete uri; + return NO_ERROR; +} + +int AbilitySchedulerStub::DenormalizeUriInner(MessageParcel &data, MessageParcel &reply) +{ + Uri *uri = data.ReadParcelable(); + if (uri == nullptr) { + HILOG_ERROR("AbilitySchedulerStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + + Uri ret(""); + ret = DenormalizeUri(*uri); + if (!reply.WriteParcelable(&ret)) { + HILOG_ERROR("fail to WriteParcelable type"); + return ERR_INVALID_VALUE; + } + delete uri; + return NO_ERROR; +} +int AbilitySchedulerStub::UpdateConfigurationInner(MessageParcel &data, MessageParcel &reply) +{ + DummyConfiguration *globalConfiguration = data.ReadParcelable(); + if (globalConfiguration == nullptr) { + HILOG_ERROR("AbilitySchedulerStub globalConfiguration is nullptr"); + return ERR_INVALID_VALUE; + } + ScheduleUpdateConfiguration(*globalConfiguration); + delete globalConfiguration; + return NO_ERROR; +} + +int AbilitySchedulerStub::MutiWinModeChangedInner(MessageParcel &data, MessageParcel &reply) +{ + int32_t winModeKey = data.ReadInt32(); + bool flag = data.ReadBool(); + NotifyMultiWinModeChanged(winModeKey, flag); + return NO_ERROR; +} + +int AbilitySchedulerStub::TopActiveAbilityChangedInner(MessageParcel &data, MessageParcel &reply) +{ + bool flag = data.ReadBool(); + NotifyTopActiveAbilityChanged(flag); + return NO_ERROR; +} + void AbilitySchedulerRecipient::OnRemoteDied(const wptr &remote) { HILOG_ERROR("recv AbilitySchedulerRecipient death notice"); diff --git a/services/abilitymgr/src/ability_stack_manager.cpp b/services/abilitymgr/src/ability_stack_manager.cpp index a6ad13e9efd..ec9739120d7 100644 --- a/services/abilitymgr/src/ability_stack_manager.cpp +++ b/services/abilitymgr/src/ability_stack_manager.cpp @@ -16,12 +16,15 @@ #include "ability_stack_manager.h" #include +#include #include "hilog_wrapper.h" #include "ability_util.h" #include "ability_manager_errors.h" #include "ability_manager_service.h" #include "app_scheduler.h" +#include "common_event.h" +#include "common_event_manager.h" namespace OHOS { namespace AAFwk { @@ -36,6 +39,9 @@ void AbilityStackManager::Init() defaultMissionStack_ = std::make_shared(DEFAULT_MISSION_STACK_ID, userId_); missionStackList_.push_back(defaultMissionStack_); currentMissionStack_ = launcherMissionStack_; + + resumeMissionContainer_ = std::make_shared( + DelayedSingleton::GetInstance()->GetEventHandler()); } AbilityStackManager::~AbilityStackManager() @@ -43,6 +49,7 @@ AbilityStackManager::~AbilityStackManager() int AbilityStackManager::StartAbility(const AbilityRequest &abilityRequest) { + HILOG_DEBUG("Start ability."); std::lock_guard guard(stackLock_); auto currentTopAbilityRecord = GetCurrentTopAbility(); @@ -51,23 +58,24 @@ int AbilityStackManager::StartAbility(const AbilityRequest &abilityRequest) return LOCK_MISSION_STATE_DENY_REQUEST; } - if (abilityRequest.abilityInfo.applicationInfo.isLauncherApp && - abilityRequest.abilityInfo.type == AppExecFwk::AbilityType::PAGE && currentTopAbilityRecord && - AbilitUtil::IsSystemDialogAbility( + auto abilityInfo = abilityRequest.abilityInfo; + auto type = abilityInfo.type; + if (abilityInfo.applicationInfo.isLauncherApp && type == AppExecFwk::AbilityType::PAGE && currentTopAbilityRecord && + AbilityUtil::IsSystemDialogAbility( currentTopAbilityRecord->GetAbilityInfo().bundleName, currentTopAbilityRecord->GetAbilityInfo().name)) { - HILOG_ERROR("page ability is dialog type, cannot return to luncher"); + HILOG_ERROR("Page ability is dialog type, cannot return to luncher."); return ERR_INVALID_VALUE; } if (!waittingAbilityQueue_.empty()) { - HILOG_INFO("waiting queue is not empty, so enqueue ability for waiting."); + HILOG_INFO("Waiting queue is not empty, so enqueue ability for waiting."); EnqueueWaittingAbility(abilityRequest); return START_ABILITY_WAITING; } if (currentTopAbilityRecord != nullptr) { std::string element = currentTopAbilityRecord->GetWant().GetElement().GetURI(); - HILOG_DEBUG("%s, current top %s", __func__, element.c_str()); + HILOG_DEBUG("current top: %{public}s", element.c_str()); if (currentTopAbilityRecord->GetAbilityState() != ACTIVE) { HILOG_INFO("Top ability is not active, so enqueue ability for waiting."); EnqueueWaittingAbility(abilityRequest); @@ -75,85 +83,238 @@ int AbilityStackManager::StartAbility(const AbilityRequest &abilityRequest) } } + // need to start ability as special + if (abilityRequest.startSetting && !abilityRequest.abilityInfo.applicationInfo.isLauncherApp) { + auto windowkey = static_cast( + std::atoi(abilityRequest.startSetting->GetProperty(AbilityStartSetting::WINDOW_MODE_KEY).c_str())); + HILOG_DEBUG("Start ability with settings ..."); + if (windowkey == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING || + windowkey == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY) { + return StartAbilityAsSpecialLocked(currentTopAbilityRecord, abilityRequest); + } + } + return StartAbilityLocked(currentTopAbilityRecord, abilityRequest); } int AbilityStackManager::StartAbilityLocked( const std::shared_ptr ¤tTopAbility, const AbilityRequest &abilityRequest) { - if (!currentMissionStack_) { - HILOG_ERROR("currentMissionStack_ is nullptr"); - return INNER_ERR; - } - + HILOG_DEBUG("Start ability locked."); + CHECK_POINTER_AND_RETURN(currentMissionStack_, INNER_ERR); // 1. choose target mission stack - std::shared_ptr stack = GetTargetMissionStack(abilityRequest); - if (stack == nullptr) { - HILOG_ERROR("stack is nullptr"); - return CREATE_MISSION_STACK_FAILED; - } + std::shared_ptr targetStack = GetTargetMissionStack(abilityRequest); + CHECK_POINTER_AND_RETURN(targetStack, CREATE_MISSION_STACK_FAILED); + auto lastTopAbility = targetStack->GetTopAbilityRecord(); + // 2. move target mission stack to top, currentMissionStack will be changed. - MoveMissionStackToTop(stack); + MoveMissionStackToTop(targetStack); + // 3. get mission record and ability recode std::shared_ptr targetAbilityRecord; std::shared_ptr targetMissionRecord; GetMissionRecordAndAbilityRecord(abilityRequest, currentTopAbility, targetAbilityRecord, targetMissionRecord); if (targetAbilityRecord == nullptr || targetMissionRecord == nullptr) { - HILOG_ERROR("failed to get ability record or mission record"); + HILOG_ERROR("Failed to get ability record or mission record."); MoveMissionStackToTop(lastMissionStack_); return ERR_INVALID_VALUE; } - // // add caller record targetAbilityRecord->AddCallerRecord(abilityRequest.callerToken, abilityRequest.requestCode); - MoveMissionAndAbility(currentTopAbility, targetAbilityRecord, targetMissionRecord, true); + MoveMissionAndAbility(currentTopAbility, targetAbilityRecord, targetMissionRecord); - // load ability or inactive top ability - // If top ability is null, then launch the first Ability. - // If top ability is not null,. then inactive current top ability - int result = ERR_OK; + // 4. start processing ability lifecycle if (currentTopAbility == nullptr) { + // top ability is null, then launch the first Ability. targetAbilityRecord->SetLauncherRoot(); - result = targetAbilityRecord->LoadAbility(); + return targetAbilityRecord->LoadAbility(); } else { - currentTopAbility->Inactivate(); + // complete ability background if needed. + return StartAbilityLifeCycle(lastTopAbility, currentTopAbility, targetAbilityRecord); } - return result; } -void AbilityStackManager::MoveMissionAndAbility(const std::shared_ptr ¤tTopAbility, - std::shared_ptr &targetAbilityRecord, std::shared_ptr &targetMissionRecord, - const bool isSetPreMission) +int AbilityStackManager::StartAbilityLifeCycle(std::shared_ptr lastTopAbility, + std::shared_ptr currentTopAbility, std::shared_ptr targetAbility) { - HILOG_INFO("%{public}s, %{public}d", __func__, __LINE__); - if (!targetAbilityRecord || !targetMissionRecord) { - HILOG_ERROR("%{public}s, targetAbilityRecord or targetMissionRecord is nullptr", __func__); - return; + CHECK_POINTER_AND_RETURN(targetAbility, ERR_INVALID_VALUE); + CHECK_POINTER_AND_RETURN(currentTopAbility, ERR_INVALID_VALUE); + enum ChangeType { T_ACTIVE, T_CHANGE, T_DEFAULT } changeType; + + bool isMissionChanged = currentTopAbility->GetMissionRecordId() != targetAbility->GetMissionRecordId(); + bool isStackChanged = currentTopAbility->GetMissionStackId() != targetAbility->GetMissionStackId(); + bool isCurrentFull = IsFullScreenStack(currentTopAbility->GetMissionStackId()); + bool isTargetFull = IsFullScreenStack(targetAbility->GetMissionStackId()); + + std::shared_ptr needBackgroundAbility; + + // set target changeType + if (isMissionChanged) { + if (isStackChanged) { + if (isCurrentFull && isTargetFull) { + changeType = T_DEFAULT; + } else if (!isCurrentFull && isTargetFull) { + auto needAbility = (targetAbility->GetMissionStackId() == DEFAULT_MISSION_STACK_ID) + ? launcherMissionStack_->GetTopAbilityRecord() + : defaultMissionStack_->GetTopAbilityRecord(); + changeType = T_CHANGE; + needBackgroundAbility = + (needAbility && needAbility->IsAbilityState(AbilityState::ACTIVE)) ? needAbility : lastTopAbility; + } else { + auto IsChanged = [&lastTopAbility, &targetAbility, stackManager = shared_from_this()]() { + bool isSameMission = lastTopAbility->GetMissionRecordId() == targetAbility->GetMissionRecordId(); + bool isSyncVisual = stackManager->SupportSyncVisualByStackId(targetAbility->GetMissionStackId()); + return (isSameMission || (!isSameMission && !isSyncVisual)) && + lastTopAbility->IsAbilityState(AbilityState::ACTIVE) + ? T_CHANGE + : T_ACTIVE; + }; + changeType = lastTopAbility ? IsChanged() : T_ACTIVE; + needBackgroundAbility = (changeType == T_CHANGE) ? lastTopAbility : nullptr; + } + } else { + if (SupportSyncVisualByStackId(targetAbility->GetMissionStackId())) { + auto targetMission = targetAbility->GetMissionRecord(); + auto secondAbility = targetMission ? targetMission->GetLastTopAbility() : nullptr; + if (secondAbility && secondAbility->IsAbilityState(AbilityState::ACTIVE)) { + needBackgroundAbility = secondAbility; + changeType = T_CHANGE; + } else { + changeType = T_ACTIVE; + } + } else { + changeType = T_DEFAULT; + } + } + } else { + changeType = T_DEFAULT; + } + + needBackgroundAbility = (changeType == T_DEFAULT) ? currentTopAbility : needBackgroundAbility; + + changeType = needBackgroundAbility ? changeType : T_ACTIVE; + + HILOG_DEBUG("ChangeType: %{public}d, needBackAbility : %{public}s", + changeType, + needBackgroundAbility ? needBackgroundAbility->GetAbilityInfo().name.c_str() : "none"); + + // deal ability lifecycle. + switch (changeType) { + // 1. last top ability don't need inactive , target ability active directly. + case T_ACTIVE: { + targetAbility->ProcessActivate(); + break; + } + // 2. change inactive ability, add pre and next flag. + case T_CHANGE: { + targetAbility->SetPreAbilityRecord(needBackgroundAbility); + needBackgroundAbility->SetNextAbilityRecord(targetAbility); + needBackgroundAbility->Inactivate(); + break; + } + // 3. usually, last top ability need inactive, target ability need active. + case T_DEFAULT: + default: { + needBackgroundAbility->Inactivate(); + break; + } + } + return ERR_OK; +} + +int AbilityStackManager::StartAbilityAsSpecialLocked( + const std::shared_ptr ¤tTopAbility, const AbilityRequest &abilityRequest) +{ + HILOG_DEBUG("Start ability as special locked."); + CHECK_POINTER_AND_RETURN(currentTopAbility, INNER_ERR); + CHECK_RET_RETURN_RET( + CheckMultiWindowCondition(currentTopAbility, abilityRequest), "Check multiwindow condition is failed."); + + // 1. choose target mission stack + auto targetStack = GetTargetMissionStack(abilityRequest); + CHECK_POINTER_AND_RETURN(targetStack, CREATE_MISSION_STACK_FAILED); + auto lastTopAbility = targetStack->GetTopAbilityRecord(); + + // 2. get mission record and ability recode + std::shared_ptr targetAbilityRecord; + std::shared_ptr targetMissionRecord; + GetMissionRecordAndAbilityRecord(abilityRequest, currentTopAbility, targetAbilityRecord, targetMissionRecord); + if (targetAbilityRecord == nullptr || targetMissionRecord == nullptr) { + HILOG_ERROR("Failed to get ability record or mission record."); + return ERR_INVALID_VALUE; } + targetAbilityRecord->AddCallerRecord(abilityRequest.callerToken, abilityRequest.requestCode); + + MissionOption option; + option.userId = userId_; + option.missionId = targetMissionRecord->GetMissionRecordId(); + option.winModeKey = static_cast( + std::atoi(abilityRequest.startSetting->GetProperty(AbilityStartSetting::WINDOW_MODE_KEY).c_str())); + targetMissionRecord->SetMissionOption(option); + + // 3. first create mission record or stack is not changed, + // just load target ability and inactive the current top ability. + if (targetMissionRecord->GetMissionStack() == nullptr || + targetMissionRecord->GetMissionStack()->GetMissionStackId() == targetStack->GetMissionStackId()) { + MoveMissionStackToTop(targetStack); + MoveMissionAndAbility(currentTopAbility, targetAbilityRecord, targetMissionRecord); + HILOG_DEBUG("First create mission record ,missionId:%{public}d", targetMissionRecord->GetMissionRecordId()); + return StartAbilityLifeCycle(lastTopAbility, currentTopAbility, targetAbilityRecord); + } + + // 4. mission stack is changed, move mission to target stack. + isMultiWinMoving_ = true; + CompleteMoveMissionToStack(targetMissionRecord, targetStack); + MoveMissionAndAbility(currentTopAbility, targetAbilityRecord, targetMissionRecord); + HILOG_DEBUG("Mission stack is changed, move mission to target stack ,missionId:%{public}d", + targetMissionRecord->GetMissionRecordId()); + CHECK_RET_RETURN_RET(DispatchLifecycle(currentTopAbility, targetAbilityRecord, false), "Dispatch lifecycle error."); + // Judging target system window mode, and notify event. + auto willWinMode = JudgingTargetSystemWindowMode(option.winModeKey); + auto targetWinMode = GetTargetSystemWindowMode(willWinMode); + NotifyWindowModeChanged(targetWinMode); + return ERR_OK; +} + +void AbilityStackManager::MoveMissionAndAbility(const std::shared_ptr ¤tTopAbility, + std::shared_ptr &targetAbilityRecord, std::shared_ptr &targetMissionRecord) +{ + HILOG_INFO("Move mission and ability."); + CHECK_POINTER(targetAbilityRecord); + CHECK_POINTER(targetMissionRecord); // set relationship of mission record and ability record if (currentTopAbility != nullptr) { targetAbilityRecord->SetPreAbilityRecord(currentTopAbility); currentTopAbility->SetNextAbilityRecord(targetAbilityRecord); // move mission to end, don't set pre mission - if (isSetPreMission) { - auto targetPreMission = targetMissionRecord->GetPreMissionRecord(); - if (targetPreMission) { - currentTopAbility->GetMissionRecord()->SetPreMissionRecord(targetPreMission); - } - targetMissionRecord->SetPreMissionRecord(currentTopAbility->GetMissionRecord()); - if (currentTopAbility->IsLauncherAbility()) { - targetMissionRecord->SetIsLauncherCreate(); - } + auto targetPreMission = targetMissionRecord->GetPreMissionRecord(); + if (targetPreMission) { + currentTopAbility->GetMissionRecord()->SetPreMissionRecord(targetPreMission); + } + targetMissionRecord->SetPreMissionRecord(currentTopAbility->GetMissionRecord()); + if (currentTopAbility->IsLauncherAbility()) { + targetMissionRecord->SetIsLauncherCreate(); } } // add caller record targetAbilityRecord->SetMissionRecord(targetMissionRecord); + // check mission window mode. + if (targetAbilityRecord->GetMissionRecord() == nullptr) { + auto option = targetMissionRecord->GetMissionOption(); + if (option.winModeKey == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING || + option.winModeKey == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY || + option.winModeKey == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY) { + auto setting = AbilityStartSetting::GetEmptySetting(); + setting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, std::to_string(option.winModeKey)); + targetAbilityRecord->SetStartSetting(setting); + } + } // add ability record to mission record. // if this ability record exist this mission record, do not add. targetMissionRecord->AddAbilityRecordToTop(targetAbilityRecord); // reparent mission record, currentMissionStack is the target mission stack. - targetMissionRecord->SetParentStack(currentMissionStack_, currentMissionStack_->GetMissionStackId()); + targetMissionRecord->SetMissionStack(currentMissionStack_, currentMissionStack_->GetMissionStackId()); // add mission record to mission stack. // if this mission record exist this mission stack, do not add. currentMissionStack_->AddMissionRecordToTop(targetMissionRecord); @@ -164,29 +325,20 @@ void AbilityStackManager::MoveMissionAndAbility(const std::shared_ptr &token, int resultCode, const Want *resultWant) { + HILOG_INFO("Terminate ability."); std::lock_guard guard(stackLock_); - std::shared_ptr abilityRecord = Token::GetAbilityRecordByToken(token); - if (abilityRecord == nullptr) { - HILOG_ERROR("token is invalid"); - return ERR_INVALID_VALUE; - } + auto abilityRecord = Token::GetAbilityRecordByToken(token); + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); // if ability was already in terminate list, don't do anything but wait. - if (abilityRecord->IsTerminating()) { - HILOG_INFO("ability is on terminating"); - return ERR_OK; - } + CHECK_TRUE_RETURN_RET(abilityRecord->IsTerminating(), ERR_OK, "Ability is on terminating."); // check if ability is in stack to avoid user create fake token. - if (GetAbilityRecordByToken(token) == nullptr) { - HILOG_ERROR("ability is not in stack, nor in terminating list."); - return INNER_ERR; - } - std::shared_ptr missionRecord = abilityRecord->GetMissionRecord(); - if (missionRecord == nullptr) { - HILOG_ERROR("missionRecord is nullptr"); - return INNER_ERR; - } + CHECK_POINTER_AND_RETURN_LOG( + GetAbilityRecordByToken(token), INNER_ERR, "Ability is not in stack, nor in terminating list."); + + auto missionRecord = abilityRecord->GetMissionRecord(); + CHECK_POINTER_AND_RETURN(missionRecord, INNER_ERR); if (abilityRecord->IsLauncherAbility() && abilityRecord->IsLauncherRoot()) { - HILOG_INFO("Don't allow terminate root launcher"); + HILOG_WARN("Don't allow terminate root launcher"); return TERMINATE_LAUNCHER_DENIED; } @@ -195,26 +347,41 @@ int AbilityStackManager::TerminateAbility(const sptr &token, int return LOCK_MISSION_STATE_DENY_REQUEST; } + // if ability is in multiwindow stack, and is bottom ability of this mission, + // just background, don't schedule terminate + if (!IsFullScreenStack(abilityRecord->GetMissionStackId()) && + missionRecord->GetBottomAbilityRecord() == abilityRecord) { + HILOG_INFO("Mulitwindow stack , bottom ability of mission .just background, don't schedule terminate."); + return MoveMissionToEndLocked(missionRecord->GetMissionRecordId()); + } + + HILOG_INFO("Schedule normal terminate process."); abilityRecord->SetTerminatingState(); return TerminateAbilityLocked(abilityRecord, resultCode, resultWant); } int AbilityStackManager::TerminateAbility(const std::shared_ptr &caller, int requestCode) { - HILOG_INFO("%{public}s, called", __func__); + HILOG_INFO("Terminate ability."); std::lock_guard guard(stackLock_); std::shared_ptr targetAbility = nullptr; + int result = static_cast(ABILITY_VISIBLE_FALSE_DENY_REQUEST); for (auto &stack : missionStackList_) { targetAbility = stack->GetAbilityRecordByCaller(caller, requestCode); if (targetAbility) { + result = AbilityUtil::JudgeAbilityVisibleControl(targetAbility->GetAbilityInfo()); break; } } if (!targetAbility) { HILOG_ERROR("%{public}s, Can't find target ability", __func__); - return INNER_ERR; + return NO_FOUND_ABILITY_BY_CALLER; + } + if (result != ERR_OK) { + HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); + return result; } if (!CanStopInLockMissionState(targetAbility)) { @@ -222,7 +389,7 @@ int AbilityStackManager::TerminateAbility(const std::shared_ptr & return LOCK_MISSION_STATE_DENY_REQUEST; } - return TerminateAbilityLocked(targetAbility, -1, nullptr); + return TerminateAbility(targetAbility->GetToken(), DEFAULT_INVAL_VALUE, nullptr); } int AbilityStackManager::TerminateAbilityLocked( @@ -233,21 +400,22 @@ int AbilityStackManager::TerminateAbilityLocked( HILOG_ERROR("abilityRecord is invalid"); return ERR_INVALID_VALUE; } + + if (abilityRecord->IsRestarting()) { + HILOG_ERROR("abilityRecord is restarting, deny terminate."); + return ERR_INVALID_VALUE; + } // save result to caller AbilityRecord if (resultWant != nullptr) { abilityRecord->SaveResultToCallers(resultCode, resultWant); } // common case, ability terminate at active and at top position - if (abilityRecord == GetCurrentTopAbility()) { - HILOG_DEBUG("terminate top ability %d", abilityRecord->GetAbilityState()); - // if ability is onActive or on activating state, we must activate next top ability. - if (abilityRecord->IsAbilityState(AbilityState::ACTIVE) || - abilityRecord->IsAbilityState(AbilityState::ACTIVATING) || - abilityRecord->IsAbilityState(AbilityState::INITIAL)) { - RemoveTerminatingAbility(abilityRecord); - abilityRecord->Inactivate(); - return ERR_OK; - } + if (abilityRecord->IsAbilityState(AbilityState::ACTIVE) || + abilityRecord->IsAbilityState(AbilityState::ACTIVATING) || + abilityRecord->IsAbilityState(AbilityState::INITIAL)) { + RemoveTerminatingAbility(abilityRecord); + abilityRecord->Inactivate(); + return ERR_OK; } // it's not common case when ability terminate at non-active state and non-top position. if (abilityRecord->IsAbilityState(AbilityState::INACTIVE)) { @@ -260,7 +428,7 @@ int AbilityStackManager::TerminateAbilityLocked( RemoveTerminatingAbility(abilityRecord); abilityRecord->SendResultToCallers(); auto task = [abilityRecord, stackManager = shared_from_this()]() { - HILOG_WARN("disconnect ability terminate timeout."); + HILOG_WARN("Disconnect ability terminate timeout."); stackManager->CompleteTerminate(abilityRecord); }; abilityRecord->Terminate(task); @@ -271,7 +439,7 @@ int AbilityStackManager::TerminateAbilityLocked( RemoveTerminatingAbility(abilityRecord); abilityRecord->SendResultToCallers(); } else { - HILOG_WARN("abilityState is invalid"); + HILOG_WARN("Ability state is invalid."); } return ERR_OK; } @@ -280,7 +448,7 @@ int AbilityStackManager::RemoveMissionById(int missionId) { std::lock_guard guard(stackLock_); if (missionId < 0) { - HILOG_ERROR("missionId is invalid"); + HILOG_ERROR("Mission id is invalid."); return ERR_INVALID_VALUE; } if (lockMissionContainer_ && lockMissionContainer_->IsLockedMissionState()) { @@ -292,74 +460,72 @@ int AbilityStackManager::RemoveMissionById(int missionId) int AbilityStackManager::RemoveMissionByIdLocked(int missionId) { - if (defaultMissionStack_ == nullptr) { - HILOG_ERROR("defaultMissionStack_ is invalid"); - return ERR_NO_INIT; - } + CHECK_POINTER_AND_RETURN_LOG(defaultMissionStack_, ERR_NO_INIT, "defaultMissionStack_ is invalid."); + auto missionRecord = GetMissionRecordFromAllStacks(missionId); - if (missionRecord == nullptr) { - HILOG_ERROR("missionId is invalid"); - return REMOVE_MISSION_ID_NOT_EXIST; + CHECK_POINTER_AND_RETURN_LOG(missionRecord, REMOVE_MISSION_ID_NOT_EXIST, "Mission id is invalid."); + CHECK_TRUE_RETURN_RET(IsLauncherMission(missionId), + REMOVE_MISSION_LAUNCHER_DENIED, + "Don't allow to terminate mission which has launcher ability."); + + auto currentStack = missionRecord->GetMissionStack(); + CHECK_POINTER_AND_RETURN_LOG(currentStack, REMOVE_MISSION_FAILED, "Current stack is nullptr."); + + auto topAbility = missionRecord->GetTopAbilityRecord(); + CHECK_POINTER_AND_RETURN(topAbility, REMOVE_MISSION_FAILED); + + std::shared_ptr activeAbility; + if (topAbility->IsAbilityState(ACTIVE) || topAbility->IsAbilityState(ACTIVATING)) { + activeAbility = topAbility; } - if (IsLauncherMission(missionId)) { - HILOG_ERROR("don't allow to terminate mission which has launcher ability"); - return REMOVE_MISSION_LAUNCHER_DENIED; + +#define TERMINATE(ability) \ + ability->SetTerminatingState(); \ + auto ret = TerminateAbilityLocked(ability, DEFAULT_INVAL_VALUE, nullptr); \ + if (ret != ERR_OK) { \ + HILOG_ERROR("Remove mission error: %{public}d.", ret); \ + return REMOVE_MISSION_FAILED; \ } std::vector abilityInfos; missionRecord->GetAllAbilityInfo(abilityInfos); - // If the mission has the ability to be in active, activing, or inactive-visible state, - // don't allow to remove this mission. for (auto &ability : abilityInfos) { auto abilityRecord = missionRecord->GetAbilityRecordById(ability.id); - if (abilityRecord != nullptr) { - if (abilityRecord == GetCurrentTopAbility() || abilityRecord->IsAbilityState(AbilityState::ACTIVE) || - abilityRecord->IsAbilityState(AbilityState::ACTIVATING)) { - return REMOVE_MISSION_ACTIVE_DENIED; - } - auto windowInfo = abilityRecord->GetWindowInfo(); - if (windowInfo != nullptr && windowInfo->isVisible_ && - abilityRecord->IsAbilityState(AbilityState::INACTIVE)) { - return REMOVE_MISSION_ACTIVE_DENIED; - } + if (abilityRecord == nullptr || abilityRecord->IsTerminating()) { + HILOG_WARN("Ability record is not exist or is on terminating."); + continue; } - } - for (auto &ability : abilityInfos) { - auto abilityRecord = missionRecord->GetAbilityRecordById(ability.id); - if (abilityRecord == nullptr || abilityRecord->IsTerminating()) { - HILOG_WARN("ability record is not exist or is on terminating"); + if (abilityRecord == activeAbility) { continue; } if (abilityRecord->IsAbilityState(AbilityState::INITIAL)) { - HILOG_INFO("ability record state is INITIAL, remove ability, continue"); + HILOG_INFO("Ability record state is INITIAL, remove ability, continue."); missionRecord->RemoveAbilityRecord(abilityRecord); - if (missionRecord->GetAbilityRecordCount() == 0) { - auto stack = missionRecord->GetParentStack(); - if (stack) { - stack->RemoveMissionRecord(missionRecord->GetMissionRecordId()); - } + if (missionRecord->IsEmpty()) { + RemoveMissionRecordById(missionRecord->GetMissionRecordId()); + JudgingIsRemoveMultiScreenStack(currentStack); } continue; } - abilityRecord->SetTerminatingState(); - int ret = TerminateAbilityLocked(abilityRecord, -1, nullptr); - if (ret != ERR_OK) { - HILOG_ERROR("remove mission error: %{public}d.", ret); - return REMOVE_MISSION_FAILED; - } + TERMINATE(abilityRecord); } + + if (activeAbility) { + TERMINATE(activeAbility); + } + return ERR_OK; -} +} // namespace AAFwk int AbilityStackManager::RemoveStack(int stackId) { - HILOG_DEBUG("AbilityStackManager::RemoveStack, stackId : %{public}d", stackId); + HILOG_DEBUG("stackId : %{public}d", stackId); std::lock_guard guard(stackLock_); - if (stackId < 0) { - HILOG_ERROR("stackId is invalid"); + if (stackId > MAX_MISSION_STACK_ID || stackId < MIN_MISSION_STACK_ID) { + HILOG_ERROR("stackId:%{public}d is invalid.", stackId); return ERR_INVALID_VALUE; } @@ -373,27 +539,18 @@ int AbilityStackManager::RemoveStack(int stackId) int AbilityStackManager::RemoveStackLocked(int stackId) { - HILOG_DEBUG("AbilityStackManager::RemoveStackLocked, stackId : %{public}d", stackId); - - if (missionStackList_.empty()) { - HILOG_ERROR("mission stack list is empty."); - return MISSION_STACK_LIST_IS_EMPTY; - } + HILOG_DEBUG("stackId : %{public}d", stackId); + CHECK_TRUE_RETURN_RET(missionStackList_.empty(), MISSION_STACK_LIST_IS_EMPTY, "Mission stack list is empty."); // don't allow remove launcher mission stack. - if (stackId == LAUNCHER_MISSION_STACK_ID) { - HILOG_ERROR("don't allow remove launcher mission stack."); - return REMOVE_STACK_LAUNCHER_DENIED; - } + CHECK_TRUE_RETURN_RET(stackId == LAUNCHER_MISSION_STACK_ID, + REMOVE_STACK_LAUNCHER_DENIED, + "Don't allow remove launcher mission stack."); auto isExist = [stackId]( const std::shared_ptr &stack) { return stackId == stack->GetMissionStackId(); }; auto iter = std::find_if(missionStackList_.begin(), missionStackList_.end(), isExist); - if (iter == missionStackList_.end()) { - HILOG_ERROR("remove stack id is not exist."); - return REMOVE_STACK_ID_NOT_EXIST; - } - + CHECK_TRUE_RETURN_RET(iter == missionStackList_.end(), REMOVE_STACK_ID_NOT_EXIST, "Remove stack id is not exist."); // remove mission record from mission stack. if (*iter != nullptr) { std::vector missionInfos; @@ -401,7 +558,7 @@ int AbilityStackManager::RemoveStackLocked(int stackId) for (auto &mission : missionInfos) { int result = RemoveMissionByIdLocked(mission.id); if (result != ERR_OK) { - HILOG_ERROR("remove mission failed, mission id : %{public}d", mission.id); + HILOG_ERROR("Remove mission failed, mission id : %{public}d", mission.id); return result; } } @@ -410,21 +567,34 @@ int AbilityStackManager::RemoveStackLocked(int stackId) return ERR_OK; } +void AbilityStackManager::SetMissionStackSetting(const StackSetting &stackSetting) +{ + HILOG_DEBUG("Set mission stack setting, stackId : %{public}d", stackSetting.stackId); + std::lock_guard guard(stackLock_); + if (lockMissionContainer_ && lockMissionContainer_->IsLockedMissionState()) { + HILOG_ERROR("current is lock mission state, refusing to operate other mission."); + return; + } + auto isExist = [stackId = stackSetting.stackId](const StackSetting &it) { return stackId == it.stackId; }; + auto iter = std::find_if(stackSettings_.begin(), stackSettings_.end(), isExist); + if (iter != stackSettings_.end()) { + stackSettings_.erase(iter); + } + StackSetting settings = stackSetting; + stackSettings_.emplace_back(settings); +} + /** * remove AbilityRecord from stack to terminate list. * update MissionStack to prepare next top ability. */ void AbilityStackManager::RemoveTerminatingAbility(const std::shared_ptr &abilityRecord) { - if (!abilityRecord) { - HILOG_ERROR("%{public}s, abilityRecord is nullptr", __func__); - return; - } - std::shared_ptr missionRecord = abilityRecord->GetMissionRecord(); - if (!missionRecord) { - HILOG_ERROR("%{public}s, missionRecord is nullptr", __func__); - return; - } + CHECK_POINTER(abilityRecord); + auto missionRecord = abilityRecord->GetMissionRecord(); + CHECK_POINTER(missionRecord); + auto currentStack = missionRecord->GetMissionStack(); + CHECK_POINTER(currentStack); auto isActive = (abilityRecord->IsAbilityState(AbilityState::ACTIVE) || abilityRecord->IsAbilityState(AbilityState::ACTIVATING) || @@ -432,20 +602,47 @@ void AbilityStackManager::RemoveTerminatingAbility(const std::shared_ptrRemoveAbilityRecord(abilityRecord); terminateAbilityRecordList_.push_back(abilityRecord); - // if MissionRecord is empty, remove it and update missionStack by caller. - if (missionRecord->GetAbilityRecordCount() == 0) { + + std::shared_ptr needTopAbility; + + if (!missionRecord->IsEmpty()) { + needTopAbility = missionRecord->GetTopAbilityRecord(); + CHECK_POINTER(needTopAbility); + abilityRecord->SetNextAbilityRecord(needTopAbility); + return; + } + + if (!isActive) { + RemoveMissionRecordById(missionRecord->GetMissionRecordId()); + JudgingIsRemoveMultiScreenStack(currentStack); + return; + } + + if (currentStack->IsEqualStackId(FLOATING_MISSION_STACK_ID)) { + RemoveMissionRecordById(missionRecord->GetMissionRecordId()); + JudgingIsRemoveMultiScreenStack(currentStack); + MoveMissionStackToTop(GetTopFullScreenStack()); + needTopAbility = GetCurrentTopAbility(); + abilityRecord->SetNextAbilityRecord(needTopAbility); + return; + } + + if (IsFullScreenStack(currentStack->GetMissionStackId())) { auto isExist = (!missionRecord->IsLauncherCreate() && missionRecord->GetPreMissionRecord() != nullptr && launcherMissionStack_->IsExistMissionRecord( - missionRecord->GetPreMissionRecord()->GetMissionRecordId()) && - isActive); - if ((missionRecord->IsLauncherCreate() && isActive) || - (missionRecord == missionStackList_.back()->GetTopMissionRecord()) || isExist || - (missionRecord == missionStackList_.front()->GetBottomMissionRecord())) { + missionRecord->GetPreMissionRecord()->GetMissionRecordId())); + if ((missionRecord->IsLauncherCreate()) || (missionRecord == missionStackList_.back()->GetTopMissionRecord()) || + isExist || (missionRecord == missionStackList_.front()->GetBottomMissionRecord())) { RemoveMissionRecordById(missionRecord->GetMissionRecordId()); MoveMissionStackToTop(launcherMissionStack_); } else { RemoveMissionRecordById(missionRecord->GetMissionRecordId()); } + auto fullScreenStack = GetTopFullScreenStack(); + CHECK_POINTER(fullScreenStack); + needTopAbility = fullScreenStack->GetTopAbilityRecord(); + CHECK_POINTER(needTopAbility); + abilityRecord->SetNextAbilityRecord(needTopAbility); } } @@ -499,7 +696,7 @@ std::shared_ptr AbilityStackManager::GetStackById(int stackId) std::shared_ptr AbilityStackManager::GetTopMissionRecord() const { if (currentMissionStack_ == nullptr) { - HILOG_ERROR("currentMissionStack_ is nullptr"); + HILOG_ERROR("currentMissionStack_ is nullptr."); return nullptr; } return currentMissionStack_->GetTopMissionRecord(); @@ -508,7 +705,7 @@ std::shared_ptr AbilityStackManager::GetTopMissionRecord() const std::shared_ptr AbilityStackManager::GetMissionRecordById(int id) const { if (currentMissionStack_ == nullptr) { - HILOG_ERROR("currentMissionStack_ is nullptr"); + HILOG_ERROR("currentMissionStack_ is nullptr."); return nullptr; } return currentMissionStack_->GetMissionRecordById(id); @@ -525,6 +722,17 @@ std::shared_ptr AbilityStackManager::GetMissionRecordFromAllStack return nullptr; } +std::shared_ptr AbilityStackManager::GetMissionRecordByName(std::string name) const +{ + for (auto missionStack : missionStackList_) { + std::shared_ptr missionRecord = missionStack->GetTargetMissionRecord(name); + if (missionRecord != nullptr) { + return missionRecord; + } + } + return nullptr; +} + std::shared_ptr AbilityStackManager::GetAbilityRecordByToken(const sptr &token) { std::lock_guard guard(stackLock_); @@ -562,11 +770,11 @@ bool AbilityStackManager::RemoveMissionRecordById(int id) void AbilityStackManager::MoveMissionStackToTop(const std::shared_ptr &stack) { if (stack == nullptr) { - HILOG_ERROR("stack is nullptr"); + HILOG_ERROR("Stack is nullptr."); return; } if (missionStackList_.front() == stack) { - HILOG_DEBUG("stack is at the top of list, mission id: %d", stack->GetMissionStackId()); + HILOG_DEBUG("Stack is at the top of list, mission id: %d", stack->GetMissionStackId()); return; } lastMissionStack_ = currentMissionStack_; @@ -577,33 +785,88 @@ void AbilityStackManager::MoveMissionStackToTop(const std::shared_ptr AbilityStackManager::GetTargetMissionStack(const AbilityRequest &abilityRequest) { + // priority : starting launcher ability . if (abilityRequest.abilityInfo.applicationInfo.isLauncherApp) { return launcherMissionStack_; } + + // next: start ability for settings(multiwindow) + if (abilityRequest.startSetting != nullptr) { + return GetTargetMissionStackBySetting(abilityRequest); + } + + // other: refer to the stack of the caller ability. + return GetTargetMissionStackByDefault(abilityRequest); +} + +std::shared_ptr AbilityStackManager::GetTargetMissionStackByDefault(const AbilityRequest &abilityRequest) +{ + bool isSingleton = abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SINGLETON; + std::shared_ptr requestMission = nullptr; + if (isSingleton) { + std::string bundleName = AbilityUtil::ConvertBundleNameSingleton( + abilityRequest.abilityInfo.bundleName, abilityRequest.abilityInfo.name); + requestMission = GetMissionRecordByName(bundleName); + } else { + requestMission = GetMissionRecordByName(abilityRequest.abilityInfo.bundleName); + } + + bool isExist = requestMission != nullptr; + auto currentTop = GetCurrentTopAbility(); + if (currentTop) { + // caller is launcher , request is not launcher, exist ability just restart. + if (isExist && (currentTop->IsLauncherAbility() || (!currentTop->IsLauncherAbility() && isSingleton) || + (!currentTop->IsLauncherAbility() && + currentTop->GetAbilityInfo().launchMode == AppExecFwk::LaunchMode::SINGLETON))) { + return requestMission->GetMissionStack(); + } + // caller and request is not launcher, start ability at current mission stack. + if (!currentTop->IsLauncherAbility() && !isSingleton && + currentTop->GetAbilityInfo().launchMode != AppExecFwk::LaunchMode::SINGLETON) { + auto callerParent = currentTop->GetMissionRecord(); + return callerParent->GetMissionStack(); + } + } + + return defaultMissionStack_; +} + +std::shared_ptr AbilityStackManager::GetTargetMissionStackBySetting(const AbilityRequest &abilityRequest) +{ + if (abilityRequest.startSetting != nullptr) { + AbilityWindowConfiguration windowMode = static_cast( + std::atoi(abilityRequest.startSetting->GetProperty(AbilityStartSetting::WINDOW_MODE_KEY).c_str())); + switch (windowMode) { + case AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING: + return GetOrCreateMissionStack(FLOATING_MISSION_STACK_ID, true); + case AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY: + return GetOrCreateMissionStack(SPLIT_SCREEN_MISSION_STACK_ID, true); + default: + break; + } + } + return defaultMissionStack_; } int AbilityStackManager::AttachAbilityThread(const sptr &scheduler, const sptr &token) { std::lock_guard guard(stackLock_); - std::shared_ptr abilityRecord = GetAbilityRecordByToken(token); - if (abilityRecord == nullptr) { - HILOG_ERROR("abilityRecord is null"); - return ERR_INVALID_VALUE; - } + auto abilityRecord = GetAbilityRecordByToken(token); + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); std::string element = abilityRecord->GetWant().GetElement().GetURI(); - HILOG_DEBUG("%s, ability: %s", __func__, element.c_str()); + HILOG_DEBUG("Ability: %{public}s", element.c_str()); std::shared_ptr handler = DelayedSingleton::GetInstance()->GetEventHandler(); - if (handler == nullptr) { - HILOG_ERROR("fail to get AbilityEventHandler"); - return ERR_INVALID_VALUE; - } + CHECK_POINTER_AND_RETURN_LOG(handler, ERR_INVALID_VALUE, "Fail to get AbilityEventHandler."); handler->RemoveEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecord->GetEventId()); abilityRecord->SetScheduler(scheduler); + if (abilityRecord->IsRestarting()) { + abilityRecord->RestoreAbilityState(); + } DelayedSingleton::GetInstance()->MoveToForground(token); return ERR_OK; @@ -612,27 +875,24 @@ int AbilityStackManager::AttachAbilityThread(const sptr &sche int AbilityStackManager::AbilityTransitionDone(const sptr &token, int state) { std::lock_guard guard(stackLock_); - std::shared_ptr abilityRecord = GetAbilityRecordByToken(token); + auto abilityRecord = GetAbilityRecordByToken(token); if (abilityRecord == nullptr) { - HILOG_INFO("abilityRecord may in terminate list"); + HILOG_INFO("Ability record may in terminate list."); abilityRecord = GetAbilityFromTerminateList(token); - if (abilityRecord == nullptr) { - HILOG_ERROR("abilityRecord is null"); - return ERR_INVALID_VALUE; - } + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); } std::string element = abilityRecord->GetWant().GetElement().GetURI(); int targetState = AbilityRecord::ConvertLifeCycleToAbilityState(static_cast(state)); std::string abilityState = AbilityRecord::ConvertAbilityState(static_cast(targetState)); - HILOG_INFO("%{public}s, ability: %{public}s, state: %{public}s", __func__, element.c_str(), abilityState.c_str()); + HILOG_INFO("ability: %{public}s, state: %{public}s", element.c_str(), abilityState.c_str()); return DispatchState(abilityRecord, targetState); } int AbilityStackManager::DispatchState(const std::shared_ptr &abilityRecord, int state) { - HILOG_DEBUG("%{public}s", __func__); + HILOG_DEBUG("Dispatch state."); switch (state) { case AbilityState::ACTIVE: { return DispatchActive(abilityRecord, state); @@ -647,7 +907,7 @@ int AbilityStackManager::DispatchState(const std::shared_ptr &abi return DispatchTerminate(abilityRecord, state); } default: { - HILOG_WARN("don't support transiting state: %d", state); + HILOG_WARN("Don't support transiting state: %d", state); return ERR_INVALID_VALUE; } } @@ -655,195 +915,280 @@ int AbilityStackManager::DispatchState(const std::shared_ptr &abi int AbilityStackManager::DispatchActive(const std::shared_ptr &abilityRecord, int state) { - std::shared_ptr handler = - DelayedSingleton::GetInstance()->GetEventHandler(); - if (handler == nullptr) { - HILOG_ERROR("fail to get AbilityEventHandler"); - return ERR_INVALID_VALUE; - } - if (abilityRecord == nullptr) { - return ERR_INVALID_VALUE; - } + auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); + CHECK_POINTER_AND_RETURN_LOG(handler, ERR_INVALID_VALUE, "Fail to get AbilityEventHandler."); + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + if (!abilityRecord->IsAbilityState(AbilityState::ACTIVATING)) { - HILOG_ERROR("ability transition life state error. expect %{public}d, actual %{public}d callback %{public}d", + HILOG_ERROR("Ability transition life state error. expect %{public}d, actual %{public}d callback %{public}d", AbilityState::ACTIVATING, abilityRecord->GetAbilityState(), state); return ERR_INVALID_VALUE; } + handler->RemoveEvent(AbilityManagerService::ACTIVE_TIMEOUT_MSG, abilityRecord->GetEventId()); auto task = [stackManager = shared_from_this(), abilityRecord]() { stackManager->CompleteActive(abilityRecord); }; handler->PostTask(task); + return ERR_OK; } int AbilityStackManager::DispatchInactive(const std::shared_ptr &abilityRecord, int state) { - std::shared_ptr handler = - DelayedSingleton::GetInstance()->GetEventHandler(); - if (handler == nullptr) { - HILOG_ERROR("fail to get AbilityEventHandler"); - return ERR_INVALID_VALUE; - } - if (abilityRecord == nullptr) { - return ERR_INVALID_VALUE; - } + auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); + CHECK_POINTER_AND_RETURN_LOG(handler, ERR_INVALID_VALUE, "Fail to get AbilityEventHandler."); + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + if (!abilityRecord->IsAbilityState(AbilityState::INACTIVATING)) { - HILOG_ERROR("ability transition life state error. expect %{public}d, actual %{public}d callback %{public}d", + HILOG_ERROR("Ability transition life state error. expect %{public}d, actual %{public}d callback %{public}d", AbilityState::INACTIVATING, abilityRecord->GetAbilityState(), state); return ERR_INVALID_VALUE; } + handler->RemoveEvent(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecord->GetEventId()); auto task = [stackManager = shared_from_this(), abilityRecord]() { stackManager->CompleteInactive(abilityRecord); }; handler->PostTask(task); + return ERR_OK; } int AbilityStackManager::DispatchBackground(const std::shared_ptr &abilityRecord, int state) { - std::shared_ptr handler = - DelayedSingleton::GetInstance()->GetEventHandler(); - if (handler == nullptr) { - HILOG_ERROR("fail to get AbilityEventHandler"); - return ERR_INVALID_VALUE; - } + auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); + CHECK_POINTER_AND_RETURN_LOG(handler, ERR_INVALID_VALUE, "Fail to get AbilityEventHandler."); + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + if (!abilityRecord->IsAbilityState(AbilityState::MOVING_BACKGROUND)) { - HILOG_ERROR("ability transition life state error. expect %{public}d, actual %{public}d callback %{public}d", + HILOG_ERROR("Ability transition life state error. expect %{public}d, actual %{public}d callback %{public}d", AbilityState::MOVING_BACKGROUND, abilityRecord->GetAbilityState(), state); return ERR_INVALID_VALUE; } + // remove background timeout task. handler->RemoveTask(std::to_string(abilityRecord->GetEventId())); auto task = [stackManager = shared_from_this(), abilityRecord]() { stackManager->CompleteBackground(abilityRecord); }; handler->PostTask(task); + return ERR_OK; } int AbilityStackManager::DispatchTerminate(const std::shared_ptr &abilityRecord, int state) { - std::shared_ptr handler = - DelayedSingleton::GetInstance()->GetEventHandler(); - if (handler == nullptr) { - HILOG_ERROR("fail to get AbilityEventHandler"); - return INNER_ERR; - } + auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); + CHECK_POINTER_AND_RETURN_LOG(handler, ERR_INVALID_VALUE, "Fail to get AbilityEventHandler."); + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + if (!abilityRecord->IsAbilityState(AbilityState::TERMINATING)) { - HILOG_ERROR("ability transition life state error. expect %{public}d, actual %{public}d callback %{public}d", + HILOG_ERROR("Ability transition life state error. expect %{public}d, actual %{public}d callback %{public}d", AbilityState::TERMINATING, abilityRecord->GetAbilityState(), state); return INNER_ERR; } + // remove terminate timeout task. handler->RemoveTask(std::to_string(abilityRecord->GetEventId())); auto task = [stackManager = shared_from_this(), abilityRecord]() { stackManager->CompleteTerminate(abilityRecord); }; handler->PostTask(task); + return ERR_OK; } void AbilityStackManager::AddWindowInfo(const sptr &token, int32_t windowToken) { - HILOG_DEBUG("add window id."); + HILOG_DEBUG("Add window id %{public}d.", windowToken); std::lock_guard guard(stackLock_); // create WindowInfo and add to its AbilityRecord - std::shared_ptr abilityRecord = GetAbilityRecordByToken(token); - if (abilityRecord == nullptr) { - HILOG_ERROR("abilityRecord is null. unable to add window info"); - return; - } - if (abilityRecord->GetWindowInfo() != nullptr) { - HILOG_WARN("WindowInfo is already added. Can't add again."); + auto abilityRecord = GetAbilityRecordByToken(token); + CHECK_POINTER(abilityRecord); + if (abilityRecord->GetWindowInfo()) { + HILOG_DEBUG("WindowInfo is already added. Can't add again. %{public}d.", windowToken); return; } - int abilityState = abilityRecord->GetAbilityState(); - if (abilityState != ACTIVATING) { - HILOG_INFO("add windowInfo at state: %{public}d.", abilityState); + + if (!abilityRecord->IsAbilityState(ACTIVATING)) { + HILOG_INFO("Add windowInfo at state: %{public}d.", abilityRecord->GetAbilityState()); } if (windowTokenToAbilityMap_[windowToken] != nullptr) { // It shouldn't happen. Possible reasons for this case: // 1. windowmanager generates same window token. // 2. abilityms doesn't destroy ability in terminate process. - HILOG_ERROR("window token has been added to other AbilityRecord. ability name: %{private}s", + HILOG_ERROR("Window token has been added to other AbilityRecord. ability name: %{private}s", abilityRecord->GetAbilityInfo().name.c_str()); } else { abilityRecord->AddWindowInfo(windowToken); windowTokenToAbilityMap_[windowToken] = abilityRecord; + HILOG_INFO("Add windowInfo complete, windowToken:%{public}d, ability:%{public}s", + windowToken, + abilityRecord->GetAbilityInfo().name.c_str()); } } void AbilityStackManager::OnAbilityRequestDone(const sptr &token, const int32_t state) { - HILOG_DEBUG("ability request app state %{public}d done", state); + HILOG_DEBUG("Ability request app state %{public}d done.", state); std::lock_guard guard(stackLock_); AppAbilityState abilitState = DelayedSingleton::GetInstance()->ConvertToAppAbilityState(state); if (abilitState == AppAbilityState::ABILITY_STATE_FOREGROUND) { - std::shared_ptr abilityRecord = GetAbilityRecordByToken(token); - if (abilityRecord == nullptr) { - HILOG_ERROR("abilityRecord is null"); - return; - } + auto abilityRecord = GetAbilityRecordByToken(token); + CHECK_POINTER(abilityRecord); std::string element = abilityRecord->GetWant().GetElement().GetURI(); - HILOG_DEBUG("%{public}s, ability: %{public}s", __func__, element.c_str()); + HILOG_DEBUG("ability: %{public}s", element.c_str()); abilityRecord->Activate(); } } -void AbilityStackManager::CompleteActive(const std::shared_ptr &abilityRecord) +void AbilityStackManager::OnAppStateChanged(const AppInfo &info) { std::lock_guard guard(stackLock_); - if (!abilityRecord) { - HILOG_ERROR("%{public}s, abilityRecord is nullptr", __func__); - return; + + for (auto &stack : missionStackList_) { + std::vector missions; + stack->GetAllMissionInfo(missions); + for (auto &missionInfo : missions) { + auto mission = stack->GetMissionRecordById(missionInfo.id); + if (!mission) { + HILOG_ERROR("Mission is nullptr."); + continue; + } + std::vector abilitys; + mission->GetAllAbilityInfo(abilitys); + for (auto &abilityInfo : abilitys) { + auto ability = mission->GetAbilityRecordById(abilityInfo.id); + if (!ability) { + HILOG_ERROR("Ability is nullptr."); + continue; + } + + if (ability->GetApplicationInfo().name == info.appName && + (info.processName == ability->GetAbilityInfo().process || + info.processName == ability->GetApplicationInfo().bundleName)) { + ability->SetAppState(info.state); + } + } + } } +} + +void AbilityStackManager::CompleteActive(const std::shared_ptr &abilityRecord) +{ + std::lock_guard guard(stackLock_); + + CHECK_POINTER(abilityRecord); std::string element = abilityRecord->GetWant().GetElement().GetURI(); - HILOG_INFO("%{public}s, ability: %{public}s", __func__, element.c_str()); + HILOG_INFO("ability: %{public}s", element.c_str()); abilityRecord->SetAbilityState(AbilityState::ACTIVE); + // update top active ability + UpdateFocusAbilityRecord(abilityRecord); - std::shared_ptr handler = - DelayedSingleton::GetInstance()->GetEventHandler(); - if (handler == nullptr) { - HILOG_ERROR("fail to get AbilityEventHandler"); + // multi window moving, complete state. + if (abilityRecord->GetInMovingState()) { + // top ability active at last, finish moving. + if (abilityRecord == GetCurrentTopAbility()) { + HILOG_DEBUG("Complete multi window moving,target state is active."); + abilityRecord->SetInMovingState(false); + isMultiWinMoving_ = false; + return; + } + // background to active state. + abilityRecord->SetInMovingState(false); + ContinueLifecycle(); return; } + DelayedSingleton::GetInstance()->NotifyBmsAbilityLifeStatus( + abilityRecord->GetAbilityInfo().bundleName, + abilityRecord->GetAbilityInfo().name, + AbilityUtil::UTCTimeSeconds()); +#if BINDER_IPC_32BIT + HILOG_INFO("notify bms ability life status, bundle name:%{public}s, ability name:%{public}s, time:%{public}lld", + abilityRecord->GetAbilityInfo().bundleName.c_str(), + abilityRecord->GetAbilityInfo().name.c_str(), + AbilityUtil::UTCTimeSeconds()); +#else + HILOG_INFO("notify bms ability life status, bundle name:%{public}s, ability name:%{public}s, time:%{public}ld", + abilityRecord->GetAbilityInfo().bundleName.c_str(), + abilityRecord->GetAbilityInfo().name.c_str(), + AbilityUtil::UTCTimeSeconds()); +#endif + + auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); + CHECK_POINTER_LOG(handler, "Fail to get AbilityEventHandler."); if (abilityRecord->GetPowerState()) { - if (abilityRecord == GetCurrentTopAbility()) { - HILOG_DEBUG("top ability, complete active."); + CHECK_POINTER(powerStorage_); + bool isActiveAbility = false; + auto powerActiveStorages = powerStorage_->GetPowerOffActiveRecord(); + for (auto &powerActiveStorage : powerActiveStorages) { + auto storageActiveAbility = powerActiveStorage.ability.lock(); + if (abilityRecord == storageActiveAbility) { + isActiveAbility = true; + } + } + HILOG_DEBUG("isActiveAbility value %{public}d", static_cast(isActiveAbility)); + if (isActiveAbility && abilityRecord == GetCurrentTopAbility()) { + HILOG_DEBUG("Top ability, complete active."); abilityRecord->SetPowerState(false); auto startWaittingAbilityTask = [stackManager = shared_from_this()]() { stackManager->StartWaittingAbility(); }; handler->PostTask(startWaittingAbilityTask, "startWaittingAbility"); + powerStorage_.reset(); return; } - HILOG_DEBUG("not top ability, need complete inactive."); + if (isActiveAbility) { + return; + } + HILOG_DEBUG("Not top ability, need complete inactive."); abilityRecord->ProcessInactivate(); return; } + if (abilityRecord->IsToEnd()) { + abilityRecord->SetToEnd(false); + } + /* PostTask to trigger start Ability from waiting queue */ auto startWaittingAbilityTask = [stackManager = shared_from_this()]() { stackManager->StartWaittingAbility(); }; handler->PostTask(startWaittingAbilityTask, "startWaittingAbility"); + auto preAbilityRecord = abilityRecord->GetPreAbilityRecord(); // 1. preAbility must be inactive when start ability. // move preAbility to background only if it was inactive. - std::shared_ptr preAbilityRecord = abilityRecord->GetPreAbilityRecord(); - if (preAbilityRecord != nullptr && preAbilityRecord->GetAbilityState() == AbilityState::INACTIVE && - !AbilitUtil::IsSystemDialogAbility( - abilityRecord->GetAbilityInfo().bundleName, abilityRecord->GetAbilityInfo().name)) { - std::string preElement = preAbilityRecord->GetWant().GetElement().GetURI(); - HILOG_INFO("%{public}s, pre ability record: %{public}s", __func__, preElement.c_str()); - // preAbility was inactive ,resume new want flag to false - MoveToBackgroundTask(preAbilityRecord); + if (preAbilityRecord) { + auto preStackId = preAbilityRecord->GetMissionStackId(); + auto currentStackId = abilityRecord->GetMissionStackId(); + auto preMissionId = preAbilityRecord->GetMissionRecordId(); + auto currentMissionId = abilityRecord->GetMissionRecordId(); + auto isBackground = + (!IsTopInMission(preAbilityRecord)) || preAbilityRecord->IsToEnd() || + ((IsFullScreenStack(preStackId) && IsFullScreenStack(currentStackId)) || + ((preStackId == FLOATING_MISSION_STACK_ID) && (currentStackId == FLOATING_MISSION_STACK_ID) && + preMissionId == currentMissionId) || + ((preStackId == FLOATING_MISSION_STACK_ID) && (currentStackId == FLOATING_MISSION_STACK_ID) && + !SupportSyncVisualByStackId(FLOATING_MISSION_STACK_ID) && preMissionId != currentMissionId)); + + if (isBackground && preAbilityRecord->IsAbilityState(AbilityState::INACTIVE) && + !AbilityUtil::IsSystemDialogAbility( + abilityRecord->GetAbilityInfo().bundleName, abilityRecord->GetAbilityInfo().name)) { + std::string preElement = preAbilityRecord->GetWant().GetElement().GetURI(); + HILOG_INFO("Pre ability record: %{public}s", preElement.c_str()); + // preAbility was inactive ,resume new want flag to false + MoveToBackgroundTask(preAbilityRecord); + // Flag completed move to end. + if (preAbilityRecord->IsToEnd()) { + preAbilityRecord->SetToEnd(false); + } + } } // 2. nextAbility was in terminate list when terminate ability. @@ -852,7 +1197,7 @@ void AbilityStackManager::CompleteActive(const std::shared_ptr &a if (nextAbilityRecord != nullptr && nextAbilityRecord->IsAbilityState(AbilityState::INACTIVE) && nextAbilityRecord->IsTerminating()) { std::string nextElement = nextAbilityRecord->GetWant().GetElement().GetURI(); - HILOG_INFO("%{public}s, next ability record : %{public}s", __func__, nextElement.c_str()); + HILOG_INFO("Next ability record : %{public}s", nextElement.c_str()); MoveToBackgroundTask(nextAbilityRecord); } @@ -863,26 +1208,23 @@ void AbilityStackManager::CompleteActive(const std::shared_ptr &a backAbilityRecord->IsTerminating() && (nextAbilityRecord == nullptr || nextAbilityRecord->GetRecordId() != backAbilityRecord->GetRecordId())) { std::string backElement = backAbilityRecord->GetWant().GetElement().GetURI(); - HILOG_INFO("%{public}s, back ability record: %{public}s", __func__, backElement.c_str()); + HILOG_INFO("Back ability record: %{public}s", backElement.c_str()); MoveToBackgroundTask(backAbilityRecord); } if (powerOffing_ && waittingAbilityQueue_.empty()) { - HILOG_INFO("Wait for the ability life cycle to complete and execute poweroff"); + HILOG_INFO("Wait for the ability life cycle to complete and execute poweroff."); PowerOffLocked(); } } void AbilityStackManager::MoveToBackgroundTask(const std::shared_ptr &abilityRecord) { - if (!abilityRecord) { - HILOG_ERROR("abilityRecord is nullptr"); - return; - } + CHECK_POINTER(abilityRecord); abilityRecord->SetIsNewWant(false); std::string backElement = abilityRecord->GetWant().GetElement().GetURI(); - HILOG_INFO("ability record: %{public}s", backElement.c_str()); + HILOG_INFO("Ability record: %{public}s", backElement.c_str()); auto task = [abilityRecord, stackManager = shared_from_this()]() { - HILOG_WARN("stack manager move to background timeout."); + HILOG_WARN("Stack manager move to background timeout."); stackManager->CompleteBackground(abilityRecord); }; abilityRecord->MoveToBackground(task); @@ -892,70 +1234,98 @@ void AbilityStackManager::CompleteInactive(const std::shared_ptr { std::lock_guard guard(stackLock_); std::string element = abilityRecord->GetWant().GetElement().GetURI(); - HILOG_INFO("%{public}s, ability: %{public}s", __func__, element.c_str()); + HILOG_INFO("ability: %{public}s", element.c_str()); abilityRecord->SetAbilityState(AbilityState::INACTIVE); - // ability state is inactive - if (abilityRecord->GetPowerState()) { + + // 0. multi window moving , complete lifecycle. + if (abilityRecord->GetInMovingState()) { if (abilityRecord == GetCurrentTopAbility()) { - abilityRecord->SetPowerState(false); + ContinueLifecycle(); + return; + } + MoveToBackgroundTask(abilityRecord); + abilityRecord->SetInMovingState(false); + // to process next active ability + ContinueLifecycle(); + return; + } + + if (abilityRecord->IsToEnd()) { + auto nextAbility = abilityRecord->GetNextAbilityRecord(); + if (!nextAbility || (nextAbility && !nextAbility->IsToEnd())) { + abilityRecord->SetToEnd(false); MoveToBackgroundTask(abilityRecord); return; } + } - HILOG_DEBUG("complete ,target state is inactive."); - abilityRecord->SetPowerState(false); + // ability state is inactive + if (abilityRecord->GetPowerState()) { CHECK_POINTER(powerStorage_); - auto powerStorages = powerStorage_->GetPowerOffRecord(); - for (auto &powerStorage : powerStorages) { - auto stack = GetStackById(powerStorage.StackId); - CHECK_POINTER_CONTINUE(stack); - auto missionRecord = stack->GetMissionRecordById(powerStorage.missionId); - CHECK_POINTER_CONTINUE(missionRecord); - auto topAbility = missionRecord->GetTopAbilityRecord(); - CHECK_POINTER_CONTINUE(topAbility); - if (topAbility->GetPowerState() && topAbility != GetCurrentTopAbility()) { - HILOG_DEBUG("wait other ability to complete lifecycle. Ability: %{public}s.", - topAbility->GetAbilityInfo().name.c_str()); + auto powerActiveStorages = powerStorage_->GetPowerOffActiveRecord(); + for (auto &powerActiveStorage : powerActiveStorages) { + auto storageActiveAbility = powerActiveStorage.ability.lock(); + if (abilityRecord == storageActiveAbility) { + abilityRecord->SetPowerState(false); + MoveToBackgroundTask(abilityRecord); return; } } - auto currentTopAbility = GetCurrentTopAbility(); - CHECK_POINTER(currentTopAbility); - HILOG_DEBUG("At last, complete top ability lifecycle, target state is active."); - currentTopAbility->ProcessActivate(); - powerStorage_.reset(); + HILOG_DEBUG("Complete ,target state is inactive."); + abilityRecord->SetPowerState(false); + auto powerInActiveStorages = powerStorage_->GetPowerOffInActiveRecord(); + for (auto &powerInActiveStorage : powerInActiveStorages) { + auto storageInActiveAbility = powerInActiveStorage.ability.lock(); + CHECK_POINTER_CONTINUE(storageInActiveAbility); + if (storageInActiveAbility->GetPowerState()) { + HILOG_DEBUG("Wait other ability to complete lifecycle. Ability: %{public}s.", + storageInActiveAbility->GetAbilityInfo().name.c_str()); + return; + } + } + if (ChangedPowerStorageAbilityToActive(powerStorage_) != ERR_OK) { + HILOG_ERROR("ChangedPowerStorageAbilityToActive Fail"); + return; + } return; } // 1. it may be inactive callback of terminate ability. if (abilityRecord->IsTerminating()) { abilityRecord->SendResultToCallers(); if (abilityRecord->IsForceTerminate()) { - HILOG_WARN("ability is forced to terminate."); + HILOG_WARN("Ability is forced to terminate."); MoveToBackgroundTask(abilityRecord); return; } - std::shared_ptr topAbilityRecord = GetCurrentTopAbility(); - if (topAbilityRecord == nullptr) { - HILOG_ERROR("no top ability! Jump to launcher."); + auto nextActiveAbility = abilityRecord->GetNextAbilityRecord(); + CHECK_POINTER_LOG(nextActiveAbility, "No top ability! Jump to launcher."); + if (nextActiveAbility->IsAbilityState(ACTIVE)) { + MoveToBackgroundTask(abilityRecord); + UpdateFocusAbilityRecord(nextActiveAbility, true); return; } // need to specify the back ability as the current ability - topAbilityRecord->SetBackAbilityRecord(abilityRecord); + nextActiveAbility->SetBackAbilityRecord(abilityRecord); // top ability.has been pushed into stack, but haven't load. // so we need load it first - topAbilityRecord->ProcessActivate(); + nextActiveAbility->ProcessActivate(); return; } - // 2. it may be callback of start ability. - // if next ability has been launched and is in bottom of mission, just resume other than loading ability. - std::shared_ptr nextAbilityRecord = abilityRecord->GetNextAbilityRecord(); - if (nextAbilityRecord == nullptr) { - HILOG_ERROR("failed to get next ability record"); + + // 2. it may be callback of restart ability. + if (abilityRecord->IsRestarting()) { + HILOG_INFO("%{public}s, back ability record: %{public}s", __func__, element.c_str()); + MoveToBackgroundTask(abilityRecord); return; } + // 3. it may be callback of start ability. + // if next ability has been launched and is in bottom of mission, just resume other than loading ability. + auto nextAbilityRecord = abilityRecord->GetNextAbilityRecord(); + CHECK_POINTER_LOG(nextAbilityRecord, "Failed to get next ability record."); + std::string nextElement = nextAbilityRecord->GetWant().GetElement().GetURI(); - HILOG_DEBUG("next ability record: %{public}s", nextElement.c_str()); + HILOG_DEBUG("Next ability record: %{public}s", nextElement.c_str()); nextAbilityRecord->ProcessActivate(); } @@ -964,10 +1334,11 @@ void AbilityStackManager::CompleteBackground(const std::shared_ptr guard(stackLock_); std::string element = abilityRecord->GetWant().GetElement().GetURI(); sptr token = abilityRecord->GetToken(); - HILOG_INFO("%{public}s, ability: %{public}s", __func__, element.c_str()); + HILOG_INFO("ability: %{public}s", element.c_str()); - if (abilityRecord->GetAbilityState() == ACTIVATING || abilityRecord->GetAbilityState() == ACTIVE) { - HILOG_ERROR("%{public}s, ability may be activing or active, it can't complete background ", __func__); + if (abilityRecord->GetAbilityState() == ACTIVATING || abilityRecord->GetAbilityState() == ACTIVE || + abilityRecord->GetAbilityState() == INITIAL) { + HILOG_ERROR("Ability may be activing or active, it can't complete background."); return; } @@ -975,45 +1346,63 @@ void AbilityStackManager::CompleteBackground(const std::shared_ptr::GetInstance()->MoveToBackground(token); - // Abilities ahead of the one started with SingleTask mode were put in terminate list, we need to terminate them. + // Abilities ahead of the one started with SingleTask mode were put in terminate list, we need to terminate + // them. for (auto terminateAbility : terminateAbilityRecordList_) { if (terminateAbility->IsAbilityState(AbilityState::BACKGROUND)) { auto timeoutTask = [terminateAbility, stackManager = shared_from_this()]() { - HILOG_WARN("disconnect ability terminate timeout."); + HILOG_WARN("Disconnect ability terminate timeout."); stackManager->CompleteTerminate(terminateAbility); }; terminateAbility->Terminate(timeoutTask); } } + + if (abilityRecord->IsRestarting() && abilityRecord->IsAbilityState(AbilityState::BACKGROUND)) { + auto timeoutTask = [abilityRecord, stackManager = shared_from_this()]() { + HILOG_WARN("disconnect ability terminate timeout."); + stackManager->CompleteTerminate(abilityRecord); + }; + abilityRecord->Terminate(timeoutTask); + } } void AbilityStackManager::CompleteTerminate(const std::shared_ptr &abilityRecord) { std::lock_guard guard(stackLock_); - if (!abilityRecord) { - HILOG_ERROR("%{public}s, abilityRecord is nullptr", __func__); + + CHECK_POINTER(abilityRecord); + std::string element = abilityRecord->GetWant().GetElement().GetURI(); + HILOG_INFO("ability: %{public}s", element.c_str()); + + if (!abilityRecord->IsAbilityState(AbilityState::TERMINATING)) { + HILOG_ERROR("%{public}s, ability is not terminating.", __func__); return; } - std::string element = abilityRecord->GetWant().GetElement().GetURI(); - HILOG_INFO("%{public}s, ability: %{public}s", __func__, element.c_str()); // notify AppMS terminate if (abilityRecord->TerminateAbility() != ERR_OK) { // Don't return here - HILOG_ERROR("AppMS fail to terminate ability"); + HILOG_ERROR("AppMS fail to terminate ability."); } // destroy abilityRecord auto windowInfo = abilityRecord->GetWindowInfo(); if (windowInfo != nullptr) { windowTokenToAbilityMap_.erase(windowInfo->windowToken_); } + + if (abilityRecord->IsRestarting()) { + abilityRecord->SetAbilityState(AbilityState::INITIAL); + abilityRecord->SetScheduler(nullptr); + abilityRecord->LoadAbility(); + } for (auto it : terminateAbilityRecordList_) { if (it == abilityRecord) { terminateAbilityRecordList_.remove(it); - HILOG_DEBUG("destroy ability record count %ld", abilityRecord.use_count()); + HILOG_DEBUG("Destroy ability record count %ld", abilityRecord.use_count()); break; } - HILOG_WARN("can't find ability in terminate list."); + HILOG_WARN("Can't find ability in terminate list."); } } @@ -1052,6 +1441,21 @@ void AbilityStackManager::DumpStackList(std::vector &info) } } +void AbilityStackManager::DumpFocusMap(std::vector &info) +{ + std::lock_guard guard(stackLock_); + std::string dumpInfo = "User ID #" + std::to_string(userId_); + info.push_back(dumpInfo); + for (auto iter : focusAbilityRecordMap_) { + std::string displayInfo = " Display ID #" + std::to_string(iter.first); + info.push_back(displayInfo); + auto ability = iter.second; + if (ability.lock()) { + ability.lock()->Dump(info); + } + } +} + void AbilityStackManager::GetAllStackInfo(StackInfo &stackInfo) { std::lock_guard guard(stackLock_); @@ -1125,15 +1529,12 @@ void AbilityStackManager::EnqueueWaittingAbility(const AbilityRequest &abilityRe void AbilityStackManager::StartWaittingAbility() { - std::shared_ptr topAbility; std::lock_guard guard(stackLock_); - topAbility = GetCurrentTopAbility(); - if (!topAbility) { - HILOG_INFO("%{public}s, topAbility is nullptr", __func__); - return; - } - if (topAbility->GetAbilityState() != ACTIVE) { - HILOG_INFO("top ability is not active, must return for waiting again"); + auto topAbility = GetCurrentTopAbility(); + CHECK_POINTER(topAbility); + + if (!topAbility->IsAbilityState(ACTIVE)) { + HILOG_INFO("Top ability is not active, must return for start waiting again."); return; } @@ -1141,6 +1542,7 @@ void AbilityStackManager::StartWaittingAbility() AbilityRequest abilityRequest = waittingAbilityQueue_.front(); waittingAbilityQueue_.pop(); StartAbilityLocked(topAbility, abilityRequest); + return; } } @@ -1148,11 +1550,9 @@ void AbilityStackManager::GetMissionRecordAndAbilityRecord(const AbilityRequest const std::shared_ptr ¤tTopAbility, std::shared_ptr &targetAbilityRecord, std::shared_ptr &targetMissionRecord) { - HILOG_DEBUG("%{public}s, %{public}d", __func__, __LINE__); - if (currentMissionStack_ == nullptr) { - HILOG_ERROR("currentMissionStack_ is nullptr"); - return; - } + HILOG_DEBUG("Get mission record and ability record."); + CHECK_POINTER(currentMissionStack_); + // The singleInstance start mode, mission name is #bundleName:abilityName. if (abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SINGLETON) { GetRecordBySingleton(abilityRequest, currentTopAbility, targetAbilityRecord, targetMissionRecord); @@ -1166,13 +1566,9 @@ void AbilityStackManager::GetRecordBySingleton(const AbilityRequest &abilityRequ const std::shared_ptr ¤tTopAbility, std::shared_ptr &targetAbilityRecord, std::shared_ptr &targetMissionRecord) { - if (currentMissionStack_ == nullptr) { - HILOG_ERROR("currentMissionStack_ is nullptr"); - return; - } - std::string bundleName = MISSION_NAME_MARK_HEAD + abilityRequest.abilityInfo.bundleName + MISSION_NAME_SEPARATOR + - abilityRequest.abilityInfo.name; - std::shared_ptr missionRecord = currentMissionStack_->GetTargetMissionRecord(bundleName); + std::string bundleName = + AbilityUtil::ConvertBundleNameSingleton(abilityRequest.abilityInfo.bundleName, abilityRequest.abilityInfo.name); + auto missionRecord = GetMissionRecordByName(bundleName); if (missionRecord == nullptr) { targetAbilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); targetMissionRecord = std::make_shared(bundleName); @@ -1181,6 +1577,7 @@ void AbilityStackManager::GetRecordBySingleton(const AbilityRequest &abilityRequ if (targetAbilityRecord != nullptr) { targetAbilityRecord->SetWant(abilityRequest.want); targetAbilityRecord->SetIsNewWant(true); + CheckMissionRecordIsResume(missionRecord); } targetMissionRecord = missionRecord; } @@ -1190,11 +1587,6 @@ void AbilityStackManager::GetRecordByStandard(const AbilityRequest &abilityReque const std::shared_ptr ¤tTopAbility, std::shared_ptr &targetAbilityRecord, std::shared_ptr &targetMissionRecord) { - if (currentMissionStack_ == nullptr) { - HILOG_ERROR("currentMissionStack_ is nullptr"); - return; - } - bool isStackChanged = false; if (currentTopAbility) { isStackChanged = (currentTopAbility->IsLauncherAbility() && !IsLauncherAbility(abilityRequest)) || @@ -1204,7 +1596,7 @@ void AbilityStackManager::GetRecordByStandard(const AbilityRequest &abilityReque if (currentTopAbility == nullptr || (currentTopAbility && isStackChanged) || (currentTopAbility && currentTopAbility->GetAbilityInfo().launchMode == AppExecFwk::LaunchMode::SINGLETON)) { // first get target mission record by bundleName - auto missionRecord = currentMissionStack_->GetTargetMissionRecord(abilityRequest.abilityInfo.bundleName); + auto missionRecord = GetMissionRecordByName(abilityRequest.abilityInfo.bundleName); if (missionRecord == nullptr) { targetAbilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); targetMissionRecord = std::make_shared(abilityRequest.abilityInfo.bundleName); @@ -1213,6 +1605,8 @@ void AbilityStackManager::GetRecordByStandard(const AbilityRequest &abilityReque * Check whether the requested ability is not at the top of the stack of the target mission, * True: Need to create a new one . Other: Restart the top ability of this mission. */ + CheckMissionRecordIsResume(missionRecord); + if (currentTopAbility && (!isStackChanged) && (currentTopAbility->GetAbilityInfo().launchMode == AppExecFwk::LaunchMode::SINGLETON) && ((!missionRecord->IsTopAbilityRecordByName(abilityRequest.abilityInfo.name)) || @@ -1232,15 +1626,15 @@ void AbilityStackManager::GetRecordByStandard(const AbilityRequest &abilityReque } } else if (currentTopAbility && (!isStackChanged)) { // The requested ability is already top ability. Reuse top ability. + targetMissionRecord = currentTopAbility->GetMissionRecord(); + CheckMissionRecordIsResume(targetMissionRecord); if (abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SINGLETOP && currentTopAbility->GetMissionRecord()->IsTopAbilityRecordByName(abilityRequest.abilityInfo.name)) { targetAbilityRecord = currentTopAbility; targetAbilityRecord->SetWant(abilityRequest.want); targetAbilityRecord->SetIsNewWant(true); - targetMissionRecord = currentTopAbility->GetMissionRecord(); } else { targetAbilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - targetMissionRecord = currentTopAbility->GetMissionRecord(); } } } @@ -1261,14 +1655,14 @@ bool AbilityStackManager::IsLauncherMission(int id) int AbilityStackManager::GetRecentMissions( const int32_t numMax, const int32_t flags, std::vector &recentList) { - HILOG_INFO("%{public}s,%{public}d", __PRETTY_FUNCTION__, __LINE__); + HILOG_INFO("Get recent missions."); std::lock_guard guard(stackLock_); if (numMax < 0) { - HILOG_ERROR("get recent missions, numMax is invalid"); + HILOG_ERROR("numMax is invalid"); return ERR_INVALID_VALUE; } if (flags < RECENT_WITH_EXCLUDED || flags > RECENT_IGNORE_UNAVAILABLE) { - HILOG_ERROR("get recent missions, flags is invalid"); + HILOG_ERROR("flags is invalid"); return ERR_INVALID_VALUE; } @@ -1278,11 +1672,8 @@ int AbilityStackManager::GetRecentMissions( int AbilityStackManager::GetRecentMissionsLocked( const int32_t numMax, const int32_t flags, std::vector &recentList) { - HILOG_INFO("%{public}s,%{public}d", __func__, __LINE__); - if (defaultMissionStack_ == nullptr) { - HILOG_ERROR("defaultMissionStack_ is invalid"); - return ERR_NO_INIT; - } + HILOG_INFO("Get recent missions locked."); + CHECK_POINTER_AND_RETURN(defaultMissionStack_, ERR_NO_INIT); bool withExcluded = (static_cast(flags) & RECENT_WITH_EXCLUDED) != 0; std::vector missionInfos; @@ -1297,16 +1688,16 @@ int AbilityStackManager::GetRecentMissionsLocked( if (!withExcluded) { auto missionRecord = defaultMissionStack_->GetMissionRecordById(mission.id); if (!missionRecord) { - HILOG_ERROR("mission is nullptr, continue"); + HILOG_ERROR("Mission is nullptr, continue."); continue; } auto ability = missionRecord->GetTopAbilityRecord(); if (!ability) { - HILOG_ERROR("ability is nullptr, continue"); + HILOG_ERROR("Ability is nullptr, continue."); continue; } if (ability->IsAbilityState(AbilityState::INITIAL)) { - HILOG_INFO("flag is RECENT_IGNORE_UNAVAILABLE, ability state: INITIAL, continue"); + HILOG_INFO("Flag is RECENT_IGNORE_UNAVAILABLE, ability state: INITIAL, continue."); continue; } } @@ -1321,16 +1712,13 @@ int AbilityStackManager::GetRecentMissionsLocked( void AbilityStackManager::CreateRecentMissionInfo( const MissionRecordInfo &mission, AbilityMissionInfo &recentMissionInfo) { - HILOG_INFO("%{public}s,%{public}d", __func__, __LINE__); + HILOG_INFO("Create recent mission info."); recentMissionInfo.id = mission.id; - recentMissionInfo.runingState = -1; + recentMissionInfo.runingState = DEFAULT_INVAL_VALUE; - auto missionRecord = defaultMissionStack_->GetMissionRecordById(mission.id); - if (missionRecord == nullptr) { - HILOG_INFO("%{public}s,mission record is not exist", __func__); - return; - } - auto parentStack = missionRecord->GetParentStack(); + auto missionRecord = GetMissionRecordFromAllStacks(mission.id); + CHECK_POINTER_LOG(missionRecord, "Mission record is not exist."); + auto parentStack = missionRecord->GetMissionStack(); recentMissionInfo.missionStackId = parentStack->GetMissionStackId(); auto baseAbility = missionRecord->GetBottomAbilityRecord(); if (baseAbility != nullptr) { @@ -1385,12 +1773,78 @@ int AbilityStackManager::GetMissionLockModeState() return lockMissionContainer_->GetLockedMissionState(); } +int AbilityStackManager::UpdateConfiguration(const DummyConfiguration &config) +{ + HILOG_INFO("%{public}s called", __FUNCTION__); + std::lock_guard guard(stackLock_); + + // update all stack configuration. + for (auto &stack : missionStackList_) { + CHECK_POINTER_AND_RETURN(stack, ERR_INVALID_VALUE); + HILOG_DEBUG("stack id : %{public}d", stack->GetMissionStackId()); + std::shared_ptr configSptr = std::make_shared(config); + stack->UpdateConfiguration(configSptr); + } + + return ProcessConfigurationChange(); +} + +int AbilityStackManager::ProcessConfigurationChange() +{ + HILOG_INFO("%{public}s called.", __FUNCTION__); + + // all active ability check whether process onconfigurationchanged + for (auto &stack : missionStackList_) { + CHECK_POINTER_AND_RETURN(stack, ERR_INVALID_VALUE); + HILOG_DEBUG("stack id : %{public}d", stack->GetMissionStackId()); + std::vector missionInfos; + stack->GetAllMissionInfo(missionInfos); + for (auto &mission : missionInfos) { + auto missionRecord = stack->GetMissionRecordById(mission.id); + if (!missionRecord) { + continue; + } + for (auto &it : mission.abilityRecordInfos) { + auto abilityRecord = missionRecord->GetAbilityRecordById(it.id); + if (abilityRecord && abilityRecord->IsAbilityState(AbilityState::ACTIVE)) { + abilityRecord->ProcessConfigurationChange(); + } + } + } + } + + return ERR_OK; +} + +void AbilityStackManager::RestartAbility(const std::shared_ptr abilityRecord) +{ + HILOG_INFO("%{public}s called", __FUNCTION__); + CHECK_POINTER(abilityRecord); + abilityRecord->SetRestarting(true); + if (abilityRecord->IsAbilityState(AbilityState::ACTIVE) || + abilityRecord->IsAbilityState(AbilityState::ACTIVATING)) { + abilityRecord->Inactivate(); + } else if (abilityRecord->IsAbilityState(AbilityState::INACTIVE) || + abilityRecord->IsAbilityState(AbilityState::INACTIVATING)) { + MoveToBackgroundTask(abilityRecord); + } else if (abilityRecord->IsAbilityState(AbilityState::BACKGROUND) || + abilityRecord->IsAbilityState(AbilityState::MOVING_BACKGROUND)) { + auto timeoutTask = [abilityRecord, stackManager = shared_from_this()]() { + HILOG_WARN("disconnect ability terminate timeout."); + stackManager->CompleteTerminate(abilityRecord); + }; + abilityRecord->Terminate(timeoutTask); + } else { + HILOG_WARN("target ability can't be restarted."); + } +} + int AbilityStackManager::MoveMissionToTop(int32_t missionId) { - HILOG_INFO("%{public}s,%{public}d", __PRETTY_FUNCTION__, __LINE__); + HILOG_INFO("Move mission to top."); std::lock_guard guard(stackLock_); if (missionId < 0) { - HILOG_ERROR("%{public}s, mission id is invalid", __func__); + HILOG_ERROR("Mission id is invalid."); return ERR_INVALID_VALUE; } @@ -1404,56 +1858,86 @@ int AbilityStackManager::MoveMissionToTop(int32_t missionId) int AbilityStackManager::MoveMissionToTopLocked(int32_t missionId) { - HILOG_INFO("%{public}s,%{public}d", __PRETTY_FUNCTION__, __LINE__); - if (!defaultMissionStack_ || !launcherMissionStack_) { - HILOG_ERROR("mission stack is invalid"); - return ERR_NO_INIT; + HILOG_INFO("Move mission to top locked."); + + if (isMultiWinMoving_) { + HILOG_ERROR("System is moving multi window state, request deny."); + return MOVE_MISSION_TO_STACK_MOVING_DENIED; } + CHECK_TRUE_RETURN_RET((!defaultMissionStack_ || !launcherMissionStack_), ERR_NO_INIT, "Mission stack is invalid."); auto currentTopAbility = GetCurrentTopAbility(); - if (!currentTopAbility) { - return MOVE_MISSION_FAILED; - } + CHECK_POINTER_AND_RETURN(currentTopAbility, MOVE_MISSION_FAILED); + + auto currentStack = currentTopAbility->GetMissionRecord()->GetMissionStack(); + CHECK_POINTER_AND_RETURN(currentStack, MOVE_MISSION_FAILED); auto requestMissionRecord = GetMissionRecordFromAllStacks(missionId); - if (!requestMissionRecord) { - HILOG_ERROR("Mission does not exist"); - return MOVE_MISSION_FAILED; - } + CHECK_POINTER_AND_RETURN(requestMissionRecord, MOVE_MISSION_FAILED); + + CheckMissionRecordIsResume(requestMissionRecord); auto requestAbilityRecord = requestMissionRecord->GetTopAbilityRecord(); - if (!requestAbilityRecord) { - HILOG_ERROR("the bottom ability does not exist"); - return MOVE_MISSION_FAILED; + CHECK_POINTER_AND_RETURN(requestAbilityRecord, MOVE_MISSION_FAILED); + + auto requestStack = requestMissionRecord->GetMissionStack(); + CHECK_POINTER_AND_RETURN(requestStack, MOVE_MISSION_FAILED); + + // request ability active, current ability active, change focus + if (requestAbilityRecord->IsAbilityState(ACTIVE)) { + MoveMissionStackToTop(requestStack); + requestStack->MoveMissionRecordToTop(requestMissionRecord); + UpdateFocusAbilityRecord(requestAbilityRecord, true); + return ERR_OK; } - auto requestStack = requestMissionRecord->GetParentStack(); - MoveMissionStackToTop(requestStack); - MoveMissionAndAbility(currentTopAbility, requestAbilityRecord, requestMissionRecord, true); + if (currentStack->IsEqualStackId(FLOATING_MISSION_STACK_ID) && + IsFullScreenStack(requestStack->GetMissionStackId())) { + auto fullScreenStack = GetTopFullScreenStack(); + CHECK_POINTER_AND_RETURN(fullScreenStack, MOVE_MISSION_FAILED); + currentTopAbility = fullScreenStack->GetTopAbilityRecord(); + } - int result = ERR_OK; - if (currentTopAbility == nullptr) { - requestAbilityRecord->SetLauncherRoot(); - result = requestAbilityRecord->LoadAbility(); - } else { - currentTopAbility->Inactivate(); + if (IsFullScreenStack(currentStack->GetMissionStackId()) && + requestStack->IsEqualStackId(FLOATING_MISSION_STACK_ID)) { + auto floatingStack = GetOrCreateMissionStack(FLOATING_MISSION_STACK_ID, false); + auto topAbility = floatingStack->GetTopAbilityRecord(); + if (SupportSyncVisualByStackId(FLOATING_MISSION_STACK_ID) || + (!SupportSyncVisualByStackId(FLOATING_MISSION_STACK_ID) && requestAbilityRecord == topAbility)) { + MoveMissionStackToTop(requestStack); + requestAbilityRecord->ProcessActivate(); + return ERR_OK; + } + currentTopAbility = topAbility; } - return result; + + MoveMissionStackToTop(requestStack); + MoveMissionAndAbility(currentTopAbility, requestAbilityRecord, requestMissionRecord); + + currentTopAbility->Inactivate(); + return ERR_OK; } int AbilityStackManager::MoveMissionToEnd(const sptr &token, const bool nonFirst) { std::lock_guard guard(stackLock_); + if (lockMissionContainer_ && lockMissionContainer_->IsLockedMissionState()) { HILOG_ERROR("current is lock mission state, refusing to operate other mission."); return ERR_INVALID_VALUE; } + + if (isMultiWinMoving_) { + HILOG_ERROR("System is moving multi window state, request deny."); + return MOVE_MISSION_TO_STACK_MOVING_DENIED; + } + return MoveMissionToEndLocked(token, nonFirst); } int AbilityStackManager::MoveMissionToEndLocked(const sptr &token, const bool nonFirst) { - HILOG_INFO("%{public}s,%{public}d", __func__, __LINE__); + HILOG_INFO("Move mission to end locked."); CHECK_POINTER_AND_RETURN(token, MOVE_MISSION_FAILED); @@ -1463,76 +1947,113 @@ int AbilityStackManager::MoveMissionToEndLocked(const sptr &token auto missionRecord = abilityRecord->GetMissionRecord(); CHECK_POINTER_AND_RETURN(missionRecord, MOVE_MISSION_FAILED); - auto currentTopAbility = missionRecord->GetTopAbilityRecord(); - CHECK_POINTER_AND_RETURN(currentTopAbility, MOVE_MISSION_FAILED); - - if (!currentTopAbility->IsAbilityState(AbilityState::ACTIVE) || - currentTopAbility->GetAbilityInfo().applicationInfo.isLauncherApp) { - HILOG_ERROR("ability is not active, or ability is launcher, can't move mission to end"); - return MOVE_MISSION_FAILED; - } - if (!nonFirst) { if (missionRecord->GetBottomAbilityRecord() != abilityRecord) { - HILOG_ERROR("nonFirst is false, it's not the bottom of the mission, can't move mission to end"); + HILOG_ERROR("nonFirst is false, it's not the bottom of the mission, can't move mission to end."); return MOVE_MISSION_FAILED; } } - auto isActiveLauncher = (missionRecord->IsLauncherCreate() || - missionRecord->GetParentStack()->GetBottomMissionRecord() == missionRecord); + return MoveMissionToEndLocked(missionRecord->GetMissionRecordId()); +} + +int AbilityStackManager::MoveMissionToEndLocked(int missionId) +{ + HILOG_INFO("Move mission to end locked by mission id."); + + if (isMultiWinMoving_) { + HILOG_ERROR("System is moving multi window state, request deny."); + return MOVE_MISSION_TO_STACK_MOVING_DENIED; + } + + if (lockMissionContainer_ && lockMissionContainer_->IsLockedMissionState()) { + HILOG_ERROR("current is lock mission state, refusing to operate other mission."); + return ERR_INVALID_VALUE; + } + auto requestMission = GetMissionRecordFromAllStacks(missionId); + CHECK_POINTER_AND_RETURN(requestMission, MOVE_MISSION_FAILED); + auto requestAbility = requestMission->GetTopAbilityRecord(); + CHECK_POINTER_AND_RETURN(requestAbility, MOVE_MISSION_FAILED); + auto requestStack = requestMission->GetMissionStack(); + CHECK_POINTER_AND_RETURN(requestStack, MOVE_MISSION_FAILED); - auto currentStack = missionRecord->GetParentStack(); + if (!requestAbility->IsAbilityState(AbilityState::ACTIVE) || + requestAbility->GetAbilityInfo().applicationInfo.isLauncherApp) { + HILOG_ERROR("Ability is not active, or ability is launcher, can't move mission to end."); + return MOVE_MISSION_FAILED; + } + // current top ability hold focus + auto currentTopAbility = GetCurrentTopAbility(); + CHECK_POINTER_AND_RETURN(currentTopAbility, MOVE_MISSION_FAILED); + auto currentMission = currentTopAbility->GetMissionRecord(); + CHECK_POINTER_AND_RETURN(currentMission, MOVE_MISSION_FAILED); + auto currentStack = currentMission->GetMissionStack(); CHECK_POINTER_AND_RETURN(currentStack, MOVE_MISSION_FAILED); - currentStack->MoveMissionRecordToBottom(missionRecord); - missionRecord->SetIsLauncherCreate(); std::shared_ptr targetAbilityRecord; std::shared_ptr targetMissionRecord; std::shared_ptr targetMissionStack; + if (IsFullScreenStack(currentStack->GetMissionStackId()) && + requestStack->GetMissionStackId() == FLOATING_MISSION_STACK_ID) { + requestStack->MoveMissionRecordToBottom(requestMission); + requestAbility->SetToEnd(true); + requestAbility->Inactivate(); + return ERR_OK; + } + + if (currentStack->GetMissionStackId() == FLOATING_MISSION_STACK_ID && + requestStack->GetMissionStackId() == FLOATING_MISSION_STACK_ID) { + requestStack->MoveMissionRecordToBottom(requestMission); + requestAbility->SetToEnd(true); + requestAbility->Inactivate(); + // floating hold focus, shift focus to full screen stack + if (currentTopAbility == requestAbility) { + auto fullScreenStack = GetTopFullScreenStack(); + CHECK_POINTER_AND_RETURN(fullScreenStack, MOVE_MISSION_FAILED); + MoveMissionStackToTop(fullScreenStack); + auto fullScreenTopAbility = fullScreenStack->GetTopAbilityRecord(); + CHECK_POINTER_AND_RETURN(fullScreenTopAbility, MOVE_MISSION_FAILED); + UpdateFocusAbilityRecord(fullScreenTopAbility, true); + } + return ERR_OK; + } + + auto isActiveLauncher = (requestMission->IsLauncherCreate() || + requestMission->GetMissionStack()->GetBottomMissionRecord() == requestMission); + requestStack->MoveMissionRecordToBottom(requestMission); + requestMission->SetIsLauncherCreate(); + if (isActiveLauncher) { MoveMissionStackToTop(launcherMissionStack_); targetMissionStack = launcherMissionStack_; targetMissionRecord = launcherMissionStack_->GetTopMissionRecord(); targetAbilityRecord = targetMissionRecord->GetTopAbilityRecord(); } else { - targetMissionStack = currentStack; + targetMissionStack = requestStack; targetMissionRecord = targetMissionStack->GetTopMissionRecord(); targetAbilityRecord = targetMissionRecord->GetTopAbilityRecord(); } - if (currentTopAbility) { - targetAbilityRecord->SetPreAbilityRecord(currentTopAbility); - currentTopAbility->SetNextAbilityRecord(targetAbilityRecord); - } + targetAbilityRecord->SetPreAbilityRecord(requestAbility); + requestAbility->SetNextAbilityRecord(targetAbilityRecord); - int result = ERR_OK; - if (!currentTopAbility) { - targetAbilityRecord->SetLauncherRoot(); - result = targetAbilityRecord->LoadAbility(); - } else { - currentTopAbility->Inactivate(); - } - return result; + targetAbilityRecord->SetToEnd(true); + requestAbility->SetToEnd(true); + requestAbility->Inactivate(); + return ERR_OK; } void AbilityStackManager::OnAbilityDied(std::shared_ptr abilityRecord) { - HILOG_INFO("%{public}s,%{public}d", __PRETTY_FUNCTION__, __LINE__); + HILOG_INFO("On ability died."); std::lock_guard guard(stackLock_); - if (!abilityRecord) { - HILOG_ERROR("OnAbilityDied record is nullptr"); - return; - } - - if (!launcherMissionStack_ || !defaultMissionStack_) { - HILOG_ERROR("mission stack is invalid"); - return; - } + CHECK_POINTER(abilityRecord); + CHECK_POINTER(launcherMissionStack_); + CHECK_POINTER(defaultMissionStack_); if (abilityRecord->GetAbilityInfo().type != AbilityType::PAGE) { - HILOG_ERROR("ability type is not page"); + HILOG_ERROR("Ability type is not page."); return; } // release mission when locked. @@ -1554,46 +2075,52 @@ void AbilityStackManager::OnAbilityDied(std::shared_ptr abilityRe void AbilityStackManager::OnAbilityDiedByLauncher(std::shared_ptr abilityRecord) { - HILOG_INFO("%{public}s,%{public}d", __func__, __LINE__); - if (!abilityRecord || !launcherMissionStack_) { - HILOG_ERROR("ability is nullptr."); - return; - } + HILOG_INFO("On ability died by launcher."); + CHECK_POINTER(abilityRecord); + CHECK_POINTER(launcherMissionStack_); auto mission = abilityRecord->GetMissionRecord(); if (!mission || !launcherMissionStack_->IsExistMissionRecord(mission->GetMissionRecordId()) || !mission->IsExistAbilityRecord(abilityRecord->GetRecordId())) { - HILOG_ERROR("mission or ability record is not in launcher stack."); + HILOG_ERROR("Mission or ability record is not in launcher stack."); return; } + if (!abilityRecord->IsUninstallAbility()) { + HILOG_INFO("Save mission"); + resumeMissionContainer_->Save(mission); + } else { + resumeMissionContainer_->Remove(mission->GetMissionRecordId()); + } + // Terminate launcher ability on the top of dead ability std::vector abilityInfos; mission->GetAllAbilityInfo(abilityInfos); for (auto &it : abilityInfos) { auto ability = mission->GetAbilityRecordById(it.id); if (!ability) { - HILOG_WARN("ability is nullptr."); + HILOG_WARN("Ability is nullptr."); continue; } if (ability == abilityRecord) { break; } if (ability->IsTerminating()) { - HILOG_ERROR("ability is terminating."); + HILOG_ERROR("Ability is terminating."); continue; } - HILOG_DEBUG("terminate launcher ability."); + HILOG_DEBUG("Terminate launcher ability."); ability->SetTerminatingState(); - TerminateAbilityLocked(ability, -1, nullptr); + TerminateAbilityLocked(ability, DEFAULT_INVAL_VALUE, nullptr); } // Process the dead ability record if (mission->GetBottomAbilityRecord() == abilityRecord && abilityRecord->IsLauncherRoot()) { - HILOG_DEBUG("root launcher ability died, set state: INITIAL"); + HILOG_DEBUG("Root launcher ability died, set state: INITIAL."); + abilityRecord->ClearFlag(); abilityRecord->SetAbilityState(AbilityState::INITIAL); } else { mission->RemoveAbilityRecord(abilityRecord); - if (mission->GetAbilityRecordCount() == 0) { + if (mission->IsEmpty()) { launcherMissionStack_->RemoveMissionRecord(mission->GetMissionRecordId()); } } @@ -1604,13 +2131,11 @@ void AbilityStackManager::OnAbilityDiedByLauncher(std::shared_ptr void AbilityStackManager::DelayedStartLauncher() { auto abilityManagerService = DelayedSingleton::GetInstance(); + CHECK_POINTER(abilityManagerService); auto handler = abilityManagerService->GetEventHandler(); - if (!handler) { - HILOG_ERROR("handler is nullptr."); - return; - } + CHECK_POINTER(handler); auto timeoutTask = [stackManager = shared_from_this()]() { - HILOG_DEBUG("the launcher needs to be restarted."); + HILOG_DEBUG("The launcher needs to be restarted."); stackManager->BackToLauncher(); }; handler->PostTask(timeoutTask, "Launcher_Restart", AbilityManagerService::RESTART_TIMEOUT); @@ -1618,22 +2143,40 @@ void AbilityStackManager::DelayedStartLauncher() void AbilityStackManager::OnAbilityDiedByDefault(std::shared_ptr abilityRecord) { - HILOG_INFO("%{public}s,%{public}d", __func__, __LINE__); - if (!abilityRecord) { - HILOG_ERROR("ability is nullptr,%{public}d", __LINE__); - return; - } + HILOG_INFO("On ability died by default."); + CHECK_POINTER(abilityRecord); auto mission = abilityRecord->GetMissionRecord(); - if (!mission || !mission->IsExistAbilityRecord(abilityRecord->GetRecordId())) { - HILOG_ERROR("mission is nullptr or not exist"); + CHECK_POINTER(mission); + if (!mission->IsExistAbilityRecord(abilityRecord->GetRecordId())) { + HILOG_ERROR("Mission is nullptr or not exist."); return; } - auto topAbility = mission->GetTopAbilityRecord(); - if (!topAbility) { - return; + if (abilityRecord->IsAbilityState(AbilityState::ACTIVATING) || + abilityRecord->IsAbilityState(AbilityState::INITIAL)) { + auto preAbility = abilityRecord->GetPreAbilityRecord(); + if (preAbility && preAbility->IsAbilityState(AbilityState::INACTIVE)) { + MoveToBackgroundTask(preAbility); + } + } + + if (!abilityRecord->IsUninstallAbility()) { + HILOG_INFO("Save mission"); + resumeMissionContainer_->Save(mission); + } else { + resumeMissionContainer_->Remove(mission->GetMissionRecordId()); } - auto isBackLauncher = topAbility->IsAbilityState(AbilityState::ACTIVE); + + auto topAbility = mission->GetTopAbilityRecord(); + CHECK_POINTER(topAbility); + auto stack = mission->GetMissionStack(); + CHECK_POINTER(stack); + auto isFloatingFocusDied = + ((topAbility == GetCurrentTopAbility()) && stack->IsEqualStackId(FLOATING_MISSION_STACK_ID) && + (topAbility->IsAbilityState(ACTIVE) || topAbility->IsAbilityState(ACTIVATING))); + + auto isFullStackActiveDied = (IsFullScreenStack(stack->GetMissionStackId()) && + (topAbility->IsAbilityState(ACTIVE) || topAbility->IsAbilityState(ACTIVATING))); std::vector abilityInfos; mission->GetAllAbilityInfo(abilityInfos); @@ -1644,67 +2187,82 @@ void AbilityStackManager::OnAbilityDiedByDefault(std::shared_ptr continue; } if (ability == abilityRecord) { - if (isBackLauncher) { - DelayedStartLauncher(); - } - if (abilityRecord->IsUninstallAbility()) { - HILOG_INFO("ability uninstall,%{public}d", __LINE__); - mission->RemoveAbilityRecord(abilityRecord); - if (mission->GetAbilityRecordCount() == 0) { - defaultMissionStack_->RemoveMissionRecord(mission->GetMissionRecordId()); - } - if (defaultMissionStack_->GetMissionRecordCount() == 0) { - MoveMissionStackToTop(launcherMissionStack_); - } - break; - } - if (mission->GetBottomAbilityRecord() == ability) { - HILOG_INFO("ability died, state: INITIAL, %{public}d", __LINE__); - abilityRecord->SetAbilityState(AbilityState::INITIAL); - } else { - HILOG_INFO("ability died, remove record, %{public}d", __LINE__); - mission->RemoveAbilityRecord(abilityRecord); - } break; } if (ability->IsTerminating()) { HILOG_ERROR("ability is terminating, %{public}d", __LINE__); continue; } - HILOG_INFO("terminate ability, %{public}d", __LINE__); + HILOG_INFO("Terminate ability, %{public}d", __LINE__); ability->SetForceTerminate(true); ability->SetTerminatingState(); - TerminateAbilityLocked(ability, -1, nullptr); + TerminateAbilityLocked(ability, DEFAULT_INVAL_VALUE, nullptr); + } + + if (abilityRecord->IsUninstallAbility()) { + HILOG_INFO("Ability uninstall,%{public}d", __LINE__); + mission->RemoveAbilityRecord(abilityRecord); + if (mission->IsEmpty()) { + auto stack = mission->GetMissionStack(); + RemoveMissionRecordById(mission->GetMissionRecordId()); + JudgingIsRemoveMultiScreenStack(stack); + } + } else { + if (mission->GetBottomAbilityRecord() == abilityRecord) { + HILOG_INFO("Ability died, state: INITIAL, %{public}d", __LINE__); + abilityRecord->ClearFlag(); + abilityRecord->SetAbilityState(AbilityState::INITIAL); + } else { + HILOG_INFO("Ability died, remove record, %{public}d", __LINE__); + mission->RemoveAbilityRecord(abilityRecord); + } + } + + if (isFloatingFocusDied) { + HILOG_INFO("floating focus ability died, back to full stack"); + auto fullScreenStack = GetTopFullScreenStack(); + CHECK_POINTER(fullScreenStack); + auto topFullScreenAbility = fullScreenStack->GetTopAbilityRecord(); + CHECK_POINTER(fullScreenStack); + MoveMissionStackToTop(fullScreenStack); + if (topFullScreenAbility->IsAbilityState(AbilityState::ACTIVE)) { + UpdateFocusAbilityRecord(topFullScreenAbility, true); + } else { + topFullScreenAbility->ProcessActivate(); + } + return; + } + + if (isFullStackActiveDied) { + HILOG_INFO("full stack active ability died, back to launcher."); + DelayedStartLauncher(); } } void AbilityStackManager::BackToLauncher() { - HILOG_INFO("%{public}s,%{public}d", __PRETTY_FUNCTION__, __LINE__); + HILOG_INFO("Back to launcher."); std::lock_guard guard(stackLock_); - if (!defaultMissionStack_ || !launcherMissionStack_) { - HILOG_ERROR("mission stack is invalid"); - return; - } - - auto currentTopAbility = GetCurrentTopAbility(); - if (currentTopAbility && currentTopAbility->IsAbilityState(AbilityState::ACTIVE)) { - HILOG_WARN("current top ability is active, no need to start launcher."); + CHECK_POINTER(defaultMissionStack_); + CHECK_POINTER(launcherMissionStack_); + + auto fullScreenStack = GetTopFullScreenStack(); + CHECK_POINTER(fullScreenStack); + auto currentTopAbility = fullScreenStack->GetTopAbilityRecord(); + if (currentTopAbility && (currentTopAbility->IsAbilityState(AbilityState::ACTIVE) || + currentTopAbility->IsAbilityState(AbilityState::ACTIVATING))) { + HILOG_WARN("Current top ability is active, no need to start launcher."); return; } auto launcherAbility = GetLauncherRootAbility(); - if (!launcherAbility) { - HILOG_ERROR("there is no root launcher ability record, back to launcher failed."); - return; - } + CHECK_POINTER_LOG(launcherAbility, "There is no root launcher ability record, back to launcher failed."); MoveMissionStackToTop(launcherMissionStack_); auto missionRecord = launcherAbility->GetMissionRecord(); - if (!missionRecord) { - HILOG_ERROR("can't get root launcher ability record's mission, back to launcher failed."); - return; - } + CHECK_POINTER_LOG(missionRecord, "Can't get root launcher ability record's mission, back to launcher failed."); + + CheckMissionRecordIsResume(missionRecord); if (currentTopAbility) { launcherAbility->SetPreAbilityRecord(currentTopAbility); @@ -1722,7 +2280,7 @@ void AbilityStackManager::BackToLauncher() std::shared_ptr AbilityStackManager::GetLauncherRootAbility() const { if (!launcherMissionStack_) { - HILOG_ERROR("mission stack is invalid"); + HILOG_ERROR("Mission stack is invalid."); return nullptr; } std::vector missionInfos; @@ -1744,24 +2302,18 @@ std::shared_ptr AbilityStackManager::GetLauncherRootAbility() con void AbilityStackManager::UninstallApp(const std::string &bundleName) { - HILOG_INFO("%{public}s, bundleName: %{public}s %{public}d", __func__, bundleName.c_str(), __LINE__); + HILOG_INFO("Uninstall app, bundleName: %{public}s", bundleName.c_str()); auto abilityManagerService = DelayedSingleton::GetInstance(); - if (!abilityManagerService) { - HILOG_ERROR("Ability on scheduler died: failed to get ams."); - return; - } + CHECK_POINTER(abilityManagerService); auto handler = abilityManagerService->GetEventHandler(); - if (!handler) { - HILOG_ERROR("Ability on scheduler died: failed to get ams handler."); - return; - } + CHECK_POINTER(handler); auto task = [bundleName, this]() { AddUninstallTags(bundleName); }; handler->PostTask(task); } void AbilityStackManager::AddUninstallTags(const std::string &bundleName) { - HILOG_INFO("%{public}s, bundleName: %{public}s %{public}d", __func__, bundleName.c_str(), __LINE__); + HILOG_INFO("Add uninstall tags, bundleName: %{public}s", bundleName.c_str()); std::lock_guard guard(stackLock_); for (auto &stack : missionStackList_) { std::vector missions; @@ -1769,7 +2321,7 @@ void AbilityStackManager::AddUninstallTags(const std::string &bundleName) for (auto &missionInfo : missions) { auto mission = stack->GetMissionRecordById(missionInfo.id); if (!mission) { - HILOG_ERROR("mission is nullptr"); + HILOG_ERROR("Mission is nullptr."); continue; } std::vector abilitys; @@ -1777,7 +2329,7 @@ void AbilityStackManager::AddUninstallTags(const std::string &bundleName) for (auto &abilityInfo : abilitys) { auto ability = mission->GetAbilityRecordById(abilityInfo.id); if (!ability) { - HILOG_ERROR("ability is nullptr"); + HILOG_ERROR("Ability is nullptr."); continue; } @@ -1785,6 +2337,8 @@ void AbilityStackManager::AddUninstallTags(const std::string &bundleName) if (ability->IsAbilityState(AbilityState::INITIAL)) { mission->RemoveAbilityRecord(ability); stack->RemoveMissionRecord(mission->GetMissionRecordId()); + CHECK_POINTER(resumeMissionContainer_); + resumeMissionContainer_->Remove(mission->GetMissionRecordId()); if (lockMissionContainer_ && lockMissionContainer_->IsLockedMissionState()) { if (lockMissionContainer_->IsSameLockedMission(mission->GetName())) { lockMissionContainer_->ReleaseLockedMission(mission, -1, true); @@ -1797,11 +2351,16 @@ void AbilityStackManager::AddUninstallTags(const std::string &bundleName) } } } + // Multi screen stack may be empty + auto floatingStack = GetOrCreateMissionStack(FLOATING_MISSION_STACK_ID, false); + JudgingIsRemoveMultiScreenStack(floatingStack); + auto splitScreenStack = GetOrCreateMissionStack(SPLIT_SCREEN_MISSION_STACK_ID, false); + JudgingIsRemoveMultiScreenStack(splitScreenStack); } std::shared_ptr AbilityStackManager::GetAbilityRecordByEventId(int64_t eventId) const { - HILOG_DEBUG("%{public}s", __func__); + HILOG_DEBUG("Get ability record by eventId."); for (auto &stack : missionStackList_) { std::vector missionInfos; stack->GetAllMissionInfo(missionInfos); @@ -1813,7 +2372,6 @@ std::shared_ptr AbilityStackManager::GetAbilityRecordByEventId(in for (auto &it : mission.abilityRecordInfos) { auto abilityRecord = missionRecord->GetAbilityRecordById(it.id); if (abilityRecord && abilityRecord->GetEventId() == eventId) { - HILOG_DEBUG("%{public}s get ability record", __func__); return abilityRecord; } } @@ -1824,7 +2382,7 @@ std::shared_ptr AbilityStackManager::GetAbilityRecordByEventId(in void AbilityStackManager::OnTimeOut(uint32_t msgId, int64_t eventId) { - HILOG_DEBUG("%{public}s", __func__); + HILOG_DEBUG("On timeout."); std::lock_guard guard(stackLock_); auto abilityRecord = GetAbilityRecordByEventId(eventId); if (abilityRecord == nullptr) { @@ -1839,8 +2397,10 @@ void AbilityStackManager::OnTimeOut(uint32_t msgId, int64_t eventId) lockMissionContainer_->ReleaseLockedMission(mission, -1, true); } } + CHECK_POINTER_LOG(abilityRecord, "stack manager on time out event: ability record is nullptr."); + + HILOG_DEBUG("Ability timeout ,msg:%{public}d,name:%{public}s", msgId, abilityRecord->GetAbilityInfo().name.c_str()); - HILOG_DEBUG("ability timeout ,msg:%{public}d,name:%{public}s", msgId, abilityRecord->GetAbilityInfo().name.c_str()); switch (msgId) { case AbilityManagerService::LOAD_TIMEOUT_MSG: ActiveTopAbility(abilityRecord); @@ -1854,95 +2414,583 @@ void AbilityStackManager::OnTimeOut(uint32_t msgId, int64_t eventId) } } -void AbilityStackManager::ActiveTopAbility(const std::shared_ptr &abilityRecord) +int AbilityStackManager::MoveMissionToFloatingStack(const MissionOption &missionOption) { - HILOG_INFO("%{public}s called", __func__); - if (!abilityRecord) { - HILOG_ERROR("%{public}s, abilityRecord is nullptr", __func__); - return; + HILOG_DEBUG("Move mission to floating stack, missionId: %{public}d", missionOption.missionId); + std::lock_guard guard(stackLock_); + if (lockMissionContainer_ && lockMissionContainer_->IsLockedMissionState()) { + HILOG_ERROR("current is lock mission state, refusing to operate other mission."); + return ERR_INVALID_VALUE; } - - if (abilityRecord->IsLauncherRoot()) { - HILOG_ERROR("%{public}s, launcher attach timeout, active launcher", __func__); - // BackToLauncher(); - return; + if (missionOption.missionId == DEFAULT_INVAL_VALUE) { + HILOG_ERROR("Mission id is invalid."); + return ERR_INVALID_DATA; } + if (JudgingTargetSystemWindowMode(missionOption.winModeKey) != SystemWindowMode::FLOATING_WINDOW_MODE) { + HILOG_ERROR("The requested mode is error."); + return ERR_INVALID_DATA; + } + std::list missionOptions; + MissionOption option = missionOption; + missionOptions.push_back(option); - auto missionRecord = abilityRecord->GetMissionRecord(); - if (!missionRecord) { - HILOG_ERROR("%{public}s, missionRecord is nullptr", __func__); - return; + return MoveMissionsToStackLocked(missionOptions); +} + +int AbilityStackManager::MoveMissionToSplitScreenStack(const MissionOption &missionOption) +{ + HILOG_DEBUG("Move mission to split screen stack, missionId:%{public}d", missionOption.missionId); + std::lock_guard guard(stackLock_); + if (lockMissionContainer_ && lockMissionContainer_->IsLockedMissionState()) { + HILOG_ERROR("current is lock mission state, refusing to operate other mission."); + return ERR_INVALID_VALUE; + } + if (missionOption.missionId == DEFAULT_INVAL_VALUE) { + HILOG_ERROR("mission id is invalid."); + return ERR_INVALID_DATA; + } + if (JudgingTargetSystemWindowMode(missionOption.winModeKey) != SystemWindowMode::SPLITSCREEN_WINDOW_MODE) { + HILOG_ERROR("The requested mode is error."); + return ERR_INVALID_DATA; + } + std::list missionOptions; + MissionOption option = missionOption; + missionOptions.push_back(option); + + return MoveMissionsToStackLocked(missionOptions); +} + +int AbilityStackManager::MoveMissionsToStackLocked(const std::list &missionOptions) +{ + HILOG_DEBUG("Request mission option size :%{public}d", missionOptions.size()); + + // check condition whether can enter or exit multiwindow mode. + CHECK_RET_RETURN_RET(CheckMultiWindowCondition(missionOptions), "check multiwindow condition is failed."); + + // complete mission stack moving and notify ability window mode has changed. + auto lastTopAbility = GetCurrentTopAbility(); + isMultiWinMoving_ = true; + for (auto &it : missionOptions) { + auto sourceMission = GetMissionRecordFromAllStacks(it.missionId); + CheckMissionRecordIsResume(sourceMission); + CHECK_POINTER_AND_RETURN(sourceMission, MOVE_MISSION_TO_STACK_NOT_EXIST_MISSION); + CHECK_RET_RETURN_RET(CompleteMissionMoving(sourceMission, JudgingTargetStackId(it.winModeKey)), + "complete mission moving failed."); + sourceMission->SetMissionOption(it); + } + + // to do ,split srceen mode ,change second screen missionoption. + + // schulde ability lifescycle (all stack) + auto currentTopAbility = GetCurrentTopAbility(); + bool isFullScreen = + missionOptions.front().winModeKey == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FULLSCREEN; + // top ability active and display fullscreen, others background state. + CHECK_RET_RETURN_RET( + DispatchLifecycle(lastTopAbility, currentTopAbility, isFullScreen), "Dispatch lifecycle error."); + + // Judging target system window mode, and notify event. + auto willWinMode = JudgingTargetSystemWindowMode(missionOptions.front().winModeKey); + auto targetWinMode = GetTargetSystemWindowMode(willWinMode); + NotifyWindowModeChanged(targetWinMode); + + return ERR_OK; +} + +int AbilityStackManager::MaximizeMultiWindow(int missionId) +{ + HILOG_DEBUG("Maximize multi window, missionId:%{public}d", missionId); + std::lock_guard guard(stackLock_); + if (lockMissionContainer_ && lockMissionContainer_->IsLockedMissionState()) { + HILOG_ERROR("current is lock mission state, refusing to operate other mission."); + return ERR_INVALID_VALUE; + } + + auto missionRecord = GetMissionRecordFromAllStacks(missionId); + CHECK_POINTER_AND_RETURN(missionRecord, MAXIMIZE_MULTIWINDOW_NOT_EXIST); + auto parentStack = missionRecord->GetMissionStack(); + CHECK_POINTER_AND_RETURN(parentStack, ERR_INVALID_DATA); + if (!parentStack->IsEqualStackId(FLOATING_MISSION_STACK_ID)) { + HILOG_ERROR("This mission is not exist in multiwindow stack."); + return MAXIMIZE_MULTIWINDOW_NOT_EXIST; + } + auto topAbility = missionRecord->GetTopAbilityRecord(); + CHECK_POINTER_AND_RETURN(topAbility, ERR_INVALID_DATA); + if (!topAbility->IsAbilityState(AbilityState::INACTIVE) && !topAbility->IsAbilityState(AbilityState::ACTIVE)) { + HILOG_ERROR("This mission is not visible, maximize failed."); + return MAXIMIZE_MULTIWINDOW_FAILED; + } + // construct mission option, request to move mission to default stack. + MissionOption option; + option.missionId = missionId; + option.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FULLSCREEN; + std::list missionOptions; + missionOptions.push_back(option); + + return MoveMissionsToStackLocked(missionOptions); +} + +void AbilityStackManager::ContinueLifecycle() +{ + HILOG_INFO("Continue lifecycle."); + for (auto &stack : missionStackList_) { + CHECK_POINTER(stack); + std::vector missionInfos; + stack->GetAllMissionInfo(missionInfos); + for (auto &it : missionInfos) { + std::shared_ptr missionRecord = stack->GetMissionRecordById(it.id); + CHECK_POINTER(missionRecord); + auto topAbility = missionRecord->GetTopAbilityRecord(); + CHECK_POINTER(topAbility); + if (topAbility->GetInMovingState() && topAbility != GetCurrentTopAbility()) { + HILOG_DEBUG("Wait other ability to complete lifecycle. Ability: %{public}s.", + topAbility->GetAbilityInfo().name.c_str()); + return; + } + } + } + + auto currentTopAbility = GetCurrentTopAbility(); + CHECK_POINTER(currentTopAbility); + HILOG_DEBUG("At last, complete top ability lifecycle, target state is active."); + if (currentTopAbility->IsAbilityState(AbilityState::ACTIVE)) { + UpdateFocusAbilityRecord(currentTopAbility, true); + currentTopAbility->SetInMovingState(false); + isMultiWinMoving_ = false; + } else { + currentTopAbility->ProcessActivate(); + } +} + +int AbilityStackManager::DispatchLifecycle(const std::shared_ptr &lastTopAbility, + const std::shared_ptr ¤tTopAbility, bool isTopFullScreen) +{ + CHECK_POINTER_AND_RETURN(lastTopAbility, ERR_INVALID_DATA); + CHECK_POINTER_AND_RETURN(currentTopAbility, ERR_INVALID_DATA); + + auto lastMission = lastTopAbility->GetMissionRecord(); + CHECK_POINTER_AND_RETURN(lastMission, ERR_INVALID_DATA); + auto lastMissionStack = lastMission->GetMissionStack(); + CHECK_POINTER_AND_RETURN(lastMissionStack, ERR_INVALID_DATA); + + auto topFullStack = GetTopFullScreenStack(); + CHECK_POINTER_AND_RETURN(topFullStack, ERR_INVALID_DATA); + + for (auto &stack : missionStackList_) { + CHECK_POINTER_AND_RETURN(stack, ERR_INVALID_DATA); + bool isSyncVisual = SupportSyncVisualByStackId(stack->GetMissionStackId()); + + HILOG_DEBUG("Processing stack lifescycle: stack id: %{public}d, isSyncVisual: %{public}d", + stack->GetMissionStackId(), + isSyncVisual); + + std::vector missionInfos; + stack->GetAllMissionInfo(missionInfos); + for (auto &it : missionInfos) { + std::shared_ptr missionRecord = stack->GetMissionRecordById(it.id); + CHECK_POINTER_AND_RETURN(missionRecord, ERR_INVALID_DATA); + auto topAbility = missionRecord->GetTopAbilityRecord(); + CHECK_POINTER_AND_RETURN(topAbility, ERR_INVALID_DATA); + // last top active ability , need to inactive. + if (topAbility == lastTopAbility || topAbility == currentTopAbility) { + HILOG_DEBUG("Last top active ability or Current top ability, lifecycle at last."); + topAbility->SetInMovingState(true); + continue; + } + // top ability active , others need to background state. + if (isTopFullScreen) { + HILOG_DEBUG("Top ability will full screen, others need to background."); + topAbility->ProcessInactivateInMoving(); + continue; + } + // Except the top mission of the stack, all the others are in the background state, + // When this mission stack not support sync visual. + if (!stack->IsTopMissionRecord(missionRecord)) { + if (!isSyncVisual) { + HILOG_DEBUG("This mission stack not support sync visual. need to background."); + topAbility->ProcessInactivateInMoving(); + } + continue; + } + // process top mission. + // fullscreen stack, only the top ability is active state, others keep background state. + if (stack == topFullStack) { + HILOG_DEBUG("Fullscreen stack ,top abiltiy need to active."); + topAbility->ProcessActivateInMoving(); + continue; + } + // others force background state. + HILOG_DEBUG("Others keep background state."); + topAbility->ProcessInactivateInMoving(); + } + } + + bool isNotTopInFullScreen = + IsFullScreenStack(lastTopAbility->GetMissionStackId()) && + (!lastMissionStack->IsTopMissionRecord(lastMission) || lastMissionStack != topFullStack); + bool isNotTopInMultiWin = !IsFullScreenStack(lastTopAbility->GetMissionStackId()) && + !SupportSyncVisualByStackId(lastTopAbility->GetMissionStackId()) && + (!lastMissionStack->IsTopMissionRecord(lastMission) || + (lastMission->GetMissionRecordId() == (currentTopAbility->GetMissionRecordId()))); + if (lastTopAbility == currentTopAbility) { + ; + } else if (isNotTopInFullScreen || isNotTopInMultiWin || isTopFullScreen) { + HILOG_DEBUG("Last top active ability , need to inactive."); + lastTopAbility->ProcessInactivateInMoving(); + } else { + lastTopAbility->SetInMovingState(false); + } + + // if there is no ability to wait for processing active, just active top ability immediately + ContinueLifecycle(); + + return ERR_OK; +} + +SystemWindowMode AbilityStackManager::GetTargetSystemWindowMode(const SystemWindowMode &willWinMode) +{ + if (curSysWindowMode_ == willWinMode) { + return curSysWindowMode_; + } + + bool isCrossFlag = curSysWindowMode_ == SystemWindowMode::FLOATING_AND_SPLITSCREEN_WINDOW_MODE; + switch (willWinMode) { + case SystemWindowMode::SPLITSCREEN_WINDOW_MODE: + case SystemWindowMode::FLOATING_WINDOW_MODE: + return (isCrossFlag || curSysWindowMode_ != SystemWindowMode::DEFAULT_WINDOW_MODE) ? curSysWindowMode_ + : willWinMode; + default: + break; + } + + // will win mode is default mode ,need to check current mission stack list. + bool isFloating = GetOrCreateMissionStack(FLOATING_MISSION_STACK_ID, false) != nullptr; + bool isSplitScreen = GetOrCreateMissionStack(SPLIT_SCREEN_MISSION_STACK_ID, false) != nullptr; + + if (isFloating && isSplitScreen) { + return SystemWindowMode::FLOATING_AND_SPLITSCREEN_WINDOW_MODE; + } else if (isFloating) { + return SystemWindowMode::FLOATING_WINDOW_MODE; + } else if (isSplitScreen) { + return SystemWindowMode::SPLITSCREEN_WINDOW_MODE; + } else { + return willWinMode; + } +} + +int AbilityStackManager::CheckMultiWindowCondition(const std::list &missionOptions) const +{ + HILOG_DEBUG("Check multi window condition."); + if (isMultiWinMoving_) { + HILOG_ERROR("System is moving multi window state, request deny."); + return MOVE_MISSION_TO_STACK_MOVING_DENIED; + } + + auto currentTopAbilityRecord = GetCurrentTopAbility(); + if (currentTopAbilityRecord && + AbilityUtil::IsSystemDialogAbility( + currentTopAbilityRecord->GetAbilityInfo().bundleName, currentTopAbilityRecord->GetAbilityInfo().name)) { + HILOG_ERROR("Top page ability is dialog type, cannot return to launcher"); + return MOVE_MISSION_TO_STACK_MOVING_DENIED; + } + + if (missionOptions.empty() || missionOptions.size() > MAX_CAN_MOVE_MISSIONS) { + HILOG_ERROR("Moving missions has been out of size, Maximum:%{public}d.", MAX_CAN_MOVE_MISSIONS); + return MOVE_MISSION_TO_STACK_OUT_OF_SIZE; + } + // check request missions exist, and has same window mode. + auto lastOption = missionOptions.front(); + for (auto &it : missionOptions) { + if (!it.IsSameWindowMode(lastOption.winModeKey)) { + HILOG_ERROR("Mission options are not in same win mode."); + return MOVE_MISSION_TO_STACK_NOT_SAME_WIN_MODE; + } + auto targetMission = GetMissionRecordFromAllStacks(it.missionId); + if (!targetMission) { + HILOG_ERROR("Moving mission record is not exist."); + return MOVE_MISSION_TO_STACK_NOT_EXIST_MISSION; + } + auto parentStack = targetMission->GetMissionStack(); + if (parentStack && parentStack->GetMissionStackId() == JudgingTargetStackId(it.winModeKey)) { + HILOG_ERROR("Refuse moving mission to its own stack."); + return MOVE_MISSION_TO_STACK_NOT_EXIST_MISSION; + } + if (!targetMission->SupportMultWindow()) { + HILOG_ERROR("Moving mission record is not support multi window."); + return MOVE_MISSION_TO_STACK_NOT_SUPPORT_MULTI_WIN; + } + } + + // check whether target mission stack will be overflow. + if (!CheckMissionStackWillOverflow(missionOptions)) { + HILOG_ERROR("Mission stack will overflow, refuse to move mission."); + return MOVE_MISSION_TO_STACK_TARGET_STACK_OVERFLOW; + } + + return ERR_OK; +} + +int AbilityStackManager::CheckMultiWindowCondition( + const std::shared_ptr ¤tTopAbility, const AbilityRequest &abilityRequest) const +{ + HILOG_DEBUG("Check multi window condition."); + CHECK_POINTER_AND_RETURN_LOG(abilityRequest.startSetting, START_ABILITY_SETTING_FAILED, "startsetting is nullptr."); + + if (isMultiWinMoving_) { + HILOG_ERROR("System is moving multi window state, request deny."); + return START_ABILITY_SETTING_FAILED; + } + + if (currentTopAbility && AbilityUtil::IsSystemDialogAbility(currentTopAbility->GetAbilityInfo().bundleName, + currentTopAbility->GetAbilityInfo().name)) { + HILOG_ERROR("Top page ability is dialog type, cannot return to launcher."); + return START_ABILITY_SETTING_FAILED; + } + + // if (ERR_OK != DelayedSingleton::GetInstance()->CheckPermission( + // abilityRequest.abilityInfo.bundleName, AbilityConfig::FLOATING_WINDOW_PERMISSION)) { + // HILOG_ERROR("Request ability not system float window permission."); + // return START_ABILITY_SETTING_NOT_SUPPORT_MULTI_WIN; + // } + + // check whether target mission stack will be overflow. + MissionOption option; + option.winModeKey = static_cast( + std::atoi(abilityRequest.startSetting->GetProperty(AbilityStartSetting::WINDOW_MODE_KEY).c_str())); + std::list list; + list.push_back(option); + if (!CheckMissionStackWillOverflow(list)) { + HILOG_ERROR("Mission stack will overflow."); + return START_ABILITY_SETTING_NOT_SUPPORT_MULTI_WIN; + } + + return ERR_OK; +} + +bool AbilityStackManager::CheckMissionStackWillOverflow(const std::list &missionOptions) const +{ + std::map calcMap; + for (auto &it : missionStackList_) { + calcMap.emplace(it->GetMissionStackId(), it->GetMissionRecordCount()); + } + + auto isOverFlow = [&](int stackId, std::map &calcMap) { + calcMap[stackId]++; + if (GetMaxHoldMissionsByStackId(stackId) > 0 && calcMap[stackId] > GetMaxHoldMissionsByStackId(stackId)) { + HILOG_ERROR( + "Over limit of holding mission, stackId:%{public}d , size:%{public}d", stackId, calcMap[stackId]); + return false; + } + return true; + }; + + // check whether splitscreen and floating stack will overflow. + for (auto &option : missionOptions) { + auto stackId = JudgingTargetStackId(option.winModeKey); + if (!isOverFlow(stackId, calcMap)) { + return false; + } + } + + return true; +} + +int AbilityStackManager::CompleteMissionMoving(std::shared_ptr &sourceMission, int stackId) +{ + CHECK_POINTER_AND_RETURN(sourceMission, MOVE_MISSION_TO_STACK_NOT_EXIST_MISSION); + auto targetStack = GetOrCreateMissionStack(stackId, true); + CHECK_POINTER_AND_RETURN(targetStack, ERR_INVALID_DATA); + + CHECK_RET_RETURN_RET(CompleteMoveMissionToStack(sourceMission, targetStack), "Moving mission record failed."); + + return ERR_OK; +} + +std::shared_ptr AbilityStackManager::GetOrCreateMissionStack(int stackId, bool isCreateFlag) +{ + HILOG_DEBUG("Target stack id:%{public}d", stackId); + if (stackId > MAX_MISSION_STACK_ID || stackId < MIN_MISSION_STACK_ID) { + HILOG_ERROR("stack id:%{public}d is not defined.", stackId); + return nullptr; + } + auto isExist = [stackId]( + const std::shared_ptr &stack) { return stackId == stack->GetMissionStackId(); }; + auto iter = std::find_if(missionStackList_.begin(), missionStackList_.end(), isExist); + if (iter != missionStackList_.end()) { + HILOG_DEBUG("Get target mission stack success."); + return *iter; + } + + if (isCreateFlag) { + HILOG_DEBUG("Target mission stack is not exist, need to create."); + std::shared_ptr missionStack = std::make_shared(stackId, userId_); + missionStackList_.push_back(missionStack); + HILOG_DEBUG("Add stackId(%{public}d) to missionStackList, mission stack size:%{public}d", + stackId, + missionStackList_.size()); + return missionStack; + } + + HILOG_DEBUG("Target mission stack is not exist."); + return nullptr; +} + +int AbilityStackManager::CompleteMoveMissionToStack( + const std::shared_ptr &sourceMission, const std::shared_ptr &targetStack) +{ + CHECK_POINTER_AND_RETURN(sourceMission, ERR_INVALID_DATA); + CHECK_POINTER_AND_RETURN(targetStack, ERR_INVALID_DATA); + auto sourceStack = sourceMission->GetMissionStack(); + CHECK_POINTER_AND_RETURN(sourceStack, ERR_INVALID_DATA); + + bool isTop = sourceMission->IsLauncherCreate() && sourceMission == GetTopMissionRecord(); + + HILOG_DEBUG("Mission reparent : src stack id:%{public}d, target stack id:%{public}d, isTop:%{public}d", + sourceStack->GetMissionStackId(), + targetStack->GetMissionStackId(), + isTop); + + // remove mission record from source stack. + sourceStack->RemoveMissionRecord(sourceMission->GetMissionRecordId()); + // add mission to target mission stack top. + targetStack->AddMissionRecordToTop(sourceMission); + targetStack->MoveMissionRecordToTop(sourceMission); + sourceMission->SetMissionStack(targetStack, targetStack->GetMissionStackId()); + if ((sourceStack->IsEmpty() || isTop) && targetStack != defaultMissionStack_) { + MoveMissionStackToTop(launcherMissionStack_); + } + if (sourceStack->IsEmpty() && (!IsFullScreenStack(sourceStack->GetMissionStackId()))) { + HILOG_DEBUG("Remove stack when mission count is zero. stack:%{public}d.", sourceStack->GetMissionStackId()); + missionStackList_.remove(sourceStack); } + // move target mission stack to top. + MoveMissionStackToTop(targetStack); + + return ERR_OK; +} + +void AbilityStackManager::ActiveTopAbility(const std::shared_ptr &abilityRecord) +{ + HILOG_INFO("Active top ability."); + CHECK_POINTER(abilityRecord); + DelayedSingleton::GetInstance()->AttachTimeOut(abilityRecord->GetToken()); + + if (abilityRecord->IsLauncherRoot()) { + HILOG_INFO("Launcher root load timeout, restart."); + DelayedStartLauncher(); + return; + } + + // Pre ability does not need to judge null + auto preAbility = abilityRecord->GetPreAbilityRecord(); + auto missionRecord = abilityRecord->GetMissionRecord(); + CHECK_POINTER(missionRecord); + auto stack = missionRecord->GetMissionStack(); + CHECK_POINTER(stack); + + // remove ability and mission and stack missionRecord->RemoveAbilityRecord(abilityRecord); - if (missionRecord->GetAbilityRecordCount() == 0) { + if (missionRecord->IsEmpty()) { RemoveMissionRecordById(missionRecord->GetMissionRecordId()); + JudgingIsRemoveMultiScreenStack(stack); + } + + if (preAbility && preAbility->IsAbilityState(INACTIVE)) { + HILOG_INFO("Load timeout, restart pre ability."); + MoveMissionStackToTop(preAbility->GetMissionRecord()->GetMissionStack()); + preAbility->ProcessActivate(); + } else { + auto topFullScreenStack = GetTopFullScreenStack(); + CHECK_POINTER(topFullScreenStack); + auto topFullScreenAbility = topFullScreenStack->GetTopAbilityRecord(); + if (topFullScreenAbility && topFullScreenAbility->IsAbilityState(INACTIVE)) { + HILOG_INFO("Load timeout, top full screen ability restart."); + MoveMissionStackToTop(topFullScreenStack); + topFullScreenAbility->ProcessActivate(); + } else { + HILOG_INFO("Load timeout, back to launcher."); + BackToLauncher(); + } } - ActiveTopAbility(true, LAUNCHER_MISSION_STACK_ID); } -void AbilityStackManager::ActiveTopAbility(const bool isAll, int32_t stackId) +int AbilityStackManager::GetMaxHoldMissionsByStackId(int stackId) const { - HILOG_INFO("%{public}s called, isAll:%{public}d, stackId:%{public}d", __func__, static_cast(isAll), stackId); - std::shared_ptr topAbility; - if (isAll) { - topAbility = GetCurrentTopAbility(); - } else { - auto isExist = [stackId](const std::shared_ptr &stack) { - return stack->GetMissionStackId() == stackId; - }; - auto finder = std::find_if(missionStackList_.begin(), missionStackList_.end(), isExist); - if (finder != missionStackList_.end()) { - topAbility = (*finder)->GetTopAbilityRecord(); + for (auto &it : stackSettings_) { + if (it.stackId == stackId) { + return it.maxHoldMission; } } + return DEFAULT_INVAL_VALUE; +} - if (!topAbility) { - HILOG_INFO("%{public}s top ability is nullptr, back to launcher", __func__); - BackToLauncher(); - return; +bool AbilityStackManager::SupportSyncVisualByStackId(int stackId) const +{ + for (auto &it : stackSettings_) { + if (it.stackId == stackId && (!IsFullScreenStack(stackId))) { + return it.isSyncVisual; + } + } + return false; +} + +SystemWindowMode AbilityStackManager::JudgingTargetSystemWindowMode(AbilityWindowConfiguration config) const +{ + switch (config) { + // to do, split multi screen ,add key + case AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY: + case AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY: + return SystemWindowMode::SPLITSCREEN_WINDOW_MODE; + case AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING: + return SystemWindowMode::FLOATING_WINDOW_MODE; + default: + return SystemWindowMode::DEFAULT_WINDOW_MODE; + } +} + +int AbilityStackManager::JudgingTargetStackId(AbilityWindowConfiguration config) const +{ + switch (config) { + // to do, split multi screen ,add key + case AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY: + return SPLIT_SCREEN_MISSION_STACK_ID; + case AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING: + return FLOATING_MISSION_STACK_ID; + default: + return DEFAULT_MISSION_STACK_ID; } - topAbility->ProcessActivate(); } bool AbilityStackManager::IsFirstInMission(const sptr &token) { - HILOG_INFO("%{public}s,%{public}d", __PRETTY_FUNCTION__, __LINE__); + HILOG_INFO("Is first in mission."); std::lock_guard guard(stackLock_); - if (token == nullptr) { - HILOG_ERROR("token is nullptr"); - return false; - } + CHECK_POINTER_RETURN_BOOL(token); auto abilityRecord = GetAbilityRecordByToken(token); - if (!abilityRecord) { - HILOG_ERROR("abilityRecord is nullptr"); - return false; - } + CHECK_POINTER_RETURN_BOOL(abilityRecord); auto missionRecord = abilityRecord->GetMissionRecord(); - if (!missionRecord) { - HILOG_ERROR("missionRecord is nullptr"); - return false; - } + CHECK_POINTER_RETURN_BOOL(missionRecord); return (missionRecord->GetBottomAbilityRecord() == abilityRecord); } int AbilityStackManager::PowerOff() { - HILOG_INFO("%{public}s,%{public}d", __PRETTY_FUNCTION__, __LINE__); + HILOG_INFO("Power off."); std::lock_guard guard(stackLock_); return PowerOffLocked(); } int AbilityStackManager::PowerOffLocked() { - HILOG_INFO("%{public}s,%{public}d", __PRETTY_FUNCTION__, __LINE__); + HILOG_INFO("Power off locked."); auto currentTopAbility = GetCurrentTopAbility(); if ((currentTopAbility && !currentTopAbility->IsAbilityState(AbilityState::ACTIVE)) || !waittingAbilityQueue_.empty()) { - HILOG_WARN("current top ability is not active, waiting ability lifecycle complete"); + HILOG_WARN("Current top ability is not active, waiting ability lifecycle complete"); // In CompleteActive,waiting ability lifecycle complete,execute PowerOffLocked again powerOffing_ = true; return POWER_OFF_WAITING; @@ -1959,11 +3007,12 @@ int AbilityStackManager::PowerOffLocked() auto abilityRecord = missionRecord->GetTopAbilityRecord(); CHECK_POINTER(abilityRecord); if (abilityRecord->IsAbilityState(AbilityState::ACTIVE)) { + powerStorage_->SetPowerOffActiveRecord(abilityRecord); abilityRecord->SetPowerState(true); abilityRecord->ProcessInactivate(); } if (abilityRecord->IsAbilityState(AbilityState::INACTIVE)) { - powerStorage_->SetPowerOffRecord(abilityRecord); + powerStorage_->SetPowerOffInActiveRecord(abilityRecord); MoveToBackgroundTask(abilityRecord); } }; @@ -1974,40 +3023,59 @@ int AbilityStackManager::PowerOffLocked() int AbilityStackManager::PowerOn() { - HILOG_INFO("%{public}s,%{public}d", __func__, __LINE__); + HILOG_INFO("Power on."); std::lock_guard guard(stackLock_); return PowerOnLocked(); } int AbilityStackManager::PowerOnLocked() { - HILOG_INFO("%{public}s,%{public}d", __func__, __LINE__); + HILOG_INFO("Power on locked."); powerOffing_ = false; CHECK_POINTER_AND_RETURN(powerStorage_, POWER_ON_FAILED); - auto powerStorages = powerStorage_->GetPowerOffRecord(); - if (powerStorages.empty()) { - auto currentTopAbility = GetCurrentTopAbility(); - CHECK_POINTER_AND_RETURN(currentTopAbility, POWER_ON_FAILED); - HILOG_DEBUG("there is no ability in inactive state. start the ability at the top of the stack"); - currentTopAbility->ProcessActivate(); - powerStorage_.reset(); + auto powerInActiveStorages = powerStorage_->GetPowerOffInActiveRecord(); + if (powerInActiveStorages.empty()) { + if (ChangedPowerStorageAbilityToActive(powerStorage_) != ERR_OK) { + HILOG_ERROR("ChangedPowerStorageAbilityToActive Fail"); + return POWER_ON_FAILED; + } return ERR_OK; } - for (auto &powerStorage : powerStorages) { - auto stack = GetStackById(powerStorage.StackId); - CHECK_POINTER_CONTINUE(stack); - auto missionRecord = stack->GetMissionRecordById(powerStorage.missionId); - CHECK_POINTER_CONTINUE(missionRecord); - auto topAbility = missionRecord->GetTopAbilityRecord(); - CHECK_POINTER_CONTINUE(topAbility); - topAbility->SetPowerState(true); - topAbility->ProcessActivate(); + for (auto &powerInActiveStorage : powerInActiveStorages) { + auto storageInActiveAbility = powerInActiveStorage.ability.lock(); + CHECK_POINTER_CONTINUE(storageInActiveAbility); + storageInActiveAbility->SetPowerState(true); + storageInActiveAbility->ProcessActivate(); } return ERR_OK; } +int AbilityStackManager::ChangedPowerStorageAbilityToActive(std::shared_ptr &powerStorage) +{ + HILOG_INFO("%{public}s", __func__); + CHECK_POINTER_AND_RETURN(powerStorage, ERR_INVALID_VALUE); + auto powerActiveStorages = powerStorage->GetPowerOffActiveRecord(); + // Start the ability except the top of the stack + for (auto &powerActiveStorage : powerActiveStorages) { + auto storageActiveAbility = powerActiveStorage.ability.lock(); + CHECK_POINTER_CONTINUE(storageActiveAbility); + storageActiveAbility->SetPowerState(true); + if (storageActiveAbility == GetCurrentTopAbility()) { + HILOG_DEBUG("There is no ability in active state except the top of the stack"); + continue; + } + storageActiveAbility->ProcessActivate(); + } + // Finally,Start stack top ability + auto currentTopAbility = GetCurrentTopAbility(); + CHECK_POINTER_AND_RETURN(currentTopAbility, ERR_INVALID_VALUE); + currentTopAbility->ProcessActivate(); + HILOG_DEBUG("start the ability at the top of the stack"); + return ERR_OK; +} + int AbilityStackManager::StartLockMission(int uid, int missionId, bool isSystemApp, int isLock) { HILOG_INFO("%{public}s", __func__); @@ -2061,6 +3129,12 @@ bool AbilityStackManager::CheckLockMissionCondition( return false; } + auto fullScreenStack = IsFullScreenStack(mission->GetMissionStack()->GetMissionStackId()); + if (!fullScreenStack) { + HILOG_ERROR("Multi-window active,lock mission failed."); + return false; + } + auto topability = mission->GetTopAbilityRecord(); auto bottomability = mission->GetBottomAbilityRecord(); auto abilityManagerService = DelayedSingleton::GetInstance(); @@ -2093,8 +3167,8 @@ bool AbilityStackManager::CanStartInLockMissionState( // current ability singeton mode if (currentTopAbility->GetAbilityInfo().launchMode == AppExecFwk::LaunchMode::SINGLETON) { if (abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SINGLETON) { - std::string bundleName = MISSION_NAME_MARK_HEAD + abilityRequest.abilityInfo.bundleName + - MISSION_NAME_SEPARATOR + abilityRequest.abilityInfo.name; + std::string bundleName = AbilityConfig::MISSION_NAME_MARK_HEAD + abilityRequest.abilityInfo.bundleName + + AbilityConfig::MISSION_NAME_SEPARATOR + abilityRequest.abilityInfo.name; return lockMissionContainer_->IsSameLockedMission(bundleName); } return false; @@ -2132,5 +3206,244 @@ void AbilityStackManager::SendUnlockMissionMessage() HILOG_ERROR("current is lock mission state, refusing to operate other mission."); } +bool AbilityStackManager::IsTopInMission(const std::shared_ptr &abilityRecord) const +{ + CHECK_POINTER_RETURN_BOOL(abilityRecord); + auto missionRecord = abilityRecord->GetMissionRecord(); + CHECK_POINTER_RETURN_BOOL(missionRecord); + + return (missionRecord->GetTopAbilityRecord() == abilityRecord); +} + +bool AbilityStackManager::IsFrontInAllStack(const std::shared_ptr &stack) const +{ + return stack == missionStackList_.front(); +} + +bool AbilityStackManager::IsFullScreenStack(int stackId) const +{ + return (stackId == DEFAULT_MISSION_STACK_ID || stackId == LAUNCHER_MISSION_STACK_ID); +} + +std::shared_ptr AbilityStackManager::GetTopFullScreenStack() +{ + auto isExist = [&](const std::shared_ptr &stack) { + return IsFullScreenStack(stack->GetMissionStackId()); + }; + auto iter = std::find_if(missionStackList_.begin(), missionStackList_.end(), isExist); + if (iter != missionStackList_.end()) { + return (*iter); + } + return nullptr; +} + +int AbilityStackManager::MinimizeMultiWindow(int missionId) +{ + std::lock_guard guard(stackLock_); + if (lockMissionContainer_ && lockMissionContainer_->IsLockedMissionState()) { + HILOG_ERROR("current is lock mission state, refusing to operate other mission."); + return ERR_INVALID_VALUE; + } + return MinimizeMultiWindowLocked(missionId); +} + +int AbilityStackManager::MinimizeMultiWindowLocked(int missionId) +{ + HILOG_INFO("Minimize multi window locked."); + auto missionRecord = GetMissionRecordFromAllStacks(missionId); + CHECK_POINTER_AND_RETURN(missionRecord, MINIMIZE_MULTI_WINDOW_FAILED); + + auto stack = missionRecord->GetMissionStack(); + CHECK_POINTER_AND_RETURN(stack, MINIMIZE_MULTI_WINDOW_FAILED); + + if (!stack->IsEqualStackId(FLOATING_MISSION_STACK_ID)) { + HILOG_ERROR("Mission is not in the float stack, can't be minimized."); + return MINIMIZE_MULTI_WINDOW_FAILED; + } + + return MoveMissionToEndLocked(missionRecord->GetMissionRecordId()); +} + +int AbilityStackManager::ChangeFocusAbility( + const sptr &lostFocusToken, const sptr &getFocusToken) +{ + HILOG_INFO("Change focus ability."); + std::lock_guard guard(stackLock_); + CHECK_POINTER_AND_RETURN(lostFocusToken, ERR_INVALID_VALUE); + CHECK_POINTER_AND_RETURN(getFocusToken, ERR_INVALID_VALUE); + if (getFocusToken == lostFocusToken) { + HILOG_WARN("get token is equal to lost token."); + return CHANGE_FOCUS_ABILITY_FAILED; + } + + auto currentAbility = GetCurrentTopAbility(); + CHECK_POINTER_AND_RETURN(currentAbility, CHANGE_FOCUS_ABILITY_FAILED); + if (!currentAbility->IsAbilityState(AbilityState::ACTIVE) || !waittingAbilityQueue_.empty()) { + HILOG_WARN("Top ability is not active or waiting queue is not empty, change focus failed"); + return CHANGE_FOCUS_ABILITY_FAILED; + } + + auto targetAbility = Token::GetAbilityRecordByToken(getFocusToken); + CHECK_POINTER_AND_RETURN(targetAbility, CHANGE_FOCUS_ABILITY_FAILED); + return ChangeFocusAbilityLocked(targetAbility); +} + +int AbilityStackManager::ChangeFocusAbilityLocked(const std::shared_ptr &targetAbility) +{ + HILOG_INFO("Change focus ability locked."); + CHECK_POINTER_AND_RETURN(targetAbility, ERR_INVALID_VALUE); + + auto currentAbility = GetCurrentTopAbility(); + CHECK_POINTER_AND_RETURN(currentAbility, CHANGE_FOCUS_ABILITY_FAILED); + + if (targetAbility == currentAbility || !targetAbility->IsAbilityState(ACTIVE)) { + HILOG_ERROR("Target ability is current ability, or target ability is not active, can't change focus."); + return CHANGE_FOCUS_ABILITY_FAILED; + } + + auto targetMission = targetAbility->GetMissionRecord(); + CHECK_POINTER_AND_RETURN_LOG( + targetMission, CHANGE_FOCUS_ABILITY_FAILED, " TargetMission is nullptr, change focus failed."); + + return MoveMissionToTop(targetMission->GetMissionRecordId()); +} + +int AbilityStackManager::GetFloatingMissions(std::vector &list) +{ + HILOG_INFO("Get floating missions."); + std::lock_guard guard(stackLock_); + + auto floatingStack = GetOrCreateMissionStack(FLOATING_MISSION_STACK_ID, false); + CHECK_POINTER_AND_RETURN_LOG( + floatingStack, GET_FLOATING_STACK_FAILED, "Floating stack is not exist, get floating missions failed."); + + std::vector missionInfos; + floatingStack->GetAllMissionInfo(missionInfos); + for (auto &mission : missionInfos) { + AbilityMissionInfo recentMissionInfo; + CreateRecentMissionInfo(mission, recentMissionInfo); + list.emplace_back(recentMissionInfo); + } + + return ERR_OK; +} + +int AbilityStackManager::CloseMultiWindow(int missionId) +{ + HILOG_INFO("Close multi window."); + std::lock_guard guard(stackLock_); + if (lockMissionContainer_ && lockMissionContainer_->IsLockedMissionState()) { + HILOG_ERROR("current is lock mission state, refusing to operate other mission."); + return ERR_INVALID_VALUE; + } + + auto mission = GetMissionRecordFromAllStacks(missionId); + CHECK_POINTER_AND_RETURN(mission, CLOSE_MULTI_WINDOW_FAILED); + + auto stack = mission->GetMissionStack(); + CHECK_POINTER_AND_RETURN(stack, CLOSE_MULTI_WINDOW_FAILED); + + if (IsFullScreenStack(stack->GetMissionStackId())) { + HILOG_ERROR("Full screen stack is not close."); + return CLOSE_MULTI_WINDOW_FAILED; + } + + return RemoveMissionByIdLocked(missionId); +} + +void AbilityStackManager::JudgingIsRemoveMultiScreenStack(std::shared_ptr &stack) +{ + HILOG_INFO("Judging is remove multi screen stack."); + + if (stack && !IsFullScreenStack(stack->GetMissionStackId()) && stack->IsEmpty()) { + HILOG_DEBUG("Current stack is empty, remove."); + missionStackList_.remove(stack); + + auto targetWinMode = GetTargetSystemWindowMode(SystemWindowMode::DEFAULT_WINDOW_MODE); + NotifyWindowModeChanged(targetWinMode); + } +} + +void AbilityStackManager::NotifyWindowModeChanged(const SystemWindowMode &windowMode) +{ + HILOG_INFO("Notify window mode changed, will window mode: %{public}d", windowMode); + if (curSysWindowMode_ == windowMode) { + HILOG_ERROR("change mode is current mode"); + return; + } + + HILOG_INFO("current mode : %{public}d , target window mode : %{public}d", curSysWindowMode_, windowMode); + + curSysWindowMode_ = windowMode; + + std::string data; + switch (windowMode) { + case SystemWindowMode::SPLITSCREEN_WINDOW_MODE: + data = "SPLITSCREEN_WINDOW_MODE"; + break; + case SystemWindowMode::FLOATING_WINDOW_MODE: + data = "FLOATING_WINDOW_MODE"; + break; + case SystemWindowMode::FLOATING_AND_SPLITSCREEN_WINDOW_MODE: + data = "FLOATING_AND_SPLITSCREEN_WINDOW_MODE"; + break; + default: + data = "DEFAULT_WINDOW_MODE"; + break; + } + + HILOG_INFO("Publish common event : system window mode changed"); + EventFwk::CommonEventData commonData; + Want want; + want.SetAction(AbilityConfig::EVENT_SYSTEM_WINDOW_MODE_CHANGED); + commonData.SetWant(want); + commonData.SetCode(AbilityConfig::EVENT_CODE_SYSTEM_WINDOW_MODE_CHANGED); + commonData.SetData(data); + EventFwk::CommonEventManager::PublishCommonEvent(commonData); +} + +void AbilityStackManager::UpdateFocusAbilityRecord(const std::shared_ptr &abilityRecord, bool isNotify) +{ + CHECK_POINTER(abilityRecord); + auto getMissionOptionDisplayId = [target = abilityRecord]() { + auto missionRecord = target->GetMissionRecord(); + return missionRecord ? missionRecord->GetMissionOption().displayKey : DISPLAY_DEFAULT_ID; + }; + auto setting = abilityRecord->GetStartSetting(); + int displayId = setting ? std::atoi(setting->GetProperty(AbilityStartSetting::WINDOW_DISPLAY_ID_KEY).c_str()) + : getMissionOptionDisplayId(); + UpdateFocusAbilityRecord(displayId, abilityRecord, isNotify); +} + +void AbilityStackManager::UpdateFocusAbilityRecord( + int displayId, const std::shared_ptr &focusAbility, bool isNotify) +{ + CHECK_POINTER(focusAbility); + auto iter = focusAbilityRecordMap_.find(displayId); + if (iter != focusAbilityRecordMap_.end()) { + auto loseFocusAbility = iter->second.lock(); + if (loseFocusAbility && isNotify) { + loseFocusAbility->TopActiveAbilityChanged(false); + } + focusAbilityRecordMap_.erase(iter); + } + + HILOG_INFO("top active ability changed, displayId:%{public}d, name:%{public}s", + displayId, + focusAbility->GetAbilityInfo().name.c_str()); + + if (isNotify) { + focusAbility->TopActiveAbilityChanged(true); + } + focusAbilityRecordMap_.emplace(displayId, focusAbility); +} + +void AbilityStackManager::CheckMissionRecordIsResume(const std::shared_ptr &mission) +{ + if (resumeMissionContainer_ && resumeMissionContainer_->IsResume(mission->GetMissionRecordId())) { + resumeMissionContainer_->Resume(mission); + } +} + } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_start_setting.cpp b/services/abilitymgr/src/ability_start_setting.cpp new file mode 100644 index 00000000000..886f13d4a9a --- /dev/null +++ b/services/abilitymgr/src/ability_start_setting.cpp @@ -0,0 +1,180 @@ +/* + * 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_start_setting.h" +#include +#include "string_ex.h" + +using namespace OHOS; + +namespace OHOS { +namespace AAFwk { + +const std::string AbilityStartSetting::BOUNDS_KEY = "bounds"; +const std::string AbilityStartSetting::WINDOW_DISPLAY_ID_KEY = "windowId"; +const std::string AbilityStartSetting::WINDOW_MODE_KEY = "windowMode"; + +/** + * @brief Construct copy function. + * @param other indicates instance of abilitystartsetting object + * @return none. + */ +AbilityStartSetting::AbilityStartSetting(const AbilityStartSetting &other) +{ + abilityStarKey_.clear(); + abilityStarKey_ = other.abilityStarKey_; +} +/** + * @brief Overload assignment operation. + * @param other indicates instance of abilitystartsetting object. + * @return Returns current instance of abilitystartsetting object. + */ +AbilityStartSetting &AbilityStartSetting::operator=(const AbilityStartSetting &other) +{ + if (this != &other) { + abilityStarKey_.clear(); + abilityStarKey_ = other.abilityStarKey_; + } + return *this; +} +/** + * @brief Inner function to create AbilityStartSetting + * + * @return Returns the shared_ptr of AbilityStartSetting object. + */ +std::shared_ptr AbilityStartSettingCreator() +{ + std::shared_ptr abilityStartSetting{new (std::nothrow) AbilityStartSetting()}; + return abilityStartSetting; +} + +/** + * @brief Obtains an empty AbilityStartSetting object. + * + * @return Returns the btains an empty AbilityStartSetting object. + */ +std::shared_ptr AbilityStartSetting::GetEmptySetting() +{ + return AbilityStartSettingCreator(); +} + +/** + * @brief Obtains the names of all the attributes that have been added to this AbilityStartSetting object. + * + * @return Returns the set of attribute names included in this AbilityStartSetting object. + */ +std::set AbilityStartSetting::GetPropertiesKey() +{ + std::set abilityStartSet; + abilityStartSet.clear(); + + for (auto it : abilityStarKey_) { + abilityStartSet.emplace(it.first); + } + return abilityStartSet; +} + +/** + * @brief Checks whether this AbilityStartSetting object is empty. + * + * @return Returns true if this AbilityStartSetting object is empty and animatorOption is null; returns false otherwise. + */ +bool AbilityStartSetting::IsEmpty() +{ + return (abilityStarKey_.size() == 0); +} + +/** + * @brief Sets the names of all the attributes of the AbilityStartSetting object. + * + * @param key Indicates the name of the key. + * @param value The window display mode of the values. + */ +void AbilityStartSetting::AddProperty(const std::string &key, const std::string &value) +{ + abilityStarKey_[key] = value; +} + +/** + * @brief Gets the name of the attributes of the AbilityStartSetting object. + * + * @param key Indicates the name of the key. + * @return Returns value Indicates the value of the attributes of the AbilityStartSetting object + */ +std::string AbilityStartSetting::GetProperty(const std::string &key) +{ + auto it = abilityStarKey_.find(key); + if (it == abilityStarKey_.end()) { + return std::string(); + } + return abilityStarKey_[key]; +} + +/** + * @brief Write the data of AbilityStartSetting to the file stream + * @param parcel indicates write the data of AbilityStartSetting to the file stream through parcel + * @return bool + */ +bool AbilityStartSetting::Marshalling(Parcel &parcel) const +{ + size_t size = abilityStarKey_.size(); + + // 1. Number of key value pairs written + parcel.WriteUint32((uint32_t)size); + + std::map::const_iterator it; + + // 2. Write the key and value strings + for (auto pair : abilityStarKey_) { + // 1.key + parcel.WriteString16(Str8ToStr16(pair.first)); + // 2.data content + parcel.WriteString16(Str8ToStr16(pair.second)); + } + + return true; +} + +/** + * @brief Reading file stream through parcel to generate AbilityStartSetting instance + * @param parcel indicates reading file stream through parcel to generate AbilityStartSetting instance + * @return AbilityStartSetting shared_ptr + */ +AbilityStartSetting *AbilityStartSetting::Unmarshalling(Parcel &parcel) +{ + AbilityStartSetting *abilityStartSetting = new (std::nothrow) AbilityStartSetting(); + if (abilityStartSetting == nullptr) { + return nullptr; + } + // 1. Number of key value pairs read + uint32_t size = 0; + parcel.ReadUint32(size); + std::u16string keyReadString16; + std::u16string dataReadString16; + for (size_t i = 0; (i < size) && abilityStartSetting; i++) { + // 1.key + keyReadString16 = parcel.ReadString16(); + // 2.data content + dataReadString16 = parcel.ReadString16(); + abilityStartSetting->abilityStarKey_[Str16ToStr8(keyReadString16)] = Str16ToStr8(dataReadString16); + keyReadString16.clear(); + dataReadString16.clear(); + } + + return abilityStartSetting; +} + +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/app_scheduler.cpp b/services/abilitymgr/src/app_scheduler.cpp index 99695c40223..3836273affc 100644 --- a/services/abilitymgr/src/app_scheduler.cpp +++ b/services/abilitymgr/src/app_scheduler.cpp @@ -55,7 +55,7 @@ bool AppScheduler::Init(const std::weak_ptr &callback) int AppScheduler::LoadAbility(const sptr &token, const sptr &preToken, const AppExecFwk::AbilityInfo &abilityInfo, const AppExecFwk::ApplicationInfo &applicationInfo) { - HILOG_DEBUG("%{public}s, %{public}d", __func__, __LINE__); + HILOG_DEBUG("Load ability."); CHECK_POINTER_AND_RETURN(appMgrClient_, INNER_ERR); /* because the errcode type of AppMgr Client API will be changed to int, * so must to covert the return result */ @@ -69,7 +69,7 @@ int AppScheduler::LoadAbility(const sptr &token, const sptr &token) { - HILOG_DEBUG("%{public}s, %{public}d", __func__, __LINE__); + HILOG_DEBUG("Terminate ability."); CHECK_POINTER_AND_RETURN(appMgrClient_, INNER_ERR); /* because the errcode type of AppMgr Client API will be changed to int, * so must to covert the return result */ @@ -83,14 +83,14 @@ int AppScheduler::TerminateAbility(const sptr &token) void AppScheduler::MoveToForground(const sptr &token) { - HILOG_DEBUG("%{public}s, %{public}d", __func__, __LINE__); + HILOG_DEBUG("Move to forground."); CHECK_POINTER(appMgrClient_); appMgrClient_->UpdateAbilityState(token, AppExecFwk::AbilityState::ABILITY_STATE_FOREGROUND); } void AppScheduler::MoveToBackground(const sptr &token) { - HILOG_DEBUG("%{public}s, %{public}d", __func__, __LINE__); + HILOG_DEBUG("Move to background."); CHECK_POINTER(appMgrClient_); appMgrClient_->UpdateAbilityState(token, AppExecFwk::AbilityState::ABILITY_STATE_BACKGROUND); } @@ -98,14 +98,14 @@ void AppScheduler::MoveToBackground(const sptr &token) void AppScheduler::AbilityBehaviorAnalysis(const sptr &token, const sptr &preToken, const int32_t visibility, const int32_t perceptibility, const int32_t connectionState) { - HILOG_DEBUG("%{public}s, %{public}d", __func__, __LINE__); + HILOG_DEBUG("Ability behavior analysis."); CHECK_POINTER(appMgrClient_); appMgrClient_->AbilityBehaviorAnalysis(token, preToken, visibility, perceptibility, connectionState); } void AppScheduler::KillProcessByAbilityToken(const sptr &token) { - HILOG_DEBUG("%{public}s, %{public}d", __func__, __LINE__); + HILOG_DEBUG("Kill process by ability token."); CHECK_POINTER(appMgrClient_); appMgrClient_->KillProcessByAbilityToken(token); } @@ -132,7 +132,7 @@ AppAbilityState AppScheduler::GetAbilityState() const void AppScheduler::OnAbilityRequestDone(const sptr &token, const AppExecFwk::AbilityState state) { - HILOG_INFO("%{public}s, %{public}d, state:%{public}d", __func__, __LINE__, static_cast(state)); + HILOG_INFO("On ability request done, state:%{public}d", static_cast(state)); auto callback = callback_.lock(); CHECK_POINTER(callback); appAbilityState_ = ConvertToAppAbilityState(static_cast(state)); @@ -141,7 +141,6 @@ void AppScheduler::OnAbilityRequestDone(const sptr &token, const int AppScheduler::KillApplication(const std::string &bundleName) { - HILOG_DEBUG("%{public}s, %{public}d", __func__, __LINE__); CHECK_POINTER_AND_RETURN(appMgrClient_, INNER_ERR); int ret = (int)appMgrClient_->KillApplication(bundleName); if (ret != ERR_OK) { @@ -154,22 +153,32 @@ int AppScheduler::KillApplication(const std::string &bundleName) void AppScheduler::AttachTimeOut(const sptr &token) { - HILOG_DEBUG("%{public}s, %{public}d", __func__, __LINE__); CHECK_POINTER(appMgrClient_); appMgrClient_->AbilityAttachTimeOut(token); } int AppScheduler::CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) { - HILOG_DEBUG("%{public}s, %{public}d", __func__, __LINE__); CHECK_POINTER_AND_RETURN(appMgrClient_, INNER_ERR); auto ret = static_cast(appMgrClient_->CompelVerifyPermission(permission, pid, uid, message)); if (ret != ERR_OK) { - HILOG_ERROR("compel verify permission failed"); + HILOG_ERROR("Compel verify permission failed."); return INNER_ERR; } return ERR_OK; } + +void AppScheduler::OnAppStateChanged(const AppExecFwk::AppProcessData &appData) +{ + auto callback = callback_.lock(); + CHECK_POINTER(callback); + AppInfo info; + info.appName = appData.appName; + info.processName = appData.processName; + info.uid = appData.uid; + info.state = static_cast(appData.appState); + callback->OnAppStateChanged(info); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/configuration_holder.cpp b/services/abilitymgr/src/configuration_holder.cpp new file mode 100644 index 00000000000..72e3f6b6699 --- /dev/null +++ b/services/abilitymgr/src/configuration_holder.cpp @@ -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. + */ +#include "configuration_holder.h" +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AAFwk { + +void ConfigurationHolder::UpdateConfiguration(const std::shared_ptr config) +{ + if (GetChildSize() == 0 && GetParent()) { + HILOG_INFO("%{public}s child update configuration at the time of activing.", __func__); + return; + } + auto configChanges = baseConfiguration_ ? baseConfiguration_->Differ(config) : CHANGE_CONFIG_ALL_CHANGED; + if (configChanges > 0) { + // update base configuration immediately + baseConfiguration_ = config; + } + + DealUpdateConfiguration(); +} + +std::shared_ptr ConfigurationHolder::GetConfiguration() const +{ + return baseConfiguration_; +} + +void ConfigurationHolder::DealUpdateConfiguration() +{ + for (unsigned int index = 0; index < GetChildSize(); index++) { + auto child = FindChild(index); + if (child) { + child->UpdateConfiguration(baseConfiguration_); + } + } +} + +bool ConfigurationHolder::ProcessConfigurationChange() +{ + HILOG_INFO("%{public}s", __func__); + auto parent = GetParent(); + auto targetConfig = parent ? parent->GetConfiguration() : baseConfiguration_; + if (targetConfig == nullptr && baseConfiguration_ == nullptr) { + HILOG_DEBUG("targetConfig and baseConfiguration_ is nullptr, no change."); + return false; + } + + return ProcessConfigurationChangeInner(targetConfig); +} + +bool ConfigurationHolder::ForceProcessConfigurationChange(const std::shared_ptr &config) +{ + return ProcessConfigurationChangeInner(config); +} + +bool ConfigurationHolder::ProcessConfigurationChangeInner(const std::shared_ptr &config) +{ + auto configChanges = baseConfiguration_ ? baseConfiguration_->Differ(config) : CHANGE_CONFIG_ALL_CHANGED; + if (configChanges > 0) { + // update base configuration immediately + baseConfiguration_ = config; + HILOG_DEBUG("have changes."); + if (baseConfiguration_) { + return OnConfigurationChanged(*(baseConfiguration_.get()), configChanges); + } + } + HILOG_DEBUG("there is no change."); + return false; +} + +bool ConfigurationHolder::OnConfigurationChanged(const DummyConfiguration &config, unsigned int configChanges) +{ + return false; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/connection_record.cpp b/services/abilitymgr/src/connection_record.cpp index 1db654ef2b2..9ac21d41ba9 100644 --- a/services/abilitymgr/src/connection_record.cpp +++ b/services/abilitymgr/src/connection_record.cpp @@ -125,7 +125,7 @@ void ConnectionRecord::CompleteConnect(int resultCode) if (connCallback_) { connCallback_->OnAbilityConnectDone(element, remoteObject, resultCode); } - HILOG_INFO("%{public}s, result: %{public}d. connectstate:%{public}d.", __func__, resultCode, state_); + HILOG_INFO("result: %{public}d. connectstate:%{public}d.", resultCode, state_); } void ConnectionRecord::CompleteDisconnect(int resultCode) @@ -139,7 +139,7 @@ void ConnectionRecord::CompleteDisconnect(int resultCode) if (connCallback_) { connCallback_->OnAbilityDisconnectDone(element, resultCode); } - HILOG_INFO("%{public}s, result: %{public}d. connectstate:%{public}d.", __func__, resultCode, state_); + HILOG_INFO("result: %{public}d. connectstate:%{public}d.", resultCode, state_); } void ConnectionRecord::ScheduleDisconnectAbilityDone() diff --git a/services/abilitymgr/src/data_ability_caller_recipient.cpp b/services/abilitymgr/src/data_ability_caller_recipient.cpp new file mode 100644 index 00000000000..e0639f57e7d --- /dev/null +++ b/services/abilitymgr/src/data_ability_caller_recipient.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "data_ability_caller_recipient.h" +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AAFwk { +void DataAbilityCallerRecipient::OnRemoteDied(const wptr &remote) +{ + HILOG_ERROR("recv DataAbilityCallerRecipient death notice"); + + if (handler_) { + handler_(remote); + } +} + +DataAbilityCallerRecipient::DataAbilityCallerRecipient(RemoteDiedHandler handler) : handler_(handler) +{ + HILOG_ERROR("%{public}s", __func__); +} + +DataAbilityCallerRecipient::~DataAbilityCallerRecipient() +{ + HILOG_ERROR("%{public}s", __func__); +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/data_ability_manager.cpp b/services/abilitymgr/src/data_ability_manager.cpp index 4ec44c6fccc..532cefd261e 100644 --- a/services/abilitymgr/src/data_ability_manager.cpp +++ b/services/abilitymgr/src/data_ability_manager.cpp @@ -42,7 +42,7 @@ DataAbilityManager::~DataAbilityManager() } sptr DataAbilityManager::Acquire( - const AbilityRequest &abilityRequest, bool tryBind, const sptr &client) + const AbilityRequest &abilityRequest, bool tryBind, const sptr &client, bool isSystem) { HILOG_DEBUG("%{public}s(%{public}d)", __PRETTY_FUNCTION__, __LINE__); @@ -59,7 +59,7 @@ sptr DataAbilityManager::Acquire( std::shared_ptr clientAbilityRecord; const std::string dataAbilityName(abilityRequest.abilityInfo.bundleName + '.' + abilityRequest.abilityInfo.name); - if (client) { + if (client && !isSystem) { clientAbilityRecord = Token::GetAbilityRecordByToken(client); if (!clientAbilityRecord) { HILOG_ERROR("Data ability manager acquire: invalid client token."); @@ -110,8 +110,8 @@ sptr DataAbilityManager::Acquire( return nullptr; } - if (clientAbilityRecord) { - dataAbilityRecord->AddClient(clientAbilityRecord, tryBind); + if (client) { + dataAbilityRecord->AddClient(client, tryBind, isSystem); } if (DEBUG_ENABLED) { @@ -121,16 +121,14 @@ sptr DataAbilityManager::Acquire( return scheduler; } -int DataAbilityManager::Release(const sptr &scheduler, const sptr &client) +int DataAbilityManager::Release( + const sptr &scheduler, const sptr &client, bool isSystem) { HILOG_DEBUG("%{public}s(%{public}d)", __PRETTY_FUNCTION__, __LINE__); CHECK_POINTER_AND_RETURN(scheduler, ERR_NULL_OBJECT); CHECK_POINTER_AND_RETURN(client, ERR_NULL_OBJECT); - auto clientAbilityRecord = Token::GetAbilityRecordByToken(client); - CHECK_POINTER_AND_RETURN(clientAbilityRecord, ERR_UNKNOWN_OBJECT); - std::lock_guard locker(mutex_); if (DEBUG_ENABLED) { @@ -152,13 +150,21 @@ int DataAbilityManager::Release(const sptr &scheduler, const return ERR_UNKNOWN_OBJECT; } - if (dataAbilityRecord->GetClientCount(clientAbilityRecord) == 0) { + auto abilityRecord = dataAbilityRecord->GetAbilityRecord(); + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_UNKNOWN_OBJECT); + int result = AbilityUtil::JudgeAbilityVisibleControl(abilityRecord->GetAbilityInfo()); + if (result != ERR_OK) { + HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); + return result; + } + + if (dataAbilityRecord->GetClientCount(client) == 0) { HILOG_ERROR("Release data ability with wrong client."); return ERR_UNKNOWN_OBJECT; } HILOG_INFO("Releasing data ability '%{public}s'...", it->first.c_str()); - dataAbilityRecord->RemoveClient(clientAbilityRecord); + dataAbilityRecord->RemoveClient(client, isSystem); if (DEBUG_ENABLED) { DumpLocked(__func__, __LINE__); @@ -300,6 +306,29 @@ void DataAbilityManager::OnAbilityDied(const std::shared_ptr &abi } } +void DataAbilityManager::OnAppStateChanged(const AppInfo &info) +{ + std::lock_guard locker(mutex_); + + for (auto it = dataAbilityRecordsLoaded_.begin(); it != dataAbilityRecordsLoaded_.end(); ++it) { + auto abilityRecord = it->second->GetAbilityRecord(); + if (abilityRecord && abilityRecord->GetApplicationInfo().name == info.appName && + (info.processName == abilityRecord->GetAbilityInfo().process || + info.processName == abilityRecord->GetApplicationInfo().bundleName)) { + abilityRecord->SetAppState(info.state); + } + } + + for (auto it = dataAbilityRecordsLoading_.begin(); it != dataAbilityRecordsLoading_.end(); ++it) { + auto abilityRecord = it->second->GetAbilityRecord(); + if (abilityRecord && abilityRecord->GetApplicationInfo().name == info.appName && + (info.processName == abilityRecord->GetAbilityInfo().process || + info.processName == abilityRecord->GetApplicationInfo().bundleName)) { + abilityRecord->SetAppState(info.state); + } + } +} + std::shared_ptr DataAbilityManager::GetAbilityRecordById(int64_t id) { HILOG_DEBUG("%{public}s(%{public}d)", __PRETTY_FUNCTION__, __LINE__); diff --git a/services/abilitymgr/src/data_ability_record.cpp b/services/abilitymgr/src/data_ability_record.cpp index cbfe4fe813d..91b3cd27327 100644 --- a/services/abilitymgr/src/data_ability_record.cpp +++ b/services/abilitymgr/src/data_ability_record.cpp @@ -179,7 +179,7 @@ int DataAbilityRecord::OnTransitionDone(int state) return ERR_OK; } -int DataAbilityRecord::AddClient(const std::shared_ptr &client, bool tryBind) +int DataAbilityRecord::AddClient(const sptr &client, bool tryBind, bool isSystem) { HILOG_INFO("Adding data ability client..."); @@ -204,28 +204,47 @@ int DataAbilityRecord::AddClient(const std::shared_ptr &client, b return ERR_NULL_OBJECT; } + if (isSystem) { + HILOG_ERROR("When the caller is system,add death monitoring"); + if (client != nullptr && callerDeathRecipient_ != nullptr) { + client->RemoveDeathRecipient(callerDeathRecipient_); + } + if (callerDeathRecipient_ == nullptr) { + callerDeathRecipient_ = new DataAbilityCallerRecipient( + std::bind(&DataAbilityRecord::OnSchedulerDied, this, std::placeholders::_1)); + } + if (client != nullptr) { + client->AddDeathRecipient(callerDeathRecipient_); + } + } + // One client can be added multi-times, so 'RemoveClient()' must be called in corresponding times. auto &clientInfo = clients_.emplace_back(); - clientInfo.ability = client; + clientInfo.client = client; clientInfo.tryBind = tryBind; - - appScheduler->AbilityBehaviorAnalysis(ability_->GetToken(), client->GetToken(), 0, 0, 1); + clientInfo.isSystem = isSystem; + if (!isSystem) { + auto clientAbilityRecord = Token::GetAbilityRecordByToken(client); + CHECK_POINTER_AND_RETURN(clientAbilityRecord, ERR_UNKNOWN_OBJECT); + appScheduler->AbilityBehaviorAnalysis(ability_->GetToken(), clientAbilityRecord->GetToken(), 0, 0, 1); + HILOG_INFO("Ability ability '%{public}s|%{public}s'.", + clientAbilityRecord->GetApplicationInfo().bundleName.c_str(), + clientAbilityRecord->GetAbilityInfo().name.c_str()); + } if (clients_.size() == 1) { HILOG_INFO("Moving data ability app to foreground..."); appScheduler->MoveToForground(ability_->GetToken()); } - HILOG_INFO("Ability '%{public}s|%{public}s' ----> Data ability '%{public}s|%{public}s'.", - client->GetApplicationInfo().bundleName.c_str(), - client->GetAbilityInfo().name.c_str(), + HILOG_INFO("Data ability '%{public}s|%{public}s'.", ability_->GetApplicationInfo().bundleName.c_str(), ability_->GetAbilityInfo().name.c_str()); return ERR_OK; } -int DataAbilityRecord::RemoveClient(const std::shared_ptr &client) +int DataAbilityRecord::RemoveClient(const sptr &client, bool isSystem) { HILOG_INFO("Removing data ability client..."); @@ -256,12 +275,17 @@ int DataAbilityRecord::RemoveClient(const std::shared_ptr &client } for (auto it(clients_.begin()); it != clients_.end(); ++it) { - if (it->ability == client) { - appScheduler->AbilityBehaviorAnalysis(ability_->GetToken(), client->GetToken(), 0, 0, 0); + if (it->client == client) { + if (!isSystem) { + auto clientAbilityRecord = Token::GetAbilityRecordByToken(client); + CHECK_POINTER_AND_RETURN(clientAbilityRecord, ERR_UNKNOWN_OBJECT); + appScheduler->AbilityBehaviorAnalysis(ability_->GetToken(), clientAbilityRecord->GetToken(), 0, 0, 0); + HILOG_INFO("Ability ability '%{public}s|%{public}s'.", + clientAbilityRecord->GetApplicationInfo().bundleName.c_str(), + clientAbilityRecord->GetAbilityInfo().name.c_str()); + } clients_.erase(it); - HILOG_INFO("Ability '%{public}s|%{public}s' --X-> Data ability '%{public}s|%{public}s'.", - client->GetApplicationInfo().bundleName.c_str(), - client->GetAbilityInfo().name.c_str(), + HILOG_INFO("Data ability '%{public}s|%{public}s'.", ability_->GetApplicationInfo().bundleName.c_str(), ability_->GetAbilityInfo().name.c_str()); break; @@ -305,8 +329,37 @@ int DataAbilityRecord::RemoveClients(const std::shared_ptr &clien HILOG_DEBUG("Removing data ability clients with filter..."); auto it = clients_.begin(); while (it != clients_.end()) { - if (it->ability == client) { - appScheduler->AbilityBehaviorAnalysis(ability_->GetToken(), client->GetToken(), 0, 0, 0); + if (!it->isSystem) { + auto clientAbilityRecord = Token::GetAbilityRecordByToken(it->client); + CHECK_POINTER_CONTINUE(clientAbilityRecord); + if (clientAbilityRecord == client) { + appScheduler->AbilityBehaviorAnalysis( + ability_->GetToken(), clientAbilityRecord->GetToken(), 0, 0, 0); + it = clients_.erase(it); + HILOG_INFO("Ability '%{public}s|%{public}s' --X-> Data ability '%{public}s|%{public}s'.", + client->GetApplicationInfo().bundleName.c_str(), + client->GetAbilityInfo().name.c_str(), + ability_->GetApplicationInfo().bundleName.c_str(), + ability_->GetAbilityInfo().name.c_str()); + } else { + ++it; + } + } else { + ++it; + } + } + } else { + HILOG_DEBUG("Removing data ability clients..."); + auto it = clients_.begin(); + while (it != clients_.end()) { + if (!it->isSystem) { + auto clientAbilityRecord = Token::GetAbilityRecordByToken(it->client); + if (!clientAbilityRecord) { + HILOG_DEBUG("clientAbilityRecord is null,clear record"); + it = clients_.erase(it); + continue; + } + appScheduler->AbilityBehaviorAnalysis(ability_->GetToken(), clientAbilityRecord->GetToken(), 0, 0, 0); it = clients_.erase(it); HILOG_INFO("Ability '%{public}s|%{public}s' --X-> Data ability '%{public}s|%{public}s'.", client->GetApplicationInfo().bundleName.c_str(), @@ -317,18 +370,6 @@ int DataAbilityRecord::RemoveClients(const std::shared_ptr &clien ++it; } } - } else { - HILOG_DEBUG("Removing data ability clients..."); - while (!clients_.empty()) { - auto tmpClient = clients_.front().ability; - appScheduler->AbilityBehaviorAnalysis(ability_->GetToken(), tmpClient->GetToken(), 0, 0, 0); - clients_.pop_front(); - HILOG_INFO("Ability '%{public}s|%{public}s' --X-> Data ability '%{public}s|%{public}s'.", - tmpClient->GetApplicationInfo().bundleName.c_str(), - tmpClient->GetAbilityInfo().name.c_str(), - ability_->GetApplicationInfo().bundleName.c_str(), - ability_->GetAbilityInfo().name.c_str()); - } } if (clients_.empty()) { @@ -339,7 +380,7 @@ int DataAbilityRecord::RemoveClients(const std::shared_ptr &clien return ERR_OK; } -size_t DataAbilityRecord::GetClientCount(const std::shared_ptr &client) const +size_t DataAbilityRecord::GetClientCount(const sptr &client) const { CHECK_POINTER_AND_RETURN(ability_, 0); CHECK_POINTER_AND_RETURN(scheduler_, 0); @@ -351,7 +392,7 @@ size_t DataAbilityRecord::GetClientCount(const std::shared_ptr &c if (client) { return std::count_if( - clients_.begin(), clients_.end(), [client](const ClientInfo &ci) { return ci.ability == client; }); + clients_.begin(), clients_.end(), [client](const ClientInfo &ci) { return ci.client == client; }); } return clients_.size(); @@ -374,13 +415,15 @@ int DataAbilityRecord::KillBoundClientProcesses() } for (auto it = clients_.begin(); it != clients_.end(); ++it) { - if (it->tryBind) { + if (it->tryBind && false == it->isSystem) { + auto clientAbilityRecord = Token::GetAbilityRecordByToken(it->client); + CHECK_POINTER_CONTINUE(clientAbilityRecord); HILOG_INFO("Killing bound client '%{public}s|%{public}s' of data ability '%{public}s|%{public}s'...", - it->ability->GetApplicationInfo().bundleName.c_str(), - it->ability->GetAbilityInfo().name.c_str(), + clientAbilityRecord->GetApplicationInfo().bundleName.c_str(), + clientAbilityRecord->GetAbilityInfo().name.c_str(), ability_->GetApplicationInfo().bundleName.c_str(), ability_->GetAbilityInfo().name.c_str()); - appScheduler->KillProcessByAbilityToken(it->ability->GetToken()); + appScheduler->KillProcessByAbilityToken(clientAbilityRecord->GetToken()); } } @@ -419,12 +462,20 @@ void DataAbilityRecord::Dump() const int i = 0; for (auto it = clients_.begin(); it != clients_.end(); ++it) { - auto record = it->ability; - HILOG_INFO(" %{public}2d '%{public}s|%{public}s' - tryBind: %{public}s", - i++, - record->GetApplicationInfo().bundleName.c_str(), - record->GetAbilityInfo().name.c_str(), - it->tryBind ? "true" : "false"); + if (false == it->isSystem) { + auto clientAbilityRecord = Token::GetAbilityRecordByToken(it->client); + CHECK_POINTER_CONTINUE(clientAbilityRecord); + HILOG_INFO(" %{public}2d '%{public}s|%{public}s' - tryBind: %{public}s", + i++, + clientAbilityRecord->GetApplicationInfo().bundleName.c_str(), + clientAbilityRecord->GetAbilityInfo().name.c_str(), + it->tryBind ? "true" : "false"); + } else { + HILOG_INFO(" %{public}2d '%{public}s' - tryBind: %{public}s", + i++, + "caller is system", + it->tryBind ? "true" : "false"); + } } } @@ -437,11 +488,72 @@ void DataAbilityRecord::Dump(std::vector &info) const info.emplace_back(" main name [" + ability_->GetAbilityInfo().name + "]"); info.emplace_back(" bundle name [" + ability_->GetAbilityInfo().bundleName + "]"); info.emplace_back(" ability type [DATA]"); + info.emplace_back(" app state #" + AbilityRecord::ConvertAppState(ability_->GetAppState())); info.emplace_back(" Clients: " + std::to_string(clients_.size())); for (auto &&client : clients_) { - info.emplace_back(" > " + client.ability->GetAbilityInfo().bundleName + "/" + - client.ability->GetAbilityInfo().name + " tryBind #" + (client.tryBind ? "true" : "false")); + if (false == client.isSystem) { + auto clientAbilityRecord = Token::GetAbilityRecordByToken(client.client); + CHECK_POINTER_CONTINUE(clientAbilityRecord); + info.emplace_back(" > " + clientAbilityRecord->GetAbilityInfo().bundleName + "/" + + clientAbilityRecord->GetAbilityInfo().name + " tryBind #" + + (client.tryBind ? "true" : "false") + " isSystem # " + + (client.isSystem ? "true" : "false")); + } else { + info.emplace_back(std::string(" > Caller is System / tryBind # ") + + (client.tryBind ? "true" : "false") + " isSystem # " + + (client.isSystem ? "true" : "false")); + } + } +} + +void DataAbilityRecord::OnSchedulerDied(const wptr &remote) +{ + HILOG_INFO("'%{public}s':", __func__); + auto object = remote.promote(); + + if (clients_.empty()) { + HILOG_DEBUG("BUG: Data ability record has no clients."); + return; + } + + auto appScheduler = DelayedSingleton::GetInstance(); + if (!appScheduler) { + HILOG_ERROR("Data ability remove clients: invalid app scheduler."); + return; + } + + if (object) { + auto it = clients_.begin(); + while (it != clients_.end()) { + if (it->client == object) { + HILOG_DEBUG("remove system caller record with filter..."); + it = clients_.erase(it); + HILOG_INFO("Data ability '%{public}s|%{public}s'.", + ability_->GetApplicationInfo().bundleName.c_str(), + ability_->GetAbilityInfo().name.c_str()); + } else { + ++it; + } + } + } else { + auto it = clients_.begin(); + while (it != clients_.end()) { + if (it->isSystem) { + HILOG_DEBUG("remove system caller record..."); + it = clients_.erase(it); + HILOG_INFO("Data ability '%{public}s|%{public}s'.", + ability_->GetApplicationInfo().bundleName.c_str(), + ability_->GetAbilityInfo().name.c_str()); + } else { + ++it; + } + } + } + + if (clients_.empty()) { + HILOG_INFO("Moving data ability to background..."); + appScheduler->MoveToBackground(ability_->GetToken()); } } } // namespace AAFwk diff --git a/services/abilitymgr/src/kernal_system_app_manager.cpp b/services/abilitymgr/src/kernal_system_app_manager.cpp index 59dc41c7615..47f9b2b7253 100644 --- a/services/abilitymgr/src/kernal_system_app_manager.cpp +++ b/services/abilitymgr/src/kernal_system_app_manager.cpp @@ -64,8 +64,7 @@ int KernalSystemAppManager::StartAbilityLocked(const AbilityRequest &abilityRequ CHECK_POINTER_AND_RETURN(targetAbility, ERR_INVALID_VALUE); targetAbility->SetKernalSystemAbility(); - HILOG_INFO("%{public}s Load kernal system ability, bundleName:%{public}s , abilityName:%{public}s", - __func__, + HILOG_INFO("Load kernal system ability, bundleName:%{public}s , abilityName:%{public}s", abilityRequest.abilityInfo.bundleName.c_str(), abilityRequest.abilityInfo.name.c_str()); @@ -81,14 +80,14 @@ int KernalSystemAppManager::StartAbilityLocked(const AbilityRequest &abilityRequ int KernalSystemAppManager::AttachAbilityThread( const sptr &scheduler, const sptr &token) { - HILOG_INFO("%{public}s.", __func__); + HILOG_INFO("Attach ability thread."); std::lock_guard guard(stackLock_); auto abilityRecord = GetAbilityRecordByToken(token); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); std::string flag = KernalSystemAppManager::GetFlagOfAbility( abilityRecord->GetAbilityInfo().bundleName, abilityRecord->GetAbilityInfo().name); - HILOG_INFO("%{public}s, ability: %{public}s", __func__, flag.c_str()); + HILOG_INFO("ability: %{public}s", flag.c_str()); auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); CHECK_POINTER_AND_RETURN(handler, ERR_INVALID_VALUE); @@ -103,7 +102,7 @@ int KernalSystemAppManager::AttachAbilityThread( void KernalSystemAppManager::OnAbilityRequestDone(const sptr &token, const int32_t state) { - HILOG_INFO("%{public}s", __func__); + HILOG_INFO("On ability request done."); std::lock_guard guard(stackLock_); AppAbilityState abilitState = DelayedSingleton::GetInstance()->ConvertToAppAbilityState(state); if (abilitState == AppAbilityState::ABILITY_STATE_FOREGROUND) { @@ -113,9 +112,21 @@ void KernalSystemAppManager::OnAbilityRequestDone(const sptr &tok } } +void KernalSystemAppManager::OnAppStateChanged(const AppInfo &info) +{ + std::lock_guard guard(stackLock_); + for (auto ability : abilities_) { + if (ability && ability->GetApplicationInfo().name == info.appName && + (info.processName == ability->GetAbilityInfo().process || + info.processName == ability->GetApplicationInfo().bundleName)) { + ability->SetAppState(info.state); + } + } +} + int KernalSystemAppManager::AbilityTransitionDone(const sptr &token, int state) { - HILOG_INFO("%{public}s", __func__); + HILOG_INFO("Ability transition done."); std::lock_guard guard(stackLock_); auto abilityRecord = GetAbilityRecordByToken(token); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); @@ -124,7 +135,7 @@ int KernalSystemAppManager::AbilityTransitionDone(const sptr &tok abilityRecord->GetAbilityInfo().bundleName, abilityRecord->GetAbilityInfo().name); int targetState = AbilityRecord::ConvertLifeCycleToAbilityState(static_cast(state)); std::string abilityState = AbilityRecord::ConvertAbilityState(static_cast(targetState)); - HILOG_INFO("%{public}s, ability: %{public}s, state: %{public}s", __func__, flag.c_str(), abilityState.c_str()); + HILOG_INFO("ability: %{public}s, state: %{public}s", flag.c_str(), abilityState.c_str()); switch (targetState) { case AbilityState::ACTIVE: { @@ -156,7 +167,7 @@ int KernalSystemAppManager::DispatchActive(const std::shared_ptr void KernalSystemAppManager::CompleteActive(const std::shared_ptr &abilityRecord) { - HILOG_INFO("%{public}s", __func__); + HILOG_INFO("Complete active."); std::lock_guard guard(stackLock_); abilityRecord->SetAbilityState(AbilityState::ACTIVE); @@ -273,8 +284,7 @@ void KernalSystemAppManager::DequeueWaittingAbility() if (!waittingAbilityQueue_.empty()) { AbilityRequest abilityRequest = waittingAbilityQueue_.front(); waittingAbilityQueue_.pop(); - HILOG_INFO("%{public}s ,bundleName:%{public}s , abilityName:%{public}s", - __func__, + HILOG_INFO("bundleName: %{public}s, abilityName: %{public}s", abilityRequest.abilityInfo.bundleName.c_str(), abilityRequest.abilityInfo.name.c_str()); @@ -357,5 +367,27 @@ void KernalSystemAppManager::OnTimeOut(uint32_t msgId, int64_t eventId) break; } } + +int KernalSystemAppManager::UpdateConfiguration(const DummyConfiguration &config) +{ + std::lock_guard guard(stackLock_); + std::shared_ptr configPtr = std::make_shared(config); + for (auto &ability : abilities_) { + if (ability) { + if (ability->IsAbilityState(AbilityState::ACTIVE)) { + HILOG_DEBUG("system ui update configuration."); + ability->ForceProcessConfigurationChange(configPtr); + } + } + } + return ERR_OK; +} + +void KernalSystemAppManager::RestartAbility(const std::shared_ptr abilityRecord) +{ + CHECK_POINTER(abilityRecord); + HILOG_DEBUG("Restart ability system ui. %{public}s", abilityRecord->GetAbilityInfo().name.c_str()); + return; +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/lifecycle_deal.cpp b/services/abilitymgr/src/lifecycle_deal.cpp index 65d73e68cb5..25befa3056a 100644 --- a/services/abilitymgr/src/lifecycle_deal.cpp +++ b/services/abilitymgr/src/lifecycle_deal.cpp @@ -33,10 +33,9 @@ void LifecycleDeal::SetScheduler(const sptr &scheduler) void LifecycleDeal::Activate(const Want &want, LifeCycleStateInfo &stateInfo) { - HILOG_INFO("%{public}s, %{public}d", __func__, __LINE__); + HILOG_INFO("Activate."); CHECK_POINTER(abilityScheduler_); - HILOG_INFO("%{public}s, caller %{public}s, %{public}s, %{public}s", - __func__, + HILOG_INFO("caller %{public}s, %{public}s, %{public}s", stateInfo.caller.deviceId.c_str(), stateInfo.caller.bundleName.c_str(), stateInfo.caller.abilityName.c_str()); @@ -46,7 +45,7 @@ void LifecycleDeal::Activate(const Want &want, LifeCycleStateInfo &stateInfo) void LifecycleDeal::Inactivate(const Want &want, LifeCycleStateInfo &stateInfo) { - HILOG_INFO("%{public}s, %{public}d", __func__, __LINE__); + HILOG_INFO("Inactivate."); CHECK_POINTER(abilityScheduler_); stateInfo.state = AbilityLifeCycleState::ABILITY_STATE_INACTIVE; abilityScheduler_->ScheduleAbilityTransaction(want, stateInfo); @@ -54,7 +53,7 @@ void LifecycleDeal::Inactivate(const Want &want, LifeCycleStateInfo &stateInfo) void LifecycleDeal::MoveToBackground(const Want &want, LifeCycleStateInfo &stateInfo) { - HILOG_INFO("%{public}s, %{public}d", __func__, __LINE__); + HILOG_INFO("Move to background."); CHECK_POINTER(abilityScheduler_); stateInfo.state = AbilityLifeCycleState::ABILITY_STATE_BACKGROUND; abilityScheduler_->ScheduleAbilityTransaction(want, stateInfo); @@ -62,21 +61,21 @@ void LifecycleDeal::MoveToBackground(const Want &want, LifeCycleStateInfo &state void LifecycleDeal::ConnectAbility(const Want &want) { - HILOG_INFO("%{public}s, %{public}d", __func__, __LINE__); + HILOG_INFO("Connect ability."); CHECK_POINTER(abilityScheduler_); abilityScheduler_->ScheduleConnectAbility(want); } void LifecycleDeal::DisconnectAbility(const Want &want) { - HILOG_INFO("%{public}s, %{public}d", __func__, __LINE__); + HILOG_INFO("Disconnect ability."); CHECK_POINTER(abilityScheduler_); abilityScheduler_->ScheduleDisconnectAbility(want); } void LifecycleDeal::Terminate(const Want &want, LifeCycleStateInfo &stateInfo) { - HILOG_INFO("%{public}s, %{public}d", __func__, __LINE__); + HILOG_INFO("Terminate."); CHECK_POINTER(abilityScheduler_); stateInfo.state = AbilityLifeCycleState::ABILITY_STATE_INITIAL; abilityScheduler_->ScheduleAbilityTransaction(want, stateInfo); @@ -84,9 +83,30 @@ void LifecycleDeal::Terminate(const Want &want, LifeCycleStateInfo &stateInfo) void LifecycleDeal::CommandAbility(const Want &want, bool reStart, int startId) { - HILOG_INFO("%{public}s, %{public}d", __func__, __LINE__); + HILOG_INFO("Command ability."); CHECK_POINTER(abilityScheduler_); abilityScheduler_->ScheduleCommandAbility(want, reStart, startId); } + +void LifecycleDeal::SaveAbilityState(PacMap &outState) +{ + HILOG_INFO("%{public}s, %{public}d", __func__, __LINE__); + CHECK_POINTER(abilityScheduler_); + abilityScheduler_->ScheduleSaveAbilityState(outState); +} + +void LifecycleDeal::RestoreAbilityState(const PacMap &inState) +{ + HILOG_INFO("%{public}s, %{public}d", __func__, __LINE__); + CHECK_POINTER(abilityScheduler_); + abilityScheduler_->ScheduleRestoreAbilityState(inState); +} + +void LifecycleDeal::UpdateConfiguration(const DummyConfiguration &config) +{ + HILOG_INFO("%{public}s, %{public}d", __func__, __LINE__); + CHECK_POINTER(abilityScheduler_); + abilityScheduler_->ScheduleUpdateConfiguration(config); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/lifecycle_state_info.cpp b/services/abilitymgr/src/lifecycle_state_info.cpp index 1dee0e1bd7a..0c24ec6b1c6 100644 --- a/services/abilitymgr/src/lifecycle_state_info.cpp +++ b/services/abilitymgr/src/lifecycle_state_info.cpp @@ -32,6 +32,12 @@ bool LifeCycleStateInfo::ReadFromParcel(Parcel &parcel) return false; } caller = *callerInfo; + AbilityStartSetting *pSetting = parcel.ReadParcelable(); + if (pSetting != nullptr) { + setting = std::shared_ptr(pSetting); + } else { + setting = nullptr; + } return true; } @@ -68,7 +74,11 @@ bool LifeCycleStateInfo::Marshalling(Parcel &parcel) const return false; } // write caller - if (parcel.WriteParcelable(&caller)) { + if (!parcel.WriteParcelable(&caller)) { + return false; + } + // write setting + if (!parcel.WriteParcelable(setting.get())) { return false; } return true; diff --git a/services/abilitymgr/src/mission_option.cpp b/services/abilitymgr/src/mission_option.cpp new file mode 100644 index 00000000000..68aa6f260e2 --- /dev/null +++ b/services/abilitymgr/src/mission_option.cpp @@ -0,0 +1,94 @@ +/* + * 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 "mission_option.h" +#include "string_ex.h" + +namespace OHOS { +namespace AAFwk { +bool MissionOption::IsSameWindowMode(const AbilityWindowConfiguration &key) const +{ + return ((winModeKey == key) || + (winModeKey == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY && + key == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY) || + (key == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY && + winModeKey == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY)); +} + +bool MissionOption::ReadFromParcel(Parcel &parcel) +{ + userId = parcel.ReadInt32(); + missionId = parcel.ReadInt32(); + winModeKey = static_cast(parcel.ReadInt32()); + displayKey = parcel.ReadInt32(); + + int32_t size = parcel.ReadInt32(); + for (int32_t i = 0; i < size; i++) { + std::string key = Str16ToStr8(parcel.ReadString16()); + std::string data = Str16ToStr8(parcel.ReadString16()); + properties_[key] = data; + } + + return true; +} + +MissionOption *MissionOption::Unmarshalling(Parcel &parcel) +{ + MissionOption *option = new (std::nothrow) MissionOption(); + if (option == nullptr) { + return nullptr; + } + + if (!option->ReadFromParcel(parcel)) { + delete option; + option = nullptr; + } + + return option; +} + +bool MissionOption::Marshalling(Parcel &parcel) const +{ + parcel.WriteInt32(userId); + parcel.WriteInt32(missionId); + parcel.WriteInt32(static_cast(winModeKey)); + parcel.WriteInt32(displayKey); + + parcel.WriteInt32(properties_.size()); + for (auto pair : properties_) { + parcel.WriteString16(Str8ToStr16(pair.first)); + parcel.WriteString16(Str8ToStr16(pair.second)); + } + + return true; +} + +void MissionOption::AddProperty(const std::string &key, const std::string &value) +{ + properties_[key] = value; +} + +void MissionOption::GetProperty(const std::string &key, std::string &value) +{ + auto it = properties_.find(key); + if (it == properties_.end()) { + value = std::string(); + return; + } + value = properties_[key]; +} + +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/mission_record.cpp b/services/abilitymgr/src/mission_record.cpp index fcf14f9b8ca..d88c0bc685b 100644 --- a/services/abilitymgr/src/mission_record.cpp +++ b/services/abilitymgr/src/mission_record.cpp @@ -25,6 +25,18 @@ int MissionRecord::nextMissionId_ = 0; MissionRecord::MissionRecord(const std::string &bundleName) : bundleName_(bundleName) { missionId_ = GetNextMissionId(); + option_.missionId = missionId_; +} + +MissionRecord::MissionRecord(const std::shared_ptr &mission) +{ + bundleName_ = mission->bundleName_; + missionId_ = mission->missionId_; + abilities_.insert(abilities_.begin(), mission->abilities_.begin(), mission->abilities_.end()); + isLauncherCreate_ = mission->isLauncherCreate_; + preMissionRecord_ = mission->preMissionRecord_; + parentMissionStack_ = mission->parentMissionStack_; + missionDescriptionInfo_ = mission->missionDescriptionInfo_; } MissionRecord::~MissionRecord() @@ -63,6 +75,16 @@ std::shared_ptr MissionRecord::GetTopAbilityRecord() const return abilities_.front(); } +std::shared_ptr MissionRecord::GetLastTopAbility() const +{ + if (abilities_.empty() || abilities_.size() == 1) { + HILOG_WARN("no last top ability."); + return nullptr; + } + auto iter = abilities_.begin(); + return (*(++iter)); +} + std::shared_ptr MissionRecord::GetAbilityRecordByToken(const sptr &token) const { auto abilityToFind = Token::GetAbilityRecordByToken(token); @@ -119,6 +141,7 @@ void MissionRecord::AddAbilityRecordToTop(std::shared_ptr ability auto iter = std::find_if(abilities_.begin(), abilities_.end(), isExist); if (iter == abilities_.end()) { abilities_.push_front(ability); + ability->ForceProcessConfigurationChange(GetConfiguration()); } } @@ -220,18 +243,107 @@ bool MissionRecord::IsExistAbilityRecord(int32_t id) return false; } -void MissionRecord::SetParentStack(const std::shared_ptr &parent, int stackId) +bool MissionRecord::SupportMultWindow() const +{ + auto bottom = GetBottomAbilityRecord(); + if (bottom != nullptr) { + return bottom->SupportMultWindow(); + } + return false; +} + +void MissionRecord::SetMissionStack(const std::shared_ptr &missionStack, int stackId) { - CHECK_POINTER(parent); - parentMissionStack_ = parent; + CHECK_POINTER(missionStack); + parentMissionStack_ = missionStack; + UpdateConfiguration(missionStack->GetConfiguration()); for (auto &it : abilities_) { it->SetMissionStackId(stackId); } } -std::shared_ptr MissionRecord::GetParentStack() const +std::shared_ptr MissionRecord::GetMissionStack() const +{ + return parentMissionStack_.lock(); +} + +void MissionRecord::SetMissionOption(const MissionOption &option) +{ + if (option.winModeKey != option_.winModeKey) { + HILOG_ERROR("Batch processing notify multi window mode changed."); + for (auto &it : abilities_) { + CHECK_POINTER(it); + bool flag = option_.winModeKey != AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED && + option_.winModeKey != AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FULLSCREEN; + // true : old is multi win, target is fullscreen. + // false : old is fullscreen, target is multi win. + auto key = flag ? option_.winModeKey : option.winModeKey; + if (it->IsReady()) { + it->NotifyMultiWinModeChanged(key, !flag); + } + } + } + + option_ = option; +} + +const MissionOption &MissionRecord::GetMissionOption() const +{ + return option_; +} + +bool MissionRecord::IsEmpty() +{ + return abilities_.empty(); +} + +std::shared_ptr MissionRecord::GetParent() { return parentMissionStack_.lock(); } + +unsigned int MissionRecord::GetChildSize() +{ + return abilities_.size(); +} + +std::shared_ptr MissionRecord::FindChild(unsigned int index) +{ + if (index < abilities_.size() && index >= 0) { + auto iter = abilities_.begin(); + std::advance(iter, index); + return (*iter); + } + return nullptr; +} + +void MissionRecord::Resume(const std::shared_ptr &backup) +{ + HILOG_INFO("mission resume."); + // backup abilities_ size = 1, singleton ability need resume + if (std::equal(abilities_.begin(), abilities_.end(), backup->abilities_.begin()) && backup->abilities_.size() > 1) { + HILOG_ERROR("List equality, no resume"); + return; + } + + std::list> diffAbilitys; + for (auto &ability : backup->abilities_) { + if (abilities_.front() == ability) { + break; + } + + ability->SetAbilityState(AbilityState::INITIAL); + // ability->ClearFlag(); + diffAbilitys.emplace_back(ability); + } + + abilities_.insert(abilities_.begin(), diffAbilitys.begin(), diffAbilitys.end()); + + for (auto &ability : abilities_) { + if (ability->IsAbilityState(AbilityState::INITIAL)) { + ability->SetRestarting(true); + } + } +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/mission_stack.cpp b/services/abilitymgr/src/mission_stack.cpp index 566488f4c94..884505d5907 100644 --- a/services/abilitymgr/src/mission_stack.cpp +++ b/services/abilitymgr/src/mission_stack.cpp @@ -98,6 +98,11 @@ std::shared_ptr MissionStack::GetTopMissionRecord() return missions_.front(); } +bool MissionStack::IsTopMissionRecord(std::shared_ptr &missionRecord) const +{ + return missions_.front() == missionRecord; +} + std::shared_ptr MissionStack::GetBottomMissionRecord() { if (missions_.empty()) { @@ -263,5 +268,35 @@ bool MissionStack::IsExistMissionRecord(int missionId) } return false; } + +bool MissionStack::IsEqualStackId(int stackId) +{ + return (stackId == missionStackId_); +} + +bool MissionStack::IsEmpty() +{ + return missions_.empty(); +} + +std::shared_ptr MissionStack::GetParent() +{ + return nullptr; +} + +unsigned int MissionStack::GetChildSize() +{ + return missions_.size(); +} + +std::shared_ptr MissionStack::FindChild(unsigned int index) +{ + if (index < missions_.size() && index >= 0) { + auto iter = missions_.begin(); + std::advance(iter, index); + return (*iter); + } + return nullptr; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/pending_want_common_event.cpp b/services/abilitymgr/src/pending_want_common_event.cpp index a40b18a6dc6..4949f9580fd 100644 --- a/services/abilitymgr/src/pending_want_common_event.cpp +++ b/services/abilitymgr/src/pending_want_common_event.cpp @@ -34,7 +34,7 @@ void PendingWantCommonEvent::SetFinishedReceiver(const sptr &fini void PendingWantCommonEvent::OnReceiveEvent(const EventFwk::CommonEventData &data) { - HILOG_INFO("%{public}s:receive common event callback.", __func__); + HILOG_INFO("Receive common event callback."); if (finishedReceiver_ != nullptr) { HILOG_INFO("PendingWantCommonEvent::OnReceiveEvent begin."); finishedReceiver_->PerformReceive(data.GetWant(), data.GetCode(), "", wantParams_, false, false, 0); diff --git a/services/abilitymgr/src/pending_want_key.cpp b/services/abilitymgr/src/pending_want_key.cpp index 78118da6ee8..c8edd85b99d 100644 --- a/services/abilitymgr/src/pending_want_key.cpp +++ b/services/abilitymgr/src/pending_want_key.cpp @@ -20,6 +20,16 @@ namespace OHOS { namespace AAFwk { PendingWantKey::PendingWantKey() + : type_{}, + bundleName_{}, + requestWho_{}, + requestCode_{}, + requestWant_{}, + requestResolvedType_{}, + allWantsInfos_{}, + flags_{}, + code_{}, + userId_{} {} void PendingWantKey::SetType(const int32_t type) @@ -77,12 +87,12 @@ int32_t PendingWantKey::GetType() return type_; } -std::string &PendingWantKey::GetBundleName() +std::string PendingWantKey::GetBundleName() { return bundleName_; } -std::string &PendingWantKey::GetRequestWho() +std::string PendingWantKey::GetRequestWho() { return requestWho_; } @@ -92,17 +102,17 @@ int32_t PendingWantKey::GetRequestCode() return requestCode_; } -Want &PendingWantKey::GetRequestWant() +Want PendingWantKey::GetRequestWant() { return requestWant_; } -std::string &PendingWantKey::GetRequestResolvedType() +std::string PendingWantKey::GetRequestResolvedType() { return requestResolvedType_; } -std::vector &PendingWantKey::GetAllWantsInfos() +std::vector PendingWantKey::GetAllWantsInfos() { return allWantsInfos_; } diff --git a/services/abilitymgr/src/pending_want_manager.cpp b/services/abilitymgr/src/pending_want_manager.cpp index abce811e732..d102fa43f07 100644 --- a/services/abilitymgr/src/pending_want_manager.cpp +++ b/services/abilitymgr/src/pending_want_manager.cpp @@ -37,13 +37,13 @@ PendingWantManager::~PendingWantManager() HILOG_DEBUG("%{public}s(%{public}d)", __PRETTY_FUNCTION__, __LINE__); } -sptr PendingWantManager::GetWantSender(const int32_t callingUid, const int32_t uid, +sptr PendingWantManager::GetWantSender(const int32_t callingUid, const int32_t uid, const bool isSystemApp, const WantSenderInfo &wantSenderInfo, const sptr &callerToken) { HILOG_INFO("PendingWantManager::GetWantSender begin."); std::lock_guard locker(mutex_); - if (callingUid != 0 && callingUid != SYSTEM_UID) { + if (callingUid != 0 && callingUid != SYSTEM_UID && !isSystemApp) { if (callingUid != uid) { HILOG_INFO("is not allowed to send"); return nullptr; @@ -59,9 +59,9 @@ sptr PendingWantManager::GetWantSenderLocked(const int32_t callingU { HILOG_INFO("%{public}s:begin.", __func__); - bool needCreate = ((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0; - bool needCancel = ((int)wantSenderInfo.flags & (int)Flags::CANCEL_PRESENT_FLAG) != 0; - bool needUpdate = ((int)wantSenderInfo.flags & (int)Flags::UPDATE_PRESENT_FLAG) != 0; + bool needCreate = ((uint32_t)wantSenderInfo.flags & (uint32_t)Flags::NO_BUILD_FLAG) != 0; + bool needCancel = ((uint32_t)wantSenderInfo.flags & (uint32_t)Flags::CANCEL_PRESENT_FLAG) != 0; + bool needUpdate = ((uint32_t)wantSenderInfo.flags & (uint32_t)Flags::UPDATE_PRESENT_FLAG) != 0; wantSenderInfo.flags &= ~((uint32_t)Flags::NO_BUILD_FLAG | (uint32_t)Flags::CANCEL_PRESENT_FLAG | (uint32_t)Flags::UPDATE_PRESENT_FLAG); @@ -180,7 +180,8 @@ int32_t PendingWantManager::SendWantSender(const sptr &target, cons return record->SenderInner(info); } -void PendingWantManager::CancelWantSender(const int32_t callingUid, const int32_t uid, const sptr &sender) +void PendingWantManager::CancelWantSender( + const int32_t callingUid, const int32_t uid, const bool isSystemApp, const sptr &sender) { HILOG_INFO("%{public}s:begin.", __func__); @@ -190,9 +191,11 @@ void PendingWantManager::CancelWantSender(const int32_t callingUid, const int32_ } std::lock_guard locker(mutex_); - if (callingUid != uid) { - HILOG_DEBUG("is not allowed to send"); - return; + if (callingUid != 0 && callingUid != SYSTEM_UID && !isSystemApp) { + if (callingUid != uid) { + HILOG_INFO("is not allowed to send"); + return; + } } sptr record = iface_cast(sender->AsObject()); CancelWantSenderLocked(*record, true); @@ -209,21 +212,23 @@ void PendingWantManager::CancelWantSenderLocked(PendingWantRecord &record, bool } int32_t PendingWantManager::PendingWantStartAbility( - const Want &want, const sptr &callerToken, int32_t requestCode) + const Want &want, const sptr &callerToken, int32_t requestCode, int32_t callerUid) { HILOG_INFO("%{public}s:begin.", __func__); - return DelayedSingleton::GetInstance()->StartAbility(want, callerToken, requestCode); + return DelayedSingleton::GetInstance()->StartAbility( + want, callerToken, requestCode, callerUid); } -int32_t PendingWantManager::PendingWantStartAbilitys( - const std::vector wantsInfo, const sptr &callerToken, int32_t requestCode) +int32_t PendingWantManager::PendingWantStartAbilitys(const std::vector wantsInfo, + const sptr &callerToken, int32_t requestCode, int32_t callerUid) { HILOG_INFO("%{public}s:begin.", __func__); int32_t result = ERR_OK; for (const auto &item : wantsInfo) { const auto &want = item.want; - result = DelayedSingleton::GetInstance()->StartAbility(want, callerToken, requestCode); + result = DelayedSingleton::GetInstance()->StartAbility( + want, callerToken, requestCode, callerUid); if (result != ERR_OK && result != START_ABILITY_WAITING) { HILOG_ERROR("%{public}s:result != ERR_OK && result != START_ABILITY_WAITING.", __func__); return result; diff --git a/services/abilitymgr/src/pending_want_record.cpp b/services/abilitymgr/src/pending_want_record.cpp index f60d5887dda..c4b73b0223c 100644 --- a/services/abilitymgr/src/pending_want_record.cpp +++ b/services/abilitymgr/src/pending_want_record.cpp @@ -19,17 +19,13 @@ namespace OHOS { namespace AAFwk { -PendingWantRecord::PendingWantRecord() +PendingWantRecord::PendingWantRecord() : pendingWantManager_{}, uid_{}, callerToken_{}, key_{} {} PendingWantRecord::PendingWantRecord(const std::shared_ptr &pendingWantManager, int32_t uid, const sptr &callerToken, std::shared_ptr key) -{ - pendingWantManager_ = pendingWantManager; - uid_ = uid; - callerToken_ = callerToken; - key_ = key; -} + : pendingWantManager_(pendingWantManager), uid_(uid), callerToken_(callerToken), key_(key) +{} PendingWantRecord::~PendingWantRecord() {} @@ -74,7 +70,7 @@ int32_t PendingWantRecord::SenderInner(SenderInfo &senderInfo) return ERR_INVALID_VALUE; } - if ((key_->GetFlags() & (int32_t)Flags::ONE_TIME_FLAG) != 0) { + if (((uint32_t)key_->GetFlags() & (uint32_t)Flags::ONE_TIME_FLAG) != 0) { pendingWantManager->CancelWantSenderLocked(*this, true); } @@ -82,7 +78,7 @@ int32_t PendingWantRecord::SenderInner(SenderInfo &senderInfo) if (key_->GetAllWantsInfos().size() != 0) { want = key_->GetRequestWant(); } - bool immutable = (key_->GetFlags() & (int32_t)Flags::CONSTANT_FLAG) != 0; + bool immutable = ((uint32_t)key_->GetFlags() & (uint32_t)Flags::CONSTANT_FLAG) != 0; senderInfo.resolvedType = key_->GetRequestResolvedType(); if (!immutable) { want.AddFlags(key_->GetFlags()); @@ -92,17 +88,17 @@ int32_t PendingWantRecord::SenderInner(SenderInfo &senderInfo) int res = NO_ERROR; switch (key_->GetType()) { case (int32_t)OperationType::START_ABILITY: - res = pendingWantManager->PendingWantStartAbility(want, callerToken_, -1); + res = pendingWantManager->PendingWantStartAbility(want, callerToken_, -1, callerUid_); break; case (int32_t)OperationType::START_ABILITIES: { std::vector allWantsInfos = key_->GetAllWantsInfos(); allWantsInfos.back().want = want; - res = pendingWantManager->PendingWantStartAbilitys(allWantsInfos, callerToken_, -1); + res = pendingWantManager->PendingWantStartAbilitys(allWantsInfos, callerToken_, -1, callerUid_); break; } case (int32_t)OperationType::START_SERVICE: case (int32_t)OperationType::START_FOREGROUND_SERVICE: - res = pendingWantManager->PendingWantStartAbility(want, callerToken_, -1); + res = pendingWantManager->PendingWantStartAbility(want, callerToken_, -1, callerUid_); break; case (int32_t)OperationType::SEND_COMMON_EVENT: res = pendingWantManager->PendingWantPublishCommonEvent(want, senderInfo, callerUid_); diff --git a/services/abilitymgr/src/power_storage.cpp b/services/abilitymgr/src/power_storage.cpp index b0549d63de0..8dc9ef8616b 100644 --- a/services/abilitymgr/src/power_storage.cpp +++ b/services/abilitymgr/src/power_storage.cpp @@ -19,20 +19,36 @@ namespace OHOS { namespace AAFwk { -void PowerStorage::SetPowerOffRecord(const std::shared_ptr &ability) +void PowerStorage::SetPowerOffInActiveRecord(const std::shared_ptr &ability) { CHECK_POINTER(ability); PowerOffRecord record; record.ability = ability; - record.StackId = ability->GetMissionRecord()->GetParentStack()->GetMissionStackId(); + record.StackId = ability->GetMissionRecord()->GetMissionStack()->GetMissionStackId(); record.missionId = ability->GetMissionRecord()->GetMissionRecordId(); record.state = ability->GetAbilityState(); - record_.emplace_back(record); + inActiveRecord_.emplace_back(record); } -std::vector PowerStorage::GetPowerOffRecord() const +std::vector PowerStorage::GetPowerOffInActiveRecord() const { - return record_; + return inActiveRecord_; +} + +void PowerStorage::SetPowerOffActiveRecord(const std::shared_ptr &ability) +{ + CHECK_POINTER(ability); + PowerOffRecord record; + record.ability = ability; + record.StackId = ability->GetMissionRecord()->GetMissionStack()->GetMissionStackId(); + record.missionId = ability->GetMissionRecord()->GetMissionRecordId(); + record.state = ability->GetAbilityState(); + activeRecord_.emplace_back(record); +} + +std::vector PowerStorage::GetPowerOffActiveRecord() const +{ + return activeRecord_; } } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/resume_mission_container.cpp b/services/abilitymgr/src/resume_mission_container.cpp new file mode 100644 index 00000000000..f23fcadc75d --- /dev/null +++ b/services/abilitymgr/src/resume_mission_container.cpp @@ -0,0 +1,70 @@ +/* + * 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 "resume_mission_container.h" +#include "hilog_wrapper.h" +#include "ability_util.h" + +namespace OHOS { +namespace AAFwk { + +ResumeMissionContainer::ResumeMissionContainer(const std::shared_ptr &handler) : handler_(handler) +{} + +void ResumeMissionContainer::Save(const std::shared_ptr &mission) +{ + HILOG_INFO("Save."); + CHECK_POINTER(mission); + + auto missionId = mission->GetMissionRecordId(); + auto finder = missionMaps_.find(missionId); + std::shared_ptr backup; + if (finder == missionMaps_.end()) { + HILOG_INFO("Backup"); + backup = std::make_shared(mission); + missionMaps_.emplace(missionId, backup); + } + + if (backup) { + HILOG_INFO("start save time..."); + handler_->PostTask( + [this, missionId]() { Remove(missionId); }, taskName_ + std::to_string(missionId), recordSaveTime_); + } +} + +void ResumeMissionContainer::Resume(const std::shared_ptr &mission) +{ + HILOG_INFO("Resume."); + CHECK_POINTER(mission); + + auto backup = missionMaps_.find(mission->GetMissionRecordId()); + mission->Resume(backup->second); + missionMaps_.erase(mission->GetMissionRecordId()); +} + +void ResumeMissionContainer::Remove(int missionId) +{ + HILOG_INFO("Remove."); + missionMaps_.erase(missionId); + handler_->RemoveTask(taskName_ + std::to_string(missionId)); +} + +bool ResumeMissionContainer::IsResume(int missionId) +{ + return (missionMaps_.find(missionId) != missionMaps_.end()); +} + +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/sa_mgr_client.cpp b/services/abilitymgr/src/sa_mgr_client.cpp index f9674723ba2..e8798f65e0d 100644 --- a/services/abilitymgr/src/sa_mgr_client.cpp +++ b/services/abilitymgr/src/sa_mgr_client.cpp @@ -37,7 +37,7 @@ sptr SaMgrClient::GetSystemAbility(const int32_t systemAbilityId) if (saMgr_ == nullptr) { saMgr_ = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (saMgr_ == nullptr) { - HILOG_ERROR("%s:fail to get Registry", __func__); + HILOG_ERROR("Fail to get registry."); return nullptr; } } diff --git a/services/abilitymgr/src/stack_setting.cpp b/services/abilitymgr/src/stack_setting.cpp new file mode 100644 index 00000000000..994800206ea --- /dev/null +++ b/services/abilitymgr/src/stack_setting.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "stack_setting.h" + +#include "hilog_wrapper.h" +#include "string_ex.h" + +namespace OHOS { +namespace AAFwk { +bool StackSetting::ReadFromParcel(Parcel &parcel) +{ + userId = parcel.ReadInt32(); + stackId = static_cast(parcel.ReadInt32()); + maxHoldMission = parcel.ReadInt32(); + isSyncVisual = parcel.ReadBool(); + return true; +} + +StackSetting *StackSetting::Unmarshalling(Parcel &parcel) +{ + StackSetting *setiing = new (std::nothrow) StackSetting(); + if (setiing == nullptr) { + return nullptr; + } + + if (!setiing->ReadFromParcel(parcel)) { + delete setiing; + setiing = nullptr; + } + return setiing; +} + +bool StackSetting::Marshalling(Parcel &parcel) const +{ + parcel.WriteInt32(userId); + parcel.WriteInt32(static_cast(stackId)); + parcel.WriteInt32(maxHoldMission); + parcel.WriteBool(isSyncVisual); + return true; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/BUILD.gn b/services/abilitymgr/test/BUILD.gn index a5142290da2..08d00a7b040 100644 --- a/services/abilitymgr/test/BUILD.gn +++ b/services/abilitymgr/test/BUILD.gn @@ -20,13 +20,24 @@ EVENT_DIR = "//base/notification/ces_standard/" ohos_source_set("abilityms_test_source") { sources = abilityms_files include_dirs = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/", "${EVENT_DIR}/frameworks/core/include", "${EVENT_DIR}/interfaces/innerkits/native/include", "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr", ] + external_dependent_files = [ + "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_state_callback_host.cpp", + "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp", + "//foundation/appexecfwk/standard/common/log/src/app_log_wrapper.cpp", + "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp", + ] + + sources += external_dependent_files + public_configs = [ "${services_path}/abilitymgr:abilityms_config", "${services_path}/abilitymgr/test/mock:aafwk_mock_config", @@ -73,6 +84,7 @@ group("unittest") { "unittest/phone/ability_with_applications_test:unittest", "unittest/phone/abilityms_appms_test:unittest", "unittest/phone/app_scheduler_test:unittest", + "unittest/phone/configuration_holder_test:unittest", "unittest/phone/connection_record_test:unittest", "unittest/phone/data_ability_manager_test:unittest", "unittest/phone/data_ability_record_test:unittest", @@ -85,6 +97,7 @@ group("unittest") { "unittest/phone/pending_want_key_test:unittest", "unittest/phone/pending_want_manager_test:unittest", "unittest/phone/pending_want_record_test:unittest", + "unittest/phone/resume_mission_container_test:unittest", "unittest/phone/sender_info_test:unittest", "unittest/phone/terminate_ability_test:unittest", "unittest/phone/want_receiver_proxy_test:unittest", diff --git a/services/abilitymgr/test/mock/appmgr_test_service/BUILD.gn b/services/abilitymgr/test/mock/appmgr_test_service/BUILD.gn old mode 100644 new mode 100755 index 350ad664aed..2dc9a664957 --- a/services/abilitymgr/test/mock/appmgr_test_service/BUILD.gn +++ b/services/abilitymgr/test/mock/appmgr_test_service/BUILD.gn @@ -9,13 +9,22 @@ # 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. +# limitations under the License. import("//build/ohos.gni") import("//foundation/aafwk/standard/aafwk.gni") config("appmgr_test_service_config") { - include_dirs = [ "include/" ] + include_dirs = [ + "//foundation/aafwk/standard/services/abilitymgr/test/mock/appmgr_test_service/include/", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/services/common/include", + "//base/notification/ces_standard/frameworks/core/include", + "//base/notification/ces_standard/interfaces/innerkits/native/include", + ] } ohos_source_set("appmgr_test_service") { @@ -23,15 +32,12 @@ ohos_source_set("appmgr_test_service") { "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/aakit/include", + "//third_party/jsoncpp/include", ] sources = [ "src/appmgr_test_service.cpp" ] - configs = [ - ":appmgr_test_service_config", - "${services_path}/abilitymgr:abilityms_config", - "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_core_mock_config", - ] + configs = [ ":appmgr_test_service_config" ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] @@ -40,10 +46,8 @@ ohos_source_set("appmgr_test_service") { "${innerkits_path}/want:want", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", - - # "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - # "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", ] external_deps = [ diff --git a/services/abilitymgr/test/mock/include/mock_app_mgr_client.h b/services/abilitymgr/test/mock/include/mock_app_mgr_client.h index 6c9e12c1cf2..295ce00f600 100644 --- a/services/abilitymgr/test/mock/include/mock_app_mgr_client.h +++ b/services/abilitymgr/test/mock/include/mock_app_mgr_client.h @@ -19,7 +19,6 @@ #include "gmock/gmock.h" #include "app_mgr_client.h" #include "hilog_wrapper.h" -#include "app_mgr_constants.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/test/mock/include/mock_configuration_holder.h b/services/abilitymgr/test/mock/include/mock_configuration_holder.h new file mode 100644 index 00000000000..efd4cd09a84 --- /dev/null +++ b/services/abilitymgr/test/mock/include/mock_configuration_holder.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_AAFWK_SERVICES_TEST_MT_MOCK_APP_MANAGER_CLIENT_H +#define FOUNDATION_AAFWK_SERVICES_TEST_MT_MOCK_APP_MANAGER_CLIENT_H + +#include + +#include "configuration_holder.h" + +namespace OHOS { +namespace AppExecFwk { + +class MockConfigurationHolder : public AAFwk::ConfigurationHolder { +public: + MockConfigurationHolder() + {} + ~MockConfigurationHolder() + {} + + std::shared_ptr GetParent() + { + return nullptr; + } + + unsigned int GetChildSize() + { + return 1; + } + + std::shared_ptr FindChild(unsigned int index) + { + return nullptr; + } +}; + +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_AAFWK_SERVICES_TEST_MT_MOCK_APP_MGR_CLIENT_H diff --git a/services/abilitymgr/test/mock/libs/aakit/BUILD.gn b/services/abilitymgr/test/mock/libs/aakit/BUILD.gn old mode 100644 new mode 100755 index 9cf4517c3fc..20ab44215e2 --- a/services/abilitymgr/test/mock/libs/aakit/BUILD.gn +++ b/services/abilitymgr/test/mock/libs/aakit/BUILD.gn @@ -9,15 +9,23 @@ # 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. +# limitations under the License. import("//build/ohos.gni") import("//foundation/aafwk/standard/aafwk.gni") config("aakit_mock_config") { include_dirs = [ + "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/aakit/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include/", "include/", + "//third_party/jsoncpp/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include/", + "//foundation/aafwk/standard/services/common/include/", ] } @@ -27,21 +35,18 @@ ohos_source_set("aakit_mock") { "src/mock_ability_connect_callback.cpp", ] - configs = [ - ":aakit_mock_config", - "${services_path}/abilitymgr:abilityms_config", - "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_core_mock_config", - "${services_path}/common:common_config", - ] + configs = [ ":aakit_mock_config" ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ + "${innerkits_path}/want:want", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] external_deps = [ diff --git a/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h b/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h index 4fec9c0536d..15eb81732a6 100644 --- a/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h +++ b/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h @@ -50,6 +50,8 @@ public: void ScheduleRestoreAbilityState(const PacMap &inState) override; + void ScheduleUpdateConfiguration(const DummyConfiguration &config) override; + std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; int OpenFile(const Uri &uri, const std::string &mode) override; @@ -71,6 +73,12 @@ public: int BatchInsert(const Uri &uri, const std::vector &values) override; + void NotifyMultiWinModeChanged(int32_t winModeKey, bool flag) override; + Uri NormalizeUri(const Uri &uri) override; + Uri DenormalizeUri(const Uri &uri) override; + + void NotifyTopActiveAbilityChanged(bool flag) override; + private: AbilityResult result_; }; diff --git a/services/abilitymgr/test/mock/libs/aakit/src/ability_scheduler.cpp b/services/abilitymgr/test/mock/libs/aakit/src/ability_scheduler.cpp index 9be782990c3..80a8a48f7f3 100644 --- a/services/abilitymgr/test/mock/libs/aakit/src/ability_scheduler.cpp +++ b/services/abilitymgr/test/mock/libs/aakit/src/ability_scheduler.cpp @@ -60,6 +60,9 @@ void AbilityScheduler::ScheduleSaveAbilityState(PacMap &outState) void AbilityScheduler::ScheduleRestoreAbilityState(const PacMap &inState) {} +void AbilityScheduler::ScheduleUpdateConfiguration(const DummyConfiguration &config) +{} + std::vector AbilityScheduler::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) { std::vector values; @@ -112,5 +115,22 @@ int AbilityScheduler::BatchInsert(const Uri &uri, const std::vector -#include "ability_info.h" -#include "application_info.h" -#include "app_mgr_constants.h" -#include "iremote_object.h" -#include "refbase.h" -#include "iapp_state_callback.h" - -namespace OHOS { -namespace AppExecFwk { - -class AppMgrClient { -public: - AppMgrClient() - {} - virtual ~AppMgrClient() - {} - - virtual AppMgrResultCode LoadAbility(const sptr &token, const sptr &preToken, - const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo); - - virtual AppMgrResultCode TerminateAbility(const sptr &token); - - virtual AppMgrResultCode UpdateAbilityState(const sptr &token, const AbilityState state); - - virtual AppMgrResultCode RegisterAppStateCallback(const sptr &callback); - - virtual AppMgrResultCode ConnectAppMgrService(); - - virtual AppMgrResultCode AbilityBehaviorAnalysis(const sptr &token, - const sptr &preToken, const int32_t visibility, const int32_t perceptibility, - const int32_t connectionState); - - virtual AppMgrResultCode KillProcessByAbilityToken(const sptr &token); - - virtual AppMgrResultCode KillApplication(const std::string &bundleName); - - virtual int MoveMissionToEnd(const sptr &token, const bool nonFirst); - - virtual bool IsFirstInMission(const sptr &token); - - virtual int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message); - - virtual void AbilityAttachTimeOut(const sptr &token); - - static int loadAbilityCount; - static int terminateAbilityCount; - static int backgroundCount; - static int foregroundCount; - -private: - sptr callback_; - sptr remote_; -}; - -} // namespace AppExecFwk -} // namespace OHOS -#endif // OHOS_APPEXECFWK_APP_MGR_CLIENT_H +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APP_MGR_CLIENT_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APP_MGR_CLIENT_H + +#include "iremote_object.h" +#include "refbase.h" + +#include "ability_info.h" +#include "application_info.h" +// #include "app_mgr_constants.h" +#include "iapp_state_callback.h" +#include "running_process_info.h" + +namespace OHOS { +namespace AppExecFwk { + +class AppServiceManager; + +class AppMgrClient { +public: + AppMgrClient(); + virtual ~AppMgrClient(); + + /** + * Load ability. + * + * @param token, Ability identify. + * @param abilityInfo, Ability information. + * @param appInfo, Application information. + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode LoadAbility(const sptr &token, const sptr &preToken, + const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo); + + /** + * Terminate ability. + * + * @param token Ability identify. + * + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode TerminateAbility(const sptr &token); + + /** + * Update ability state. + * + * @param token Ability identify. + * @param state Ability running state. + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode UpdateAbilityState(const sptr &token, const AbilityState state); + + /** + * Register Application state callback. + * + * @param callback IAppStateCallback + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode RegisterAppStateCallback(const sptr &callback); + + /** + * Connect service. + * + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode ConnectAppMgrService(); + + /** + * Ability manager resst. + * + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode Reset(); + + /** + * AbilityBehaviorAnalysis, ability behavior analysis assistant process optimization. + * + * @param token, the unique identification to start the ability. + * @param preToken, the unique identification to call the ability. + * @param visibility, the visibility information about windows info. + * @param perceptibility, the Perceptibility information about windows info. + * @param connectionState, the service ability connection state. + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode AbilityBehaviorAnalysis(const sptr &token, + const sptr &preToken, const int32_t visibility, const int32_t perceptibility, + const int32_t connectionState); + + /** + * KillProcessByAbilityToken, call KillProcessByAbilityToken() through proxy object, + * kill the process by ability token. + * + * @param token, the unique identification to the ability. + * @return Returns RESULT_OK on success, others on failure. + */ + virtual AppMgrResultCode KillProcessByAbilityToken(const sptr &token); + + /** + * KillApplication, call KillApplication() through proxy object, kill the application. + * + * @param bundleName, bundle name in Application record. + * @return ERR_OK, return back success, others fail. + */ + virtual AppMgrResultCode KillApplication(const std::string &bundleName); + + /** + * ClearUpApplicationData, call ClearUpApplicationData() through proxy project, + * clear the application data. + * + * @param bundleName, bundle name in Application record. + * @return + */ + virtual AppMgrResultCode ClearUpApplicationData(const std::string &bundleName); + + /** + * GetAllRunningProcesses, call GetAllRunningProcesses() through proxy project. + * Obtains information about application processes that are running on the device. + * + * @param info, app name in Application record. + * @return ERR_OK ,return back success��others fail. + */ + virtual AppMgrResultCode GetAllRunningProcesses(std::vector &info); + + /** + * SetAppSuspendTimes, Setting the Freezing Time of APP Background. + * + * @param time, The timeout recorded when the application enters the background . + * + * @return Success or Failure . + */ + virtual AppMgrResultCode SetAppFreezingTime(int time); + + /** + * GetAppFreezingTime, Getting the Freezing Time of APP Background. + * + * @param time, The timeout recorded when the application enters the background . + * + * @return Success or Failure . + */ + virtual AppMgrResultCode GetAppFreezingTime(int &time); + virtual void AbilityAttachTimeOut(const sptr &token); + + /** + * Checks whether a specified permission has been granted to the process identified by pid and uid + * + * @param permission Indicates the permission to check. + * @param pid Indicates the ID of the process to check. + * @param uid Indicates the UID of the process to check. + * @param message Describe success or failure + * + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message); + +private: + void SetServiceManager(std::unique_ptr serviceMgr); + +private: + std::unique_ptr serviceManager_; + sptr remote_; + sptr callback_; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APP_MGR_CLIENT_H diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_interface.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_interface.h new file mode 100644 index 00000000000..766e8d23f2b --- /dev/null +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_interface.h @@ -0,0 +1,160 @@ +/* + * 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_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_INTERFACE_H + +#include "iremote_broker.h" +#include "iremote_object.h" + +#include "ability_info.h" +#include "application_info.h" +#include "app_record_id.h" +#include "iapp_state_callback.h" +#include "ams_mgr_interface.h" +#include "running_process_info.h" + +namespace OHOS { +namespace AppExecFwk { + +class IAppMgr : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.AppMgr"); + + /** + * AttachApplication, call AttachApplication() through proxy object, + * get all the information needed to start the Application (data related to the Application ). + * + * @param app, information needed to start the Application. + * @return + */ + virtual void AttachApplication(const sptr &app) = 0; + + /** + * ApplicationForegrounded, call ApplicationForegrounded() through proxy object, + * set the application to Foreground State. + * + * @param recordId, a unique record that identifies this Application from others. + * @return + */ + virtual void ApplicationForegrounded(const int32_t recordId) = 0; + + /** + * ApplicationBackgrounded, call ApplicationBackgrounded() through proxy object, + * set the application to Backgrounded State. + * + * @param recordId, a unique record that identifies this Application from others. + * @return + */ + virtual void ApplicationBackgrounded(const int32_t recordId) = 0; + + /** + * ApplicationTerminated, call ApplicationTerminated() through proxy object, + * terminate the application. + * + * @param recordId, a unique record that identifies this Application from others. + * @return + */ + virtual void ApplicationTerminated(const int32_t recordId) = 0; + + /** + * CheckPermission, call CheckPermission() through proxy object, check the permission. + * + * @param recordId, a unique record that identifies this Application from others. + * @param permission, check the permissions. + * @return ERR_OK, return back success, others fail. + */ + virtual int CheckPermission(const int32_t recordId, const std::string &permission) = 0; + + /** + * AbilityCleaned,call through AbilityCleaned() proxy project, clean Ability record. + * + * @param token, a unique record that identifies AbilityCleaned from others. + * @return + */ + virtual void AbilityCleaned(const sptr &token) = 0; + + /** + * GetAmsMgr, call GetAmsMgr() through proxy object, get AMS interface instance. + * + * @return sptr, return to AMS interface instance. + */ + virtual sptr GetAmsMgr() = 0; + + /** + * ClearUpApplicationData, call ClearUpApplicationData() through proxy project, + * clear the application data. + * + * @param bundleName, bundle name in Application record. + * @return + */ + virtual int32_t ClearUpApplicationData(const std::string &bundleName) = 0; + + /** + * IsBackgroundRunningRestricted, call IsBackgroundRunningRestricted() through proxy project, + * Checks whether the process of this application is forbidden to run in the background. + * + * @param bundleName, bundle name in Application record. + * @return ERR_OK, return back success, others fail. + */ + virtual int IsBackgroundRunningRestricted(const std::string &bundleName) = 0; + + /** + * GetAllRunningProcesses, call GetAllRunningProcesses() through proxy project. + * Obtains information about application processes that are running on the device. + * + * @param info, app name in Application record. + * @return ERR_OK ,return back success,others fail. + */ + virtual int GetAllRunningProcesses(std::vector &info) = 0; + + /** + * SetAppSuspendTimes, Setting the Freezing Time of APP Background. + * + * @param time, The timeout recorded when the application enters the background . + * + * @return Success or Failure . + */ + virtual void SetAppFreezingTime(int time) = 0; + + /** + * GetAppFreezingTime, Getting the Freezing Time of APP Background. + * + * @param time, The timeout recorded when the application enters the background . + * + * @return Success or Failure . + */ + virtual void GetAppFreezingTime(int &time) = 0; + + enum class Message { + AMS_APP_ATTACH_APPLICATION = 0, + AMS_APP_APPLICATION_FOREGROUNDED, + AMS_APP_APPLICATION_BACKGROUNDED, + AMS_APP_APPLICATION_TERMINATED, + AMS_APP_CHECK_PERMISSION, + AMS_APP_ABILITY_CLEANED, + AMS_APP_GET_MGR_INSTANCE, + AMS_APP_CLEAR_UP_APPLICATION_DATA, + AMS_APP_IS_BACKGROUND_RUNNING_RESTRICTED, + AMS_APP_GET_ALL_RUNNING_PROCESSES, + AMS_APP_SET_APP_FREEZING_TIME, + AMS_APP_GET_APP_FREEZING_TIME, + }; +}; + +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_INTERFACE_H diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_process_data.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_process_data.h new file mode 100644 index 00000000000..aae4d474947 --- /dev/null +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_process_data.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_PROCESS_DATA_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_PROCESS_DATA_H + +#include + +#include "parcel.h" + +#include "app_mgr_constants.h" + +namespace OHOS { +namespace AppExecFwk { + +struct AppProcessData : public Parcelable { + /** + * @brief read this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + * @return Returns true if read successed; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * @brief Marshals this Sequenceable object into a Parcel. + * + * @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this Sequenceable object from a Parcel. + * + * @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled. + */ + static AppProcessData *Unmarshalling(Parcel &parcel); + + std::string appName; + std::string processName; + ApplicationState appState = ApplicationState::APP_STATE_CREATE; + pid_t pid = 0; + int32_t uid = 0; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_PROCESS_DATA_H diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_state_callback_host.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_state_callback_host.h index e767e5a55aa..591c68102ae 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_state_callback_host.h +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_state_callback_host.h @@ -16,25 +16,48 @@ #ifndef OHOS_AppExecFwk_APP_STATE_CALLBACK_HOST_H #define OHOS_AppExecFwk_APP_STATE_CALLBACK_HOST_H +#include +#include "iremote_stub.h" +#include "nocopyable.h" +#include "string_ex.h" #include "app_mgr_constants.h" -#include "iapp_state_callback.h" +#include "appmgr/iapp_state_callback.h" #include "iremote_object.h" namespace OHOS { namespace AppExecFwk { -class AppStateCallbackHost : public IAppStateCallback { +class AppStateCallbackHost : public IRemoteStub { public: - AppStateCallbackHost() = default; - virtual ~AppStateCallbackHost() = default; + AppStateCallbackHost(); + virtual ~AppStateCallbackHost(); - void OnAppStateChanged(const std::string &__attribute__((unused)) appName, - const ApplicationState __attribute__((unused)) state) override - {} + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; - void OnAbilityRequestDone(const sptr &__attribute__((unused)) token, - const AbilityState __attribute__((unused)) state) override - {} + /** + * AbilityMgr's request is done. + * + * @param token Ability token. + * @param state Application state. + */ + virtual void OnAbilityRequestDone(const sptr &, const AbilityState) override; + + /** + * Application state changed callback. + * + * @param appProcessData Process data + */ + virtual void OnAppStateChanged(const AppProcessData &) override; + +private: + int32_t HandleOnAppStateChanged(MessageParcel &data, MessageParcel &reply); + int32_t HandleOnAbilityRequestDone(MessageParcel &data, MessageParcel &reply); + + using AppStateCallbackFunc = int32_t (AppStateCallbackHost::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(AppStateCallbackHost); }; } // namespace AppExecFwk diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/iapp_state_callback.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/iapp_state_callback.h index 3ae29fcb345..e9fdfe6d3d8 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/iapp_state_callback.h +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/iapp_state_callback.h @@ -1,42 +1,55 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_APPEXECFWK_IAPP_STATE_CALLBACK_H -#define OHOS_APPEXECFWK_IAPP_STATE_CALLBACK_H - -#include -#include "app_mgr_constants.h" -#include "iapp_state_callback.h" -#include "iremote_object.h" - -namespace OHOS { -namespace AppExecFwk { - -class IAppStateCallback : public virtual RefBase { -public: - /** - * MOCApplication state changed callback. - */ - virtual void OnAppStateChanged(const std::string &appName, const ApplicationState state) = 0; - - /** - * mock AbilityMgr's request is done. - */ - virtual void OnAbilityRequestDone(const sptr &token, const AbilityState state) = 0; -}; - -} // namespace AppExecFwk -} // namespace OHOS -#endif // OHOS_APPEXECFWK_IAPP_STATE_CALLBACK_H +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IAPP_STATE_CALLBACK_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IAPP_STATE_CALLBACK_H + +#include "iremote_broker.h" +#include "iremote_object.h" + +#include "app_mgr_constants.h" +#include "app_process_data.h" + +namespace OHOS { +namespace AppExecFwk { + +class IAppStateCallback : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.AppStateCallback"); + + /** + * Application state changed callback. + * + * @param appProcessData Process data + */ + virtual void OnAppStateChanged(const AppProcessData &appProcessData) = 0; + + /** + * AbilityMgr's request is done. + * + * @param token Ability token. + * @param state Application state. + */ + virtual void OnAbilityRequestDone(const sptr &token, const AbilityState state) = 0; + + enum class Message { + TRANSACT_ON_APP_STATE_CHANGED = 0, + TRANSACT_ON_ABILITY_REQUEST_DONE, + }; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IAPP_STATE_CALLBACK_H diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_installer_interface.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_installer_interface.h new file mode 100644 index 00000000000..4746db4dd98 --- /dev/null +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_installer_interface.h @@ -0,0 +1,70 @@ +/* + * 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_APPEXECFWK_CORE_INCLUDE_BUNDLEMGR_BUNDLE_INSTALLER_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_BUNDLEMGR_BUNDLE_INSTALLER_INTERFACE_H + +#include "status_receiver_interface.h" +#include "install_param.h" + +namespace OHOS { +namespace AppExecFwk { + +class IBundleInstaller : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.BundleInstaller"); + /** + * @brief Installs an application, the final result will be notified from the statusReceiver object. + * @attention Notice that the bundleFilePath should be an absolute path. + * @param bundleFilePath Indicates the path for storing the ohos Ability Package (HAP) of the application + * to install or update. + * @param installParam Indicates the install parameters. + * @param statusReceiver Indicates the callback object that using for notifing the install result. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool Install(const std::string &bundleFilePath, const InstallParam &installParam, + const sptr &statusReceiver) = 0; + + /** + * @brief Uninstalls an application, the result will be notified from the statusReceiver object. + * @param bundleName Indicates the bundle name of the application to uninstall. + * @param installParam Indicates the uninstall parameters. + * @param statusReceiver Indicates the callback object that using for notifing the uninstall result. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool Uninstall(const std::string &bundleName, const InstallParam &installParam, + const sptr &statusReceiver) = 0; + + /** + * @brief Uninstalls a module in an application, the result will be notified from the statusReceiver object. + * @param bundleName Indicates the bundle name of the module to uninstall. + * @param modulePackage Indicates the module package of the module to uninstall. + * @param installParam Indicates the uninstall parameters. + * @param statusReceiver Indicates the callback object that using for notifing the uninstall result. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool Uninstall(const std::string &bundleName, const std::string &modulePackage, + const InstallParam &installParam, const sptr &statusReceiver) = 0; + + enum class Message { + INSTALL, + UNINSTALL, + UNINSTALL_MODULE, + }; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_BUNDLEMGR_BUNDLE_INSTALLER_INTERFACE_H \ No newline at end of file diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h index ea605bf59ab..7d5c9febf86 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h @@ -13,292 +13,213 @@ * limitations under the License. */ -#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_BUNDLEMGR_BUNDLE_MGR_INTERFACE_H -#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_BUNDLEMGR_BUNDLE_MGR_INTERFACE_H +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_BUNDLEMGR_INCLUDE_MOCK_BUNDLE_MGR_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_BUNDLEMGR_INCLUDE_MOCK_BUNDLE_MGR_INTERFACE_H #include "ability_info.h" #include "application_info.h" +#include "iremote_broker.h" +#include "iremote_object.h" + #include "bundle_info.h" #include "hap_module_info.h" -#include "permission_def.h" -#include "bundle_installer_interface.h" -#include "bundle_status_callback_interface.h" -#include "clean_cache_callback_interface.h" #include "ohos/aafwk/content/want.h" +#include "permission_def.h" +#include "module_usage_record.h" + +using OHOS::AAFwk::Want; namespace OHOS { namespace AppExecFwk { - enum class DumpFlag { - DUMP_BUNDLE_LIST = 1, // corresponse to option "-bundle-list" - DUMP_ALL_BUNDLE_INFO, // corresponse to option "-bundle" - DUMP_BUNDLE_INFO, // corresponse to option "-bundle [name]" + DUMP_BUNDLE_LIST = 1, + DUMP_ALL_BUNDLE_INFO, + DUMP_BUNDLE_INFO, }; -class IBundleMgr : public IRemoteBroker { +enum class InstallFlag { + NORMAL = 0, + // Allow to replace the existing bundle when the new version isn't lower than the old one. + // If the bundle does not exist, just like normal flag. + REPLACE_EXISTING = 1, +}; + +enum class InstallLocation { + INTERNAL_ONLY = 1, + PREFER_EXTERNAL = 2, +}; + +struct InstallParam : public Parcelable { + InstallFlag installFlag = InstallFlag::NORMAL; + InstallLocation installLocation = InstallLocation::INTERNAL_ONLY; + int userId = -1; + // Is keep user data while uninstall. + bool isKeepData = false; + bool noCheckSignature = false; + + // the parcel object function is not const. + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static InstallParam *Unmarshalling(Parcel &parcel); +}; +class IBundleStatusCallback : public IRemoteBroker { public: - DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.BundleMgr"); + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.BundleStatusCallback"); - using Want = OHOS::AAFwk::Want; + virtual void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, + const std::string &bundleName) = 0; + + enum class Message { + ON_BUNDLE_STATE_CHANGED, + }; +}; + +class ICleanCacheCallback : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.CleanCacheCallback"); + + virtual void OnCleanCacheFinished(bool succeeded) = 0; + + enum class Message { + ON_CLEAN_CACHE_CALLBACK, + }; +}; + +class OnPermissionChangedCallback : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.OnPermissionChangedCallback"); /** - * @brief Obtains the ApplicationInfo based on a given bundle name. - * @param appName Indicates the application bundle name to be queried. - * @param flag Indicates the flag used to specify information contained - * in the ApplicationInfo object that will be returned. - * @param userId Indicates the user ID. - * @param appInfo Indicates the obtained ApplicationInfo object. - * @return Returns true if the application is successfully obtained; returns false otherwise. + * @brief Called when an application's permission changed. + * @param uid Indicates the uid of the application which permission changed. */ + virtual void OnChanged(const int32_t uid) = 0; + + enum class Message { + ON_CHANGED, + }; +}; + +class IStatusReceiver : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.StatusReceiver"); + + virtual void OnStatusNotify(const int progress) = 0; + virtual void OnFinished(const int32_t resultCode, const std::string &resultMsg) = 0; + + enum class Message { + ON_STATUS_NOTIFY, + ON_FINISHED, + }; + + enum { + SUCCESS = 0, + ERR_INSTALL_INTERNAL_ERROR, + ERR_INSTALL_PARSE_FAILED, + ERR_INSTALL_VERSION_DOWNGRADE, + ERR_INSTALL_VERIFICATION_FAILED, + ERR_INSTALL_NO_SIGNATURE_INFO, + ERR_INSTALL_UPDATE_INCOMPATIBLE, + ERR_INSTALL_INVALID_BUNDLE_FILE, + ERR_INSTALL_MISSING_INSTALLED_BUNDLE, + ERR_INSTALL_ALREADY_EXIST, + ERR_INSTALL_PARSE_UNEXPECTED, + ERR_INSTALL_PARSE_MISSING_BUNDLE, + ERR_INSTALL_PARSE_MISSING_ABILITY, + ERR_INSTALL_PARSE_NO_PROFILE, + ERR_INSTALL_PARSE_BAD_PROFILE, + ERR_INSTALL_PARSE_PROFILE_PROP_TYPE_ERROR, + ERR_INSTALL_PARSE_PROFILE_MISSING_PROP, + ERR_UNINSTALL_INVALID_NAME, + ERR_UNKNOW, + }; +}; + +class IBundleInstaller : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.BundleInstaller"); + + virtual bool Install(const std::string &bundleFilePath, const InstallParam &installParam, + const sptr &statusReceiver) = 0; + virtual bool Uninstall(const std::string &bundleName, const InstallParam &installParam, + const sptr &statusReceiver) = 0; + + enum class Message { + INSTALL, + UNINSTALL, + }; +}; + +class IBundleMgr : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.aafwk.BundleMgr"); virtual bool GetApplicationInfo( const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) = 0; - /** - * @brief Obtains information about all installed applications of a specified user. - * @param flag Indicates the flag used to specify information contained - * in the ApplicationInfo objects that will be returned. - * @param userId Indicates the user ID. - * @param appInfos Indicates all of the obtained ApplicationInfo objects. - * @return Returns true if the application is successfully obtained; returns false otherwise. - */ virtual bool GetApplicationInfos( const ApplicationFlag flag, const int userId, std::vector &appInfos) = 0; - /** - * @brief Obtains the BundleInfo based on a given bundle name. - * @param bundleName Indicates the application bundle name to be queried. - * @param flag Indicates the information contained in the BundleInfo object to be returned. - * @param bundleInfo Indicates the obtained BundleInfo object. - * @return Returns true if the BundleInfo is successfully obtained; returns false otherwise. - */ virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) = 0; - /** - * @brief Obtains BundleInfo of all bundles available in the system. - * @param flag Indicates the flag used to specify information contained in the BundleInfo that will be returned. - * @param bundleInfos Indicates all of the obtained BundleInfo objects. - * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. - */ virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) = 0; - /** - * @brief Obtains the application UID based on the given bundle name and user ID. - * @param bundleName Indicates the bundle name of the application. - * @param userId Indicates the user ID. - * @return Returns the uid if successfully obtained; returns -1 otherwise. - */ virtual int GetUidByBundleName(const std::string &bundleName, const int userId) = 0; - /** - * @brief Obtains the bundle name of a specified application based on the given UID. - * @param uid Indicates the uid. - * @param bundleName Indicates the obtained bundle name. - * @return Returns true if the bundle name is successfully obtained; returns false otherwise. - */ + virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) = 0; virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) = 0; - /** - * @brief Obtains an array of all group IDs associated with a specified bundle. - * @param bundleName Indicates the bundle name. - * @param gids Indicates the group IDs associated with the specified bundle. - * @return Returns true if the gids is successfully obtained; returns false otherwise. - */ + virtual bool GetBundlesForUid(const int uid, std::vector &bundleNames) = 0; + virtual bool GetNameForUid(const int uid, std::string &name) = 0; virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) = 0; - /** - * @brief Obtains the type of a specified application based on the given bundle name. - * @param bundleName Indicates the bundle name. - * @return Returns "system" if the bundle is a system application; returns "third-party" otherwise. - */ virtual std::string GetAppType(const std::string &bundleName) = 0; - /** - * @brief Check whether the app is system app by it's UID. - * @param uid Indicates the uid. - * @return Returns true if the bundle is a system application; returns false otherwise. - */ virtual bool CheckIsSystemAppByUid(const int uid) = 0; - /** - * @brief Obtains the BundleInfo of application bundles based on the specified metaData. - * @param metaData Indicates the metadata to get in the bundle. - * @param bundleInfos Indicates all of the obtained BundleInfo objects. - * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. - */ virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) = 0; - /** - * @brief Query the AbilityInfo by the given Want. - * @param want Indicates the information of the ability. - * @param abilityInfo Indicates the obtained AbilityInfo object. - * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. - */ virtual bool QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) = 0; - /** - * @brief Query the AbilityInfo by ability.uri in config.json. - * @param abilityUri Indicates the uri of the ability. - * @param abilityInfo Indicates the obtained AbilityInfo object. - * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. - */ + virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) = 0; virtual bool QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) = 0; - /** - * @brief Obtains the BundleInfo of all keep-alive applications in the system. - * @param bundleInfos Indicates all of the obtained BundleInfo objects. - * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. - */ virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) = 0; - /** - * @brief Obtains the label of a specified ability. - * @param bundleName Indicates the bundle name. - * @param className Indicates the ability class name. - * @return Returns the label of the ability if exist; returns empty string otherwise. - */ virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) = 0; - /** - * @brief Obtains information about an application bundle contained in a ohos Ability Package (HAP). - * @param hapFilePath Indicates the absolute file path of the HAP. - * @param flag Indicates the information contained in the BundleInfo object to be returned. - * @param bundleInfo Indicates the obtained BundleInfo object. - * @return Returns true if the BundleInfo is successfully obtained; returns false otherwise. - */ virtual bool GetBundleArchiveInfo( const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) = 0; - /** - * @brief Obtain the HAP module info of a specific ability. - * @param abilityInfo Indicates the ability. - * @param hapModuleInfo Indicates the obtained HapModuleInfo object. - * @return Returns true if the HapModuleInfo is successfully obtained; returns false otherwise. - */ virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) = 0; - /** - * @brief Obtains the Want for starting the main ability of an application based on the given bundle name. - * @param bundleName Indicates the bundle name. - * @param want Indicates the obtained launch Want object. - * @return Returns true if the launch Want object is successfully obtained; returns false otherwise. - */ virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) = 0; - /** - * @brief Checks whether the publickeys of two bundles are the same. - * @param firstBundleName Indicates the first bundle name. - * @param secondBundleName Indicates the second bundle name. - * @return Returns SIGNATURE_UNKNOWN_BUNDLE if at least one of the given bundles is not found; - * returns SIGNATURE_NOT_MATCHED if their publickeys are different; - * returns SIGNATURE_MATCHED if their publickeys are the same. - */ virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) = 0; - /** - * @brief Checks whether a specified bundle has been granted a specific permission. - * @param bundleName Indicates the name of the bundle to check. - * @param permission Indicates the permission to check. - * @return Returns 0 if the bundle has the permission; returns -1 otherwise. - */ virtual int CheckPermission(const std::string &bundleName, const std::string &permission) = 0; - /** - * @brief Obtains detailed information about a specified permission. - * @param permissionName Indicates the name of the ohos permission. - * @param permissionDef Indicates the object containing detailed information about the given ohos permission. - * @return Returns true if the PermissionDef object is successfully obtained; returns false otherwise. - */ virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) = 0; - /** - * @brief Obtains all known permission groups in the system. - * @param permissionDefs Indicates the list of objects containing the permission group information. - * @return Returns true if the PermissionDef objects is successfully obtained; returns false otherwise. - */ virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) = 0; - /** - * @brief Obtains all known permission groups in the system. - * @param permissions Indicates the permission array. - * @param appNames Indicates the list of application names that have the specified permissions. - * @return Returns true if the application names is successfully obtained; returns false otherwise. - */ virtual bool GetAppsGrantedPermissions( const std::vector &permissions, std::vector &appNames) = 0; - /** - * @brief Checks whether the system has a specified capability. - * @param capName Indicates the name of the system feature to check. - * @return Returns true if the given feature specified by name is available in the system; returns false otherwise. - */ virtual bool HasSystemCapability(const std::string &capName) = 0; - /** - * @brief Obtains the capabilities that are available in the system. - * @param systemCaps Indicates the list of capabilities available in the system. - * @return Returns true if capabilities in the system are successfully obtained; returns false otherwise. - */ virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) = 0; - /** - * @brief Checks whether the current device has been started in safe mode. - * @return Returns true if the device is in safe mode; returns false otherwise. - */ virtual bool IsSafeMode() = 0; - /** - * @brief Clears cache data of a specified application. - * @param bundleName Indicates the bundle name of the application whose cache data is to be cleared. - * @param cleanCacheCallback Indicates the callback to be invoked for returning the operation result. - * @return Returns true if this function is successfully called; returns false otherwise. - */ virtual bool CleanBundleCacheFiles( const std::string &bundleName, const sptr &cleanCacheCallback) = 0; - /** - * @brief Clears application running data of a specified application. - * @param bundleName Indicates the bundle name of the application whose data is to be cleared. - * @return Returns true if the data cleared successfully; returns false otherwise. - */ virtual bool CleanBundleDataFiles(const std::string &bundleName) = 0; - /** - * @brief Register the specific bundle status callback. - * @param bundleStatusCallback Indicates the callback to be invoked for returning the bundle status changed result. - * @return Returns true if this function is successfully called; returns false otherwise. - */ virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) = 0; - /** - * @brief Clear the specific bundle status callback. - * @param bundleStatusCallback Indicates the callback to be cleared. - * @return Returns true if this function is successfully called; returns false otherwise. - */ virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) = 0; - /** - * @brief Unregister all the callbacks of status changed. - * @return Returns true if this function is successfully called; returns false otherwise. - */ virtual bool UnregisterBundleStatusCallback() = 0; - /** - * @brief Dump the bundle informations with specific flags. - * @param flag Indicates the information contained in the dump result. - * @param bundleName Indicates the bundle name if needed. - * @param result Indicates the dump information result. - * @return Returns true if the dump result is successfully obtained; returns false otherwise. - */ virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) = 0; - /** - * @brief Checks whether a specified application is enabled. - * @param bundleName Indicates the bundle name of the application. - * @return Returns true if the application is enabled; returns false otherwise. - */ virtual bool IsApplicationEnabled(const std::string &bundleName) = 0; - /** - * @brief Sets whether to enable a specified application. - * @param bundleName Indicates the bundle name of the application. - * @param isEnable Specifies whether to enable the application. - * The value true means to enable it, and the value false means to disable it. - * @return Returns true if the application is enabled; returns false otherwise. - */ virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) = 0; - /** - * @brief Obtains the interface used to install and uninstall bundles. - * @return Returns a pointer to IBundleInstaller class if exist; returns nullptr otherwise. - */ - virtual sptr GetBundleInstaller() = 0; - - /** - * @brief Requests a certain permission from user. - * @param bundleName Indicates the name of the bundle to request permission. - * @param permission Indicates the permission to request permission. - * @param userId Indicates the user id. - * @return Returns true if the permission request successfully; returns false otherwise. - */ + virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) = 0; + virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) = 0; + virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) = 0; + virtual bool CanRequestPermission( + const std::string &bundleName, const std::string &permissionName, const int userId) = 0; virtual bool RequestPermissionFromUser( - const std::string &bundleName, const std::string &permission, const int userId) - { - return true; - } - + const std::string &bundleName, const std::string &permission, const int userId) = 0; + virtual bool RegisterAllPermissionsChanged(const sptr &callback) = 0; + virtual bool RegisterPermissionsChanged( + const std::vector &uids, const sptr &callback) = 0; + virtual bool UnregisterPermissionsChanged(const sptr &callback) = 0; + virtual sptr GetBundleInstaller() = 0; + virtual bool GetModuleUsageRecords( + const int32_t number, std::vector &moduleUsageRecords) = 0; + virtual bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) = 0; enum class Message { GET_APPLICATION_INFO, GET_APPLICATION_INFOS, GET_BUNDLE_INFO, GET_BUNDLE_INFOS, GET_UID_BY_BUNDLE_NAME, + GET_APPID_BY_BUNDLE_NAME, GET_BUNDLE_NAME_FOR_UID, + GET_BUNDLES_FOR_UID, + GET_NAME_FOR_UID, GET_BUNDLE_GIDS, GET_APP_TYPE, CHECK_IS_SYSTEM_APP_BY_UID, @@ -326,10 +247,17 @@ public: DUMP_INFOS, IS_APPLICATION_ENABLED, SET_APPLICATION_ENABLED, + IS_ABILITY_ENABLED, + SET_ABILITY_ENABLED, + GET_ABILITY_ICON, + CAN_REQUEST_PERMISSION, + REQUEST_PERMISSION_FROM_USER, + REGISTER_ALL_PERMISSIONS_CHANGED, + REGISTER_PERMISSIONS_CHANGED, + UNREGISTER_PERMISSIONS_CHANGED, GET_BUNDLE_INSTALLER, }; }; - } // namespace AppExecFwk } // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_BUNDLEMGR_BUNDLE_MGR_INTERFACE_H +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_BUNDLEMGR_INCLUDE_MOCK_BUNDLE_MGR_INTERFACE_H \ No newline at end of file diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_status_callback_interface.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_status_callback_interface.h new file mode 100644 index 00000000000..7764cff7cbb --- /dev/null +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_status_callback_interface.h @@ -0,0 +1,66 @@ +/* + * 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_APPEXECFWK_CORE_INCLUDE_BUNDLE_STATUS_CALLBACK_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_BUNDLE_STATUS_CALLBACK_INTERFACE_H + +#include "iremote_broker.h" + +namespace OHOS { +namespace AppExecFwk { + +const std::string INSTALL_SUCCESS = "install success !"; +const std::string UNINSTALL_SUCCESS = "uninstall success !"; + +enum class InstallType { INSTALL_CALLBACK, UNINSTALL_CALLBACK }; + +class IBundleStatusCallback : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.BundleStatusCallback"); + /** + * @brief Called when the installation, update, or uninstallation state of an application changes. + * @param installType Indicates the installation, update, or uninstallation state. + * The value 0 indicates that the application is being installed or updated, + * and 1 indicates that the application is being uninstalled. + * @param resultCode Indicates the status code returned for the application installation, update, or uninstallation + * result. + * @param resultMessage Indicates the result message returned with the status code. + * @param bundleName Indicates the name of the bundle whose state has changed. + */ + virtual void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, + const std::string &bundleName) = 0; + + enum class Message { + ON_BUNDLE_STATE_CHANGED, + }; + + std::string GetBundleName() + { + return bundleName_; + } + + void SetBundleName(const std::string &bundleName) + { + bundleName_ = bundleName; + } + +private: + std::string bundleName_; +}; + +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_BUNDLE_STATUS_CALLBACK_INTERFACE_H diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h index b3072522690..cb76985ea02 100755 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h @@ -24,6 +24,8 @@ #include "ohos/aafwk/content/want.h" #include "iremote_proxy.h" #include "iremote_stub.h" +#include "shortcut_info.h" +#include "form_info.h" namespace OHOS { namespace AppExecFwk { @@ -122,60 +124,6 @@ auto HiDataInfo = [](std::string bundleName, AbilityInfo &abilityInfo, ElementNa }; } // namespace -class BundleMgrProxy : public IRemoteProxy { -public: - explicit BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) - {} - virtual ~BundleMgrProxy() - {} - int QueryWantAbility(const AAFwk::Want &want, std::vector &abilityInfos); - - bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override; - - bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override; - - bool GetApplicationInfo( - const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; - - bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override; - - MOCK_METHOD3(GetApplicationInfos, - bool(const ApplicationFlag flag, const int userId, std::vector &appInfos)); - - MOCK_METHOD2(GetBundleInfos, bool(const BundleFlag flag, std::vector &bundleInfos)); - MOCK_METHOD2(GetUidByBundleName, int(const std::string &bundleName, const int userId)); - MOCK_METHOD2(GetBundleNameForUid, bool(const int uid, std::string &bundleName)); - MOCK_METHOD2(GetBundleGids, bool(const std::string &bundleName, std::vector &gids)); - MOCK_METHOD1(GetAppType, std::string(const std::string &bundleName)); - MOCK_METHOD1(CheckIsSystemAppByUid, bool(const int uid)); - MOCK_METHOD2(GetBundleInfosByMetaData, bool(const std::string &metaData, std::vector &bundleInfos)); - MOCK_METHOD1(QueryKeepAliveBundleInfos, bool(std::vector &bundleInfos)); - MOCK_METHOD2(GetAbilityLabel, std::string(const std::string &bundleName, const std::string &className)); - MOCK_METHOD3( - GetBundleArchiveInfo, bool(const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo)); - MOCK_METHOD2(GetHapModuleInfo, bool(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo)); - MOCK_METHOD2(GetLaunchWantForBundle, bool(const std::string &bundleName, Want &want)); - MOCK_METHOD2(CheckPublicKeys, int(const std::string &firstBundleName, const std::string &secondBundleName)); - MOCK_METHOD2(CheckPermission, int(const std::string &bundleName, const std::string &permission)); - MOCK_METHOD2(GetPermissionDef, bool(const std::string &permissionName, PermissionDef &permissionDef)); - MOCK_METHOD1(GetAllPermissionGroupDefs, bool(std::vector &permissionDefs)); - MOCK_METHOD2(GetAppsGrantedPermissions, - bool(const std::vector &permissions, std::vector &appNames)); - 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_METHOD1(CleanBundleDataFiles, bool(const std::string &bundleName)); - MOCK_METHOD3(RequestPermissionFromUser, bool(const std::string &bundleName, const std::string &permission, const int userId)); - MOCK_METHOD1(RegisterBundleStatusCallback, bool(const sptr &bundleStatusCallback)); - MOCK_METHOD1(ClearBundleStatusCallback, bool(const sptr &bundleStatusCallback)); - MOCK_METHOD0(UnregisterBundleStatusCallback, bool()); - MOCK_METHOD3(DumpInfos, bool(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)); - MOCK_METHOD0(GetBundleInstaller, sptr()); -}; class BundleMgrStub : public IRemoteStub { public: @@ -186,11 +134,27 @@ public: class BundleMgrService : public BundleMgrStub { public: + BundleMgrService() + { + abilityInfoMap_.emplace(COM_IX_HIWORLD, HiWordInfo); + abilityInfoMap_.emplace(COM_IX_HIMUSIC, HiMusicInfo); + abilityInfoMap_.emplace(COM_IX_HIRADIO, HiRadioInfo); + abilityInfoMap_.emplace(COM_IX_HISERVICE, HiServiceInfo); + abilityInfoMap_.emplace(COM_IX_MUSICSERVICE, MusicServiceInfo); + abilityInfoMap_.emplace(COM_IX_HIDATA, HiDataInfo); + } + + virtual ~BundleMgrService() + {} bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override; bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override; bool GetApplicationInfo( const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; + bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override; + int GetUidByBundleName(const std::string &bundleName, const int userId) override; + bool CheckWantEntity(const AAFwk::Want &, AbilityInfo &); + MOCK_METHOD2(QueryWantAbility, int(const AAFwk::Want &want, std::vector &abilityInfos)); MOCK_METHOD3(GetApplicationInfos, bool(const ApplicationFlag flag, const int userId, std::vector &appInfos)); @@ -219,7 +183,8 @@ public: MOCK_METHOD2(CleanBundleCacheFiles, bool(const std::string &bundleName, const sptr &cleanCacheCallback)); MOCK_METHOD1(CleanBundleDataFiles, bool(const std::string &bundleName)); - MOCK_METHOD3(RequestPermissionFromUser, bool(const std::string &bundleName, const std::string &permission, const int userId)); + MOCK_METHOD3(RequestPermissionFromUser, + bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD1(RegisterBundleStatusCallback, bool(const sptr &bundleStatusCallback)); MOCK_METHOD1(ClearBundleStatusCallback, bool(const sptr &bundleStatusCallback)); MOCK_METHOD0(UnregisterBundleStatusCallback, bool()); @@ -227,23 +192,29 @@ public: MOCK_METHOD1(IsApplicationEnabled, bool(const std::string &bundleName)); MOCK_METHOD2(SetApplicationEnabled, bool(const std::string &bundleName, bool isEnable)); MOCK_METHOD0(GetBundleInstaller, sptr()); + MOCK_METHOD3(NotifyActivityLifeStatus, + bool(const std::string &bundleName, const std::string &abilityName, const int64_t launchTime)); - bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override; - int GetUidByBundleName(const std::string &bundleName, const int userId) override; - BundleMgrService() - { - abilityInfoMap_.emplace(COM_IX_HIWORLD, HiWordInfo); - abilityInfoMap_.emplace(COM_IX_HIMUSIC, HiMusicInfo); - abilityInfoMap_.emplace(COM_IX_HIRADIO, HiRadioInfo); - abilityInfoMap_.emplace(COM_IX_HISERVICE, HiServiceInfo); - abilityInfoMap_.emplace(COM_IX_MUSICSERVICE, MusicServiceInfo); - abilityInfoMap_.emplace(COM_IX_HIDATA, HiDataInfo); - } - - virtual ~BundleMgrService() - {} + MOCK_METHOD2(GetAppIdByBundleName, std::string(const std::string &bundleName, const int userId)); + MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &bundleNames)); + MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); + MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &abilityInfo)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &abilityInfo, bool isEnabled)); + MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); + MOCK_METHOD2(GetShortcutInfos, bool(const std::string &bundleName, std::vector &shortcutInfos)); - bool CheckWantEntity(const AAFwk::Want &, AbilityInfo &); + MOCK_METHOD3( + CanRequestPermission, bool(const std::string &bundleName, const std::string &permissionName, const int userId)); + MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); + MOCK_METHOD2(RegisterPermissionsChanged, + bool(const std::vector &uids, const sptr &callback)); + MOCK_METHOD1(GetAllFormsInfo, bool(std::vector &formInfos)); + MOCK_METHOD2(GetFormsInfoByApp, bool(const std::string &bundleName, std::vector &formInfos)); + MOCK_METHOD3(GetFormsInfoByModule, + bool(const std::string &bundleName, const std::string &moduleName, std::vector &formInfos)); + MOCK_METHOD1(UnregisterPermissionsChanged, bool(const sptr &callback)); + MOCK_METHOD2(QueryAbilityInfos, bool(const Want &want, std::vector &abilityInfos)); + MOCK_METHOD2(GetModuleUsageRecords, bool(const int32_t number, std::vector &moduleUsageRecords)); public: using QueryAbilityInfoFunType = diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_constants.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/on_permission_changed_callback_interface.h similarity index 48% rename from services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_constants.h rename to services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/on_permission_changed_callback_interface.h index b59daa2250a..a342dbd002a 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_constants.h +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/on_permission_changed_callback_interface.h @@ -1,47 +1,41 @@ -/* - * 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_APPEXECFWK_INCLUDE_APP_MGR_DEF_H -#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_INCLUDE_APP_MGR_DEF_H - -namespace OHOS { -namespace AppExecFwk { - -enum class ApplicationState { - APP_STATE_BEGIN = 0, - APP_STATE_CREATE = APP_STATE_BEGIN, - APP_STATE_READY, - APP_STATE_FOREGROUND, - APP_STATE_BACKGROUND, - APP_STATE_SUSPENDED, - APP_STATE_TERMINATED, - APP_STATE_END, -}; - -enum class AbilityState { - ABILITY_STATE_BEGIN = 0, - ABILITY_STATE_CREATE = ABILITY_STATE_BEGIN, - ABILITY_STATE_READY, - ABILITY_STATE_FOREGROUND, - ABILITY_STATE_BACKGROUND, - ABILITY_STATE_TERMINATED, - ABILITY_STATE_END, -}; - -enum class AppMgrResultCode { RESULT_OK = 0, ERROR_SERVICE_NOT_READY, ERROR_SERVICE_NOT_CONNECTED }; - -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_INCLUDE_APP_MGR_DEF_H +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_ON_PERMISSION_CHANGED_CALLBACK_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_ON_PERMISSION_CHANGED_CALLBACK_INTERFACE_H + +#include "iremote_broker.h" + +namespace OHOS { +namespace AppExecFwk { + +class OnPermissionChangedCallback : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.OnPermissionChangedCallback"); + /** + * @brief Called when an application's permission changed. + * @param uid Indicates the uid of the application which permission changed. + */ + virtual void OnChanged(const int32_t uid) = 0; + + enum class Message { + ON_CHANGED, + }; +}; + +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_ON_PERMISSION_CHANGED_CALLBACK_INTERFACE_H diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/status_receiver_interface.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/status_receiver_interface.h new file mode 100644 index 00000000000..c6e99e7abb0 --- /dev/null +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/status_receiver_interface.h @@ -0,0 +1,102 @@ +/* + * 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_APPEXECFWK_CORE_INCLUDE_BUNDLEMGR_STATUS_RECEIVER_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_BUNDLEMGR_STATUS_RECEIVER_INTERFACE_H + +#include "iremote_broker.h" + +namespace OHOS { +namespace AppExecFwk { + +class IStatusReceiver : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.StatusReceiver"); + + /** + * @brief Called when install status changed, with the percentage of installation progress + * @param progress Indicates the percentage of the installation progress. + */ + virtual void OnStatusNotify(const int progress) = 0; + /** + * @brief Called when an application is installed, updated, or uninstalled. + * @param resultCode Indicates the status code returned for the application installation, update, or uninstallation + * result. + * @param resultMsg Indicates the result message returned with the status code. + */ + virtual void OnFinished(const int32_t resultCode, const std::string &resultMsg) = 0; + + enum class Message { + ON_STATUS_NOTIFY, + ON_FINISHED, + }; + + enum { + SUCCESS = 0, + ERR_INSTALL_INTERNAL_ERROR, + ERR_INSTALL_HOST_INSTALLER_FAILED, + ERR_INSTALL_PARSE_FAILED, + ERR_INSTALL_VERSION_DOWNGRADE, + ERR_INSTALL_VERIFICATION_FAILED, + ERR_INSTALL_NO_SIGNATURE_INFO, + ERR_INSTALL_UPDATE_INCOMPATIBLE, + ERR_INSTALL_PARAM_ERROR, + ERR_INSTALL_PERMISSION_DENIED, + ERR_INSTALL_ENTRY_ALREADY_EXIST, + ERR_INSTALL_STATE_ERROR, + ERR_INSTALL_FILE_PATH_INVALID, + ERR_INSTALL_INVALID_HAP_NAME, + ERR_INSTALL_INVALID_BUNDLE_FILE, + ERR_INSTALL_INVALID_HAP_SIZE, + ERR_INSTALL_GENERATE_UID_ERROR, + ERR_INSTALL_INSTALLD_SERVICE_ERROR, + ERR_INSTALL_BUNDLE_MGR_SERVICE_ERROR, + ERR_INSTALL_ALREADY_EXIST, + + ERR_INSTALL_PARSE_UNEXPECTED, + ERR_INSTALL_PARSE_MISSING_BUNDLE, + ERR_INSTALL_PARSE_MISSING_ABILITY, + ERR_INSTALL_PARSE_NO_PROFILE, + ERR_INSTALL_PARSE_BAD_PROFILE, + ERR_INSTALL_PARSE_PROFILE_PROP_TYPE_ERROR, + ERR_INSTALL_PARSE_PROFILE_MISSING_PROP, + ERR_INSTALL_PARSE_PERMISSION_ERROR, + ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR, + + ERR_INSTALLD_PARAM_ERROR, + ERR_INSTALLD_GET_PROXY_ERROR, + ERR_INSTALLD_CREATE_DIR_FAILED, + ERR_INSTALLD_CREATE_DIR_EXIST, + ERR_INSTALLD_CHOWN_FAILED, + ERR_INSTALLD_REMOVE_DIR_FAILED, + ERR_INSTALLD_EXTRACT_FILES_FAILED, + ERR_INSTALLD_RNAME_DIR_FAILED, + ERR_INSTALLD_CLEAN_DIR_FAILED, + + ERR_UNINSTALL_SYSTEM_APP_ERROR, + ERR_UNINSTALL_KILLING_APP_ERROR, + ERR_UNINSTALL_INVALID_NAME, + ERR_UNINSTALL_PARAM_ERROR, + ERR_UNINSTALL_PERMISSION_DENIED, + ERR_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR, + ERR_UNINSTALL_MISSING_INSTALLED_BUNDLE, + ERR_UNINSTALL_MISSING_INSTALLED_MODULE, + ERR_UNKNOWN, + }; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_BUNDLEMGR_STATUS_RECEIVER_INTERFACE_H \ No newline at end of file diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp new file mode 100644 index 00000000000..39d6f63bf14 --- /dev/null +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_mgr_client.h" + +#include +#include +#include + +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" + +#include "app_mgr_interface.h" +#include "app_service_manager.h" + +namespace OHOS { +namespace AppExecFwk { + +AppMgrClient::AppMgrClient() +{} + +AppMgrClient::~AppMgrClient() +{} + +AppMgrResultCode AppMgrClient::LoadAbility(const sptr &token, const sptr &preToken, + const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo) +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode AppMgrClient::TerminateAbility(const sptr &token) +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode AppMgrClient::UpdateAbilityState(const sptr &token, const AbilityState state) +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode AppMgrClient::RegisterAppStateCallback(const sptr &callback) +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode AppMgrClient::Reset() +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode AppMgrClient::AbilityBehaviorAnalysis(const sptr &token, + const sptr &preToken, const int32_t visibility, const int32_t perceptibility, + const int32_t connectionState) +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode AppMgrClient::KillProcessByAbilityToken(const sptr &token) +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode AppMgrClient::KillApplication(const std::string &bundleName) +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode AppMgrClient::ClearUpApplicationData(const std::string &bundleName) +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode AppMgrClient::GetAllRunningProcesses(std::vector &info) +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode AppMgrClient::SetAppFreezingTime(int time) +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode AppMgrClient::GetAppFreezingTime(int &time) +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode AppMgrClient::ConnectAppMgrService() +{ + return AppMgrResultCode::RESULT_OK; +} + +// void AppMgrClient::SetServiceManager(std::unique_ptr serviceMgr) +// {} + +void AppMgrClient::AbilityAttachTimeOut(const sptr &token) +{} + +int AppMgrClient::CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) +{ + return AppMgrResultCode::RESULT_OK; +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_state_callback_host.cpp b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_state_callback_host.cpp new file mode 100644 index 00000000000..f79e2397e6a --- /dev/null +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_state_callback_host.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_state_callback_host.h" +#include "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "ipc_types.h" +#include "iremote_object.h" +#include "app_state_callback_proxy.h" + +namespace OHOS { +namespace AppExecFwk { + +AppStateCallbackHost::AppStateCallbackHost() +{} + +AppStateCallbackHost::~AppStateCallbackHost() +{} + +int AppStateCallbackHost::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + return 0; +} + +void AppStateCallbackHost::OnAbilityRequestDone(const sptr &, const AbilityState) +{ + APP_LOGD("OnAbilityRequestDone called"); +} + +void AppStateCallbackHost::OnAppStateChanged(const AppProcessData &) +{ + APP_LOGD("OnAppStateChanged called"); +} + +int32_t AppStateCallbackHost::HandleOnAppStateChanged(MessageParcel &data, MessageParcel &reply) +{ + return NO_ERROR; +} + +int32_t AppStateCallbackHost::HandleOnAbilityRequestDone(MessageParcel &data, MessageParcel &reply) +{ + return NO_ERROR; +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp new file mode 100644 index 00000000000..82033a61b96 --- /dev/null +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_state_callback_proxy.h" + +#include "ipc_types.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { + +AppStateCallbackProxy::AppStateCallbackProxy(const sptr &impl) : IRemoteProxy(impl) +{} + +bool AppStateCallbackProxy::WriteInterfaceToken(MessageParcel &data) +{ + return true; +} + +void AppStateCallbackProxy::OnAbilityRequestDone(const sptr &token, const AbilityState state) +{} + +void AppStateCallbackProxy::OnAppStateChanged(const AppProcessData &appProcessData) +{} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_manager.cpp b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_manager.cpp index b0713cca1a5..97ca0952abf 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_manager.cpp +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_manager.cpp @@ -1,125 +1,104 @@ -/* - * 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 "appmgr/app_mgr_client.h" -#include "ability_info.h" -#include "ability_manager_service.h" -#include "ability_scheduler.h" -#include "application_info.h" -#include "hilog_wrapper.h" - -using namespace OHOS::AAFwk; - -namespace OHOS { -namespace AppExecFwk { - -int AppMgrClient::loadAbilityCount = 0; -int AppMgrClient::terminateAbilityCount = 0; -int AppMgrClient::foregroundCount = 0; -int AppMgrClient::backgroundCount = 0; - -AppMgrResultCode AppMgrClient::LoadAbility(const sptr &__attribute__((unused)) token, - const sptr &__attribute__((unused)) preToken, const AbilityInfo &__attribute__((unused)) abilityInfo, - const ApplicationInfo &__attribute__((unused)) appInfo) -{ - HILOG_DEBUG("AppMgrProxy LoadAbility"); - loadAbilityCount++; - return AppMgrResultCode::RESULT_OK; -} - -AppMgrResultCode AppMgrClient::TerminateAbility(const sptr &__attribute__((unused)) token) -{ - HILOG_DEBUG("AppMgrProxy TerminateAbility"); - terminateAbilityCount++; - return AppMgrResultCode::RESULT_OK; -} - -AppMgrResultCode AppMgrClient::UpdateAbilityState(const sptr &token, const AbilityState state) -{ - switch (state) { - case AppExecFwk::AbilityState::ABILITY_STATE_FOREGROUND: { - foregroundCount++; - if (callback_ != nullptr) { - callback_->OnAbilityRequestDone(token, state); - } - break; - } - case AppExecFwk::AbilityState::ABILITY_STATE_BACKGROUND: { - HILOG_DEBUG("AppMgrProxy update ability state to background"); - backgroundCount++; - if (callback_ != nullptr) { - callback_->OnAbilityRequestDone(token, state); - } - break; - } - default: { - HILOG_DEBUG("AppMgrProxy default case!"); - break; - } - } - return AppMgrResultCode::RESULT_OK; -} - -AppMgrResultCode AppMgrClient::KillProcessByAbilityToken(const sptr &token) -{ - return AppMgrResultCode::RESULT_OK; -} - -AppMgrResultCode AppMgrClient::RegisterAppStateCallback(const sptr &callback) -{ - callback_ = callback; - return AppMgrResultCode::RESULT_OK; -} - -AppMgrResultCode AppMgrClient::ConnectAppMgrService() -{ - return AppMgrResultCode::RESULT_OK; -} - -AppMgrResultCode AppMgrClient::AbilityBehaviorAnalysis(const sptr &token, - const sptr &preToken, const int32_t visibility, const int32_t perceptibility, - const int32_t connectionState) -{ - return AppMgrResultCode::RESULT_OK; -} - -AppMgrResultCode AppMgrClient::KillApplication(const std::string &bundleName) -{ - return AppMgrResultCode::RESULT_OK; -} - -int AppMgrClient::MoveMissionToEnd(const sptr &token, const bool nonFirst) -{ - return 0; -} - -bool AppMgrClient::IsFirstInMission(const sptr &token) -{ - return true; -} - -int AppMgrClient::CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) -{ - return 0; -} - -void AppMgrClient::AbilityAttachTimeOut(const sptr &token) -{ - -} - - -} // namespace AppExecFwk -} // namespace OHOS +// /* +// * Copyright (c) 2021 Huawei Device Co., Ltd. +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ + +// #include "appmgr/app_mgr_client.h" +// #include "ability_info.h" +// #include "ability_manager_service.h" +// #include "ability_scheduler.h" +// #include "application_info.h" +// #include "hilog_wrapper.h" + +// using namespace OHOS::AAFwk; + +// namespace OHOS { +// namespace AppExecFwk { + +// AppMgrResultCode AppMgrClient::LoadAbility(const sptr &__attribute__((unused)) token, +// const sptr &__attribute__((unused)) preToken, const AbilityInfo &__attribute__((unused)) +// abilityInfo, const ApplicationInfo &__attribute__((unused)) appInfo) +// { +// HILOG_DEBUG("AppMgrProxy LoadAbility"); +// return AppMgrResultCode::RESULT_OK; +// } + +// AppMgrResultCode AppMgrClient::TerminateAbility(const sptr &__attribute__((unused)) token) +// { +// HILOG_DEBUG("AppMgrProxy TerminateAbility"); + +// return AppMgrResultCode::RESULT_OK; +// } + +// AppMgrResultCode AppMgrClient::UpdateAbilityState(const sptr &token, const AbilityState state) +// { +// switch (state) { +// case AppExecFwk::AbilityState::ABILITY_STATE_FOREGROUND: { + +// if (callback_ != nullptr) { +// callback_->OnAbilityRequestDone(token, state); +// } +// break; +// } +// case AppExecFwk::AbilityState::ABILITY_STATE_BACKGROUND: { +// if (callback_ != nullptr) { +// callback_->OnAbilityRequestDone(token, state); +// } +// break; +// } +// default: { +// HILOG_DEBUG("AppMgrProxy default case!"); +// break; +// } +// } +// return AppMgrResultCode::RESULT_OK; +// } + +// AppMgrResultCode AppMgrClient::KillProcessByAbilityToken(const sptr &token) +// { +// return AppMgrResultCode::RESULT_OK; +// } + +// AppMgrResultCode AppMgrClient::RegisterAppStateCallback(const sptr &callback) +// { +// callback_ = callback; +// return AppMgrResultCode::RESULT_OK; +// } + +// AppMgrResultCode AppMgrClient::ConnectAppMgrService() +// { +// return AppMgrResultCode::RESULT_OK; +// } + +// AppMgrResultCode AppMgrClient::AbilityBehaviorAnalysis(const sptr &token, +// const sptr &preToken, const int32_t visibility, const int32_t perceptibility, +// const int32_t connectionState) +// { +// return AppMgrResultCode::RESULT_OK; +// } + +// AppMgrResultCode AppMgrClient::KillApplication(const std::string &bundleName) +// { +// return AppMgrResultCode::RESULT_OK; +// } + +// int AppMgrClient::CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) +// { +// return 0; +// } + +// void AppMgrClient::AbilityAttachTimeOut(const sptr &token) +// {} + +// } // namespace AppExecFwk +// } // namespace OHOS diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp index de3fb0972c8..43e83528e99 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp @@ -18,53 +18,12 @@ #include "application_info.h" #include "hilog_wrapper.h" #include "ability_config.h" + using namespace OHOS::AAFwk; namespace OHOS { namespace AppExecFwk { -int BundleMgrProxy::QueryWantAbility( - const AAFwk::Want &__attribute__((unused)) want, std::vector &__attribute__((unused)) abilityInfos) -{ - return 0; -} - -bool BundleMgrProxy::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) -{ - ElementName eleName = want.GetElement(); - if (eleName.GetBundleName().empty()) { - return false; - } - abilityInfo.name = eleName.GetAbilityName(); - abilityInfo.bundleName = eleName.GetBundleName(); - abilityInfo.applicationName = eleName.GetAbilityName() + "App"; - if (abilityInfo.bundleName != "com.ix.hiworld") { - abilityInfo.applicationInfo.isLauncherApp = false; - } - return true; -} - -bool BundleMgrProxy::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) -{ - return true; -} - -bool BundleMgrProxy::QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) -{ - return false; -} - -bool BundleMgrProxy::GetApplicationInfo( - const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) -{ - if (appName.empty()) { - return false; - } - appInfo.name = "Helloworld"; - appInfo.bundleName = "com.ix.hiworld"; - return true; -} - int BundleMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { return 0; @@ -85,6 +44,7 @@ bool BundleMgrService::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &ab std::string abilityNameTemp = elementTemp.GetAbilityName(); std::string bundleNameTemp = elementTemp.GetBundleName(); abilityInfo.deviceId = elementTemp.GetDeviceID(); + abilityInfo.visible = true; if (bundleNameTemp.empty() || abilityNameTemp.empty()) { return false; diff --git a/services/abilitymgr/test/unittest/phone/ability_connect_callback_stub_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_connect_callback_stub_test/BUILD.gn index 24af704dff3..d55f49db800 100644 --- a/services/abilitymgr/test/unittest/phone/ability_connect_callback_stub_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_connect_callback_stub_test/BUILD.gn @@ -41,7 +41,8 @@ ohos_unittest("ability_connect_callback_stub_test") { "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + + # "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", diff --git a/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/BUILD.gn index 4ce83388b88..b384f08a9ea 100644 --- a/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/BUILD.gn @@ -23,7 +23,6 @@ ohos_unittest("ability_connect_manage_test") { "//foundation/aafwk/standard/frameworks/kits/ability/native/src/dummy_data_ability_predicates.cpp", "//foundation/aafwk/standard/frameworks/kits/ability/native/src/dummy_result_set.cpp", "//foundation/aafwk/standard/frameworks/kits/ability/native/src/dummy_values_bucket.cpp", - "//foundation/appexecfwk/standard/common/log/src/app_log_wrapper.cpp", "ability_connect_manage_test.cpp", ] diff --git a/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/ability_connect_manage_test.cpp b/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/ability_connect_manage_test.cpp index 8c0286a4df0..03785770e66 100644 --- a/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/ability_connect_manage_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/ability_connect_manage_test.cpp @@ -92,6 +92,7 @@ AbilityRequest AbilityConnectManagerTest::GenerateAbilityRequest(const std::stri want.SetElement(element); AbilityInfo abilityInfo; + abilityInfo.visible = true; abilityInfo.applicationName = appName; abilityInfo.type = AbilityType::SERVICE; abilityInfo.name = abilityName; @@ -638,7 +639,7 @@ HWTEST_F(AbilityConnectManagerTest, AAFWK_Connect_Service_017, TestSize.Level1) abilityRecord->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); ConnectManager()->ScheduleConnectAbilityDoneLocked(token, callback); auto abilityRecordB = Token::GetAbilityRecordByToken(token); - ASSERT_TRUE(abilityRecordB); + EXPECT_TRUE(abilityRecordB); auto connectRecordList = abilityRecordB->GetConnectRecordList(); int size = connectRecordList.size(); EXPECT_EQ(1, size); diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/BUILD.gn index 4ed7bd131f0..9a6f744cc71 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/BUILD.gn @@ -23,6 +23,7 @@ ohos_unittest("ability_manager_proxy_test") { "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/ability_scheduler_mock", + "//foundation/appexecfwk/standard/common/log/include", ] sources = [ "ability_manager_proxy_test.cpp" ] @@ -41,7 +42,8 @@ ohos_unittest("ability_manager_proxy_test") { "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + + # "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h index 8f32c4824f3..36a008e8432 100755 --- a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h @@ -78,6 +78,12 @@ public: return 0; } + int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) + { + return 0; + } + virtual int TerminateAbility(const sptr &token, int resultCode, const Want *resultWant = nullptr) { return 0; @@ -232,6 +238,51 @@ public: return 0; } + int UpdateConfiguration(const DummyConfiguration &config) + { + return 0; + } + + int MoveMissionToFloatingStack(const MissionOption &missionOption) + { + return 0; + } + + int MoveMissionToSplitScreenStack(const MissionOption &missionOption) + { + return 0; + } + + int ChangeFocusAbility(const sptr &lostFocusToken, const sptr &getFocusToken) + { + return 0; + } + + int MinimizeMultiWindow(int missionId) + { + return 0; + } + + int MaximizeMultiWindow(int missionId) + { + return 0; + } + + int GetFloatingMissions(std::vector &list) + { + return 0; + } + + int CloseMultiWindow(int missionId) + { + return 0; + } + + int SetMissionStackSetting(const StackSetting &stackSetting) + { + return 0; + } + MOCK_METHOD2(TerminateAbilityByCaller, int(const sptr &callerToken, int requestCode)); MOCK_METHOD3(StartAbility, int(const Want &want, const sptr &callerToken, int requestCode)); MOCK_METHOD2( diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn index 1955cb41650..37cc3bcbc9f 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn @@ -23,6 +23,7 @@ ohos_unittest("ability_manager_service_test") { "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr", ] sources = [ "ability_manager_service_test.cpp" ] diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp index 6fa4d797e27..f8ea5cb325e 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp @@ -22,6 +22,7 @@ #undef private #undef protected +#include "app_process_data.h" #include "system_ability_definition.h" #include "ability_manager_errors.h" #include "ability_scheduler.h" @@ -1207,7 +1208,7 @@ HWTEST_F(AbilityManagerServiceTest, AbilityManagerService_AcquireDataAbility_001 OHOS::Uri dataAbilityUri("dataability:///data.bundle.DataAbility"); // assert ability record - ASSERT_TRUE(abilityRecord_); + EXPECT_TRUE(abilityRecord_); EXPECT_EQ(abilityMs_->AcquireDataAbility(dataAbilityUri, true, abilityRecord_->GetToken()), nullptr); } @@ -1224,7 +1225,7 @@ HWTEST_F(AbilityManagerServiceTest, AbilityManagerService_AcquireDataAbility_002 { OHOS::Uri dataAbilityUri("dataability:///data.bundle.DataAbility"); // assert ability record - ASSERT_TRUE(abilityRecord_); + EXPECT_TRUE(abilityRecord_); EXPECT_EQ(abilityMs_->AcquireDataAbility(dataAbilityUri, true, abilityRecord_->GetToken()), nullptr); } @@ -1240,7 +1241,7 @@ HWTEST_F(AbilityManagerServiceTest, AbilityManagerService_AcquireDataAbility_003 { OHOS::Uri dataAbilityUri("mydataability:///data.bundle.DataAbility"); // assert ability record - ASSERT_TRUE(abilityRecord_); + EXPECT_TRUE(abilityRecord_); EXPECT_EQ(abilityMs_->AcquireDataAbility(dataAbilityUri, true, abilityRecord_->GetToken()), nullptr); } @@ -1306,7 +1307,7 @@ HWTEST_F(AbilityManagerServiceTest, AbilityManagerService_AcquireDataAbility_006 HWTEST_F(AbilityManagerServiceTest, AbilityManagerService_ReleaseDataAbility_001, TestSize.Level1) { // assert ability record - ASSERT_TRUE(abilityRecord_); + EXPECT_TRUE(abilityRecord_); EXPECT_EQ(abilityMs_->ReleaseDataAbility(nullptr, nullptr), OHOS::ERR_INVALID_STATE); } diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h index 45b2faae77b..66841eee2b0 100755 --- a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h @@ -64,6 +64,12 @@ public: return 0; } + int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode = DEFAULT_INVAL_VALUE) + { + return 0; + } + virtual int TerminateAbility(const sptr &token, int resultCode, const Want *resultWant = nullptr) { return 0; @@ -229,6 +235,51 @@ public: { return 0; } + + int UpdateConfiguration(const DummyConfiguration &config) + { + return 0; + } + + int MoveMissionToFloatingStack(const MissionOption &missionOption) + { + return 0; + } + + int MoveMissionToSplitScreenStack(const MissionOption &missionOption) + { + return 0; + } + + int ChangeFocusAbility(const sptr &lostFocusToken, const sptr &getFocusToken) + { + return 0; + } + + int MinimizeMultiWindow(int missionId) + { + return 0; + } + + int MaximizeMultiWindow(int missionId) + { + return 0; + } + + int GetFloatingMissions(std::vector &list) + { + return 0; + } + + int CloseMultiWindow(int missionId) + { + return 0; + } + + int SetMissionStackSetting(const StackSetting &stackSetting) + { + return 0; + } }; } // namespace AAFwk diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_manager_test/BUILD.gn index e8c21243aa3..eca87a6990e 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_manager_test/BUILD.gn @@ -9,7 +9,7 @@ # 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. +# limitations under the License. import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") @@ -59,8 +59,9 @@ ohos_unittest("ability_manager_test") { "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + + # "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + # "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h b/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h index cf48cd111a1..f73e93a1e10 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h @@ -68,7 +68,7 @@ public: MOCK_METHOD1(UnlockMission, int(int)); MOCK_METHOD2(SetMissionDescriptionInfo, int(const sptr &token, const MissionDescriptionInfo &info)); MOCK_METHOD0(GetMissionLockModeState, int()); - + MOCK_METHOD1(UpdateConfiguration, int(const DummyConfiguration &)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo &wantSenderInfo, const sptr &callerToken)); MOCK_METHOD2(SendWantSender, int(const sptr &target, const SenderInfo &senderInfo)); @@ -81,6 +81,18 @@ public: MOCK_METHOD2(RegisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(UnregisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); + + MOCK_METHOD4(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode)); + MOCK_METHOD1(MoveMissionToFloatingStack, int(const MissionOption &missionOption)); + MOCK_METHOD1(MoveMissionToSplitScreenStack, int(const MissionOption &missionOption)); + MOCK_METHOD2( + ChangeFocusAbility, int(const sptr &lostFocusToken, const sptr &getFocusToken)); + MOCK_METHOD1(MinimizeMultiWindow, int(int missionId)); + MOCK_METHOD1(GetFloatingMissions, int(std::vector &list)); + MOCK_METHOD1(CloseMultiWindow, int(int missionId)); + MOCK_METHOD1(SetMissionStackSetting, int(const StackSetting &stackSetting)); + MOCK_METHOD1(MaximizeMultiWindow, int(int missionId)); }; } // namespace AAFwk diff --git a/services/abilitymgr/test/unittest/phone/ability_record_test/ability_record_test.cpp b/services/abilitymgr/test/unittest/phone/ability_record_test/ability_record_test.cpp index f65fa26d4fc..ef30144ae59 100755 --- a/services/abilitymgr/test/unittest/phone/ability_record_test/ability_record_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_record_test/ability_record_test.cpp @@ -42,6 +42,7 @@ public: std::shared_ptr abilityRecord_; std::shared_ptr abilityResult_; std::shared_ptr abilityRequest_; + static constexpr unsigned int CHANGE_CONFIG_LOCALE = 0x00000001; }; void AbilityRecordTest::SetUpTestCase(void) @@ -686,5 +687,36 @@ HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_CreateByConnect, TestSize.Level1) abilityRecord_->SetCreateByConnectMode(); EXPECT_EQ(true, abilityRecord_->IsCreateByConnect()); } + +/* + * Feature: AbilityRecord + * Function: OnConfigurationChanged + * SubFunction: Configuration Changed + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify Configuration Changed UT + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_OnConfigurationChanged_001, TestSize.Level1) +{ + const DummyConfiguration config; + abilityRecord_->abilityInfo_.configChanges.push_back("locale"); + EXPECT_EQ(false, abilityRecord_->OnConfigurationChanged(config, CHANGE_CONFIG_LOCALE)); +} + +/* + * Feature: AbilityRecord + * Function: OnConfigurationChanged + * SubFunction: Configuration Changed + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify Configuration Changed UT + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_OnConfigurationChanged_002, TestSize.Level1) +{ + const DummyConfiguration config; + abilityRecord_->abilityInfo_.configChanges.push_back("local"); + EXPECT_EQ(true, abilityRecord_->OnConfigurationChanged(config, CHANGE_CONFIG_LOCALE)); +} + } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/BUILD.gn index fae66549cff..7923072dcbe 100644 --- a/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/BUILD.gn @@ -42,7 +42,8 @@ ohos_unittest("ability_scheduler_proxy_test") { "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + + # "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", diff --git a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h index d3e93a97f84..f33ecb0784a 100644 --- a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h @@ -41,6 +41,8 @@ public: {} virtual void ScheduleRestoreAbilityState(const PacMap &inState) override {} + virtual void ScheduleUpdateConfiguration(const DummyConfiguration &config) override + {} virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override { @@ -93,6 +95,24 @@ public: { return -1; } + + virtual Uri NormalizeUri(const Uri &uri) override + { + Uri urivalue(""); + return urivalue; + } + + virtual Uri DenormalizeUri(const Uri &uri) override + { + Uri urivalue(""); + return urivalue; + } + + void NotifyMultiWinModeChanged(int32_t winModeKey, bool flag) override + {} + + void NotifyTopActiveAbilityChanged(bool flag) override + {} }; } // namespace AAFwk diff --git a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/BUILD.gn index 84e9977b562..f5b95d3346c 100644 --- a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/BUILD.gn @@ -23,6 +23,7 @@ ohos_unittest("ability_stack_manager_test") { "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/ability_scheduler_mock", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr/", ] sources = [ "ability_stack_manager_test.cpp" ] diff --git a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp index af4e388acd5..158ec311a61 100644 --- a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp @@ -23,6 +23,7 @@ #undef private #undef protected +#include "app_process_data.h" #include "mock_bundle_manager.h" #include "sa_mgr_client.h" #include "system_ability_definition.h" @@ -35,6 +36,15 @@ using namespace testing::ext; using namespace OHOS::AppExecFwk; namespace OHOS { namespace AAFwk { + +namespace { +const std::string LANGUAGE = "locale"; +const std::string LAYOUT = "layout"; +const std::string FONTSIZE = "fontsize"; +const std::string ORIENTATION = "orientation"; +const std::string DENSITY = "density"; +} // namespace + class AbilityStackManagerTest : public testing::Test { public: static void SetUpTestCase(void); @@ -44,7 +54,7 @@ public: void init(); AbilityRequest GenerateAbilityRequest(const std::string &deviceName, const std::string &abilityName, - const std::string &appName, const std::string &bundleName); + const std::string &appName, const std::string &bundleName, const std::vector config); void makeScene(const std::string &abilityName, const std::string &bundleName, AbilityInfo &abilityInfo, Want &want); @@ -55,6 +65,9 @@ public: AbilityRequest musicSAbilityRequest_; AbilityRequest radioAbilityRequest_; AbilityRequest radioTopAbilityRequest_; + Want want_; + AbilityInfo abilityInfo_; + ApplicationInfo appInfo_; }; void AbilityStackManagerTest::SetUpTestCase(void) @@ -76,7 +89,7 @@ void AbilityStackManagerTest::SetUp() OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject); auto ams = DelayedSingleton::GetInstance(); - // stackManager_ = ams->GetStackManager(); + ams->Init(); stackManager_ = std::make_shared(0); auto bms = ams->GetBundleManager(); EXPECT_NE(bms, nullptr); @@ -84,17 +97,18 @@ void AbilityStackManagerTest::SetUp() void AbilityStackManagerTest::init() { - launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + std::vector config; + launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld", config); - musicAbilityRequest_ = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + musicAbilityRequest_ = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic", config); - musicTopAbilityRequest_ = GenerateAbilityRequest("device", "MusicTopAbility", "music", "com.ix.hiMusic"); + musicTopAbilityRequest_ = GenerateAbilityRequest("device", "MusicTopAbility", "music", "com.ix.hiMusic", config); - musicSAbilityRequest_ = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + musicSAbilityRequest_ = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic", config); - radioAbilityRequest_ = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + radioAbilityRequest_ = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio", config); - radioTopAbilityRequest_ = GenerateAbilityRequest("device", "RadioTopAbility", "radio", "com.ix.hiRadio"); + radioTopAbilityRequest_ = GenerateAbilityRequest("device", "RadioTopAbility", "radio", "com.ix.hiRadio", config); } void AbilityStackManagerTest::makeScene( @@ -139,7 +153,8 @@ void AbilityStackManagerTest::makeScene( } AbilityRequest AbilityStackManagerTest::GenerateAbilityRequest(const std::string &deviceName, - const std::string &abilityName, const std::string &appName, const std::string &bundleName) + const std::string &abilityName, const std::string &appName, const std::string &bundleName, + const std::vector config) { ElementName element(deviceName, abilityName, bundleName); Want want; @@ -147,12 +162,13 @@ AbilityRequest AbilityStackManagerTest::GenerateAbilityRequest(const std::string AbilityInfo abilityInfo; ApplicationInfo appinfo; - + abilityInfo.visible = true; abilityInfo.name = abilityName; abilityInfo.bundleName = bundleName; abilityInfo.applicationName = appName; abilityInfo.applicationInfo.bundleName = bundleName; abilityInfo.applicationInfo.name = appName; + abilityInfo.configChanges = config; makeScene(abilityName, bundleName, abilityInfo, want); @@ -350,7 +366,7 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_009, TestSize. EXPECT_EQ(0, missionStack->GetMissionStackId()); EXPECT_EQ(1, missionStack->GetMissionRecordCount()); auto missionRecord = missionStack->GetTopMissionRecord(); - ASSERT_TRUE(missionRecord != nullptr); + EXPECT_TRUE(missionRecord != nullptr); EXPECT_EQ(1, missionRecord->GetAbilityRecordCount()); auto topAbility = stackManager_->GetCurrentTopAbility(); auto realAppinfo = topAbility->GetApplicationInfo(); @@ -848,7 +864,8 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_022, TestSize. std::string abilityName = "otherAbility"; std::string appName = "otherApp"; std::string bundleName = "com.ix.other"; - auto abilityReq = GenerateAbilityRequest(deviceName, abilityName, appName, bundleName); + std::vector config; + auto abilityReq = GenerateAbilityRequest(deviceName, abilityName, appName, bundleName, config); auto record = AbilityRecord::CreateAbilityRecord(abilityReq); auto nullToken = new Token(record); EXPECT_NE(0, stackManager_->TerminateAbility(nullToken, -1, &want)); @@ -912,7 +929,8 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_024, TestSize. std::string abilityName = "otherAbility"; std::string appName = "otherApp"; std::string bundleName = "com.ix.other"; - auto abilityReq = GenerateAbilityRequest(deviceName, abilityName, appName, bundleName); + std::vector config; + auto abilityReq = GenerateAbilityRequest(deviceName, abilityName, appName, bundleName, config); auto record = AbilityRecord::CreateAbilityRecord(abilityReq); auto token = topAbility->GetToken(); stackManager_->GetTopMissionRecord()->RemoveTopAbilityRecord(); @@ -1010,7 +1028,7 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_028, TestSize. auto token = topAbility->GetToken(); OHOS::sptr scheduler = new AbilityScheduler(); - EXPECT_EQ(stackManager_->AttachAbilityThread(scheduler, token), ERR_INVALID_VALUE); + EXPECT_EQ(stackManager_->AttachAbilityThread(scheduler, token), ERR_OK); std::shared_ptr record = nullptr; auto nullToken = new Token(record); @@ -1662,7 +1680,7 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_048, TestSize. auto missionInfo2 = stackManager_->GetMissionRecordFromAllStacks(secondMissionId); EXPECT_EQ(missionInfo1->GetTopAbilityRecord()->GetAbilityState(), OHOS::AAFwk::MOVING_BACKGROUND); - auto recordVector = stackManager_->powerStorage_->GetPowerOffRecord(); + auto recordVector = stackManager_->powerStorage_->GetPowerOffInActiveRecord(); int size = recordVector.size(); EXPECT_EQ(size, 1); // Because we only focus on the top of the stack @@ -1736,7 +1754,7 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_049, TestSize. auto missionInfo3 = stackManager_->GetMissionRecordFromAllStacks(fourthMissionId); EXPECT_EQ(missionInfo1->GetTopAbilityRecord()->GetAbilityState(), OHOS::AAFwk::MOVING_BACKGROUND); - auto recordVector = stackManager_->powerStorage_->GetPowerOffRecord(); + auto recordVector = stackManager_->powerStorage_->GetPowerOffInActiveRecord(); int size = recordVector.size(); EXPECT_EQ(size, 2); @@ -1865,7 +1883,9 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_053, TestSize. topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); // 2 - auto musicAbilityRequest2th = GenerateAbilityRequest("device", "MusicAbility2th", "music", "com.ix.hiMusic"); + std::vector config; + auto musicAbilityRequest2th = + GenerateAbilityRequest("device", "MusicAbility2th", "music", "com.ix.hiMusic", config); result = stackManager_->StartAbility(musicAbilityRequest2th); EXPECT_EQ(0, result); auto musicMisionRecord2th = stackManager_->GetTopMissionRecord(); @@ -2133,12 +2153,1017 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_060, TestSize. /* * Feature: AbilityStackManager - * Function: SetMissionDescriptionInfo + * Function: StartAbility * SubFunction: NA - * FunctionPoints: SetMissionDescriptionInfo + * FunctionPoints: Start the floating window according to the parameters * EnvConditions: NA - * CaseDescription: when the uid defferent + * CaseDescription: Start a floating window application + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_061, TestSize.Level1) +{ + stackManager_->Init(); + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + + // defult mission id + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FULLSCREEN)); + EXPECT_TRUE(abilityStartSetting); + + musicAbilityRequest_.startSetting = abilityStartSetting; + auto result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto stact = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(stact); + EXPECT_EQ(stact->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + + // promary mission id + abilityStartSetting->AddProperty( + AbilityStartSetting::WINDOW_MODE_KEY, std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY)); + EXPECT_TRUE(abilityStartSetting); + + musicAbilityRequest_.startSetting = abilityStartSetting; + result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord2 = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord2 = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord2); + EXPECT_TRUE(topAbilityRecord2); + topAbilityRecord2->SetAbilityState(OHOS::AAFwk::ACTIVE); + + stact = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(stact); + EXPECT_EQ(stact->GetMissionStackId(), SPLIT_SCREEN_MISSION_STACK_ID); +} + +/* + * Feature: AbilityStackManager + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: Start the floating window according to the parameters + * EnvConditions: NA + * CaseDescription: a lunchr + Start a floating window application + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_062, TestSize.Level1) +{ + stackManager_->Init(); + + // start a luncher + auto result = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto stact = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(stact); + EXPECT_EQ(stact->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); + + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + + // Set floating window identification + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + EXPECT_TRUE(abilityStartSetting); + + musicAbilityRequest_.startSetting = abilityStartSetting; + result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord2 = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord2 = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord2); + EXPECT_TRUE(topAbilityRecord2); + topAbilityRecord2->SetAbilityState(OHOS::AAFwk::ACTIVE); + + stact = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(stact); + EXPECT_EQ(stact->GetMissionStackId(), FLOATING_MISSION_STACK_ID); +} + +/* + * Feature: AbilityStackManager + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: Start the floating window according to the parameters + * EnvConditions: NA + * CaseDescription: a defult ability + Start a floating window application + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_063, TestSize.Level1) +{ + stackManager_->Init(); + + // start a ability + auto result = stackManager_->StartAbility(radioAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto stact = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(stact); + EXPECT_EQ(stact->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + + // Set floating window identification + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + EXPECT_TRUE(abilityStartSetting); + + musicAbilityRequest_.startSetting = abilityStartSetting; + result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord2 = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord2 = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord2); + EXPECT_TRUE(topAbilityRecord2); + topAbilityRecord2->SetAbilityState(OHOS::AAFwk::ACTIVE); + + stact = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(stact); + EXPECT_EQ(stact->GetMissionStackId(), FLOATING_MISSION_STACK_ID); +} + +/* + * Feature: AbilityStackManager + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: Start the floating window according to the parameters + * EnvConditions: NA + * CaseDescription: When an application starts a floating window, it is put on the floating window stack + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_064, TestSize.Level1) +{ + stackManager_->Init(); + + auto result = stackManager_->StartAbility(radioAbilityRequest_); + EXPECT_EQ(0, result); + auto redioMissionRecord = stackManager_->GetTopMissionRecord(); + auto redioAbilityRecord = redioMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(redioMissionRecord); + EXPECT_TRUE(redioAbilityRecord); + redioAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + + // Set floating window identification + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + EXPECT_TRUE(abilityStartSetting); + + musicAbilityRequest_.startSetting = abilityStartSetting; + result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto stact = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(stact); + EXPECT_EQ(stact->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // radioAbility move to floating stack + EXPECT_EQ(redioMissionRecord->GetMissionStack()->GetMissionStackId(), FLOATING_MISSION_STACK_ID); +} + +/* + * Feature: AbilityStackManager + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: Start the floating window according to the parameters + * EnvConditions: NA + * CaseDescription: When an singlton application starts a floating window, it is ont put on the together */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_065, TestSize.Level1) +{ + stackManager_->Init(); + + // singlton ability + auto result = stackManager_->StartAbility(radioTopAbilityRequest_); + EXPECT_EQ(0, result); + auto redioMissionRecord = stackManager_->GetTopMissionRecord(); + auto redioAbilityRecord = redioMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(redioMissionRecord); + EXPECT_TRUE(redioAbilityRecord); + redioAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + + // Set floating window identification + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + EXPECT_TRUE(abilityStartSetting); + + musicAbilityRequest_.startSetting = abilityStartSetting; + result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto stact = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(stact); + EXPECT_EQ(stact->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // radioAbility in the defult stack + EXPECT_EQ(redioMissionRecord->GetMissionStack()->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); +} + +/* + * Feature: AbilityStackManager + * Function: MoveMissionToFloatingStack + * SubFunction: NA + * FunctionPoints: Move misson to floating window stack + * EnvConditions: NA + * CaseDescription: a ability move to floating window stack + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_066, TestSize.Level1) +{ + stackManager_->Init(); + + auto result = stackManager_->StartAbility(radioTopAbilityRequest_); + EXPECT_EQ(0, result); + auto redioMissionRecord = stackManager_->GetTopMissionRecord(); + auto redioAbilityRecord = redioMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(redioMissionRecord); + EXPECT_TRUE(redioAbilityRecord); + redioAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + MissionOption missionOption; + missionOption.missionId = -10; + + auto ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, ERR_INVALID_DATA); + + missionOption.missionId = 13; + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FULLSCREEN; + ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, ERR_INVALID_DATA); + + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY; + ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, ERR_INVALID_DATA); + + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY; + ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, ERR_INVALID_DATA); + + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; + ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, MOVE_MISSION_TO_STACK_NOT_EXIST_MISSION); +} + +/* + * Feature: AbilityStackManager + * Function: MoveMissionToFloatingStack + * SubFunction: NA + * FunctionPoints: Move misson to floating window stack + * EnvConditions: NA + * CaseDescription: a ability move to floating window stack + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_067, TestSize.Level1) +{ + stackManager_->Init(); + + auto result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto musicMissionRecord = stackManager_->GetTopMissionRecord(); + auto musicAbilityRecord = musicMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(musicMissionRecord); + EXPECT_TRUE(musicAbilityRecord); + musicAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + MissionOption missionOption; + missionOption.missionId = musicMissionRecord->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; + auto ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, ERR_NONE); + + auto stack = musicMissionRecord->GetMissionStack(); + EXPECT_EQ(stack->GetMissionStackId(), FLOATING_MISSION_STACK_ID); +} + +/* + * Feature: AbilityStackManager + * Function: MoveMissionToFloatingStack + * SubFunction: NA + * FunctionPoints: Move misson to floating window stack + * EnvConditions: NA + * CaseDescription: a luncher ability move to floating window stack + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_068, TestSize.Level1) +{ + stackManager_->Init(); + + auto result = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(0, result); + auto launcherMissionRecord = stackManager_->GetTopMissionRecord(); + auto launcherAbilityRecord = launcherMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(launcherMissionRecord); + EXPECT_TRUE(launcherAbilityRecord); + launcherAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + MissionOption missionOption; + missionOption.missionId = launcherMissionRecord->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; + auto ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, MOVE_MISSION_TO_STACK_NOT_SUPPORT_MULTI_WIN); + + auto stack = launcherMissionRecord->GetMissionStack(); + EXPECT_EQ(stack->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); +} + +/* + * Feature: AbilityStackManager + * Function: ChangeFocusAbility + * SubFunction: NA + * FunctionPoints: Change Focus Ability + * EnvConditions: NA + * CaseDescription: Move focus from one application to another + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_069, TestSize.Level1) +{ + stackManager_->Init(); + + auto result = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto stactLuncher = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(stactLuncher); + + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + + // Set floating window identification + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + EXPECT_TRUE(abilityStartSetting); + + musicAbilityRequest_.startSetting = abilityStartSetting; + result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord2 = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord2 = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topMissionRecord2); + EXPECT_TRUE(topAbilityRecord2); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::INACTIVE); + topAbilityRecord2->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto stact = topMissionRecord2->GetMissionStack(); + EXPECT_TRUE(stact); + + EXPECT_EQ(stact->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + EXPECT_EQ(stactLuncher->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); + + // luncher get focus + auto ref = stackManager_->ChangeFocusAbility(topAbilityRecord2->GetToken(), topAbilityRecord->GetToken()); + EXPECT_EQ(0, ref); + stact = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(stact); + EXPECT_EQ(stact->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); +} + +/* + * Feature: AbilityStackManager + * Function: ChangeFocusAbility + * SubFunction: NA + * FunctionPoints: Change Focus Ability + * EnvConditions: NA + * CaseDescription: Move focus from one application to another + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_070, TestSize.Level1) +{ + stackManager_->Init(); + auto ref = stackManager_->ChangeFocusAbility(nullptr, nullptr); + EXPECT_EQ(ref, ERR_INVALID_VALUE); + + auto abilityrecord = AbilityRecord::CreateAbilityRecord(musicAbilityRequest_); + auto abilityrecord1 = AbilityRecord::CreateAbilityRecord(radioAbilityRequest_); + EXPECT_TRUE(abilityrecord); + EXPECT_TRUE(abilityrecord1); + abilityrecord->Init(); + abilityrecord1->Init(); + + ref = stackManager_->ChangeFocusAbility(abilityrecord->GetToken(), abilityrecord1->GetToken()); + EXPECT_EQ(ref, CHANGE_FOCUS_ABILITY_FAILED); +} + +/* + * Feature: AbilityStackManager + * Function: MoveMissionToSplitScreenStack + * SubFunction: NA + * FunctionPoints: Move misson to Split window stack + * EnvConditions: NA + * CaseDescription: a ability move to Split window stack + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_071, TestSize.Level1) +{ + stackManager_->Init(); + + auto result = stackManager_->StartAbility(radioTopAbilityRequest_); + EXPECT_EQ(0, result); + auto redioMissionRecord = stackManager_->GetTopMissionRecord(); + auto redioAbilityRecord = redioMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(redioMissionRecord); + EXPECT_TRUE(redioAbilityRecord); + redioAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + MissionOption missionOption; + missionOption.missionId = -10; + + auto ref = stackManager_->MoveMissionToSplitScreenStack(missionOption); + EXPECT_EQ(ref, ERR_INVALID_DATA); + + missionOption.missionId = 13; + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FULLSCREEN; + ref = stackManager_->MoveMissionToSplitScreenStack(missionOption); + EXPECT_EQ(ref, ERR_INVALID_DATA); + + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY; + ref = stackManager_->MoveMissionToSplitScreenStack(missionOption); + EXPECT_EQ(ref, MOVE_MISSION_TO_STACK_NOT_EXIST_MISSION); + + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY; + ref = stackManager_->MoveMissionToSplitScreenStack(missionOption); + EXPECT_EQ(ref, MOVE_MISSION_TO_STACK_NOT_EXIST_MISSION); + + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; + ref = stackManager_->MoveMissionToSplitScreenStack(missionOption); + EXPECT_EQ(ref, ERR_INVALID_DATA); +} + +/* + * Feature: AbilityStackManager + * Function: MoveMissionToSplitScreenStack + * SubFunction: NA + * FunctionPoints: Move misson to Split window stack + * EnvConditions: NA + * CaseDescription: a ability move to Split window stack + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_072, TestSize.Level1) +{ + stackManager_->Init(); + + auto result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto musicMissionRecord = stackManager_->GetTopMissionRecord(); + auto musicAbilityRecord = musicMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(musicMissionRecord); + EXPECT_TRUE(musicAbilityRecord); + musicAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + MissionOption missionOption; + missionOption.missionId = musicMissionRecord->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY; + auto ref = stackManager_->MoveMissionToSplitScreenStack(missionOption); + EXPECT_EQ(ref, ERR_NONE); + + auto stack = musicMissionRecord->GetMissionStack(); + EXPECT_EQ(stack->GetMissionStackId(), SPLIT_SCREEN_MISSION_STACK_ID); +} + +/* + * Feature: AbilityStackManager + * Function: MoveMissionToSplitScreenStack + * SubFunction: NA + * FunctionPoints: Move misson to Split window stack + * EnvConditions: NA + * CaseDescription: a luncher ability move to Split window stack + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_073, TestSize.Level1) +{ + stackManager_->Init(); + + auto result = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(0, result); + auto launcherMissionRecord = stackManager_->GetTopMissionRecord(); + auto launcherAbilityRecord = launcherMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(launcherMissionRecord); + EXPECT_TRUE(launcherAbilityRecord); + launcherAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + MissionOption missionOption; + missionOption.missionId = launcherMissionRecord->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY; + auto ref = stackManager_->MoveMissionToSplitScreenStack(missionOption); + EXPECT_EQ(ref, MOVE_MISSION_TO_STACK_NOT_SUPPORT_MULTI_WIN); + + auto stack = launcherMissionRecord->GetMissionStack(); + EXPECT_EQ(stack->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); +} + +/* + * Feature: AbilityStackManager + * Function: MoveMissionToSplitScreenStack + * SubFunction: NA + * FunctionPoints: Move misson to Split window stack + * EnvConditions: NA + * CaseDescription: a luncher ability move to Split window stack + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_074, TestSize.Level1) +{ + stackManager_->Init(); + + auto result = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(0, result); + auto launcherMissionRecord = stackManager_->GetTopMissionRecord(); + auto launcherAbilityRecord = launcherMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(launcherMissionRecord); + EXPECT_TRUE(launcherAbilityRecord); + launcherAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + MissionOption missionOption; + missionOption.missionId = launcherMissionRecord->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY; + auto ref = stackManager_->MoveMissionToSplitScreenStack(missionOption); + EXPECT_EQ(ref, MOVE_MISSION_TO_STACK_NOT_SUPPORT_MULTI_WIN); + + auto stack = launcherMissionRecord->GetMissionStack(); + EXPECT_EQ(stack->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); +} + +/* + * Feature: AbilityStackManager + * Function: MinimizeMultiWindow + * SubFunction: NA + * FunctionPoints: Move the floating window to the background + * EnvConditions: NA + * CaseDescription: Move the floating window to the background + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_075, TestSize.Level1) +{ + stackManager_->Init(); + + auto ref = stackManager_->MinimizeMultiWindow(-1); + EXPECT_EQ(ref, MINIMIZE_MULTI_WINDOW_FAILED); + + auto result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto musicMissionRecord = stackManager_->GetTopMissionRecord(); + auto musicAbilityRecord = musicMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(musicMissionRecord); + EXPECT_TRUE(musicAbilityRecord); + musicAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + ref = stackManager_->MinimizeMultiWindow(musicMissionRecord->GetMissionRecordId()); + EXPECT_EQ(ref, MINIMIZE_MULTI_WINDOW_FAILED); +} + +/* + * Feature: AbilityStackManager + * Function: MinimizeMultiWindow + * SubFunction: NA + * FunctionPoints: Move the floating window to the background + * EnvConditions: NA + * CaseDescription: Move the floating window to the background + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_076, TestSize.Level1) +{ + stackManager_->Init(); + + auto result = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + EXPECT_TRUE(abilityStartSetting); + + musicAbilityRequest_.startSetting = abilityStartSetting; + result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord2 = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord2 = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topMissionRecord2); + EXPECT_TRUE(topAbilityRecord2); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::INACTIVE); + topAbilityRecord2->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto stact = topMissionRecord2->GetMissionStack(); + EXPECT_TRUE(stact); + + EXPECT_EQ(stact->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + auto topStack = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(topStack); + EXPECT_EQ(topStack->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + // luncher move to top + auto ref = stackManager_->MinimizeMultiWindow(topMissionRecord2->GetMissionRecordId()); + EXPECT_EQ(0, ref); + + // + stact = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(stact); + EXPECT_EQ(stact->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); +} + +/* + * Feature: AbilityStackManager + * Function: MinimizeMultiWindow + * SubFunction: NA + * FunctionPoints: Move the floating window to the background + * EnvConditions: NA + * CaseDescription: Move the floating window to the background + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_077, TestSize.Level1) +{ + stackManager_->Init(); + + // start luncher + auto result = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // start top ability + result = stackManager_->StartAbility(radioTopAbilityRequest_); + EXPECT_EQ(0, result); + auto radioMissionRecord = stackManager_->GetTopMissionRecord(); + auto radioAbilityRecord = radioMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(radioMissionRecord); + EXPECT_TRUE(radioAbilityRecord); + radioAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // start float ability + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + EXPECT_TRUE(abilityStartSetting); + + musicAbilityRequest_.startSetting = abilityStartSetting; + result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord2 = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord2 = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topMissionRecord2); + EXPECT_TRUE(topAbilityRecord2); + topAbilityRecord2->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto stact = topMissionRecord2->GetMissionStack(); + EXPECT_TRUE(stact); + + EXPECT_EQ(stact->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + auto topStack = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(topStack); + EXPECT_EQ(topStack->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + // ton ability move to top + auto ref = stackManager_->MinimizeMultiWindow(topMissionRecord2->GetMissionRecordId()); + EXPECT_EQ(0, ref); + + stact = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(stact); + // current top + EXPECT_EQ(stact->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); +} + +/* + * Feature: AbilityStackManager + * Function: MaximizeMultiWindow + * SubFunction: NA + * FunctionPoints: Move the floating window to the default stack + * EnvConditions: NA + * CaseDescription: move the ability form float stack to default stack + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_078, TestSize.Level1) +{ + stackManager_->Init(); + + auto ref = stackManager_->MaximizeMultiWindow(-1); + EXPECT_EQ(ref, MAXIMIZE_MULTIWINDOW_NOT_EXIST); + + auto result = stackManager_->StartAbility(radioAbilityRequest_); + EXPECT_EQ(0, result); + auto musicMissionRecord = stackManager_->GetTopMissionRecord(); + auto musicAbilityRecord = musicMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(musicMissionRecord); + EXPECT_TRUE(musicAbilityRecord); + musicAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + ref = stackManager_->MaximizeMultiWindow(musicMissionRecord->GetMissionRecordId()); + EXPECT_EQ(ref, MAXIMIZE_MULTIWINDOW_NOT_EXIST); +} + +/* + * Feature: AbilityStackManager + * Function: MaximizeMultiWindow + * SubFunction: NA + * FunctionPoints: Move the floating window to the background + * EnvConditions: NA + * CaseDescription: Move the floating window to the background + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_079, TestSize.Level1) +{ + stackManager_->Init(); + + // start luncher + auto result = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // start top ability + result = stackManager_->StartAbility(radioAbilityRequest_); + EXPECT_EQ(0, result); + auto radioMissionRecord = stackManager_->GetTopMissionRecord(); + auto radioAbilityRecord = radioMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(radioMissionRecord); + EXPECT_TRUE(radioAbilityRecord); + radioAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // start float ability + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + EXPECT_TRUE(abilityStartSetting); + + musicAbilityRequest_.startSetting = abilityStartSetting; + result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord2 = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord2 = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topMissionRecord2); + EXPECT_TRUE(topAbilityRecord2); + topAbilityRecord2->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto stact = topMissionRecord2->GetMissionStack(); + EXPECT_TRUE(stact); + auto stack1 = radioMissionRecord->GetMissionStack(); + EXPECT_TRUE(stact); + + EXPECT_EQ(stact->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + EXPECT_EQ(stack1->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + stackManager_->isMultiWinMoving_ = false; + auto topStack = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(topStack); + EXPECT_EQ(topStack->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + auto ref = stackManager_->MaximizeMultiWindow(topMissionRecord2->GetMissionRecordId()); + EXPECT_EQ(0, ref); + + stact = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(stact); + // current top + EXPECT_EQ(stact->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + + auto topAbility = stackManager_->GetTopMissionRecord()->GetTopAbilityRecord(); + EXPECT_TRUE(topAbility); +} + +/* + * Feature: AbilityStackManager + * Function: CloseMultiWindow + * SubFunction: NA + * FunctionPoints: Close multiple windows + * EnvConditions: NA + * CaseDescription: Can I exit the front desk by closing the floating window + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_080, TestSize.Level1) +{ + stackManager_->Init(); + + auto ref = stackManager_->CloseMultiWindow(-1); + EXPECT_EQ(ref, CLOSE_MULTI_WINDOW_FAILED); + + auto result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto musicMissionRecord = stackManager_->GetTopMissionRecord(); + auto musicAbilityRecord = musicMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(musicMissionRecord); + EXPECT_TRUE(musicAbilityRecord); + musicAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + ref = stackManager_->CloseMultiWindow(musicMissionRecord->GetMissionRecordId()); + EXPECT_EQ(ref, CLOSE_MULTI_WINDOW_FAILED); + + result = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + ref = stackManager_->CloseMultiWindow(musicMissionRecord->GetMissionRecordId()); + EXPECT_EQ(ref, CLOSE_MULTI_WINDOW_FAILED); +} + +/* + * Feature: AbilityStackManager + * Function: CloseMultiWindow + * SubFunction: NA + * FunctionPoints: Close multiple windows + * EnvConditions: NA + * CaseDescription: Can I exit the front desk by closing the floating window + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_081, TestSize.Level1) +{ + stackManager_->Init(); + + auto result = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // start top ability + result = stackManager_->StartAbility(radioAbilityRequest_); + EXPECT_EQ(0, result); + auto radioMissionRecord = stackManager_->GetTopMissionRecord(); + auto radioAbilityRecord = radioMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(radioMissionRecord); + EXPECT_TRUE(radioAbilityRecord); + radioAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // start float ability + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + EXPECT_TRUE(abilityStartSetting); + + musicAbilityRequest_.startSetting = abilityStartSetting; + result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + auto topMissionRecord2 = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord2 = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topMissionRecord2); + EXPECT_TRUE(topAbilityRecord2); + topAbilityRecord2->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto stact = topMissionRecord2->GetMissionStack(); + EXPECT_TRUE(stact); + auto stack1 = radioMissionRecord->GetMissionStack(); + EXPECT_TRUE(stact); + + EXPECT_EQ(stact->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + EXPECT_EQ(stack1->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // stackManager_->isMultiWinMoving_ = false; + + auto ref = stackManager_->CloseMultiWindow(topMissionRecord2->GetMissionRecordId()); + EXPECT_EQ(0, ref); + + auto topRecord = stackManager_->GetCurrentTopAbility(); + int state = topRecord->GetAbilityState(); + EXPECT_EQ(OHOS::AAFwk::INACTIVATING, state); +} + +/* + * Feature: AbilityStackManager + * Function: RestartAbility + * SubFunction: NA + * FunctionPoints: Restart ability + * EnvConditions: NA + * CaseDescription: Restart ability + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_082, TestSize.Level1) +{ + stackManager_->Init(); + EXPECT_TRUE(stackManager_); + + auto ability = std::make_shared(want_, abilityInfo_, appInfo_); + ability->Init(); + ability->SetAbilityState(AbilityState::ACTIVE); + stackManager_->RestartAbility(ability); + EXPECT_EQ(AbilityState::INACTIVATING, ability->GetAbilityState()); + + ability->SetAbilityState(AbilityState::ACTIVATING); + stackManager_->RestartAbility(ability); + EXPECT_EQ(AbilityState::INACTIVATING, ability->GetAbilityState()); +} + +/* + * Feature: AbilityStackManager + * Function: RestartAbility + * SubFunction: NA + * FunctionPoints: Restart ability + * EnvConditions: NA + * CaseDescription: Restart ability + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_083, TestSize.Level1) +{ + stackManager_->Init(); + EXPECT_TRUE(stackManager_); + auto ability = std::make_shared(want_, abilityInfo_, appInfo_); + ability->Init(); + ability->SetAbilityState(AbilityState::INACTIVE); + stackManager_->RestartAbility(ability); + EXPECT_FALSE(ability->IsNewWant()); + + ability->SetAbilityState(AbilityState::INACTIVATING); + stackManager_->RestartAbility(ability); + EXPECT_FALSE(ability->IsNewWant()); +} + +/* + * Feature: AbilityStackManager + * Function: RestartAbility + * SubFunction: NA + * FunctionPoints: Restart ability + * EnvConditions: NA + * CaseDescription: Restart ability + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_084, TestSize.Level1) +{ + stackManager_->Init(); + EXPECT_TRUE(stackManager_); + auto ability = std::make_shared(want_, abilityInfo_, appInfo_); + ability->Init(); + ability->SetAbilityState(AbilityState::BACKGROUND); + stackManager_->RestartAbility(ability); + EXPECT_EQ(AbilityState::TERMINATING, ability->GetAbilityState()); + + ability->SetAbilityState(AbilityState::MOVING_BACKGROUND); + stackManager_->RestartAbility(ability); + EXPECT_EQ(AbilityState::TERMINATING, ability->GetAbilityState()); +} + +/* + * Feature: AbilityStackManager + * Function: ProcessConfigurationChange + * SubFunction: NA + * FunctionPoints: Process Configuration Change + * EnvConditions: NA + * CaseDescription: Process Configuration Change + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_085, TestSize.Level1) +{ + stackManager_->Init(); + EXPECT_TRUE(stackManager_); + stackManager_->missionStackList_.clear(); + std::shared_ptr mission = nullptr; + stackManager_->missionStackList_.push_back(mission); + EXPECT_EQ(ERR_INVALID_VALUE, stackManager_->ProcessConfigurationChange()); +} + +/* + * Feature: AbilityStackManager + * Function: ProcessConfigurationChange + * SubFunction: NA + * FunctionPoints: Process Configuration Change + * EnvConditions: NA + * CaseDescription: Process Configuration Change + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_086, TestSize.Level1) +{ + stackManager_->Init(); + EXPECT_TRUE(stackManager_); + stackManager_->missionStackList_.clear(); + stackManager_->missionStackList_.push_back(stackManager_->launcherMissionStack_); + + std::string bundleName = "ddddd"; + auto mission = std::make_shared(bundleName); + EXPECT_TRUE(mission); + mission->RemoveAll(); + Want want_; + AbilityInfo abilityInfo_; + ApplicationInfo appInfo_; + auto ability = std::make_shared(want_, abilityInfo_, appInfo_); + EXPECT_TRUE(ability); + mission->abilities_.push_back(ability); + stackManager_->launcherMissionStack_->RemoveAll(); + stackManager_->launcherMissionStack_->AddMissionRecordToTop(mission); + AbilityRecordInfo abilityInfo; + ability->GetAbilityRecordInfo(abilityInfo); + auto abilityRecord = mission->GetAbilityRecordById(abilityInfo.id); + EXPECT_TRUE(abilityRecord); + abilityRecord->SetAbilityState(AbilityState::ACTIVE); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/test/unittest/phone/ability_with_applications_test/mock_ability_scheduler.cpp b/services/abilitymgr/test/unittest/phone/ability_with_applications_test/mock_ability_scheduler.cpp index 39bf55f2c1c..29537fde591 100644 --- a/services/abilitymgr/test/unittest/phone/ability_with_applications_test/mock_ability_scheduler.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_with_applications_test/mock_ability_scheduler.cpp @@ -52,6 +52,9 @@ void AbilityScheduler::ScheduleSaveAbilityState(PacMap &outState) void AbilityScheduler::ScheduleRestoreAbilityState(const PacMap &inState) {} +void AbilityScheduler::ScheduleUpdateConfiguration(const DummyConfiguration &config) +{} + std::vector AbilityScheduler::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) { std::vector types; @@ -104,5 +107,23 @@ int AbilityScheduler::BatchInsert(const Uri &uri, const std::vector &token, const int32_t state)); + MOCK_METHOD1(OnAppStateChanged, void(const AppInfo &info)); }; class AbilityMsAppmsTest : public testing::Test { @@ -102,17 +104,15 @@ void AbilityMsAppmsTest::SetUp(void) callback_ = std::make_shared(); DelayedSingleton::GetInstance()->Init(callback_); - DelayedSingleton::GetInstance()->OnStart(); - auto ams = DelayedSingleton::GetInstance(); - WaitUntilTaskFinished(); startAbility(); + GTEST_LOG_(INFO) << "SetUp"; } void AbilityMsAppmsTest::TearDown(void) { - DelayedSingleton::GetInstance()->OnStop(); DelayedSingleton::DestroyInstance(); + GTEST_LOG_(INFO) << "TearDown"; } std::shared_ptr AbilityMsAppmsTest::GetAbilityRecord() const diff --git a/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp b/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp index c668c44d58f..0606bff8072 100644 --- a/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp +++ b/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp @@ -24,6 +24,7 @@ #include "app_state_call_back_mock.h" #include "ability_record.h" #include "element_name.h" +#include "app_process_data.h" using namespace testing::ext; using namespace OHOS::AppExecFwk; diff --git a/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_state_call_back_mock.h b/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_state_call_back_mock.h index 9a1bfd56b51..1a4a2a8f23a 100644 --- a/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_state_call_back_mock.h +++ b/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_state_call_back_mock.h @@ -26,10 +26,12 @@ namespace AAFwk { class AppStateCallbackMock : public AppStateCallback { public: + AppStateCallbackMock() + {} virtual ~AppStateCallbackMock() {} - MOCK_METHOD2(OnAbilityRequestDone, void(const sptr &, const int32_t)); + MOCK_METHOD1(OnAppStateChanged, void(const AppInfo &info)); }; } // namespace AAFwk diff --git a/services/abilitymgr/test/unittest/phone/configuration_holder_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/configuration_holder_test/BUILD.gn new file mode 100644 index 00000000000..387c53a19bf --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/configuration_holder_test/BUILD.gn @@ -0,0 +1,65 @@ +# 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/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "aafwk_standard/abilitymgr" + +ohos_unittest("configuration_holder_test") { + module_out_path = module_output_path + + include_dirs = [ + "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/ability_scheduler_mock", + "//foundation/aafwk/standard/services/abilitymgr/test/mock/include", + ] + + sources = [ "configuration_holder_test.cpp" ] + + configs = [ + "${services_path}/abilitymgr:abilityms_config", + "${services_path}/abilitymgr/test/mock:aafwk_mock_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}/want:want", + "${services_path}/abilitymgr/test:abilityms_test_source", + "${services_path}/abilitymgr/test/mock/libs/aakit:aakit_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":configuration_holder_test" ] +} diff --git a/services/abilitymgr/test/unittest/phone/configuration_holder_test/configuration_holder_test.cpp b/services/abilitymgr/test/unittest/phone/configuration_holder_test/configuration_holder_test.cpp new file mode 100644 index 00000000000..6d9c642f813 --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/configuration_holder_test/configuration_holder_test.cpp @@ -0,0 +1,123 @@ +/* + * 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 + +#define private public +#define protected public +#include "configuration_holder.h" +#undef private +#undef protected + +#include "mock_configuration_holder.h" + +using namespace testing::ext; + +namespace OHOS { +namespace AAFwk { + +class ConfigurationHolderTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + std::shared_ptr mockConfigurationHolder_; +}; + +void ConfigurationHolderTest::SetUpTestCase(void) +{} +void ConfigurationHolderTest::TearDownTestCase(void) +{} +void ConfigurationHolderTest::SetUp(void) +{ + mockConfigurationHolder_ = std::make_shared(); +} +void ConfigurationHolderTest::TearDown(void) +{} + +/* + * Feature: ConfigurationHolder + * Function: UpdateConfiguration + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Update Configuration + */ +HWTEST_F(ConfigurationHolderTest, UpdateConfiguration_001, TestSize.Level1) +{ + std::string name = "layout"; + auto config = std::make_shared(name); + auto config1 = std::make_shared(); + mockConfigurationHolder_->baseConfiguration_ = config1; + mockConfigurationHolder_->baseConfiguration_->testInfostr_ = "orientation"; + mockConfigurationHolder_->UpdateConfiguration(config); + + EXPECT_EQ(config, mockConfigurationHolder_->GetConfiguration()); +} + +/* + * Feature: ConfigurationHolder + * Function: ProcessConfigurationChange + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Process Configuration Change + */ +HWTEST_F(ConfigurationHolderTest, ProcessConfigurationChange_001, TestSize.Level1) +{ + mockConfigurationHolder_->baseConfiguration_ = nullptr; + EXPECT_EQ(false, mockConfigurationHolder_->ProcessConfigurationChange()); +} + +/* + * Feature: ConfigurationHolder + * Function: ProcessConfigurationChange + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Process Configuration Change + */ +HWTEST_F(ConfigurationHolderTest, ProcessConfigurationChange_002, TestSize.Level1) +{ + std::string name = "layout"; + auto config = std::make_shared(name); + mockConfigurationHolder_->baseConfiguration_ = config; + mockConfigurationHolder_->baseConfiguration_->testInfostr_ = "orientation"; + EXPECT_EQ(false, mockConfigurationHolder_->ProcessConfigurationChange()); +} + +/* + * Feature: ConfigurationHolder + * Function: ProcessConfigurationChangeInner + * SubFunction: Process Configuration Change Inner + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Process Configuration Change Inner + */ +HWTEST_F(ConfigurationHolderTest, ProcessConfigurationChangeInner_001, TestSize.Level1) +{ + std::string name = "layout"; + auto config = std::make_shared(name); + auto config1 = std::make_shared(); + mockConfigurationHolder_->baseConfiguration_ = config1; + mockConfigurationHolder_->baseConfiguration_->testInfostr_ = "orientation"; + EXPECT_EQ(false, mockConfigurationHolder_->ProcessConfigurationChangeInner(config)); + EXPECT_EQ(config, mockConfigurationHolder_->GetConfiguration()); +} + +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/connection_record_test/connection_record_test.cpp b/services/abilitymgr/test/unittest/phone/connection_record_test/connection_record_test.cpp index e680974cd4e..bfd047a448b 100644 --- a/services/abilitymgr/test/unittest/phone/connection_record_test/connection_record_test.cpp +++ b/services/abilitymgr/test/unittest/phone/connection_record_test/connection_record_test.cpp @@ -23,6 +23,7 @@ #undef private #undef protected +#include "app_process_data.h" #include "ability_manager_errors.h" #include "ability_connect_callback_stub.h" #include "ability_scheduler.h" diff --git a/services/abilitymgr/test/unittest/phone/data_ability_manager_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/data_ability_manager_test/BUILD.gn index 57e83072695..0d9567992b8 100644 --- a/services/abilitymgr/test/unittest/phone/data_ability_manager_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/data_ability_manager_test/BUILD.gn @@ -9,7 +9,7 @@ # 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. +# limitations under the License. import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") @@ -24,7 +24,8 @@ ohos_unittest("data_ability_manager_test") { "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "${services_path}/abilitymgr/test/mock/libs/ability_scheduler_mock", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + + # "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/aafwk/standard/services/common/include", diff --git a/services/abilitymgr/test/unittest/phone/data_ability_manager_test/data_ability_manager_test.cpp b/services/abilitymgr/test/unittest/phone/data_ability_manager_test/data_ability_manager_test.cpp index fd81fa244c5..b13525ccfea 100644 --- a/services/abilitymgr/test/unittest/phone/data_ability_manager_test/data_ability_manager_test.cpp +++ b/services/abilitymgr/test/unittest/phone/data_ability_manager_test/data_ability_manager_test.cpp @@ -115,13 +115,13 @@ HWTEST_F(DataAbilityManagerTest, AaFwk_DataAbilityManager_Flow_001, TestSize.Lev std::thread(func).detach(); EXPECT_CALL(*abilitySchedulerMock_, ScheduleAbilityTransaction(_, _)).Times(1); - EXPECT_NE(dataAbilityManager->Acquire(abilityRequest_, true, abilityRecordClient_->GetToken()), nullptr); + EXPECT_NE(dataAbilityManager->Acquire(abilityRequest_, true, abilityRecordClient_->GetToken(), false), nullptr); sptr token = (reinterpret_cast(DelayedSingleton::GetInstance()->appMgrClient_.get())) ->GetToken(); std::shared_ptr abilityRecord = Token::GetAbilityRecordByToken(token); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); // existing ability record EXPECT_NE(dataAbilityManager->GetAbilityRecordByToken(token), nullptr); @@ -153,7 +153,7 @@ HWTEST_F(DataAbilityManagerTest, AaFwk_DataAbilityManager_Acquire_001, TestSize. std::unique_ptr dataAbilityManager = std::make_unique(); - EXPECT_EQ(dataAbilityManager->Acquire(abilityRequest_, true, nullptr), nullptr); + EXPECT_EQ(dataAbilityManager->Acquire(abilityRequest_, true, nullptr, false), nullptr); HILOG_INFO("AaFwk_DataAbilityManager_Acquire_001 end."); } @@ -174,7 +174,7 @@ HWTEST_F(DataAbilityManagerTest, AaFwk_DataAbilityManager_Acquire_002, TestSize. // page ability type abilityRequest_.abilityInfo.type = AbilityType::PAGE; - EXPECT_EQ(dataAbilityManager->Acquire(abilityRequest_, true, abilityRecordClient_->GetToken()), nullptr); + EXPECT_EQ(dataAbilityManager->Acquire(abilityRequest_, true, abilityRecordClient_->GetToken(), false), nullptr); HILOG_INFO("AaFwk_DataAbilityManager_Acquire_002 end."); } @@ -195,7 +195,7 @@ HWTEST_F(DataAbilityManagerTest, AaFwk_DataAbilityManager_Acquire_003, TestSize. // appinfo bundle name empty abilityRequest_.appInfo.bundleName = ""; - EXPECT_EQ(dataAbilityManager->Acquire(abilityRequest_, true, abilityRecordClient_->GetToken()), nullptr); + EXPECT_EQ(dataAbilityManager->Acquire(abilityRequest_, true, abilityRecordClient_->GetToken(), false), nullptr); HILOG_INFO("AaFwk_DataAbilityManager_Acquire_003 end."); } @@ -216,7 +216,7 @@ HWTEST_F(DataAbilityManagerTest, AaFwk_DataAbilityManager_Acquire_004, TestSize. // ability name empty abilityRequest_.abilityInfo.name = ""; - EXPECT_EQ(dataAbilityManager->Acquire(abilityRequest_, true, abilityRecordClient_->GetToken()), nullptr); + EXPECT_EQ(dataAbilityManager->Acquire(abilityRequest_, true, abilityRecordClient_->GetToken(), false), nullptr); HILOG_INFO("AaFwk_DataAbilityManager_Acquire_004 end."); } @@ -246,7 +246,7 @@ HWTEST_F(DataAbilityManagerTest, AaFwk_DataAbilityManager_Acquire_005, TestSize. std::shared_ptr abilityRecordClient = std::make_shared(want, abilityInfo, applicationInfo); abilityRecordClient->Init(); - EXPECT_EQ(dataAbilityManager->Acquire(abilityRequest_, true, abilityRecordClient->GetToken()), nullptr); + EXPECT_EQ(dataAbilityManager->Acquire(abilityRequest_, true, abilityRecordClient->GetToken(), false), nullptr); HILOG_INFO("AaFwk_DataAbilityManager_Acquire_005 end."); } @@ -265,7 +265,7 @@ HWTEST_F(DataAbilityManagerTest, AaFwk_DataAbilityManager_Acquire_006, TestSize. std::unique_ptr dataAbilityManager = std::make_unique(); - EXPECT_EQ(dataAbilityManager->Acquire(abilityRequest_, true, abilityRecordClient_->GetToken()), nullptr); + EXPECT_EQ(dataAbilityManager->Acquire(abilityRequest_, true, abilityRecordClient_->GetToken(), false), nullptr); HILOG_INFO("AaFwk_DataAbilityManager_Acquire_006 end."); } @@ -284,7 +284,7 @@ HWTEST_F(DataAbilityManagerTest, AaFwk_DataAbilityManager_Release_001, TestSize. std::unique_ptr dataAbilityManager = std::make_unique(); - EXPECT_EQ(dataAbilityManager->Release(abilitySchedulerMock_, nullptr), ERR_NULL_OBJECT); + EXPECT_EQ(dataAbilityManager->Release(abilitySchedulerMock_, nullptr, false), ERR_NULL_OBJECT); HILOG_INFO("AaFwk_DataAbilityManager_Release_001 end."); } @@ -303,7 +303,7 @@ HWTEST_F(DataAbilityManagerTest, AaFwk_DataAbilityManager_Release_002, TestSize. std::unique_ptr dataAbilityManager = std::make_unique(); - EXPECT_EQ(dataAbilityManager->Release(nullptr, abilityRecordClient_->GetToken()), ERR_NULL_OBJECT); + EXPECT_EQ(dataAbilityManager->Release(nullptr, abilityRecordClient_->GetToken(), false), ERR_NULL_OBJECT); HILOG_INFO("AaFwk_DataAbilityManager_Release_002 end."); } @@ -322,7 +322,8 @@ HWTEST_F(DataAbilityManagerTest, AaFwk_DataAbilityManager_Release_003, TestSize. std::unique_ptr dataAbilityManager = std::make_unique(); - EXPECT_EQ(dataAbilityManager->Release(abilitySchedulerMock_, abilityRecordClient_->GetToken()), ERR_UNKNOWN_OBJECT); + EXPECT_EQ(dataAbilityManager->Release(abilitySchedulerMock_, abilityRecordClient_->GetToken(), false), + ERR_UNKNOWN_OBJECT); HILOG_INFO("AaFwk_DataAbilityManager_Release_003 end."); } diff --git a/services/abilitymgr/test/unittest/phone/data_ability_record_test/data_ability_record_test.cpp b/services/abilitymgr/test/unittest/phone/data_ability_record_test/data_ability_record_test.cpp index afd6bf87d9d..cd89b069531 100644 --- a/services/abilitymgr/test/unittest/phone/data_ability_record_test/data_ability_record_test.cpp +++ b/services/abilitymgr/test/unittest/phone/data_ability_record_test/data_ability_record_test.cpp @@ -22,6 +22,7 @@ #undef protected #include "ability_scheduler_mock.h" +#include "app_process_data.h" using namespace testing::ext; using namespace testing; @@ -392,7 +393,7 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_AddClient_001, TestSize. HILOG_INFO("AaFwk_DataAbilityRecord_AddClient_001 start."); std::unique_ptr dataAbilityRecord = std::make_unique(abilityRequest_); - EXPECT_EQ(dataAbilityRecord->AddClient(nullptr, true), ERR_INVALID_STATE); + EXPECT_EQ(dataAbilityRecord->AddClient(nullptr, true, false), ERR_INVALID_STATE); HILOG_INFO("AaFwk_DataAbilityRecord_AddClient_001 end."); } @@ -412,7 +413,7 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_AddClient_002, TestSize. std::unique_ptr dataAbilityRecord = std::make_unique(abilityRequest_); auto client = Token::GetAbilityRecordByToken(abilityRecord_->GetToken()); - EXPECT_EQ(dataAbilityRecord->AddClient(client, true), ERR_INVALID_STATE); + EXPECT_EQ(dataAbilityRecord->AddClient(abilityRecord_->GetToken(), true, false), ERR_INVALID_STATE); HILOG_INFO("AaFwk_DataAbilityRecord_AddClient_002 end."); } @@ -433,7 +434,7 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_AddClient_003, TestSize. auto client = Token::GetAbilityRecordByToken(abilityRecord_->GetToken()); EXPECT_EQ(dataAbilityRecord->StartLoading(), ERR_OK); - EXPECT_EQ(dataAbilityRecord->AddClient(client, true), ERR_INVALID_STATE); + EXPECT_EQ(dataAbilityRecord->AddClient(abilityRecord_->GetToken(), true, false), ERR_INVALID_STATE); HILOG_INFO("AaFwk_DataAbilityRecord_AddClient_003 end."); } @@ -456,7 +457,7 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_AddClient_004, TestSize. EXPECT_EQ(dataAbilityRecord->StartLoading(), ERR_OK); EXPECT_CALL(*abilitySchedulerMock_, ScheduleAbilityTransaction(_, _)).Times(1); EXPECT_EQ(dataAbilityRecord->Attach(abilitySchedulerMock_), ERR_OK); - EXPECT_EQ(dataAbilityRecord->AddClient(client, true), ERR_INVALID_STATE); + EXPECT_EQ(dataAbilityRecord->AddClient(abilityRecord_->GetToken(), true, false), ERR_INVALID_STATE); HILOG_INFO("AaFwk_DataAbilityRecord_AddClient_004 end."); } @@ -481,9 +482,9 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_AddClient_005, TestSize. EXPECT_EQ(dataAbilityRecord->Attach(abilitySchedulerMock_), ERR_OK); abilityState_ = ACTIVE; EXPECT_EQ(dataAbilityRecord->OnTransitionDone(abilityState_), ERR_OK); - EXPECT_EQ(dataAbilityRecord->AddClient(client, true), ERR_OK); + EXPECT_EQ(dataAbilityRecord->AddClient(abilityRecord_->GetToken(), true, false), ERR_OK); unsigned int count = 1; - EXPECT_EQ(dataAbilityRecord->GetClientCount(client), count); + EXPECT_EQ(dataAbilityRecord->GetClientCount(abilityRecord_->GetToken()), count); HILOG_INFO("AaFwk_DataAbilityRecord_AddClient_005 end."); } @@ -501,7 +502,7 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_RemoveClient_001, TestSi HILOG_INFO("AaFwk_DataAbilityRecord_RemoveClient_001 start."); std::unique_ptr dataAbilityRecord = std::make_unique(abilityRequest_); - EXPECT_EQ(dataAbilityRecord->RemoveClient(nullptr), ERR_INVALID_STATE); + EXPECT_EQ(dataAbilityRecord->RemoveClient(nullptr, false), ERR_INVALID_STATE); HILOG_INFO("AaFwk_DataAbilityRecord_RemoveClient_001 end."); } @@ -521,7 +522,7 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_RemoveClient_002, TestSi std::unique_ptr dataAbilityRecord = std::make_unique(abilityRequest_); auto client = Token::GetAbilityRecordByToken(abilityRecord_->GetToken()); - EXPECT_EQ(dataAbilityRecord->RemoveClient(client), ERR_INVALID_STATE); + EXPECT_EQ(dataAbilityRecord->RemoveClient(abilityRecord_->GetToken(), false), ERR_INVALID_STATE); HILOG_INFO("AaFwk_DataAbilityRecord_RemoveClient_002 end."); } @@ -542,7 +543,7 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_RemoveClient_003, TestSi auto client = Token::GetAbilityRecordByToken(abilityRecord_->GetToken()); EXPECT_EQ(dataAbilityRecord->StartLoading(), ERR_OK); - EXPECT_EQ(dataAbilityRecord->RemoveClient(client), ERR_INVALID_STATE); + EXPECT_EQ(dataAbilityRecord->RemoveClient(abilityRecord_->GetToken(), false), ERR_INVALID_STATE); HILOG_INFO("AaFwk_DataAbilityRecord_RemoveClient_003 end."); } @@ -565,7 +566,7 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_RemoveClient_004, TestSi EXPECT_EQ(dataAbilityRecord->StartLoading(), ERR_OK); EXPECT_CALL(*abilitySchedulerMock_, ScheduleAbilityTransaction(_, _)).Times(1); EXPECT_EQ(dataAbilityRecord->Attach(abilitySchedulerMock_), ERR_OK); - EXPECT_EQ(dataAbilityRecord->RemoveClient(client), ERR_INVALID_STATE); + EXPECT_EQ(dataAbilityRecord->RemoveClient(abilityRecord_->GetToken(), false), ERR_INVALID_STATE); HILOG_INFO("AaFwk_DataAbilityRecord_RemoveClient_004 end."); } @@ -590,7 +591,7 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_RemoveClient_005, TestSi EXPECT_EQ(dataAbilityRecord->Attach(abilitySchedulerMock_), ERR_OK); abilityState_ = ACTIVE; EXPECT_EQ(dataAbilityRecord->OnTransitionDone(abilityState_), ERR_OK); - EXPECT_EQ(dataAbilityRecord->RemoveClient(client), ERR_OK); + EXPECT_EQ(dataAbilityRecord->RemoveClient(abilityRecord_->GetToken(), false), ERR_OK); HILOG_INFO("AaFwk_DataAbilityRecord_RemoveClient_005 end."); } @@ -615,12 +616,12 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_RemoveClient_006, TestSi EXPECT_EQ(dataAbilityRecord->Attach(abilitySchedulerMock_), ERR_OK); abilityState_ = ACTIVE; EXPECT_EQ(dataAbilityRecord->OnTransitionDone(abilityState_), ERR_OK); - EXPECT_EQ(dataAbilityRecord->AddClient(client, true), ERR_OK); + EXPECT_EQ(dataAbilityRecord->AddClient(abilityRecord_->GetToken(), true, false), ERR_OK); unsigned int count = 1; - EXPECT_EQ(dataAbilityRecord->GetClientCount(client), count); - EXPECT_EQ(dataAbilityRecord->RemoveClient(client), ERR_OK); + EXPECT_EQ(dataAbilityRecord->GetClientCount(abilityRecord_->GetToken()), count); + EXPECT_EQ(dataAbilityRecord->RemoveClient(abilityRecord_->GetToken(), false), ERR_OK); count = 0; - EXPECT_EQ(dataAbilityRecord->GetClientCount(client), count); + EXPECT_EQ(dataAbilityRecord->GetClientCount(abilityRecord_->GetToken()), count); HILOG_INFO("AaFwk_DataAbilityRecord_RemoveClient_006 end."); } @@ -647,20 +648,20 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_RemoveClient_007, TestSi EXPECT_EQ(dataAbilityRecord->OnTransitionDone(abilityState_), ERR_OK); // first add client - EXPECT_EQ(dataAbilityRecord->AddClient(client, true), ERR_OK); - EXPECT_EQ(dataAbilityRecord->GetClientCount(client), (uint32_t)1); + EXPECT_EQ(dataAbilityRecord->AddClient(abilityRecord_->GetToken(), true, false), ERR_OK); + EXPECT_EQ(dataAbilityRecord->GetClientCount(abilityRecord_->GetToken()), (uint32_t)1); // second add client - EXPECT_EQ(dataAbilityRecord->AddClient(client, true), ERR_OK); - EXPECT_EQ(dataAbilityRecord->GetClientCount(client), (uint32_t)2); + EXPECT_EQ(dataAbilityRecord->AddClient(abilityRecord_->GetToken(), true, false), ERR_OK); + EXPECT_EQ(dataAbilityRecord->GetClientCount(abilityRecord_->GetToken()), (uint32_t)2); // first remove client - EXPECT_EQ(dataAbilityRecord->RemoveClient(client), ERR_OK); - EXPECT_EQ(dataAbilityRecord->GetClientCount(client), (uint32_t)1); + EXPECT_EQ(dataAbilityRecord->RemoveClient(abilityRecord_->GetToken(), false), ERR_OK); + EXPECT_EQ(dataAbilityRecord->GetClientCount(abilityRecord_->GetToken()), (uint32_t)1); // second remove client - EXPECT_EQ(dataAbilityRecord->RemoveClient(client), ERR_OK); - EXPECT_EQ(dataAbilityRecord->GetClientCount(client), (uint32_t)0); + EXPECT_EQ(dataAbilityRecord->RemoveClient(abilityRecord_->GetToken(), false), ERR_OK); + EXPECT_EQ(dataAbilityRecord->GetClientCount(abilityRecord_->GetToken()), (uint32_t)0); HILOG_INFO("AaFwk_DataAbilityRecord_RemoveClient_007 end."); } @@ -776,16 +777,16 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_RemoveClients_006, TestS EXPECT_EQ(dataAbilityRecord->OnTransitionDone(abilityState_), ERR_OK); // first add client - EXPECT_EQ(dataAbilityRecord->AddClient(client, true), ERR_OK); - EXPECT_EQ(dataAbilityRecord->GetClientCount(client), (uint32_t)1); + EXPECT_EQ(dataAbilityRecord->AddClient(abilityRecord_->GetToken(), true, false), ERR_OK); + EXPECT_EQ(dataAbilityRecord->GetClientCount(abilityRecord_->GetToken()), (uint32_t)1); // second add client - EXPECT_EQ(dataAbilityRecord->AddClient(client, true), ERR_OK); - EXPECT_EQ(dataAbilityRecord->GetClientCount(client), (uint32_t)2); + EXPECT_EQ(dataAbilityRecord->AddClient(abilityRecord_->GetToken(), true, false), ERR_OK); + EXPECT_EQ(dataAbilityRecord->GetClientCount(abilityRecord_->GetToken()), (uint32_t)2); // remove the same client EXPECT_EQ(dataAbilityRecord->RemoveClients(client), ERR_OK); - EXPECT_EQ(dataAbilityRecord->GetClientCount(client), (uint32_t)0); + EXPECT_EQ(dataAbilityRecord->GetClientCount(abilityRecord_->GetToken()), (uint32_t)0); HILOG_INFO("AaFwk_DataAbilityRecord_RemoveClients_005 end."); } @@ -805,7 +806,7 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_GetClientCount_001, Test std::unique_ptr dataAbilityRecord = std::make_unique(abilityRequest_); auto client = Token::GetAbilityRecordByToken(abilityRecord_->GetToken()); - EXPECT_EQ(dataAbilityRecord->GetClientCount(client), (uint32_t)0); + EXPECT_EQ(dataAbilityRecord->GetClientCount(abilityRecord_->GetToken()), (uint32_t)0); HILOG_INFO("AaFwk_DataAbilityRecord_GetClientCount_001 end."); } @@ -826,7 +827,7 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_GetClientCount_002, Test auto client = Token::GetAbilityRecordByToken(abilityRecord_->GetToken()); EXPECT_EQ(dataAbilityRecord->StartLoading(), ERR_OK); - EXPECT_EQ(dataAbilityRecord->GetClientCount(client), (uint32_t)0); + EXPECT_EQ(dataAbilityRecord->GetClientCount(abilityRecord_->GetToken()), (uint32_t)0); HILOG_INFO("AaFwk_DataAbilityRecord_GetClientCount_002 end."); } @@ -849,7 +850,7 @@ HWTEST_F(DataAbilityRecordTest, AaFwk_DataAbilityRecord_GetClientCount_003, Test EXPECT_EQ(dataAbilityRecord->StartLoading(), ERR_OK); EXPECT_CALL(*abilitySchedulerMock_, ScheduleAbilityTransaction(_, _)).Times(1); EXPECT_EQ(dataAbilityRecord->Attach(abilitySchedulerMock_), ERR_OK); - EXPECT_EQ(dataAbilityRecord->GetClientCount(client), (uint32_t)0); + EXPECT_EQ(dataAbilityRecord->GetClientCount(abilityRecord_->GetToken()), (uint32_t)0); HILOG_INFO("AaFwk_DataAbilityRecord_GetClientCount_003 end."); } diff --git a/services/abilitymgr/test/unittest/phone/info_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/info_test/BUILD.gn index 42d208444ef..74f13bca661 100644 --- a/services/abilitymgr/test/unittest/phone/info_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/info_test/BUILD.gn @@ -41,7 +41,8 @@ ohos_unittest("info_test") { "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + + # "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", diff --git a/services/abilitymgr/test/unittest/phone/info_test/info_test.cpp b/services/abilitymgr/test/unittest/phone/info_test/info_test.cpp index 9000adc91c0..8d22943799a 100755 --- a/services/abilitymgr/test/unittest/phone/info_test/info_test.cpp +++ b/services/abilitymgr/test/unittest/phone/info_test/info_test.cpp @@ -94,7 +94,7 @@ HWTEST_F(InfoTest, stack_info_oprator_002, TestSize.Level0) Parcel parcel; missionStackInfo_.Marshalling(parcel); MissionStackInfo *obj = missionStackInfo_.Unmarshalling(parcel); - ASSERT_TRUE(obj); + EXPECT_TRUE(obj); EXPECT_EQ(obj->id, missionStackInfo_.id); EXPECT_EQ(obj->missionRecords[0].id, info.id); } @@ -129,7 +129,7 @@ HWTEST_F(InfoTest, stack_info_oprator_003, TestSize.Level0) Parcel parcel; missionRecordInfo_.Marshalling(parcel); MissionRecordInfo *obj = missionRecordInfo_.Unmarshalling(parcel); - ASSERT_TRUE(obj); + EXPECT_TRUE(obj); EXPECT_EQ(obj->id, missionRecordInfo_.id); EXPECT_EQ(obj->abilityRecordInfos[0].id, info.id); EXPECT_EQ(obj->abilityRecordInfos[0].elementName, info.elementName); @@ -174,7 +174,7 @@ HWTEST_F(InfoTest, stack_info_oprator_004, TestSize.Level0) Parcel parcel; abilityRecordInfo_.Marshalling(parcel); AbilityRecordInfo *obj = abilityRecordInfo_.Unmarshalling(parcel); - ASSERT_TRUE(obj); + EXPECT_TRUE(obj); EXPECT_EQ(obj->id, abilityRecordInfo_.id); EXPECT_EQ(obj->elementName, abilityRecordInfo_.elementName); @@ -207,7 +207,7 @@ HWTEST_F(InfoTest, stack_info_oprator_005, TestSize.Level0) Parcel parcel; lifeCycleStateInfo_.Marshalling(parcel); LifeCycleStateInfo *obj = lifeCycleStateInfo_.Unmarshalling(parcel); - ASSERT_TRUE(obj); + EXPECT_TRUE(obj); EXPECT_EQ(obj->isNewWant, lifeCycleStateInfo_.isNewWant); EXPECT_EQ(obj->state, lifeCycleStateInfo_.state); @@ -230,7 +230,7 @@ HWTEST_F(InfoTest, stack_info_oprator_007, TestSize.Level0) Parcel parcel; imageHeader_.Marshalling(parcel); ImageHeader *obj = imageHeader_.Unmarshalling(parcel); - ASSERT_TRUE(obj); + EXPECT_TRUE(obj); EXPECT_EQ(obj->colorMode, imageHeader_.colorMode); EXPECT_EQ(obj->reserved, imageHeader_.reserved); EXPECT_EQ(obj->width, imageHeader_.width); @@ -276,7 +276,7 @@ HWTEST_F(InfoTest, stack_info_oprator_009, TestSize.Level0) Parcel parcel; recentMissionInfo_.Marshalling(parcel); AbilityMissionInfo *obj = recentMissionInfo_.Unmarshalling(parcel); - ASSERT_TRUE(obj); + EXPECT_TRUE(obj); EXPECT_EQ(obj->id, recentMissionInfo_.id); EXPECT_EQ(obj->runingState, recentMissionInfo_.runingState); EXPECT_EQ(obj->size, recentMissionInfo_.size); diff --git a/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/kernal_system_app_manager_test.cpp b/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/kernal_system_app_manager_test.cpp index 75de7db136f..84507c4c13b 100755 --- a/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/kernal_system_app_manager_test.cpp +++ b/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/kernal_system_app_manager_test.cpp @@ -64,6 +64,9 @@ public: public: std::shared_ptr kernalSystemMgr_; int usrId_ = 10; + Want want_; + AppExecFwk::AbilityInfo abilityInfo_; + AppExecFwk::ApplicationInfo appInfo_; }; void KernalSystemAppManagerTest::SetUpTestCase() @@ -606,6 +609,28 @@ HWTEST_F(KernalSystemAppManagerTest, DispatchActive_002, TestSize.Level1) isRemove = kernalSystemMgr_->RemoveAbilityRecord(nullptr); EXPECT_FALSE(isRemove); } + +/* + * Feature: KernalSystemAppManager + * Function: UpdateConfiguration + * SubFunction: Processing preconditions + * FunctionPoints: + * EnvConditions:Is Kernal System Ability + * CaseDescription: Notification status + */ +HWTEST_F(KernalSystemAppManagerTest, UpdateConfiguration_001, TestSize.Level1) +{ + EXPECT_TRUE(kernalSystemMgr_); + + auto targetAbility = std::make_shared(want_, abilityInfo_, appInfo_); + EXPECT_TRUE(targetAbility); + kernalSystemMgr_->abilities_.clear(); + kernalSystemMgr_->abilities_.push_front(targetAbility); + targetAbility->SetAbilityState(AbilityState::ACTIVE); + const DummyConfiguration config; + kernalSystemMgr_->UpdateConfiguration(config); +} + } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/test/unittest/phone/lifecycle_deal_test/lifecycle_deal_test.cpp b/services/abilitymgr/test/unittest/phone/lifecycle_deal_test/lifecycle_deal_test.cpp index cd62e814c48..11cbd8e557c 100644 --- a/services/abilitymgr/test/unittest/phone/lifecycle_deal_test/lifecycle_deal_test.cpp +++ b/services/abilitymgr/test/unittest/phone/lifecycle_deal_test/lifecycle_deal_test.cpp @@ -14,6 +14,7 @@ */ #include +#include "app_process_data.h" #include "lifecycle_deal.h" #include "ability_scheduler_mock.h" diff --git a/services/abilitymgr/test/unittest/phone/mission_record_test/mission_record_test.cpp b/services/abilitymgr/test/unittest/phone/mission_record_test/mission_record_test.cpp index 9a4f7269700..1e73f5619a3 100644 --- a/services/abilitymgr/test/unittest/phone/mission_record_test/mission_record_test.cpp +++ b/services/abilitymgr/test/unittest/phone/mission_record_test/mission_record_test.cpp @@ -14,7 +14,11 @@ */ #include +#define private public +#define protected public #include "mission_record.h" +#undef private +#undef protected using namespace testing::ext; using namespace OHOS::AppExecFwk; @@ -53,6 +57,7 @@ AbilityRequest MissionRecordTest::GenerateAbilityRequest(const std::string &devi want.SetElement(element); AbilityInfo abilityInfo; + abilityInfo.visible = true; abilityInfo.applicationName = appName; ApplicationInfo appinfo; appinfo.name = appName; @@ -303,5 +308,80 @@ HWTEST_F(MissionRecordTest, stack_operating_014, TestSize.Level1) missionRecord->SetIsLauncherCreate(); EXPECT_EQ(true, missionRecord->IsLauncherCreate()); } + +/* + * Feature: MissionRecord + * Function: NA + * SubFunction: NA + * FunctionPoints: Find Child + * EnvConditions:NA + * CaseDescription: Find Child UT. + */ +HWTEST_F(MissionRecordTest, stack_operating_015, TestSize.Level1) +{ + auto missionRecord = std::make_shared(); + EXPECT_EQ(nullptr, missionRecord->FindChild(-1)); +} + +/* + * Feature: MissionRecord + * Function: NA + * SubFunction: NA + * FunctionPoints: Find Child + * EnvConditions:NA + * CaseDescription: Find Child UT. + */ +HWTEST_F(MissionRecordTest, stack_operating_016, TestSize.Level1) +{ + auto missionRecord = std::make_shared(); + missionRecord->RemoveAll(); + auto ability = std::make_shared(want_, abilityInfo_, appInfo_); + missionRecord->AddAbilityRecordToTop(ability); + + EXPECT_EQ(nullptr, missionRecord->FindChild(2)); +} + +/* + * Feature: MissionRecord + * Function: NA + * SubFunction: NA + * FunctionPoints: Find Child + * EnvConditions:NA + * CaseDescription: Find Child UT. + */ +HWTEST_F(MissionRecordTest, stack_operating_017, TestSize.Level1) +{ + auto missionRecord = std::make_shared(); + missionRecord->RemoveAll(); + auto ability = std::make_shared(want_, abilityInfo_, appInfo_); + missionRecord->AddAbilityRecordToTop(ability); + + auto iter = missionRecord->abilities_.begin(); + EXPECT_EQ((*iter), missionRecord->FindChild(0)); +} + +/* + * Feature: MissionRecord + * Function: NA + * SubFunction: NA + * FunctionPoints: SetIsLauncherCreate IsLauncherCreate + * EnvConditions:NA + * CaseDescription: SetIsLauncherCreate IsLauncherCreate UT. + */ +HWTEST_F(MissionRecordTest, stack_Resume_001, TestSize.Level1) +{ + auto missionRecord = std::make_shared(); + + std::shared_ptr backup; + backup = std::make_shared(missionRecord); + missionRecord->abilities_.clear(); + auto ability = std::make_shared(want_, abilityInfo_, appInfo_); + backup->abilities_.push_front(ability); + + missionRecord->Resume(backup); + EXPECT_TRUE(1 == missionRecord->abilities_.size()); + EXPECT_EQ(true, ability->IsRestarting()); +} + } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/mission_stack_test/mission_stack_test.cpp b/services/abilitymgr/test/unittest/phone/mission_stack_test/mission_stack_test.cpp index edf45a5a45e..0c45e681334 100644 --- a/services/abilitymgr/test/unittest/phone/mission_stack_test/mission_stack_test.cpp +++ b/services/abilitymgr/test/unittest/phone/mission_stack_test/mission_stack_test.cpp @@ -14,8 +14,12 @@ */ #include +#define private public +#define protected public #include "mission_record.h" #include "mission_stack.h" +#undef private +#undef protected #include "hilog_wrapper.h" using namespace testing::ext; @@ -56,6 +60,7 @@ AbilityRequest GenerateAbilityRequest(const std::string &deviceName, const std:: want.SetElement(element); AbilityInfo abilityInfo; + abilityInfo.visible = true; abilityInfo.applicationName = appName; ApplicationInfo appinfo; appinfo.name = appName; @@ -448,5 +453,55 @@ HWTEST_F(MissionStackTest, MS_oprator_015, TestSize.Level0) EXPECT_EQ(true, missionStack_->RemoveMissionRecord(15)); } + +/* + * Feature: MissionStack + * Function: FindChild + * SubFunction: NA + * FunctionPoints: Find Child + * EnvConditions:NA + * CaseDescription: Find Child UT. + */ +HWTEST_F(MissionStackTest, MS_oprator_016, TestSize.Level1) +{ + EXPECT_EQ(nullptr, missionStack_->FindChild(-1)); +} + +/* + * Feature: MissionStack + * Function: FindChild + * SubFunction: NA + * FunctionPoints: Find Child + * EnvConditions:NA + * CaseDescription: Find Child UT. + */ +HWTEST_F(MissionStackTest, MS_oprator_017, TestSize.Level1) +{ + missionStack_->missions_.clear(); + auto missionRecord = std::make_shared(); + + missionStack_->missions_.push_back(missionRecord); + + EXPECT_EQ(nullptr, missionStack_->FindChild(2)); +} + +/* + * Feature: MissionStack + * Function: FindChild + * SubFunction: NA + * FunctionPoints: Find Child + * EnvConditions:NA + * CaseDescription: Find Child UT. + */ +HWTEST_F(MissionStackTest, MS_oprator_018, TestSize.Level1) +{ + missionStack_->missions_.clear(); + auto missionRecord = std::make_shared(); + + missionStack_->missions_.push_back(missionRecord); + auto iter = missionStack_->missions_.begin(); + EXPECT_EQ((*iter), missionStack_->FindChild(0)); +} + } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/pending_want_manager_test/pending_want_manager_test.cpp b/services/abilitymgr/test/unittest/phone/pending_want_manager_test/pending_want_manager_test.cpp index deb0a4289c3..b770c025daa 100644 --- a/services/abilitymgr/test/unittest/phone/pending_want_manager_test/pending_want_manager_test.cpp +++ b/services/abilitymgr/test/unittest/phone/pending_want_manager_test/pending_want_manager_test.cpp @@ -158,7 +158,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_0100, TestSize.Level1) WantSenderInfo wantSenderInfo; pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); - EXPECT_EQ(pendingManager_->GetWantSender(callingUid, uid, wantSenderInfo, nullptr), nullptr); + EXPECT_EQ(pendingManager_->GetWantSender(callingUid, uid, false, wantSenderInfo, nullptr), nullptr); } /* @@ -173,7 +173,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_0200, TestSize.Level1) WantSenderInfo wantSenderInfo; pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); - EXPECT_EQ(pendingManager_->GetWantSender(callingUid, uid, wantSenderInfo, nullptr), nullptr); + EXPECT_EQ(pendingManager_->GetWantSender(callingUid, uid, false, wantSenderInfo, nullptr), nullptr); } /* @@ -188,7 +188,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_0300, TestSize.Level1) WantSenderInfo wantSenderInfo; pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); - EXPECT_EQ(pendingManager_->GetWantSender(callingUid, uid, wantSenderInfo, nullptr), nullptr); + EXPECT_EQ(pendingManager_->GetWantSender(callingUid, uid, false, wantSenderInfo, nullptr), nullptr); } /* @@ -203,7 +203,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_0400, TestSize.Level1) WantSenderInfo wantSenderInfo; pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); - EXPECT_EQ(pendingManager_->GetWantSender(callingUid, uid, wantSenderInfo, nullptr), nullptr); + EXPECT_EQ(pendingManager_->GetWantSender(callingUid, uid, false, wantSenderInfo, nullptr), nullptr); } /* @@ -217,7 +217,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_0500, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, static_cast(Flags::NO_BUILD_FLAG), 0); - EXPECT_TRUE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_TRUE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); EXPECT_EQ(pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr), nullptr); @@ -234,7 +234,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_0600, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); EXPECT_NE(pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr), nullptr); @@ -251,7 +251,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_0700, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); EXPECT_NE(pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr), nullptr); @@ -273,7 +273,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_0800, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); EXPECT_NE(pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr), nullptr); @@ -295,7 +295,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_0900, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); EXPECT_NE(pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr), nullptr); @@ -327,7 +327,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_1000, TestSize.Level1) want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); wantSenderInfo.allWants.clear(); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); EXPECT_NE(pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr), nullptr); @@ -492,7 +492,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_1500, TestSize.Level1) want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); wantSenderInfo.allWants.clear(); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); auto pendingRecord = pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr); @@ -526,7 +526,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_1700, TestSize.Level1) want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); wantSenderInfo.allWants.clear(); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); EXPECT_NE(pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr), nullptr); @@ -557,7 +557,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_1900, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); auto pendingRecord = pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr); @@ -588,7 +588,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_2100, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); auto pendingRecord = pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr); @@ -619,7 +619,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_2300, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); auto pendingRecord = pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr); @@ -650,7 +650,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_2500, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); auto pendingRecord = pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr); @@ -681,7 +681,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_2700, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); auto pendingRecord = pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr); @@ -701,7 +701,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_2800, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); auto pendingRecord = iface_cast( @@ -723,7 +723,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_2900, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); auto pendingRecord = iface_cast( @@ -746,7 +746,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_3000, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); auto pendingRecord = iface_cast( @@ -770,14 +770,14 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_3100, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); auto pendingRecord = iface_cast( pendingManager_->GetWantSenderLocked(1, 1, wantSenderInfo.userId, wantSenderInfo, nullptr)->AsObject()); EXPECT_NE(pendingRecord, nullptr); pendingManager_->RegisterCancelListener(pendingRecord, cance); - pendingManager_->CancelWantSender(0, 0, pendingRecord); + pendingManager_->CancelWantSender(0, 0, false, pendingRecord); EXPECT_TRUE(CancelReceiver::sendCount == 100); EXPECT_TRUE((int)pendingManager_->wantRecords_.size() == 0); } @@ -793,7 +793,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_3200, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); auto pendingRecord = iface_cast( @@ -816,7 +816,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_3300, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); auto pendingRecord = iface_cast( @@ -837,7 +837,7 @@ HWTEST_F(PendingWantManagerTest, PendingWantManagerTest_3400, TestSize.Level1) ElementName element("device", "bundleName", "abilityName"); want.SetElement(element); WantSenderInfo wantSenderInfo = MakeWantSenderInfo(want, 0, 0); - EXPECT_FALSE(((int)wantSenderInfo.flags & (int)Flags::NO_BUILD_FLAG) != 0); + EXPECT_FALSE(((unsigned int)wantSenderInfo.flags & (unsigned int)Flags::NO_BUILD_FLAG) != 0); pendingManager_ = std::make_shared(); EXPECT_NE(pendingManager_, nullptr); auto pendingRecord = iface_cast( diff --git a/services/abilitymgr/test/unittest/phone/resume_mission_container_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/resume_mission_container_test/BUILD.gn new file mode 100644 index 00000000000..62a3eed21ce --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/resume_mission_container_test/BUILD.gn @@ -0,0 +1,59 @@ +# 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/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "aafwk_standard/abilitymgr" + +ohos_unittest("resume_mission_container_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/aafwk/standard/services/test/mock/include", + ] + + sources = [ "resume_mission_container_test.cpp" ] + + configs = [ "${services_path}/abilitymgr:abilityms_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}/want:want", + "${services_path}/abilitymgr/test:abilityms_test_source", + "${services_path}/abilitymgr/test/mock/libs/aakit:aakit_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":resume_mission_container_test" ] +} diff --git a/services/abilitymgr/test/unittest/phone/resume_mission_container_test/resume_mission_container_test.cpp b/services/abilitymgr/test/unittest/phone/resume_mission_container_test/resume_mission_container_test.cpp new file mode 100644 index 00000000000..a5cd986a518 --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/resume_mission_container_test/resume_mission_container_test.cpp @@ -0,0 +1,169 @@ +/* + * 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 +#define private public +#include "resume_mission_container.h" +#undef private +#include "ability_manager_service.h" + +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace AAFwk { +class MissionRecordTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void MissionRecordTest::SetUpTestCase(void) +{} +void MissionRecordTest::TearDownTestCase(void) +{} +void MissionRecordTest::SetUp(void) +{} +void MissionRecordTest::TearDown(void) +{} + +/* + * Feature: ResumeMissionContainer + * Function: NA + * SubFunction: NA + * FunctionPoints: Resume Mission Container + * EnvConditions:NA + * CaseDescription: Resume Mission Container UT. + */ +HWTEST_F(MissionRecordTest, Save_01, TestSize.Level1) +{ + + auto eventLoop = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); + auto handler = + std::make_shared(eventLoop, OHOS::DelayedSingleton::GetInstance()); + auto resumeMissionContainer = std::make_shared(handler); + resumeMissionContainer->missionMaps_.clear(); + std::string bundleName = "com.ix.aafwk.moduletest"; + auto mission = std::make_shared(bundleName); + resumeMissionContainer->Save(mission); + EXPECT_TRUE(1 == resumeMissionContainer->missionMaps_.size()); +} + +/* + * Feature: ResumeMissionContainer + * Function: NA + * SubFunction: NA + * FunctionPoints: Resume Mission Container + * EnvConditions:NA + * CaseDescription: Resume Mission Container UT. + */ +HWTEST_F(MissionRecordTest, Resume_01, TestSize.Level1) +{ + auto eventLoop = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); + auto handler = + std::make_shared(eventLoop, OHOS::DelayedSingleton::GetInstance()); + auto resumeMissionContainer = std::make_shared(handler); + resumeMissionContainer->missionMaps_.clear(); + std::string bundleName = "com.ix.aafwk.moduletest"; + auto mission = std::make_shared(bundleName); + + auto missionId = mission->GetMissionRecordId(); + std::shared_ptr backup; + backup = std::make_shared(mission); + resumeMissionContainer->missionMaps_.emplace(missionId, backup); + + resumeMissionContainer->Resume(mission); + EXPECT_TRUE(0 == resumeMissionContainer->missionMaps_.size()); +} + +/* + * Feature: ResumeMissionContainer + * Function: NA + * SubFunction: NA + * FunctionPoints: Resume Mission Container + * EnvConditions:NA + * CaseDescription: Resume Mission Container UT. + */ +HWTEST_F(MissionRecordTest, Remove_01, TestSize.Level1) +{ + auto eventLoop = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); + auto handler = + std::make_shared(eventLoop, OHOS::DelayedSingleton::GetInstance()); + auto resumeMissionContainer = std::make_shared(handler); + resumeMissionContainer->missionMaps_.clear(); + std::string bundleName = "com.ix.aafwk.moduletest"; + auto mission = std::make_shared(bundleName); + + auto missionId = mission->GetMissionRecordId(); + std::shared_ptr backup; + backup = std::make_shared(mission); + resumeMissionContainer->missionMaps_.emplace(missionId, backup); + + resumeMissionContainer->Remove(missionId); + EXPECT_TRUE(0 == resumeMissionContainer->missionMaps_.size()); +} + +/* + * Feature: ResumeMissionContainer + * Function: NA + * SubFunction: NA + * FunctionPoints: Resume Mission Container + * EnvConditions:NA + * CaseDescription: Resume Mission Container UT. + */ +HWTEST_F(MissionRecordTest, IsResume_01, TestSize.Level1) +{ + auto eventLoop = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); + auto handler = + std::make_shared(eventLoop, OHOS::DelayedSingleton::GetInstance()); + auto resumeMissionContainer = std::make_shared(handler); + resumeMissionContainer->missionMaps_.clear(); + std::string bundleName = "com.ix.aafwk.moduletest"; + auto mission = std::make_shared(bundleName); + + auto missionId = mission->GetMissionRecordId(); + std::shared_ptr backup; + backup = std::make_shared(mission); + resumeMissionContainer->missionMaps_.emplace(missionId, backup); + + EXPECT_EQ(true, resumeMissionContainer->IsResume(missionId)); +} + +/* + * Feature: ResumeMissionContainer + * Function: NA + * SubFunction: NA + * FunctionPoints: Resume Mission Container + * EnvConditions:NA + * CaseDescription: Resume Mission Container UT. + */ +HWTEST_F(MissionRecordTest, IsResume_02, TestSize.Level1) +{ + auto eventLoop = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); + auto handler = + std::make_shared(eventLoop, OHOS::DelayedSingleton::GetInstance()); + auto resumeMissionContainer = std::make_shared(handler); + resumeMissionContainer->missionMaps_.clear(); + std::string bundleName = "com.ix.aafwk.moduletest"; + auto mission = std::make_shared(bundleName); + auto missionId = mission->GetMissionRecordId(); + + EXPECT_EQ(false, resumeMissionContainer->IsResume(missionId)); +} + +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/terminate_ability_test/terminate_ability_test.cpp b/services/abilitymgr/test/unittest/phone/terminate_ability_test/terminate_ability_test.cpp index 11fb4dcd8bc..ea4a294b9a6 100755 --- a/services/abilitymgr/test/unittest/phone/terminate_ability_test/terminate_ability_test.cpp +++ b/services/abilitymgr/test/unittest/phone/terminate_ability_test/terminate_ability_test.cpp @@ -64,6 +64,9 @@ AbilityRequest GenerateAbilityRequest(const std::string &deviceName, const std:: AbilityRequest abilityRequest; abilityRequest.want = want; + AbilityInfo abilityInfo; + abilityInfo.visible = true; + abilityRequest.abilityInfo = abilityInfo; return abilityRequest; } diff --git a/services/abilitymgr/test/unittest/phone/wants_info_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/wants_info_test/BUILD.gn index 78f7255baae..3cc0c902304 100644 --- a/services/abilitymgr/test/unittest/phone/wants_info_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/wants_info_test/BUILD.gn @@ -23,6 +23,7 @@ ohos_unittest("wants_info_test") { "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", ] sources = [ "wants_info_test.cpp" ] diff --git a/services/abilitymgr/test/unittest/phone/window_info_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/window_info_test/BUILD.gn index 15018a1ec10..0bc964ec8b2 100644 --- a/services/abilitymgr/test/unittest/phone/window_info_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/window_info_test/BUILD.gn @@ -19,8 +19,12 @@ module_output_path = "aafwk_standard/abilitymgr" ohos_unittest("window_info_test") { module_out_path = module_output_path - include_dirs = - [ "${services_path}/abilitymgr/test/mock/libs/system_ability_mock" ] + include_dirs = [ + "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + ] sources = [ "window_info_test.cpp" ] diff --git a/services/test/BUILD.gn b/services/test/BUILD.gn old mode 100644 new mode 100755 index 3067295ee9e..24ae7ec09ee --- a/services/test/BUILD.gn +++ b/services/test/BUILD.gn @@ -21,7 +21,10 @@ config("aafwk_module_test_config") { configs = [ "${services_path}/abilitymgr:abilityms_config" ] - include_dirs = [ "${services_path}/test/mock/include" ] + include_dirs = [ + "${services_path}/test/mock/include", + "//third_party/jsoncpp/include", + ] } group("moduletest") { @@ -36,5 +39,6 @@ group("moduletest") { "moduletest/ipc_ability_mgr_test:moduletest", "moduletest/module_test_dump_util:module_test_dump_util", "moduletest/panding_want_manager_test:moduletest", + "//third_party/jsoncpp:jsoncpp", ] } diff --git a/services/test/mock/include/mock_ability_manager_proxy.h b/services/test/mock/include/mock_ability_manager_proxy.h index 4111964eb1a..06eb44be413 100644 --- a/services/test/mock/include/mock_ability_manager_proxy.h +++ b/services/test/mock/include/mock_ability_manager_proxy.h @@ -52,7 +52,7 @@ public: MOCK_METHOD2(TerminateAbilityResult, int(const sptr &, int startId)); MOCK_METHOD1(StopServiceAbility, int(const Want &)); MOCK_METHOD1(GetAllStackInfo, int(StackInfo &stackInfo)); - MOCK_METHOD3(GetRecentMissions, int(const int32_t, const int32_t, std::vector &)); + MOCK_METHOD3(GetRecentMissions, int(const int32_t, const int32_t, std::vector &)); MOCK_METHOD2(GetMissionSnapshot, int(const int32_t, MissionSnapshotInfo &)); MOCK_METHOD1(RemoveMission, int(int)); MOCK_METHOD1(RemoveStack, int(int)); diff --git a/services/test/mock/include/mock_ability_mgr_service.h b/services/test/mock/include/mock_ability_mgr_service.h index fe3ff466222..bf07cbcf4f3 100644 --- a/services/test/mock/include/mock_ability_mgr_service.h +++ b/services/test/mock/include/mock_ability_mgr_service.h @@ -61,6 +61,7 @@ public: MOCK_METHOD1(UnlockMission, int(int)); MOCK_METHOD2(SetMissionDescriptionInfo, int(const sptr &token, const MissionDescriptionInfo &info)); MOCK_METHOD0(GetMissionLockModeState, int()); + MOCK_METHOD1(UpdateConfiguration, int(const DummyConfiguration &)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo &wantSenderInfo, const sptr &callerToken)); MOCK_METHOD2(SendWantSender, int(const sptr &target, const SenderInfo &senderInfo)); @@ -74,6 +75,18 @@ public: MOCK_METHOD2(UnregisterCancelListener, void(const sptr &sender, const sptr &receiver)); MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); + MOCK_METHOD4(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode)); + MOCK_METHOD1(MoveMissionToFloatingStack, int(const MissionOption &missionOption)); + MOCK_METHOD1(MoveMissionToSplitScreenStack, int(const MissionOption &missionOption)); + MOCK_METHOD2( + ChangeFocusAbility, int(const sptr &lostFocusToken, const sptr &getFocusToken)); + MOCK_METHOD1(MinimizeMultiWindow, int(int missionId)); + MOCK_METHOD1(MaximizeMultiWindow, int(int missionId)); + MOCK_METHOD1(GetFloatingMissions, int(std::vector &list)); + MOCK_METHOD1(CloseMultiWindow, int(int missionId)); + MOCK_METHOD1(SetMissionStackSetting, int(const StackSetting &stackSetting)); + void Wait() { sem_.Wait(); diff --git a/services/test/mock/include/mock_ability_scheduler.h b/services/test/mock/include/mock_ability_scheduler.h index 88b60273fc1..0a650ea3033 100644 --- a/services/test/mock/include/mock_ability_scheduler.h +++ b/services/test/mock/include/mock_ability_scheduler.h @@ -34,7 +34,10 @@ public: MOCK_METHOD0(AsObject, sptr()); MOCK_METHOD1(ScheduleSaveAbilityState, void(PacMap &outState)); MOCK_METHOD1(ScheduleRestoreAbilityState, void(const PacMap &inState)); + MOCK_METHOD1(ScheduleUpdateConfiguration, void(const DummyConfiguration &)); MOCK_METHOD1(ScheduleNewWant, void(const Want &want)); + MOCK_METHOD1(NotifyTopActiveAbilityChanged, void(bool flag)); + MOCK_METHOD2(NotifyMultiWinModeChanged, void(int32_t winModeKey, bool flag)); std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) { @@ -87,6 +90,18 @@ public: { return -1; } + + virtual Uri NormalizeUri(const Uri &uri) override + { + Uri urivalue(""); + return urivalue; + } + + virtual Uri DenormalizeUri(const Uri &uri) override + { + Uri urivalue(""); + return urivalue; + } }; } // namespace AAFwk diff --git a/services/test/mock/include/mock_ability_scheduler_stub.h b/services/test/mock/include/mock_ability_scheduler_stub.h index bd061029672..95f85d1ab02 100644 --- a/services/test/mock/include/mock_ability_scheduler_stub.h +++ b/services/test/mock/include/mock_ability_scheduler_stub.h @@ -30,6 +30,7 @@ public: MOCK_METHOD3(ScheduleCommandAbility, void(const Want &, bool, int)); MOCK_METHOD1(ScheduleSaveAbilityState, void(PacMap &)); MOCK_METHOD1(ScheduleRestoreAbilityState, void(const PacMap &)); + MOCK_METHOD1(ScheduleUpdateConfiguration, void(const DummyConfiguration &)); MOCK_METHOD2(GetFileTypes, std::vector(const Uri &, const std::string &)); MOCK_METHOD2(OpenFile, int(const Uri &, const std::string &)); MOCK_METHOD2(Insert, int(const Uri &, const ValuesBucket &)); @@ -41,6 +42,10 @@ public: MOCK_METHOD2(OpenRawFile, int(const Uri &uri, const std::string &mode)); MOCK_METHOD2(Reload, bool(const Uri &uri, const PacMap &extras)); MOCK_METHOD2(BatchInsert, int(const Uri &uri, const std::vector &values)); + MOCK_METHOD1(NormalizeUri, Uri(const Uri &)); + MOCK_METHOD1(DenormalizeUri, Uri(const Uri &)); + MOCK_METHOD2(NotifyMultiWinModeChanged, void(int32_t winModeKey, bool flag)); + MOCK_METHOD1(NotifyTopActiveAbilityChanged, void(bool flag)); }; } // namespace AAFwk diff --git a/services/test/mock/include/mock_app_mgr_client.h b/services/test/mock/include/mock_app_mgr_client.h index cf65f232e6b..ebf7a4dc65f 100644 --- a/services/test/mock/include/mock_app_mgr_client.h +++ b/services/test/mock/include/mock_app_mgr_client.h @@ -25,30 +25,21 @@ namespace AppExecFwk { class MockAppMgrClient : public AppMgrClient { public: + MockAppMgrClient(); + ~MockAppMgrClient(); MOCK_METHOD4(LoadAbility, AppMgrResultCode(const sptr &, const sptr &, const AbilityInfo &, const ApplicationInfo &)); - MOCK_METHOD1(TerminateAbility, AppMgrResultCode(const sptr &)); MOCK_METHOD2(UpdateAbilityState, AppMgrResultCode(const sptr &token, const AbilityState state)); MOCK_METHOD1(KillApplication, AppMgrResultCode(const std::string &)); MOCK_METHOD1(KillProcessByAbilityToken, AppMgrResultCode(const sptr &token)); MOCK_METHOD4(CompelVerifyPermission, int(const std::string &permission, int pid, int uid, std::string &message)); MOCK_METHOD1(AbilityAttachTimeOut, void(const sptr &token)); + AppMgrResultCode AbilityBehaviorAnalysis(const sptr &token, const sptr &preToken, - const int32_t visibility, const int32_t perceptibility, const int32_t connectionState) override - { - return AppMgrResultCode::RESULT_OK; - } - - AppMgrResultCode ConnectAppMgrService() override - { - return AppMgrResultCode::RESULT_OK; - } - - AppMgrResultCode RegisterAppStateCallback(const sptr &callback) override - { - return AppMgrResultCode::RESULT_OK; - } + const int32_t visibility, const int32_t perceptibility, const int32_t connectionState) override; + AppMgrResultCode ConnectAppMgrService() override; + AppMgrResultCode RegisterAppStateCallback(const sptr &callback) override; }; } // namespace AppExecFwk diff --git a/services/test/mock/include/mock_bundle_mgr.h b/services/test/mock/include/mock_bundle_mgr.h index f02fc0731ca..cdbe7e59d54 100644 --- a/services/test/mock/include/mock_bundle_mgr.h +++ b/services/test/mock/include/mock_bundle_mgr.h @@ -47,6 +47,10 @@ auto HiWordInfo = [](std::string bundleName, AbilityInfo &abilityInfo, ElementNa abilityInfo.applicationInfo.name = "Helloworld"; abilityInfo.type = AbilityType::PAGE; abilityInfo.applicationInfo.isLauncherApp = true; + + if (elementTemp.GetAbilityName() == "luncher") { + abilityInfo.configChanges.push_back("fontSize"); + } return true; }; @@ -71,6 +75,17 @@ auto HiMusicInfo = [](std::string bundleName, AbilityInfo &abilityInfo, ElementN abilityInfo.process = "p2"; abilityInfo.launchMode = LaunchMode::SINGLETON; } + if (elementTemp.GetAbilityName() == "Music") { + abilityInfo.process = "p1"; + abilityInfo.launchMode = LaunchMode::STANDARD; + abilityInfo.configChanges.push_back("layout"); + } + + if (elementTemp.GetAbilityName() == "MusicTon") { + abilityInfo.process = "p1"; + abilityInfo.launchMode = LaunchMode::SINGLETON; + abilityInfo.configChanges.push_back("layout"); + } return true; }; @@ -88,6 +103,10 @@ auto HiRadioInfo = [](std::string bundleName, AbilityInfo &abilityInfo, ElementN if (elementTemp.GetAbilityName() == "RadioTopAbility") { abilityInfo.launchMode = LaunchMode::SINGLETON; } + if (elementTemp.GetAbilityName() == "Radio") { + abilityInfo.launchMode = LaunchMode::STANDARD; + abilityInfo.configChanges.push_back("orientation"); + } return true; }; @@ -235,6 +254,7 @@ public: MOCK_METHOD3(GetFormsInfoByModule, bool(const std::string &bundleName, const std::string &moduleName, std::vector &formInfos)); MOCK_METHOD2(GetShortcutInfos, bool(const std::string &bundleName, std::vector &shortcutInfos)); + MOCK_METHOD2(QueryAbilityInfos, bool(const Want &want, std::vector &abilityInfos)); }; class BundleMgrStub : public IRemoteStub { @@ -301,12 +321,18 @@ public: bool(const std::string &bundleName, const std::string &moduleName, std::vector &formInfos)); MOCK_METHOD2(GetShortcutInfos, bool(const std::string &bundleName, std::vector &shortcutInfos)); MOCK_METHOD2(GetUidByBundleName, int(const std::string &bundleName, const int userId)); + MOCK_METHOD2(GetModuleUsageRecords, bool(const int32_t number, std::vector &moduleUsageRecords)); + bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override; bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override; + bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) override + { + return true; + }; bool GetApplicationInfo( const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; - - + bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) override; BundleMgrService() { abilityInfoMap_.emplace(COM_IX_HIWORLD, HiWordInfo); diff --git a/services/test/mock/src/mock_app_mgr_client.cpp b/services/test/mock/src/mock_app_mgr_client.cpp new file mode 100644 index 00000000000..ed8dd2251ea --- /dev/null +++ b/services/test/mock/src/mock_app_mgr_client.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 "mock_app_mgr_client.h" + +namespace OHOS { +namespace AppExecFwk { + +MockAppMgrClient::MockAppMgrClient() +{} +MockAppMgrClient::~MockAppMgrClient() +{} + +AppMgrResultCode MockAppMgrClient::AbilityBehaviorAnalysis(const sptr &token, + const sptr &preToken, const int32_t visibility, const int32_t perceptibility, + const int32_t connectionState) +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode MockAppMgrClient::ConnectAppMgrService() +{ + return AppMgrResultCode::RESULT_OK; +} + +AppMgrResultCode MockAppMgrClient::RegisterAppStateCallback(const sptr &callback) +{ + return AppMgrResultCode::RESULT_OK; +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/test/mock/src/mock_bundle_mgr.cpp b/services/test/mock/src/mock_bundle_mgr.cpp index a7b61f255bb..16907c1ab76 100755 --- a/services/test/mock/src/mock_bundle_mgr.cpp +++ b/services/test/mock/src/mock_bundle_mgr.cpp @@ -35,6 +35,7 @@ bool BundleMgrProxy::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abil if (eleName.GetBundleName().empty()) { return false; } + abilityInfo.visible = true; abilityInfo.name = eleName.GetAbilityName(); abilityInfo.bundleName = eleName.GetBundleName(); abilityInfo.applicationName = eleName.GetAbilityName() + "App"; @@ -71,7 +72,7 @@ int BundleMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessagePa } bool BundleMgrService::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) -{ +{ bundleInfo.uid = 0; return true; } @@ -86,6 +87,7 @@ bool BundleMgrService::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &ab std::string abilityNameTemp = elementTemp.GetAbilityName(); std::string bundleNameTemp = elementTemp.GetBundleName(); abilityInfo.deviceId = elementTemp.GetDeviceID(); + abilityInfo.visible = true; if (bundleNameTemp.empty() || abilityNameTemp.empty()) { return false; @@ -153,5 +155,11 @@ bool BundleMgrService::CheckWantEntity(const AAFwk::Want &want, AbilityInfo &abi return false; } +bool BundleMgrService::NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) +{ + return true; +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/services/test/moduletest/ability_mgr_service_test/BUILD.gn b/services/test/moduletest/ability_mgr_service_test/BUILD.gn old mode 100644 new mode 100755 index 92214c2afcc..e65bc20a93b --- a/services/test/moduletest/ability_mgr_service_test/BUILD.gn +++ b/services/test/moduletest/ability_mgr_service_test/BUILD.gn @@ -19,10 +19,14 @@ module_output_path = "aafwk_standard/mstabilitymgrservice" ohos_moduletest("ability_mgr_module_test") { module_out_path = module_output_path - include_dirs = [ "${services_path}/test/mock/include" ] + include_dirs = [ + "${services_path}/test/mock/include", + "//third_party/jsoncpp/include", + ] sources = [ "ability_mgr_module_test.cpp" ] sources += [ + "//foundation/aafwk/standard/services/abilitymgr/src/aafwk_dummy_configuration.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_connect_callback_stub.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_connect_manager.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_event_handler.cpp", @@ -46,6 +50,7 @@ ohos_moduletest("ability_mgr_module_test") { "//foundation/aafwk/standard/services/abilitymgr/src/lifecycle_deal.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/lifecycle_state_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/mission_description_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/mission_option.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/mission_record.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/mission_record_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/mission_snapshot_info.cpp", @@ -62,6 +67,7 @@ ohos_moduletest("ability_mgr_module_test") { "//foundation/aafwk/standard/services/abilitymgr/src/want_sender_stub.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/wants_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/sa_mgr/src/sa_mgr_client_mock.cpp", + "//foundation/aafwk/standard/services/test/mock/src/mock_app_mgr_client.cpp", "//foundation/aafwk/standard/services/test/mock/src/mock_bundle_mgr.cpp", ] @@ -88,6 +94,7 @@ ohos_moduletest("ability_mgr_module_test") { "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp b/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp index 0c26e9cf212..ab320968aab 100644 --- a/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp +++ b/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp @@ -192,6 +192,7 @@ AbilityInfo AbilityMgrModuleTest::CreateAbilityInfo( const std::string &name, const std::string &appName, const std::string &bundleName) { AbilityInfo abilityInfo; + abilityInfo.visible = true; abilityInfo.name = name; abilityInfo.applicationName = appName; abilityInfo.bundleName = bundleName; @@ -341,10 +342,10 @@ void AbilityMgrModuleTest::CreateServiceRecord(std::shared_ptr &r const sptr &callback1, const sptr &callback2) { record = abilityMgrServ_->connectManager_->GetServiceRecordByElementName(want.GetElement().GetURI()); - ASSERT_TRUE(record); - ASSERT_TRUE(abilityMgrServ_->connectManager_->IsAbilityConnected( + EXPECT_TRUE(record); + EXPECT_TRUE(abilityMgrServ_->connectManager_->IsAbilityConnected( record, abilityMgrServ_->GetConnectRecordListByCallback(callback1))); - ASSERT_TRUE(abilityMgrServ_->connectManager_->IsAbilityConnected( + EXPECT_TRUE(abilityMgrServ_->connectManager_->IsAbilityConnected( record, abilityMgrServ_->GetConnectRecordListByCallback(callback2))); EXPECT_EQ((std::size_t)2, record->GetConnectRecordList().size()); record->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); @@ -427,11 +428,11 @@ void AbilityMgrModuleTest::WaitAMS() */ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_001, TestSize.Level1) { - ASSERT_TRUE(abilityMgrServ_); - ASSERT_TRUE(mockAppMgrClient_); + EXPECT_TRUE(abilityMgrServ_); + EXPECT_TRUE(mockAppMgrClient_); auto stackManager = abilityMgrServ_->GetStackManager(); - ASSERT_TRUE(stackManager); + EXPECT_TRUE(stackManager); std::string abilityName = "MusicAbility"; std::string bundleName = "com.ix.hiMusic"; @@ -458,7 +459,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_001, TestSize.Level1) EXPECT_TRUE(testToken); auto testAbilityRecord = stackManager->GetAbilityRecordByToken(testToken); - ASSERT_TRUE(testAbilityRecord); + EXPECT_TRUE(testAbilityRecord); EXPECT_EQ(testAbilityRecord->GetRequestCode(), testRequestCode); } @@ -488,7 +489,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_002, TestSize.Level1) std::shared_ptr abilityRecord2 = AbilityRecord::CreateAbilityRecord(abilityRequest); abilityRecord2->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*scheduler, AsObject()).Times(2); abilityRecord2->SetScheduler(scheduler); @@ -548,7 +549,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_003, TestSize.Level1) const sptr callback(new AbilityConnectionProxy(stub)); std::shared_ptr connectRecord = ConnectionRecord::CreateConnectionRecord(abilityRecord->GetToken(), abilityRecord, callback); - ASSERT_TRUE(connectRecord != nullptr); + EXPECT_TRUE(connectRecord != nullptr); connectRecord->SetConnectState(ConnectionState::CONNECTED); abilityRecord->AddConnectRecordToList(connectRecord); std::list > connectList; @@ -563,6 +564,9 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_003, TestSize.Level1) abilityMgrServ_->RemoveAllServiceRecord(); curMissionStack->RemoveAll(); + + testing::Mock::AllowLeak(stub); + testing::Mock::AllowLeak(callback); } /* @@ -584,14 +588,14 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_004, TestSize.Level1) abilityMgrServ_->OnStart(); WaitAMS(); - ASSERT_TRUE(abilityMgrServ_->dataAbilityManager_); + EXPECT_TRUE(abilityMgrServ_->dataAbilityManager_); state = abilityMgrServ_->QueryServiceState(); EXPECT_EQ(state, ServiceRunningState::STATE_RUNNING); auto handler = abilityMgrServ_->GetEventHandler(); - ASSERT_TRUE(handler); + EXPECT_TRUE(handler); auto eventRunner = handler->GetEventRunner(); - ASSERT_TRUE(eventRunner); + EXPECT_TRUE(eventRunner); EXPECT_TRUE(eventRunner->IsRunning()); abilityMgrServ_->OnStop(); @@ -644,7 +648,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_005, TestSize.Level1) */ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_006, TestSize.Level1) { - ASSERT_TRUE(abilityMgrServ_); + EXPECT_TRUE(abilityMgrServ_); std::string abilityName = "MusicAbility"; std::string bundleName = "com.ix.hiMusic"; @@ -654,14 +658,14 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_006, TestSize.Level1) abilityRequest.abilityInfo = CreateAbilityInfo(abilityName, bundleName, bundleName); abilityRequest.appInfo = CreateAppInfo(bundleName, bundleName); std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); abilityRecord->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVATING); std::shared_ptr mission = std::make_shared(bundleName); - ASSERT_TRUE(mission); + EXPECT_TRUE(mission); mission->AddAbilityRecordToTop(abilityRecord); auto stackManager_ = abilityMgrServ_->GetStackManager(); - ASSERT_TRUE(stackManager_); + EXPECT_TRUE(stackManager_); std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); curMissionStack->AddMissionRecordToTop(mission); sptr scheduler(new MockAbilityScheduler()); @@ -673,6 +677,8 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_006, TestSize.Level1) abilityMgrServ_->handler_ = handler; EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); abilityMgrServ_->AttachAbilityThread(scheduler, abilityRecord->GetToken()); + + testing::Mock::AllowLeak(scheduler); } /* @@ -694,15 +700,15 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_007, TestSize.Level1) abilityRequest.abilityInfo = CreateAbilityInfo(abilityName, bundleName, bundleName); abilityRequest.appInfo = CreateAppInfo(bundleName, bundleName); std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); abilityRecord->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVATING); std::shared_ptr mission = std::make_shared(bundleName); - ASSERT_TRUE(mission); + EXPECT_TRUE(mission); mission->AddAbilityRecordToTop(abilityRecord); auto stackManager_ = abilityMgrServ_->GetStackManager(); - ASSERT_TRUE(stackManager_); + EXPECT_TRUE(stackManager_); std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); - ASSERT_TRUE(curMissionStack); + EXPECT_TRUE(curMissionStack); curMissionStack->AddMissionRecordToTop(mission); int result = abilityMgrServ_->AbilityTransitionDone(abilityRecord->GetToken(), OHOS::AAFwk::AbilityState::ACTIVE); @@ -743,19 +749,19 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_008, TestSize.Level1) EXPECT_EQ((std::size_t)1, abilityMgrServ_->connectManager_->connectMap_.size()); EXPECT_EQ((std::size_t)1, abilityMgrServ_->connectManager_->serviceMap_.size()); std::shared_ptr record = abilityMgrServ_->connectManager_->GetServiceRecordByToken(testToken); - ASSERT_TRUE(record); + EXPECT_TRUE(record); ElementName element; std::shared_ptr connectRecord = record->GetConnectRecordList().front(); - ASSERT_TRUE(connectRecord); + EXPECT_TRUE(connectRecord); sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*scheduler, AsObject()).Times(1); EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(1); abilityMgrServ_->AttachAbilityThread(scheduler, record->GetToken()); - ASSERT_TRUE(record->isReady_); + EXPECT_TRUE(record->isReady_); EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(_, _)).Times(1); abilityMgrServ_->OnAbilityRequestDone( @@ -764,7 +770,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_008, TestSize.Level1) EXPECT_CALL(*scheduler, ScheduleConnectAbility(_)).Times(1); abilityMgrServ_->AbilityTransitionDone(record->GetToken(), AbilityLifeCycleState::ABILITY_STATE_INACTIVE); - ASSERT_TRUE(record->GetConnectingRecord()); + EXPECT_TRUE(record->GetConnectingRecord()); EXPECT_EQ(OHOS::AAFwk::ConnectionState::CONNECTING, connectRecord->GetConnectState()); EXPECT_CALL(*stub, OnAbilityConnectDone(_, _, _)).Times(1); @@ -775,6 +781,10 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_008, TestSize.Level1) abilityMgrServ_->RemoveAllServiceRecord(); curMissionStack->RemoveAll(); + + testing::Mock::AllowLeak(scheduler); + testing::Mock::AllowLeak(stub); + testing::Mock::AllowLeak(callback); } /* @@ -799,14 +809,14 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_009, TestSize.Level1) abilityMgrServ_->ConnectAbility(want, callback, nullptr); std::shared_ptr record = abilityMgrServ_->connectManager_->GetServiceRecordByElementName(want.GetElement().GetURI()); - ASSERT_TRUE(record); + EXPECT_TRUE(record); std::shared_ptr connectRecord = record->GetConnectingRecord(); - ASSERT_TRUE(connectRecord); + EXPECT_TRUE(connectRecord); connectRecord->SetConnectState(ConnectionState::CONNECTED); record->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*scheduler, AsObject()).Times(2); record->SetScheduler(scheduler); EXPECT_CALL(*scheduler, ScheduleDisconnectAbility(_)).Times(1); @@ -828,6 +838,10 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_009, TestSize.Level1) abilityMgrServ_->OnAbilityRequestDone( record->GetToken(), (int32_t)OHOS::AppExecFwk::AbilityState::ABILITY_STATE_BACKGROUND); EXPECT_EQ((std::size_t)0, abilityMgrServ_->connectManager_->GetServiceMap().size()); + + testing::Mock::AllowLeak(scheduler); + testing::Mock::AllowLeak(stub); + testing::Mock::AllowLeak(callback); } /* @@ -876,7 +890,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_010, TestSize.Level1) } sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*scheduler, AsObject()).Times(4); record1->SetScheduler(scheduler); record2->SetScheduler(scheduler); @@ -889,6 +903,11 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_010, TestSize.Level1) EXPECT_CALL(*stub2, OnAbilityDisconnectDone(_, _)).Times(2); CheckTestRecord(record1, record2, callback1, callback2); + testing::Mock::AllowLeak(stub1); + testing::Mock::AllowLeak(callback1); + testing::Mock::AllowLeak(stub2); + testing::Mock::AllowLeak(callback2); + testing::Mock::AllowLeak(scheduler); } /* @@ -928,11 +947,11 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_011, TestSize.Level1) EXPECT_FALSE(record->IsCreateByConnect()); sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*scheduler, AsObject()).Times(2); EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(1); abilityMgrServ_->AttachAbilityThread(scheduler, record->GetToken()); - ASSERT_TRUE(record->isReady_); + EXPECT_TRUE(record->isReady_); EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(_, _)).Times(1); abilityMgrServ_->OnAbilityRequestDone( @@ -959,6 +978,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_011, TestSize.Level1) } EXPECT_EQ(4, testId); abilityMgrServ_->RemoveAllServiceRecord(); + testing::Mock::AllowLeak(scheduler); } /* * Feature: AaFwk @@ -993,15 +1013,15 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_012, TestSize.Level1) EXPECT_TRUE(testToken); std::shared_ptr record = abilityMgrServ_->GetServiceRecordByElementName(want.GetElement().GetURI()); - ASSERT_TRUE(record); + EXPECT_TRUE(record); EXPECT_FALSE(record->IsCreateByConnect()); sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*scheduler, AsObject()).Times(2); EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(1); abilityMgrServ_->AttachAbilityThread(scheduler, record->GetToken()); - ASSERT_TRUE(record->isReady_); + EXPECT_TRUE(record->isReady_); EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(_, _)).Times(1); abilityMgrServ_->OnAbilityRequestDone( @@ -1022,7 +1042,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_012, TestSize.Level1) EXPECT_CALL(*scheduler, ScheduleConnectAbility(_)).Times(1); abilityMgrServ_->ConnectAbility(want, callback, nullptr); std::shared_ptr connectRecord = record->GetConnectingRecord(); - ASSERT_TRUE(connectRecord); + EXPECT_TRUE(connectRecord); EXPECT_EQ((size_t)1, abilityMgrServ_->GetConnectRecordListByCallback(callback).size()); EXPECT_CALL(*stub, OnAbilityConnectDone(_, _, _)).Times(1); @@ -1030,6 +1050,10 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_012, TestSize.Level1) EXPECT_EQ(ConnectionState::CONNECTED, connectRecord->GetConnectState()); abilityMgrServ_->RemoveAllServiceRecord(); + + testing::Mock::AllowLeak(scheduler); + testing::Mock::AllowLeak(stub); + testing::Mock::AllowLeak(callback); } /* @@ -1092,7 +1116,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_014, TestSize.Level1) record->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*scheduler, AsObject()).Times(2); record->SetScheduler(scheduler); @@ -1109,6 +1133,8 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_014, TestSize.Level1) EXPECT_EQ((std::size_t)0, abilityMgrServ_->connectManager_->GetServiceMap().size()); abilityMgrServ_->RemoveAllServiceRecord(); + + testing::Mock::AllowLeak(scheduler); } /* @@ -1135,7 +1161,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_015, TestSize.Level1) record->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*scheduler, AsObject()).Times(2); record->SetScheduler(scheduler); @@ -1152,6 +1178,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_015, TestSize.Level1) EXPECT_EQ((std::size_t)0, abilityMgrServ_->connectManager_->GetServiceMap().size()); abilityMgrServ_->RemoveAllServiceRecord(); + testing::Mock::AllowLeak(scheduler); } /* @@ -1178,7 +1205,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_016, TestSize.Level1) record->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*scheduler, AsObject()).Times(2); record->SetScheduler(scheduler); @@ -1187,7 +1214,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_016, TestSize.Level1) EXPECT_CALL(*scheduler, ScheduleConnectAbility(_)).Times(1); abilityMgrServ_->ConnectAbility(want, callback, nullptr); std::shared_ptr connectRecord = record->GetConnectingRecord(); - ASSERT_TRUE(connectRecord); + EXPECT_TRUE(connectRecord); EXPECT_EQ((size_t)1, abilityMgrServ_->GetConnectRecordListByCallback(callback).size()); EXPECT_CALL(*stub, OnAbilityConnectDone(_, _, _)).Times(1); abilityMgrServ_->ScheduleConnectAbilityDone(record->GetToken(), nullptr); @@ -1197,6 +1224,10 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_016, TestSize.Level1) EXPECT_EQ(TERMINATE_SERVICE_IS_CONNECTED, result); abilityMgrServ_->RemoveAllServiceRecord(); + + testing::Mock::AllowLeak(scheduler); + testing::Mock::AllowLeak(stub); + testing::Mock::AllowLeak(callback); } /* @@ -1223,7 +1254,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_017, TestSize.Level1) record->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*scheduler, AsObject()).Times(2); record->SetScheduler(scheduler); @@ -1232,7 +1263,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_017, TestSize.Level1) EXPECT_CALL(*scheduler, ScheduleConnectAbility(_)).Times(1); abilityMgrServ_->ConnectAbility(want, callback, nullptr); std::shared_ptr connectRecord = record->GetConnectingRecord(); - ASSERT_TRUE(connectRecord); + EXPECT_TRUE(connectRecord); EXPECT_EQ((size_t)1, abilityMgrServ_->GetConnectRecordListByCallback(callback).size()); EXPECT_CALL(*stub, OnAbilityConnectDone(_, _, _)).Times(1); abilityMgrServ_->ScheduleConnectAbilityDone(record->GetToken(), nullptr); @@ -1242,6 +1273,10 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_017, TestSize.Level1) EXPECT_EQ(TERMINATE_SERVICE_IS_CONNECTED, result); abilityMgrServ_->RemoveAllServiceRecord(); + + testing::Mock::AllowLeak(scheduler); + testing::Mock::AllowLeak(stub); + testing::Mock::AllowLeak(callback); } /* @@ -1264,13 +1299,13 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_018, TestSize.Level1) SetActive(); abilityMgrServ_->StartAbility(want, testRequestCode); std::shared_ptr record = abilityMgrServ_->GetServiceRecordByElementName(want.GetElement().GetURI()); - ASSERT_TRUE(record); + EXPECT_TRUE(record); EXPECT_FALSE(record->IsCreateByConnect()); record->AddStartId(); record->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*scheduler, AsObject()).Times(2); record->SetScheduler(scheduler); @@ -1280,7 +1315,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_018, TestSize.Level1) abilityMgrServ_->ConnectAbility(want, callback, nullptr); std::shared_ptr connectRecord = record->GetConnectingRecord(); - ASSERT_TRUE(connectRecord); + EXPECT_TRUE(connectRecord); EXPECT_EQ((size_t)1, abilityMgrServ_->GetConnectRecordListByCallback(callback).size()); EXPECT_CALL(*stub, OnAbilityConnectDone(_, _, _)).Times(1); abilityMgrServ_->ScheduleConnectAbilityDone(record->GetToken(), nullptr); @@ -1309,6 +1344,9 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_018, TestSize.Level1) EXPECT_EQ((std::size_t)0, abilityMgrServ_->connectManager_->GetServiceMap().size()); abilityMgrServ_->RemoveAllServiceRecord(); + testing::Mock::AllowLeak(scheduler); + testing::Mock::AllowLeak(stub); + testing::Mock::AllowLeak(callback); } /* @@ -1324,7 +1362,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_019, TestSize.Level1) std::string abilityName = "MusicAbilityService"; std::string bundleName = "com.ix.hiservice"; Want want = CreateWant(abilityName, bundleName); - ASSERT_TRUE(abilityMgrServ_); + EXPECT_TRUE(abilityMgrServ_); abilityMgrServ_->RemoveAllServiceRecord(); EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); int testRequestCode = 123; @@ -1336,7 +1374,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_019, TestSize.Level1) record->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*scheduler, AsObject()).Times(2); record->SetScheduler(scheduler); sptr stub(new MockAbilityConnectCallbackStub()); @@ -1344,7 +1382,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_019, TestSize.Level1) EXPECT_CALL(*scheduler, ScheduleConnectAbility(_)).Times(1); abilityMgrServ_->ConnectAbility(want, callback, nullptr); std::shared_ptr connectRecord = record->GetConnectingRecord(); - ASSERT_TRUE(connectRecord); + EXPECT_TRUE(connectRecord); EXPECT_EQ((size_t)1, abilityMgrServ_->GetConnectRecordListByCallback(callback).size()); EXPECT_CALL(*stub, OnAbilityConnectDone(_, _, _)).Times(1); abilityMgrServ_->ScheduleConnectAbilityDone(record->GetToken(), nullptr); @@ -1371,6 +1409,10 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_019, TestSize.Level1) abilityMgrServ_->OnAbilityRequestDone( record->GetToken(), (int32_t)OHOS::AppExecFwk::AbilityState::ABILITY_STATE_BACKGROUND); EXPECT_EQ((std::size_t)0, abilityMgrServ_->connectManager_->GetServiceMap().size()); + + testing::Mock::AllowLeak(scheduler); + testing::Mock::AllowLeak(stub); + testing::Mock::AllowLeak(callback); } /* @@ -1397,10 +1439,10 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_020, TestSize.Level3) EXPECT_EQ((std::size_t)1, abilityMgrServ_->connectManager_->serviceMap_.size()); std::shared_ptr record = abilityMgrServ_->connectManager_->GetServiceRecordByElementName(want.GetElement().GetURI()); - ASSERT_TRUE(record); - ASSERT_TRUE(record->IsCreateByConnect()); + EXPECT_TRUE(record); + EXPECT_TRUE(record->IsCreateByConnect()); std::shared_ptr connectRecord = record->GetConnectingRecord(); - ASSERT_TRUE(connectRecord); + EXPECT_TRUE(connectRecord); connectRecord->SetConnectState(ConnectionState::CONNECTED); record->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); @@ -1412,6 +1454,8 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_020, TestSize.Level3) EXPECT_EQ((std::size_t)0, abilityMgrServ_->connectManager_->connectMap_.size()); abilityMgrServ_->RemoveAllServiceRecord(); + testing::Mock::AllowLeak(stub); + testing::Mock::AllowLeak(callback); } /* @@ -1424,8 +1468,8 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_020, TestSize.Level3) */ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_021, TestSize.Level1) { - ASSERT_TRUE(abilityMgrServ_); - ASSERT_TRUE(mockAppMgrClient_); + EXPECT_TRUE(abilityMgrServ_); + EXPECT_TRUE(mockAppMgrClient_); ClearStack(); std::string abilityName = "MusicSAbility"; @@ -1435,7 +1479,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_021, TestSize.Level1) Want want = CreateWant(abilityName, bundleName); Want want2 = CreateWant(abilityName2, bundleName2); sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(2); EXPECT_CALL(*mockAppMgrClient_, AbilityAttachTimeOut(_)).Times(1); EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(2); @@ -1443,20 +1487,21 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_021, TestSize.Level1) EXPECT_CALL(*scheduler, AsObject()).Times(2); abilityMgrServ_->StartAbility(want); auto testAbilityRecord = GetTopAbility(); - ASSERT_TRUE(testAbilityRecord); + EXPECT_TRUE(testAbilityRecord); abilityMgrServ_->AttachAbilityThread(scheduler, testAbilityRecord->GetToken()); SetActive(); abilityMgrServ_->StartAbility(want2); auto testAbilityRecord2 = GetTopAbility(); - ASSERT_TRUE(testAbilityRecord2); + EXPECT_TRUE(testAbilityRecord2); auto stackMgr = abilityMgrServ_->GetStackManager(); - ASSERT_TRUE(stackMgr); + EXPECT_TRUE(stackMgr); stackMgr->CompleteInactive(testAbilityRecord); testAbilityRecord->SetAbilityState(OHOS::AAFwk::AbilityState::BACKGROUND); abilityMgrServ_->HandleLoadTimeOut(testAbilityRecord2->GetEventId()); testAbilityRecord = GetTopAbility(); - ASSERT_TRUE(testAbilityRecord); + EXPECT_TRUE(testAbilityRecord); EXPECT_TRUE(testAbilityRecord->GetAbilityInfo().bundleName == bundleName); + testing::Mock::AllowLeak(scheduler); } /* @@ -1469,8 +1514,8 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_021, TestSize.Level1) */ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_022, TestSize.Level1) { - ASSERT_TRUE(abilityMgrServ_); - ASSERT_TRUE(mockAppMgrClient_); + EXPECT_TRUE(abilityMgrServ_); + EXPECT_TRUE(mockAppMgrClient_); ClearStack(); std::string abilityName = "TVAbility"; @@ -1480,7 +1525,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_022, TestSize.Level1) Want want = CreateWant(abilityName, bundleName); Want want2 = CreateWant(abilityName2, bundleName2); sptr scheduler = new MockAbilityScheduler(); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(2); EXPECT_CALL(*mockAppMgrClient_, AbilityAttachTimeOut(_)).Times(1); EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(1); @@ -1488,19 +1533,20 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_022, TestSize.Level1) EXPECT_CALL(*scheduler, AsObject()).Times(2); abilityMgrServ_->StartAbility(want); auto testAbilityRecord = GetTopAbility(); - ASSERT_TRUE(testAbilityRecord); + EXPECT_TRUE(testAbilityRecord); abilityMgrServ_->AttachAbilityThread(scheduler, testAbilityRecord->GetToken()); SetActive(); abilityMgrServ_->StartAbility(want2); auto testAbilityRecord2 = GetTopAbility(); - ASSERT_TRUE(testAbilityRecord2); + EXPECT_TRUE(testAbilityRecord2); auto stackMgr = abilityMgrServ_->GetStackManager(); - ASSERT_TRUE(stackMgr); + EXPECT_TRUE(stackMgr); stackMgr->CompleteInactive(testAbilityRecord); abilityMgrServ_->HandleLoadTimeOut(testAbilityRecord2->GetEventId()); testAbilityRecord = GetTopAbility(); - ASSERT_TRUE(testAbilityRecord); + EXPECT_TRUE(testAbilityRecord); EXPECT_TRUE(testAbilityRecord->GetAbilityInfo().bundleName == bundleName); + testing::Mock::AllowLeak(scheduler); } /* @@ -1514,14 +1560,14 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_022, TestSize.Level1) */ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_023, TestSize.Level1) { - ASSERT_TRUE(abilityMgrServ_); - ASSERT_TRUE(mockAppMgrClient_); + EXPECT_TRUE(abilityMgrServ_); + EXPECT_TRUE(mockAppMgrClient_); ClearStack(); EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); Want want = CreateWant("RadioTopAbility", COM_IX_HIRADIO); abilityMgrServ_->StartAbility(want); auto testAbilityRecord = GetTopAbility(); - ASSERT_TRUE(testAbilityRecord); + EXPECT_TRUE(testAbilityRecord); SetActive(); auto resultTvFunction = abilityMgrServ_->IsFirstInMission(testAbilityRecord->GetToken()); EXPECT_EQ(resultTvFunction, true); @@ -1539,11 +1585,11 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_023, TestSize.Level1) */ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_024, TestSize.Level1) { - ASSERT_TRUE(abilityMgrServ_); - ASSERT_TRUE(mockAppMgrClient_); + EXPECT_TRUE(abilityMgrServ_); + EXPECT_TRUE(mockAppMgrClient_); ClearStack(); auto stackManager = abilityMgrServ_->GetStackManager(); - ASSERT_TRUE(stackManager); + EXPECT_TRUE(stackManager); sptr scheduler = new MockAbilityScheduler(); EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(_, _)).Times(1); @@ -1551,17 +1597,18 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_024, TestSize.Level1) Want want = CreateWant("PhoneAbility1", COM_IX_PHONE); abilityMgrServ_->StartAbility(want); auto ability = stackManager->GetCurrentTopAbility(); - ASSERT_TRUE(ability); + EXPECT_TRUE(ability); SetActive(); Want want2 = CreateWant("PhoneAbility2", COM_IX_PHONE); abilityMgrServ_->StartAbility(want2); - ASSERT_TRUE(scheduler); + EXPECT_TRUE(scheduler); auto abilityTv = stackManager->GetCurrentTopAbility(); - ASSERT_TRUE(abilityTv); + EXPECT_TRUE(abilityTv); abilityTv->SetScheduler(scheduler); SetActive(); auto resultFunction = abilityMgrServ_->MoveMissionToEnd(abilityTv->GetToken(), true); EXPECT_EQ(resultFunction, ERR_OK); + testing::Mock::AllowLeak(scheduler); } /* @@ -1574,8 +1621,8 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_024, TestSize.Level1) */ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_025, TestSize.Level1) { - ASSERT_TRUE(abilityMgrServ_); - ASSERT_TRUE(mockAppMgrClient_); + EXPECT_TRUE(abilityMgrServ_); + EXPECT_TRUE(mockAppMgrClient_); const std::string permission = "permission"; int pid = 100; int uid = 1000; diff --git a/services/test/moduletest/ability_record_test/BUILD.gn b/services/test/moduletest/ability_record_test/BUILD.gn old mode 100644 new mode 100755 index 6962574439a..27927da1cbd --- a/services/test/moduletest/ability_record_test/BUILD.gn +++ b/services/test/moduletest/ability_record_test/BUILD.gn @@ -23,6 +23,7 @@ ohos_moduletest("AbilityRecordModuleTest") { include_dirs = [ "${EVENT_DIR}/frameworks/core/include", "${EVENT_DIR}/interfaces/innerkits/native/include", + "//third_party/jsoncpp/include", ] sources = [ @@ -44,6 +45,8 @@ ohos_moduletest("AbilityRecordModuleTest") { "${services_path}/abilitymgr/src/connection_record.cpp", "${services_path}/abilitymgr/src/data_ability_manager.cpp", "${services_path}/abilitymgr/src/data_ability_record.cpp", + + # "${services_path}/abilitymgr/src/dummy_configuration.cpp", "${services_path}/abilitymgr/src/image_info.cpp", "${services_path}/abilitymgr/src/kernal_system_app_manager.cpp", "${services_path}/abilitymgr/src/lifecycle_deal.cpp", @@ -65,6 +68,7 @@ ohos_moduletest("AbilityRecordModuleTest") { "${services_path}/abilitymgr/src/want_sender_info.cpp", "${services_path}/abilitymgr/src/want_sender_stub.cpp", "${services_path}/abilitymgr/src/wants_info.cpp", + "//foundation/aafwk/standard/services/test/mock/src/mock_app_mgr_client.cpp", ] sources += [ "ability_record_module_test.cpp" ] @@ -93,6 +97,7 @@ ohos_moduletest("AbilityRecordModuleTest") { "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] diff --git a/services/test/moduletest/ability_record_test/ability_record_module_test.cpp b/services/test/moduletest/ability_record_test/ability_record_module_test.cpp index 3f3e2d8a9aa..b01d021a2f2 100644 --- a/services/test/moduletest/ability_record_test/ability_record_module_test.cpp +++ b/services/test/moduletest/ability_record_test/ability_record_module_test.cpp @@ -179,7 +179,7 @@ HWTEST_F(AbilityRecordModuleTest, Init_001, TestSize.Level2) for (int i = 0; i < COUNT; ++i) { auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); EXPECT_TRUE(abilityRecord->GetToken()); EXPECT_TRUE(abilityRecord->GetRecordId() >= 0); EXPECT_FALSE(abilityRecord->IsLauncherAbility()); @@ -203,7 +203,7 @@ HWTEST_F(AbilityRecordModuleTest, Init_002, TestSize.Level2) for (int i = 0; i < COUNT; ++i) { auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); EXPECT_TRUE(abilityRecord->GetToken()); EXPECT_TRUE(abilityRecord->IsLauncherAbility()); EXPECT_EQ(abilityRecord->GetAbilityState(), INITIAL); @@ -226,10 +226,10 @@ HWTEST_F(AbilityRecordModuleTest, LoadAbility_001, TestSize.Level3) for (int i = 0; i < COUNT; ++i) { auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); std::unique_ptr mockAppMgrClient(new MockAppMgrClient); - ASSERT_TRUE(mockAppMgrClient); + EXPECT_TRUE(mockAppMgrClient); auto mockHandler = [&](const sptr &token, const sptr &preToken, @@ -273,10 +273,10 @@ HWTEST_F(AbilityRecordModuleTest, TerminateAbility_001, TestSize.Level3) for (int i = 0; i < COUNT; ++i) { auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); auto mockAppMgrClient = std::make_unique(); - ASSERT_TRUE(mockAppMgrClient); + EXPECT_TRUE(mockAppMgrClient); EXPECT_CALL(*mockAppMgrClient, TerminateAbility(_)).Times(1).WillOnce(Return(RESULT_OK)); @@ -302,10 +302,10 @@ HWTEST_F(AbilityRecordModuleTest, AbilityScheduler_001, TestSize.Level3) { auto &abilityRequest = MakeDefaultAbilityRequest(); auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); sptr mockAbilityScheduerStub(new MockAbilitySchedulerStub); - ASSERT_TRUE(mockAbilityScheduerStub); + EXPECT_TRUE(mockAbilityScheduerStub); bool testResult = false; abilityRecord->SetScheduler(mockAbilityScheduerStub); @@ -322,7 +322,7 @@ HWTEST_F(AbilityRecordModuleTest, AbilityScheduler_001, TestSize.Level3) .WillOnce(Invoke(mockActivateHandler)); abilityRecord->Activate(); - ASSERT_TRUE(testResult); + EXPECT_TRUE(testResult); EXPECT_EQ(abilityRecord->GetAbilityState(), ACTIVATING); // Inactivate @@ -382,7 +382,7 @@ HWTEST_F(AbilityRecordModuleTest, AbilityScheduler_001, TestSize.Level3) EXPECT_CALL(*mockAbilityScheduerStub, SendResult(_, _, _)).Times(1).WillOnce(Invoke(mockSendResultHandler)); auto abilityResult = std::make_shared(abilityRequest.requestCode, testResultCode, abilityRequest.want); - ASSERT_TRUE(abilityResult); + EXPECT_TRUE(abilityResult); abilityRecord->SetResult(abilityResult); abilityRecord->SendResult(); EXPECT_TRUE(testResult); @@ -403,10 +403,10 @@ HWTEST_F(AbilityRecordModuleTest, MissionRecord_001, TestSize.Level1) auto &abilityRequest = MakeDefaultAbilityRequest(); auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); auto missionRecord = std::make_shared("test"); - ASSERT_TRUE(missionRecord); + EXPECT_TRUE(missionRecord); abilityRecord->SetMissionRecord(missionRecord); EXPECT_EQ(missionRecord, abilityRecord->GetMissionRecord()); @@ -424,13 +424,13 @@ HWTEST_F(AbilityRecordModuleTest, PreNextAbilities_001, TestSize.Level1) auto &abilityRequest = MakeDefaultAbilityRequest(); auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); auto preAbilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(preAbilityRecord); + EXPECT_TRUE(preAbilityRecord); auto nextAbilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(nextAbilityRecord); + EXPECT_TRUE(nextAbilityRecord); for (int i = 0; i < COUNT; ++i) { abilityRecord->SetPreAbilityRecord(preAbilityRecord); @@ -452,7 +452,7 @@ HWTEST_F(AbilityRecordModuleTest, EventId_001, TestSize.Level1) auto &abilityRequest = MakeDefaultAbilityRequest(); auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); for (int i = 0; i < COUNT; ++i) { abilityRecord->SetEventId(i); @@ -472,7 +472,7 @@ HWTEST_F(AbilityRecordModuleTest, AbilityState_001, TestSize.Level1) auto &abilityRequest = MakeDefaultAbilityRequest(); auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); for (int i = 0; i < COUNT; ++i) { abilityRecord->SetAbilityState(INITIAL); @@ -492,7 +492,7 @@ HWTEST_F(AbilityRecordModuleTest, Want_001, TestSize.Level1) auto &abilityRequest = MakeDefaultAbilityRequest(); auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); auto initWant = abilityRecord->GetWant(); EXPECT_EQ(initWant, abilityRequest.want); @@ -520,11 +520,11 @@ HWTEST_F(AbilityRecordModuleTest, ConnectionRecord_001, TestSize.Level2) auto &abilityRequest = MakeDefaultAbilityRequest(); auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); EXPECT_TRUE(abilityRecord->IsConnectListEmpty()); auto connectionRecord = ConnectionRecord::CreateConnectionRecord(nullptr, nullptr, nullptr); - ASSERT_TRUE(connectionRecord); + EXPECT_TRUE(connectionRecord); for (int i = 0; i < COUNT; ++i) { abilityRecord->AddConnectRecordToList(connectionRecord); @@ -561,7 +561,7 @@ HWTEST_F(AbilityRecordModuleTest, WindowInfo_001, TestSize.Level1) auto &abilityRequest = MakeDefaultAbilityRequest(); auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); EXPECT_FALSE(abilityRecord->GetWindowInfo()); for (int i = 0; i < COUNT; ++i) { @@ -584,7 +584,7 @@ HWTEST_F(AbilityRecordModuleTest, Terminating_001, TestSize.Level1) auto &abilityRequest = MakeDefaultAbilityRequest(); auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); EXPECT_FALSE(abilityRecord->IsTerminating()); abilityRecord->SetTerminatingState(); @@ -603,7 +603,7 @@ HWTEST_F(AbilityRecordModuleTest, NewWant_001, TestSize.Level1) auto &abilityRequest = MakeDefaultAbilityRequest(); auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); EXPECT_FALSE(abilityRecord->IsNewWant()); for (int i = 0; i < COUNT; ++i) { @@ -695,11 +695,12 @@ HWTEST_F(AbilityRecordModuleTest, Dump_001, TestSize.Level2) auto &abilityRequest = MakeDefaultAbilityRequest(); auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); std::vector info; abilityRecord->Dump(info); EXPECT_FALSE(info.empty()); } + } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/ability_stack_test/BUILD.gn b/services/test/moduletest/ability_stack_test/BUILD.gn old mode 100644 new mode 100755 index bdd09eac61d..4e3b8a5c377 --- a/services/test/moduletest/ability_stack_test/BUILD.gn +++ b/services/test/moduletest/ability_stack_test/BUILD.gn @@ -19,10 +19,14 @@ module_output_path = "aafwk_standard/mstabilitymgrservice" ohos_moduletest("ability_stack_module_test") { module_out_path = module_output_path - include_dirs = [ "${services_path}/test/mock/include" ] + include_dirs = [ + "${services_path}/test/mock/include", + "//third_party/jsoncpp/include", + ] sources = [ "ability_stack_module_test.cpp" ] sources += [ + "//foundation/aafwk/standard/services/abilitymgr/src/aafwk_dummy_configuration.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_connect_callback_stub.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_connect_manager.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_event_handler.cpp", @@ -62,6 +66,7 @@ ohos_moduletest("ability_stack_module_test") { "//foundation/aafwk/standard/services/abilitymgr/src/want_sender_stub.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/wants_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/sa_mgr/src/sa_mgr_client_mock.cpp", + "//foundation/aafwk/standard/services/test/mock/src/mock_app_mgr_client.cpp", "//foundation/aafwk/standard/services/test/mock/src/mock_bundle_mgr.cpp", ] configs = [ @@ -88,6 +93,7 @@ ohos_moduletest("ability_stack_module_test") { "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp b/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp index 7c67a41c1e1..301839fcbce 100644 --- a/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp +++ b/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp @@ -37,6 +37,13 @@ using namespace testing; namespace OHOS { namespace AAFwk { +namespace { +const std::string LANGUAGE = "locale"; +const std::string LAYOUT = "layout"; +const std::string FONTSIZE = "fontsize"; +const std::string ORIENTATION = "orientation"; +const std::string DENSITY = "density"; +} // namespace class AbilityStackModuleTest : public testing::Test { public: static void SetUpTestCase(void); @@ -52,45 +59,81 @@ public: public: std::shared_ptr stackManager_; - BundleMgrService *bundleObject_ = nullptr; + inline static BundleMgrService *bundleObject_; + inline static MockAppMgrClient *mockAppMgrClient; + OHOS::sptr mockScheduler_ = nullptr; }; void AbilityStackModuleTest::SetUpTestCase(void) -{} +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + if (!mockAppMgrClient) { + mockAppMgrClient = new MockAppMgrClient(); + } + + auto appScheduler = OHOS::DelayedSingleton::GetInstance(); + appScheduler->appMgrClient_.reset(mockAppMgrClient); + + if (!bundleObject_) { + bundleObject_ = new BundleMgrService(); + } + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( + OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject_); +} void AbilityStackModuleTest::TearDownTestCase(void) -{} +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + if (mockAppMgrClient) { + delete mockAppMgrClient; + mockAppMgrClient = nullptr; + } + + if (bundleObject_) { + delete bundleObject_; + bundleObject_ = nullptr; + } +} void AbilityStackModuleTest::SetUp(void) { - bundleObject_ = new BundleMgrService(); - OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( - OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject_); + GTEST_LOG_(INFO) << "SetUp"; auto ams = DelayedSingleton::GetInstance(); - // stackManager_ = ams->GetStackManager(); - stackManager_ = std::make_shared(10); auto bms = ams->GetBundleManager(); ams->OnStart(); + stackManager_ = ams->GetStackManager(); + EXPECT_TRUE(stackManager_); + stackManager_->Init(); EXPECT_NE(bms, nullptr); + + if (mockScheduler_ == nullptr) { + mockScheduler_ = new MockAbilityScheduler(); + } } void AbilityStackModuleTest::TearDown(void) { + GTEST_LOG_(INFO) << "TearDown"; auto ams = DelayedSingleton::GetInstance(); OHOS::DelayedSingleton::DestroyInstance(); + + if (mockScheduler_ != nullptr) { + mockScheduler_.clear(); + } } AbilityRequest AbilityStackModuleTest::GenerateAbilityRequest(const std::string &deviceName, const std::string &abilityName, const std::string &appName, const std::string &bundleName) { + GTEST_LOG_(INFO) << "GenerateAbilityRequest start ability :" << abilityName; ElementName element(deviceName, abilityName, bundleName); Want want; want.SetElement(element); AbilityInfo abilityInfo; ApplicationInfo appinfo; - + abilityInfo.visible = true; abilityInfo.name = abilityName; abilityInfo.bundleName = bundleName; abilityInfo.applicationName = appName; @@ -111,6 +154,7 @@ AbilityRequest AbilityStackModuleTest::GenerateAbilityRequest(const std::string void AbilityStackModuleTest::makeScene( const std::string &abilityName, const std::string &bundleName, AbilityInfo &abilityInfo, Want &want) { + GTEST_LOG_(INFO) << "makeScene"; if (bundleName == "com.ix.hiworld") { std::string entity = Want::ENTITY_HOME; want.AddEntity(entity); @@ -145,6 +189,9 @@ void AbilityStackModuleTest::makeScene( abilityInfo.launchMode = LaunchMode::STANDARD; } if (abilityName == "RadioTopAbility") { + abilityInfo.launchMode = LaunchMode::SINGLETOP; + } + if (abilityName == "RadioSAbility") { abilityInfo.launchMode = LaunchMode::SINGLETON; } } @@ -152,6 +199,7 @@ void AbilityStackModuleTest::makeScene( Want AbilityStackModuleTest::CreateWant(const std::string &entity) { + GTEST_LOG_(INFO) << "CreateWant"; Want want; if (!entity.empty()) { want.AddEntity(entity); @@ -162,7 +210,9 @@ Want AbilityStackModuleTest::CreateWant(const std::string &entity) AbilityInfo AbilityStackModuleTest::CreateAbilityInfo( const std::string &name, const std::string &appName, const std::string &bundleName) { + GTEST_LOG_(INFO) << "CreateAbilityInfo"; AbilityInfo abilityInfo; + abilityInfo.visible = true; abilityInfo.name = name; abilityInfo.applicationName = appName; abilityInfo.bundleName = bundleName; @@ -171,6 +221,8 @@ AbilityInfo AbilityStackModuleTest::CreateAbilityInfo( ApplicationInfo AbilityStackModuleTest::CreateAppInfo(const std::string &appName, const std::string &bundleName) { + GTEST_LOG_(INFO) << "CreateAppInfo"; + AbilityInfo abilityInfo; ApplicationInfo appInfo; appInfo.name = appName; appInfo.bundleName = bundleName; @@ -189,7 +241,7 @@ ApplicationInfo AbilityStackModuleTest::CreateAppInfo(const std::string &appName HWTEST_F(AbilityStackModuleTest, ability_stack_test_001, TestSize.Level1) { GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_001 start"; - + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); std::string abilityName = "ability_name"; std::string bundleName = "com.ix.aafwk.moduletest"; @@ -206,9 +258,9 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_001, TestSize.Level1) stackManager_->Init(); std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); - ASSERT_TRUE(curMissionStack); + EXPECT_TRUE(curMissionStack); stackManager_->StartAbility(abilityRequest); - EXPECT_EQ(AbilityStackManager::LAUNCHER_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); + EXPECT_EQ(LAUNCHER_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); EXPECT_EQ(1, curMissionStack->GetMissionRecordCount()); EXPECT_TRUE(curMissionStack->GetTopMissionRecord() != nullptr); EXPECT_EQ(1, curMissionStack->GetTopMissionRecord()->GetAbilityRecordCount()); @@ -230,7 +282,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_001, TestSize.Level1) HWTEST_F(AbilityStackModuleTest, ability_stack_test_002, TestSize.Level1) { GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_002 start"; - + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); std::string abilityName = "ability_name"; std::string bundleName = "com.ix.aafwk.moduletest"; @@ -241,19 +293,18 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_002, TestSize.Level1) abilityRequest.appInfo.isLauncherApp = true; // launcher ability abilityRequest.abilityInfo.applicationInfo = abilityRequest.appInfo; - stackManager_->missionStackList_.clear(); EXPECT_EQ(true, stackManager_->waittingAbilityQueue_.empty()); - stackManager_->Init(); - std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); int result = stackManager_->StartAbility(abilityRequest); - EXPECT_EQ(AbilityStackManager::LAUNCHER_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); + EXPECT_EQ(result, ERR_OK); + std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); + EXPECT_EQ(LAUNCHER_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); EXPECT_EQ(1, curMissionStack->GetMissionRecordCount()); EXPECT_EQ(1, curMissionStack->GetTopMissionRecord()->GetAbilityRecordCount()); - usleep(1000); + result = stackManager_->StartAbility(abilityRequest); // same launcher ability // not change current mission stack - EXPECT_EQ(AbilityStackManager::LAUNCHER_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); + EXPECT_EQ(LAUNCHER_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); // not add new mission to current mission stack EXPECT_EQ(1, curMissionStack->GetMissionRecordCount()); // not add new ability to current mission record @@ -275,7 +326,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_002, TestSize.Level1) HWTEST_F(AbilityStackModuleTest, ability_stack_test_003, TestSize.Level1) { GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_003 start"; - + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); std::string abilityName = "ability_name"; std::string bundleName = "com.ix.aafwk.moduletest"; int index = 1; @@ -297,7 +348,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_003, TestSize.Level1) abilityRequest2.appInfo.isLauncherApp = true; // another launcher ability abilityRequest2.abilityInfo.applicationInfo = abilityRequest2.appInfo; - stackManager_->Init(); std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); int result = stackManager_->StartAbility(abilityRequest); usleep(1000); @@ -305,7 +355,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_003, TestSize.Level1) curMissionStack->GetTopAbilityRecord()->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); result = stackManager_->StartAbility(abilityRequest2); // not change current mission stack - EXPECT_EQ(AbilityStackManager::LAUNCHER_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); + EXPECT_EQ(LAUNCHER_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); // add new mission to current mission stack EXPECT_EQ(1, curMissionStack->GetMissionRecordCount()); EXPECT_EQ(2, curMissionStack->GetTopMissionRecord()->GetAbilityRecordCount()); @@ -331,7 +381,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_004, TestSize.Level1) std::string abilityName = "ability_name"; std::string bundleName = "com.ix.aafwk.moduletest"; int index = 1; - + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); AbilityRequest abilityRequest; abilityRequest.want = CreateWant(Want::ENTITY_HOME); std::string strInd = std::to_string(index); @@ -348,17 +398,19 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_004, TestSize.Level1) abilityRequest2.appInfo.isLauncherApp = false; // non-launcher ability abilityRequest2.abilityInfo.applicationInfo = abilityRequest2.appInfo; - stackManager_->Init(); - std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); int result = stackManager_->StartAbility(abilityRequest); - usleep(1000); + EXPECT_EQ(result, ERR_OK); + + std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); EXPECT_TRUE(curMissionStack->GetTopAbilityRecord() != nullptr); curMissionStack->GetTopAbilityRecord()->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); - EXPECT_EQ(AbilityStackManager::LAUNCHER_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); + EXPECT_EQ(LAUNCHER_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); result = stackManager_->StartAbility(abilityRequest2); + EXPECT_EQ(result, ERR_OK); + curMissionStack = stackManager_->GetCurrentMissionStack(); // change current mission stack - EXPECT_EQ(AbilityStackManager::DEFAULT_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); + EXPECT_EQ(DEFAULT_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); // add new mission to current mission stack EXPECT_EQ(1, curMissionStack->GetMissionRecordCount()); EXPECT_EQ(1, curMissionStack->GetTopMissionRecord()->GetAbilityRecordCount()); @@ -380,7 +432,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_004, TestSize.Level1) HWTEST_F(AbilityStackModuleTest, ability_stack_test_005, TestSize.Level1) { GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_005 start"; - + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); std::string abilityName = "ability_name"; std::string bundleName = "com.ix.aafwk.moduletest"; @@ -391,7 +443,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_005, TestSize.Level1) abilityRequest.appInfo.isLauncherApp = true; // launcher ability abilityRequest.abilityInfo.applicationInfo = abilityRequest.appInfo; - stackManager_->Init(); std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); int result = stackManager_->StartAbility(abilityRequest); usleep(1000); @@ -400,7 +451,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_005, TestSize.Level1) result = stackManager_->TerminateAbility(curMissionStack->GetTopAbilityRecord()->GetToken(), -1, nullptr); EXPECT_EQ(TERMINATE_LAUNCHER_DENIED, result); // not change current mission stack - EXPECT_EQ(AbilityStackManager::LAUNCHER_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); + EXPECT_EQ(LAUNCHER_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); EXPECT_EQ(1, curMissionStack->GetMissionRecordCount()); // not change current ability state EXPECT_TRUE(curMissionStack->GetTopAbilityRecord() != nullptr); @@ -422,7 +473,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_005, TestSize.Level1) HWTEST_F(AbilityStackModuleTest, ability_stack_test_006, TestSize.Level1) { GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_006 start"; - + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); std::string abilityName = "ability_name"; std::string bundleName = "com.ix.aafwk.moduletest"; @@ -441,12 +492,12 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_006, TestSize.Level1) abilityRequests.push_back(abilityRequest); } - stackManager_->Init(); + // start "ability_name11" int result = stackManager_->StartAbility(abilityRequests[0]); usleep(1000); std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); - EXPECT_EQ(AbilityStackManager::DEFAULT_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); + EXPECT_EQ(DEFAULT_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); std::shared_ptr currentTopAbilityRecord = stackManager_->GetCurrentTopAbility(); EXPECT_STREQ("ability_name11", currentTopAbilityRecord->GetAbilityInfo().name.c_str()); currentTopAbilityRecord->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); @@ -454,7 +505,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_006, TestSize.Level1) // start "ability_name12" result = stackManager_->StartAbility(abilityRequests[1]); usleep(1000); - EXPECT_EQ(AbilityStackManager::DEFAULT_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); + EXPECT_EQ(DEFAULT_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); currentTopAbilityRecord = stackManager_->GetCurrentTopAbility(); EXPECT_STREQ("ability_name12", currentTopAbilityRecord->GetAbilityInfo().name.c_str()); currentTopAbilityRecord->GetPreAbilityRecord()->SetAbilityState(OHOS::AAFwk::AbilityState::INACTIVE); @@ -494,10 +545,10 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_006, TestSize.Level1) currentTopAbilityRecord->lifecycleDeal_ = nullptr; Want want; result = stackManager_->TerminateAbility(currentTopAbilityRecord->GetToken(), -1, &want); - EXPECT_EQ(AbilityStackManager::DEFAULT_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); + EXPECT_EQ(DEFAULT_MISSION_STACK_ID, curMissionStack->GetMissionStackId()); EXPECT_EQ(4, curMissionStack->GetTopMissionRecord()->GetAbilityRecordCount()); currentTopAbilityRecord = curMissionStack->GetTopAbilityRecord(); - ASSERT_TRUE(currentTopAbilityRecord != nullptr); + EXPECT_TRUE(currentTopAbilityRecord != nullptr); EXPECT_STREQ("ability_name13", currentTopAbilityRecord->GetAbilityInfo().name.c_str()); // terminate stack bottom ability @@ -505,7 +556,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_006, TestSize.Level1) result = stackManager_->TerminateAbility(bottomAbility->GetToken(), -1, &want); EXPECT_EQ(3, curMissionStack->GetTopMissionRecord()->GetAbilityRecordCount()); currentTopAbilityRecord = curMissionStack->GetTopAbilityRecord(); - ASSERT_TRUE(currentTopAbilityRecord != nullptr); + EXPECT_TRUE(currentTopAbilityRecord != nullptr); EXPECT_STREQ("ability_name13", currentTopAbilityRecord->GetAbilityInfo().name.c_str()); GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_006 end"; @@ -538,20 +589,19 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_007, TestSize.Level1) std::shared_ptr mission = std::make_shared(bundleName); mission->AddAbilityRecordToTop(abilityRecord); - stackManager_->Init(); std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); curMissionStack->AddMissionRecordToTop(mission); - auto appScheduler = OHOS::DelayedSingleton::GetInstance(); - MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); - appScheduler->appMgrClient_.reset(mockAppMgrClient); - OHOS::sptr abilityScheduler(new MockAbilityScheduler()); + EXPECT_CALL(*abilityScheduler, AsObject()).Times(2); // ams handler is non statrt so times is 0 EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(testing::_, testing::_)).Times(1); EXPECT_TRUE(abilityRecord->GetToken()); + + EXPECT_CALL(*abilityScheduler, AsObject()).WillRepeatedly(Return(nullptr)); stackManager_->AttachAbilityThread(abilityScheduler, abilityRecord->GetToken()); + GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_007 end"; } @@ -565,7 +615,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_007, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_008, TestSize.Level1) { - GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_011 start"; + GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_008 start"; std::string abilityName = "ability_name"; std::string bundleName = "com.ix.aafwk.moduletest"; @@ -580,7 +630,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_008, TestSize.Level1) abilityRecord->SetAbilityState(OHOS::AAFwk::AbilityState::TERMINATING); std::shared_ptr mission = std::make_shared(bundleName); mission->AddAbilityRecordToTop(abilityRecord); - stackManager_->Init(); + std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); curMissionStack->AddMissionRecordToTop(mission); @@ -591,7 +641,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_008, TestSize.Level1) int result = stackManager_->AbilityTransitionDone(abilityRecord->GetToken(), OHOS::AAFwk::AbilityState::INITIAL); EXPECT_EQ(OHOS::ERR_OK, result); - GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_011 end"; + GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_008 end"; } /* @@ -604,7 +654,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_008, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_009, TestSize.Level1) { - GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_012 start"; + GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_009 start"; std::string abilityName = "ability_name"; std::string bundleName = "com.ix.aafwk.moduletest"; @@ -618,14 +668,14 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_009, TestSize.Level1) abilityRecord->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); std::shared_ptr mission = std::make_shared(bundleName); mission->AddAbilityRecordToTop(abilityRecord); - stackManager_->Init(); + std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); curMissionStack->AddMissionRecordToTop(mission); stackManager_->AddWindowInfo(abilityRecord->GetToken(), 1); EXPECT_TRUE(abilityRecord->GetWindowInfo() != nullptr); - GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_012 end"; + GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_009 end"; } /* @@ -649,13 +699,13 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_010, TestSize.Level1) std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); OHOS::sptr scheduler(new MockAbilityScheduler()); - EXPECT_CALL(*scheduler, AsObject()).Times(2); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); abilityRecord->SetScheduler(scheduler); abilityRecord->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); std::shared_ptr mission = std::make_shared(bundleName); mission->AddAbilityRecordToTop(abilityRecord); - stackManager_->Init(); + std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); curMissionStack->AddMissionRecordToTop(mission); @@ -666,18 +716,14 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_010, TestSize.Level1) /* * Feature: AbilityStackManager - * Function: RemoveStack + * Function: PowerOff * SubFunction: NA - * FunctionPoints: RemoveStack + * FunctionPoints: PowerOff * EnvConditions: NA - * CaseDescription: Succeeded to verify RemoveStack + * CaseDescription: Succeeded to verify PowerOff */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_011, TestSize.Level1) { - - auto appScheduler = OHOS::DelayedSingleton::GetInstance(); - MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); - appScheduler->appMgrClient_.reset(mockAppMgrClient); EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(testing::_, testing::_)) .Times(1) @@ -685,10 +731,11 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_011, TestSize.Level1) AbilityRequest launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); - stackManager_->Init(); + stackManager_->StartAbility(launcherAbilityRequest_); auto firstTopAbility = stackManager_->GetCurrentTopAbility(); EXPECT_TRUE(firstTopAbility); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); auto transactionDoneCaller = [&](const Want &want, const LifeCycleStateInfo &targetState) { @@ -698,16 +745,15 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_011, TestSize.Level1) auto transactionDoneCaller2 = [&](const Want &want, const LifeCycleStateInfo &targetState) { stackManager_->CompleteBackground(firstTopAbility); }; - OHOS::sptr scheduler(new MockAbilityScheduler()); - - firstTopAbility->SetScheduler(scheduler); - EXPECT_CALL(*scheduler, AsObject()).Times(testing::AtLeast(1)).WillOnce(Return(nullptr)); - + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)) .Times(testing::AtLeast(2)) .WillOnce(testing::Invoke(transactionDoneCaller)) .WillOnce(testing::Invoke(transactionDoneCaller2)); + EXPECT_CALL(*scheduler, ScheduleSaveAbilityState(_)).Times(AtLeast(1)); + + firstTopAbility->SetScheduler(scheduler); int result = stackManager_->PowerOff(); EXPECT_EQ(ERR_OK, result); @@ -715,32 +761,24 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_011, TestSize.Level1) EXPECT_NE(stackManager_->powerStorage_, nullptr); EXPECT_EQ(OHOS::AAFwk::BACKGROUND, firstTopAbility->GetAbilityState()); - auto recordVector = stackManager_->powerStorage_->GetPowerOffRecord(); + auto recordVector = stackManager_->powerStorage_->GetPowerOffInActiveRecord(); EXPECT_TRUE(recordVector.empty()); - - testing::Mock::AllowLeak(mockAppMgrClient); - testing::Mock::AllowLeak(scheduler); } /* * Feature: AbilityStackManager - * Function: RemoveStack + * Function: PowerOn * SubFunction: NA - * FunctionPoints: RemoveStack + * FunctionPoints: PowerOn * EnvConditions: NA - * CaseDescription: Succeeded to verify RemoveStack + * CaseDescription: Succeeded to verify PowerOn */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_012, TestSize.Level1) { - stackManager_->Init(); - - auto appScheduler = OHOS::DelayedSingleton::GetInstance(); - MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); - appScheduler->appMgrClient_.reset(mockAppMgrClient); - EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) .Times(AtLeast(1)) .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(testing::_, testing::_)).Times(testing::AtLeast(2)); auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); stackManager_->StartAbility(launcherAbilityRequest_); @@ -766,6 +804,8 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_012, TestSize.Level1) }; OHOS::sptr scheduler(new MockAbilityScheduler()); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); + firstTopAbility->SetScheduler(scheduler); EXPECT_CALL(*scheduler, AsObject()) .Times(testing::AtLeast(1)) @@ -773,12 +813,17 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_012, TestSize.Level1) .WillOnce(Return(nullptr)) .WillOnce(Return(nullptr)); + EXPECT_CALL(*scheduler, ScheduleSaveAbilityState(testing::_)).Times(testing::AtLeast(3)); + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)) .Times(testing::AtLeast(3)) .WillOnce(testing::Invoke(transactionDoneCaller)) .WillOnce(testing::Invoke(transactionDoneCaller2)) .WillOnce(testing::Invoke(transactionDoneCaller3)) .WillOnce(testing::Invoke(transactionDoneCaller)); + EXPECT_CALL(*scheduler, ScheduleSaveAbilityState(_)).Times(AtLeast(1)); + + firstTopAbility->SetScheduler(scheduler); auto transactionDoneCaller2_1 = [&](const Want &want, const LifeCycleStateInfo &targetState) { stackManager_->CompleteInactive(secondTopAbility); @@ -793,6 +838,9 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_012, TestSize.Level1) }; OHOS::sptr scheduler2(new MockAbilityScheduler()); + + EXPECT_CALL(*scheduler2, AsObject()).WillRepeatedly(Return(nullptr)); + secondTopAbility->SetScheduler(scheduler2); EXPECT_CALL(*scheduler2, AsObject()) .Times(testing::AtLeast(1)) @@ -800,11 +848,16 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_012, TestSize.Level1) .WillOnce(Return(nullptr)) .WillOnce(Return(nullptr)); + EXPECT_CALL(*scheduler2, ScheduleSaveAbilityState(testing::_)).Times(testing::AtLeast(3)); + EXPECT_CALL(*scheduler2, ScheduleAbilityTransaction(testing::_, testing::_)) .Times(testing::AtLeast(3)) .WillOnce(testing::Invoke(transactionDoneCaller2_1)) .WillOnce(testing::Invoke(transactionDoneCaller2_2)) .WillOnce(testing::Invoke(transactionDoneCaller2_3)); + EXPECT_CALL(*scheduler2, ScheduleSaveAbilityState(_)).Times(AtLeast(1)); + + secondTopAbility->SetScheduler(scheduler2); int result = stackManager_->PowerOff(); EXPECT_EQ(ERR_OK, result); @@ -812,7 +865,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_012, TestSize.Level1) EXPECT_EQ(OHOS::AAFwk::BACKGROUND, firstTopAbility->GetAbilityState()); EXPECT_EQ(OHOS::AAFwk::BACKGROUND, secondTopAbility->GetAbilityState()); - auto recordVector = stackManager_->powerStorage_->GetPowerOffRecord(); + auto recordVector = stackManager_->powerStorage_->GetPowerOffInActiveRecord(); int size = recordVector.size(); EXPECT_EQ(size, 1); @@ -850,6 +903,8 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_012, TestSize.Level1) EXPECT_EQ(OHOS::AAFwk::ACTIVE, secondTopAbility->GetAbilityState()); testing::Mock::AllowLeak(mockAppMgrClient); + testing::Mock::AllowLeak(scheduler); + testing::Mock::AllowLeak(scheduler2); } /* @@ -862,17 +917,12 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_012, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_013, TestSize.Level1) { - stackManager_->Init(); int sysUid = 1000; EXPECT_CALL(*bundleObject_, GetUidByBundleName(_, _)) .Times(AtLeast(2)) .WillOnce(Return(sysUid)) .WillOnce(Return(sysUid)); - auto appScheduler = OHOS::DelayedSingleton::GetInstance(); - MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); - appScheduler->appMgrClient_.reset(mockAppMgrClient); - EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) .Times(AtLeast(1)) .WillOnce(Return(AppMgrResultCode::RESULT_OK)); @@ -901,9 +951,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_013, TestSize.Level1) // unlock result = stackManager_->StartLockMission(sysUid, launcherMisionRecordId, true, false); EXPECT_EQ(ERR_OK, result); - - testing::Mock::AllowLeak(mockAppMgrClient); - testing::Mock::AllowLeak(bundleObject_); } /* @@ -916,17 +963,12 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_013, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_014, TestSize.Level1) { - stackManager_->Init(); int sysUid = 1000; EXPECT_CALL(*bundleObject_, GetUidByBundleName(_, _)) .Times(AtLeast(2)) .WillOnce(Return(sysUid)) .WillOnce(Return(sysUid)); - auto appScheduler = OHOS::DelayedSingleton::GetInstance(); - MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); - appScheduler->appMgrClient_.reset(mockAppMgrClient); - EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) .Times(AtLeast(1)) .WillOnce(Return(AppMgrResultCode::RESULT_OK)); @@ -943,7 +985,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_014, TestSize.Level1) auto secondTopAbility = stackManager_->GetCurrentTopAbility(); secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); - auto redioAbilityRequest_ = GenerateAbilityRequest("device", "RadioTopAbility", "Radio", "com.ix.hiRadio"); + auto redioAbilityRequest_ = GenerateAbilityRequest("device", "RadioSAbility", "Radio", "com.ix.hiRadio"); ref = stackManager_->StartAbility(redioAbilityRequest_); EXPECT_EQ(ERR_OK, ref); auto thirdTopAbility = stackManager_->GetCurrentTopAbility(); @@ -957,13 +999,13 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_014, TestSize.Level1) }; OHOS::sptr scheduler(new MockAbilityScheduler()); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); secondTopAbility->SetScheduler(scheduler); EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)) .Times(testing::AtLeast(2)) .WillOnce(testing::Invoke(transactionDoneCaller)) .WillOnce(testing::Invoke(transactionDoneCaller2)); - EXPECT_CALL(*scheduler, AsObject()).Times(testing::AtLeast(1)).WillOnce(Return(nullptr)); auto transactionDoneCaller3 = [&](const Want &want, const LifeCycleStateInfo &targetState) { stackManager_->CompleteInactive(thirdTopAbility); }; @@ -972,13 +1014,13 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_014, TestSize.Level1) }; OHOS::sptr scheduler2(new MockAbilityScheduler()); + EXPECT_CALL(*scheduler2, AsObject()).WillRepeatedly(Return(nullptr)); thirdTopAbility->SetScheduler(scheduler2); EXPECT_CALL(*scheduler2, ScheduleAbilityTransaction(testing::_, testing::_)) .Times(testing::AtLeast(2)) .WillOnce(testing::Invoke(transactionDoneCaller3)) .WillOnce(testing::Invoke(transactionDoneCaller4)); - - EXPECT_CALL(*scheduler2, AsObject()).Times(testing::AtLeast(1)).WillOnce(Return(nullptr)); + EXPECT_CALL(*scheduler2, ScheduleSaveAbilityState(_)).Times(AtLeast(1)); secondTopAbility->SetAbilityState(OHOS::AAFwk::INACTIVE); auto musicMisionRecord = secondTopAbility->GetMissionRecord(); @@ -994,9 +1036,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_014, TestSize.Level1) // unlock result = stackManager_->StartLockMission(sysUid, musicMisionRecordId, false, false); EXPECT_EQ(ERR_OK, result); - - testing::Mock::AllowLeak(mockAppMgrClient); - testing::Mock::AllowLeak(bundleObject_); } /* @@ -1009,17 +1048,12 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_014, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_015, TestSize.Level1) { - stackManager_->Init(); int userUid = 10; EXPECT_CALL(*bundleObject_, GetUidByBundleName(_, _)) .Times(AtLeast(2)) .WillOnce(Return(userUid)) .WillOnce(Return(userUid)); - auto appScheduler = OHOS::DelayedSingleton::GetInstance(); - MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); - appScheduler->appMgrClient_.reset(mockAppMgrClient); - EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) .Times(AtLeast(1)) .WillOnce(Return(AppMgrResultCode::RESULT_OK)); @@ -1050,8 +1084,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_015, TestSize.Level1) // can start a ability ref = stackManager_->StartAbility(redioAbilityRequest_); EXPECT_EQ(ERR_OK, ref); - testing::Mock::AllowLeak(mockAppMgrClient); - testing::Mock::AllowLeak(bundleObject_); } /* @@ -1064,17 +1096,12 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_015, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_016, TestSize.Level1) { - stackManager_->Init(); int userUid = 10; EXPECT_CALL(*bundleObject_, GetUidByBundleName(_, _)) .Times(AtLeast(2)) .WillOnce(Return(userUid)) .WillOnce(Return(userUid)); - auto appScheduler = OHOS::DelayedSingleton::GetInstance(); - MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); - appScheduler->appMgrClient_.reset(mockAppMgrClient); - EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) .Times(AtLeast(1)) .WillOnce(Return(AppMgrResultCode::RESULT_OK)); @@ -1100,9 +1127,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_016, TestSize.Level1) result = stackManager_->TerminateAbility(secondTopAbility->GetToken(), -1, nullptr); EXPECT_EQ(ERR_OK, result); - - testing::Mock::AllowLeak(mockAppMgrClient); - testing::Mock::AllowLeak(bundleObject_); } /* @@ -1115,17 +1139,12 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_016, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_017, TestSize.Level1) { - stackManager_->Init(); int sysUid = 1000; EXPECT_CALL(*bundleObject_, GetUidByBundleName(_, _)) .Times(AtLeast(2)) .WillOnce(Return(sysUid)) .WillOnce(Return(sysUid)); - auto appScheduler = OHOS::DelayedSingleton::GetInstance(); - MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); - appScheduler->appMgrClient_.reset(mockAppMgrClient); - EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) .Times(AtLeast(1)) .WillOnce(Return(AppMgrResultCode::RESULT_OK)); @@ -1142,7 +1161,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_017, TestSize.Level1) auto secondTopAbility = stackManager_->GetCurrentTopAbility(); secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); - auto redioAbilityRequest_ = GenerateAbilityRequest("device", "RadioTopAbility", "Radio", "com.ix.hiRadio"); + auto redioAbilityRequest_ = GenerateAbilityRequest("device", "RadioSAbility", "Radio", "com.ix.hiRadio"); ref = stackManager_->StartAbility(redioAbilityRequest_); EXPECT_EQ(ERR_OK, ref); auto thirdTopAbility = stackManager_->GetCurrentTopAbility(); @@ -1164,32 +1183,25 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_017, TestSize.Level1) // unlock result = stackManager_->StartLockMission(sysUid, musicMisionRecordId, true, false); EXPECT_EQ(ERR_OK, result); - - testing::Mock::AllowLeak(mockAppMgrClient); - testing::Mock::AllowLeak(bundleObject_); } /* * Feature: AaFwk - * Function: StartLockMission + * Function: OnAbilityDied * SubFunction: NA - * FunctionPoints: lock a mission , It's locked mission top ability will be active + * FunctionPoints: Execute when application dies * EnvConditions: NA - * CaseDescription: when locked mission died + * CaseDescription: When the system attribute is changed, if the listener is not registered, the application needs to be + * restarted */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_018, TestSize.Level1) { - stackManager_->Init(); int userUid = 10; EXPECT_CALL(*bundleObject_, GetUidByBundleName(_, _)) .Times(AtLeast(2)) .WillOnce(Return(userUid)) .WillOnce(Return(userUid)); - auto appScheduler = OHOS::DelayedSingleton::GetInstance(); - MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); - appScheduler->appMgrClient_.reset(mockAppMgrClient); - EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) .Times(AtLeast(1)) .WillOnce(Return(AppMgrResultCode::RESULT_OK)); @@ -1210,9 +1222,2396 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_018, TestSize.Level1) stackManager_->OnAbilityDied(secondTopAbility); auto state = stackManager_->lockMissionContainer_->IsLockedMissionState(); EXPECT_FALSE(state); +} - testing::Mock::AllowLeak(mockAppMgrClient); - testing::Mock::AllowLeak(bundleObject_); +/* + * Feature: AaFwk + * Function: UpdateConfiguration + * SubFunction: NA + * FunctionPoints:Update applied + * EnvConditions: NA + * CaseDescription: 1. launcher ability default concern locale and fontSize + * 2. We pass in locale to test whether it can be called onConfigurationUpdated(ResConfig) + * + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_019, TestSize.Level1) +{ + OHOS::sptr scheduler(new MockAbilityScheduler()); + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "luncher", "launcher", "com.ix.hiworld"); + stackManager_->StartAbility(launcherAbilityRequest_); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + firstTopAbility->SetScheduler(scheduler); + + EXPECT_CALL(*scheduler, AsObject()).Times(testing::AtLeast(1)); + // Notify application executionon ConfigurationUpdated + EXPECT_CALL(*scheduler, ScheduleUpdateConfiguration(testing::_)).Times(testing::AtLeast(1)); + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)).Times(testing::AtLeast(1)); + + DummyConfiguration DummyConfiguration(FONTSIZE); + // test fun + auto ref = stackManager_->UpdateConfiguration(DummyConfiguration); + EXPECT_EQ(ERR_OK, ref); +} + +/* + * Feature: AaFwk + * Function: UpdateConfiguration + * SubFunction: NA + * FunctionPoints:Update applied + * EnvConditions: NA + * CaseDescription: 1. launcher ability + default ability default concern locale and fontSize + * 2. default ability in active + * 3. We pass in locale to test whether it can be called onConfigurationUpdated + * + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_020, TestSize.Level1) +{ + OHOS::sptr scheduler(new MockAbilityScheduler()); + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto musicAbilityRequest_ = GenerateAbilityRequest("device", "Music", "launcher", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto secondTopAbility = stackManager_->GetCurrentTopAbility(); + secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + secondTopAbility->SetScheduler(scheduler); + + EXPECT_CALL(*scheduler, AsObject()).Times(testing::AtLeast(1)); + // Notify application executionon ConfigurationUpdated + EXPECT_CALL(*scheduler, ScheduleUpdateConfiguration(testing::_)).Times(testing::AtLeast(1)); + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)).Times(testing::AtLeast(1)); + + DummyConfiguration DummyConfiguration(LAYOUT); + ref = stackManager_->UpdateConfiguration(DummyConfiguration); + EXPECT_EQ(ERR_OK, ref); +} + +/* + * Feature: AaFwk + * Function: UpdateConfiguration + * SubFunction: NA + * FunctionPoints: Update applied + * EnvConditions: NA + * CaseDescription: 1.default ability default concern locale and fontSize + * 2. When ordinary applications do not pay attention to system attributes, they will be restart + * + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_021, TestSize.Level1) +{ + OHOS::sptr scheduler(new MockAbilityScheduler()); + + // When the application restarts, it is called + auto restartCall = [&](const sptr &token, + const sptr &preToken, + const AbilityInfo &abilityInfo, + const ApplicationInfo &appInfo) { + return (AppMgrResultCode)stackManager_->AttachAbilityThread(scheduler, token); + }; + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(testing::Invoke(restartCall)); + + EXPECT_CALL(*mockAppMgrClient, TerminateAbility(_)).Times(AtLeast(1)).WillOnce(Return(AppMgrResultCode::RESULT_OK)); + // EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(_, _)) + // .Times(AtLeast(2)) + // .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + // .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + stackManager_->StartAbility(launcherAbilityRequest_); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); + firstTopAbility->SetScheduler(scheduler); + + auto transactionDoneInactive = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteInactive(firstTopAbility); + }; + + auto transactionDoneBackground = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteBackground(firstTopAbility); + }; + + auto transactionDoneTerminate = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteTerminate(firstTopAbility); + }; + + // first time call + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)) + .Times(testing::AtLeast(3)) + .WillOnce(testing::Invoke(transactionDoneInactive)) + .WillOnce(testing::Invoke(transactionDoneBackground)) + .WillOnce(testing::Invoke(transactionDoneTerminate)); + + // when restart ability save the ability state + EXPECT_CALL(*scheduler, ScheduleSaveAbilityState(testing::_)).Times(testing::AtLeast(1)); + // when restart ability restore the ability state + EXPECT_CALL(*scheduler, ScheduleRestoreAbilityState(testing::_)).Times(testing::AtLeast(1)); + + DummyConfiguration DummyConfiguration(LANGUAGE); + auto ref = stackManager_->UpdateConfiguration(DummyConfiguration); + EXPECT_EQ(ERR_OK, ref); +} + +/* + * Feature: AaFwk + * Function: UpdateConfiguration + * SubFunction: NA + * FunctionPoints: Notification application attribute change + * EnvConditions: NA + * CaseDescription: Notify if the system property change notification is registered + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_022, TestSize.Level1) +{ + OHOS::sptr scheduler(new MockAbilityScheduler()); + + // When the application restarts, it is called + auto restartCall = [&](const sptr &token, + const sptr &preToken, + const AbilityInfo &abilityInfo, + const ApplicationInfo &appInfo) { + return (AppMgrResultCode)stackManager_->AttachAbilityThread(scheduler, token); + }; + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(3)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(testing::Invoke(restartCall)); + + EXPECT_CALL(*mockAppMgrClient, TerminateAbility(_)).Times(AtLeast(1)).WillOnce(Return(AppMgrResultCode::RESULT_OK)); + // EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(_, _)) + // .Times(AtLeast(2)) + // .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + // .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + // launcher ability + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto returen = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, returen); + auto launcherAbility = stackManager_->GetCurrentTopAbility(); + launcherAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // test ability + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(musicAbilityRequest); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); + firstTopAbility->SetScheduler(scheduler); + + auto transactionDoneInactive = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteInactive(firstTopAbility); + }; + + auto transactionDoneBackground = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteBackground(firstTopAbility); + }; + + auto transactionDoneTerminate = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteTerminate(firstTopAbility); + }; + + // first time call + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)) + .Times(testing::AtLeast(3)) + .WillOnce(testing::Invoke(transactionDoneInactive)) + .WillOnce(testing::Invoke(transactionDoneBackground)) + .WillOnce(testing::Invoke(transactionDoneTerminate)); + + // when restart ability save the ability state + EXPECT_CALL(*scheduler, ScheduleSaveAbilityState(testing::_)).Times(testing::AtLeast(1)); + // when restart ability restore the ability state + EXPECT_CALL(*scheduler, ScheduleRestoreAbilityState(testing::_)).Times(testing::AtLeast(1)); + + DummyConfiguration DummyConfiguration(""); + auto ref = stackManager_->UpdateConfiguration(DummyConfiguration); + + EXPECT_EQ(ERR_OK, ref); +} + +/* + * Feature: AaFwk + * Function: UpdateConfiguration + * SubFunction: NA + * FunctionPoints:Update applied + * EnvConditions: NA + * CaseDescription: 1. sigleton auncher ability + * 2. restart ability + * + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_023, TestSize.Level1) +{ + OHOS::sptr scheduler(new MockAbilityScheduler()); + + // When the application restarts, it is called + auto restartCall = [&](const sptr &token, + const sptr &preToken, + const AbilityInfo &abilityInfo, + const ApplicationInfo &appInfo) { + return (AppMgrResultCode)stackManager_->AttachAbilityThread(scheduler, token); + }; + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(testing::Invoke(restartCall)); + + EXPECT_CALL(*mockAppMgrClient, TerminateAbility(_)).Times(AtLeast(1)).WillOnce(Return(AppMgrResultCode::RESULT_OK)); + // EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(_, _)) + // .Times(AtLeast(2)) + // .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + // .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto musicRequest = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(musicRequest); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); + firstTopAbility->SetScheduler(scheduler); + + auto transactionDoneInactive = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteInactive(firstTopAbility); + }; + + auto transactionDoneBackground = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteBackground(firstTopAbility); + }; + + auto transactionDoneTerminate = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteTerminate(firstTopAbility); + }; + + // first time call + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)) + .Times(testing::AtLeast(3)) + .WillOnce(testing::Invoke(transactionDoneInactive)) + .WillOnce(testing::Invoke(transactionDoneBackground)) + .WillOnce(testing::Invoke(transactionDoneTerminate)); + + // when restart ability save the ability state + EXPECT_CALL(*scheduler, ScheduleSaveAbilityState(testing::_)).Times(testing::AtLeast(1)); + // when restart ability restore the ability state + EXPECT_CALL(*scheduler, ScheduleRestoreAbilityState(testing::_)).Times(testing::AtLeast(1)); + + DummyConfiguration DummyConfiguration(LANGUAGE); + auto ref = stackManager_->UpdateConfiguration(DummyConfiguration); + EXPECT_EQ(ERR_OK, ref); +} + +/* + * Feature: AaFwk + * Function: UpdateConfiguration + * SubFunction: NA + * FunctionPoints:Update applied + * EnvConditions: NA + * CaseDescription: 1.sigleton auncher ability + * 2. Will call onConfigurationUpdated(ResConfig) + * + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_024, TestSize.Level1) +{ + OHOS::sptr scheduler(new MockAbilityScheduler()); + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + // singleton,focus + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicTon", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(musicAbilityRequest); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + firstTopAbility->SetScheduler(scheduler); + + EXPECT_CALL(*scheduler, AsObject()).Times(testing::AtLeast(1)); + // Notify application executionon ConfigurationUpdated + EXPECT_CALL(*scheduler, ScheduleUpdateConfiguration(testing::_)).Times(testing::AtLeast(1)); + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)).Times(testing::AtLeast(1)); + + DummyConfiguration DummyConfiguration(LAYOUT); + // test fun + auto ref = stackManager_->UpdateConfiguration(DummyConfiguration); + EXPECT_EQ(ERR_OK, ref); +} + +/* + * Feature: AaFwk + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: Resume mission record + * EnvConditions: NA + * CaseDescription: 1. start music ability standard + * 2. start radio ability standard + * 3. radio ability died + * 4. start music ability standard again + * 5. resume radio ability + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_025, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(_, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + // launcher ability + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto launcherAbility = stackManager_->GetCurrentTopAbility(); + launcherAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // music ability standard + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicAbility = stackManager_->GetCurrentTopAbility(); + musicAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // radio ability standard + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto radioAbility = stackManager_->GetCurrentTopAbility(); + radioAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // set mock scheduler + EXPECT_CALL(*mockScheduler_, AsObject()).WillRepeatedly(Return(nullptr)); + radioAbility->SetScheduler(mockScheduler_); + + // radio ability die + stackManager_->OnAbilityDied(radioAbility); + + // set top ability active + auto topAbility = stackManager_->GetCurrentTopAbility(); + EXPECT_NE(topAbility->GetAbilityInfo().name, "RadioAbility"); + topAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // start music ability again + auto musicAbilityRequest2 = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest2); + EXPECT_EQ(ERR_OK, ref); + + // attach radio ability + EXPECT_CALL(*mockScheduler_, ScheduleRestoreAbilityState(_)).Times(1); + stackManager_->AttachAbilityThread(mockScheduler_, radioAbility->GetToken()); + radioAbility->SetScheduler(nullptr); +} + +/* + * Feature: AaFwk + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: Resume mission record + * EnvConditions: NA + * CaseDescription: 1. start radio ability singleton + * 2. start music ability standard + * 3. radio ability died + * 4. start radio ability singleton again + * 5. resume radio ability + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_026, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(_, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + // launcher ability + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto launcherAbility = stackManager_->GetCurrentTopAbility(); + launcherAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // radio ability singleton + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioSAbility", "radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto radioAbility = stackManager_->GetCurrentTopAbility(); + radioAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // music ability standard + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicAbility = stackManager_->GetCurrentTopAbility(); + musicAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // set mock scheduler + EXPECT_CALL(*mockScheduler_, AsObject()).WillRepeatedly(Return(nullptr)); + radioAbility->SetScheduler(mockScheduler_); + + // radio ability die + stackManager_->OnAbilityDied(radioAbility); + + // set top ability active + auto topAbility = stackManager_->GetCurrentTopAbility(); + EXPECT_NE(topAbility->GetAbilityInfo().name, "RadioAbility"); + topAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // start radio ability singleton again + auto radioAbilityReques2 = GenerateAbilityRequest("device", "RadioSAbility", "radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(radioAbilityReques2); + EXPECT_EQ(ERR_OK, ref); + + // attach radio ability + EXPECT_CALL(*mockScheduler_, ScheduleRestoreAbilityState(_)).Times(1); + stackManager_->AttachAbilityThread(mockScheduler_, radioAbility->GetToken()); + radioAbility->SetScheduler(nullptr); +} + +/* + * Feature: AaFwk + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: Resume mission record + * EnvConditions: NA + * CaseDescription: 1. start music ability standard + * 2. start radio ability singletop + * 3. radio ability died + * 4. start radio ability singletop again + * 5. resume radio ability + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_027, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(_, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + // launcher ability + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto launcherAbility = stackManager_->GetCurrentTopAbility(); + launcherAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // music ability standard + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicAbility = stackManager_->GetCurrentTopAbility(); + musicAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // radio ability singletop + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioTopAbility", "radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto radioAbility = stackManager_->GetCurrentTopAbility(); + radioAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // set mock scheduler + EXPECT_CALL(*mockScheduler_, AsObject()).WillRepeatedly(Return(nullptr)); + radioAbility->SetScheduler(mockScheduler_); + + // radio ability die + stackManager_->OnAbilityDied(radioAbility); + + // set top ability active + auto topAbility = stackManager_->GetCurrentTopAbility(); + EXPECT_NE(topAbility->GetAbilityInfo().name, "RadioAbility"); + topAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // start radio ability singleton again + auto radioAbilityReques2 = GenerateAbilityRequest("device", "RadioTopAbility", "radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(radioAbilityReques2); + EXPECT_EQ(ERR_OK, ref); + + // attach radio ability + EXPECT_CALL(*mockScheduler_, ScheduleRestoreAbilityState(_)).Times(1); + stackManager_->AttachAbilityThread(mockScheduler_, radioAbility->GetToken()); + radioAbility->SetScheduler(nullptr); +} + +/* + * Feature: AaFwk + * Function: MoveMissionToTop + * SubFunction: NA + * FunctionPoints: Resume mission record + * EnvConditions: NA + * CaseDescription: 1. start radio ability singleton + * 2. start music ability standard + * 3. radio ability died + * 4. move misstion to top which has radio ability + * 5. resume radio ability + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_028, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(_, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + // launcher ability + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto launcherAbility = stackManager_->GetCurrentTopAbility(); + launcherAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // radio ability singleton + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioSAbility", "radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto radioAbility = stackManager_->GetCurrentTopAbility(); + radioAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // music ability standard + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicAbility = stackManager_->GetCurrentTopAbility(); + musicAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // set mock scheduler + EXPECT_CALL(*mockScheduler_, AsObject()).WillRepeatedly(Return(nullptr)); + radioAbility->SetScheduler(mockScheduler_); + + // radio ability die + stackManager_->OnAbilityDied(radioAbility); + + // set top ability active + auto topAbility = stackManager_->GetCurrentTopAbility(); + EXPECT_NE(topAbility->GetAbilityInfo().name, "RadioAbility"); + topAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // move mission to top, radio ability singleton + auto missionId = radioAbility->GetMissionRecord()->GetMissionRecordId(); + stackManager_->MoveMissionToTop(missionId); + + // attach radio ability + EXPECT_CALL(*mockScheduler_, ScheduleRestoreAbilityState(_)).Times(1); + stackManager_->AttachAbilityThread(mockScheduler_, radioAbility->GetToken()); +} + +/* + * Feature: AaFwk + * Function: MoveMissionToTop + * SubFunction: NA + * FunctionPoints: Resume mission record + * EnvConditions: NA + * CaseDescription: 1. start radio ability standard + * 2. start music ability standard + * 3. start music ability singleton + * 4. radio ability died + * 5. move mission to top which has radio ability + * 6. resume radio ability + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_029, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(_, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + // launcher ability + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto launcherAbility = stackManager_->GetCurrentTopAbility(); + launcherAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // radio ability standard + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto radioAbility = stackManager_->GetCurrentTopAbility(); + radioAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // music ability standard + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicAbility = stackManager_->GetCurrentTopAbility(); + musicAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // music ability singleton + auto musicSAbilityRequest = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicSAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicSAbility = stackManager_->GetCurrentTopAbility(); + musicSAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // set mock scheduler + EXPECT_CALL(*mockScheduler_, AsObject()).WillRepeatedly(Return(nullptr)); + radioAbility->SetScheduler(mockScheduler_); + + // radio ability die + stackManager_->OnAbilityDied(radioAbility); + + // set top ability active + auto topAbility = stackManager_->GetCurrentTopAbility(); + EXPECT_NE(topAbility->GetAbilityInfo().name, "RadioAbility"); + topAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // move mission to top + auto missionId = radioAbility->GetMissionRecord()->GetMissionRecordId(); + stackManager_->MoveMissionToTop(missionId); + + // attach radio ability + EXPECT_CALL(*mockScheduler_, ScheduleRestoreAbilityState(_)).Times(1); + stackManager_->AttachAbilityThread(mockScheduler_, radioAbility->GetToken()); + radioAbility->SetScheduler(nullptr); +} + +/* + * Feature: AaFwk + * Function: MoveMissionToEnd + * SubFunction: NA + * FunctionPoints: Resume mission record + * EnvConditions: NA + * CaseDescription: 1. start radio ability singleton + * 2. start music ability standard + * 3. radio ability died + * 4. move mission which at top to end + * 5. resume radio ability + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_030, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(_, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + // launcher ability + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto launcherAbility = stackManager_->GetCurrentTopAbility(); + launcherAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // radio ability singleton + auto radioSAbilityRequest = GenerateAbilityRequest("device", "RadioSAbility", "radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(radioSAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto radioSAbility = stackManager_->GetCurrentTopAbility(); + radioSAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // music ability standard + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicAbility = stackManager_->GetCurrentTopAbility(); + musicAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // set mock scheduler + EXPECT_CALL(*mockScheduler_, AsObject()).WillRepeatedly(Return(nullptr)); + radioSAbility->SetScheduler(mockScheduler_); + + // radio ability die + stackManager_->OnAbilityDied(radioSAbility); + + // set top ability active + auto topAbility = stackManager_->GetCurrentTopAbility(); + EXPECT_NE(topAbility->GetAbilityInfo().name, "RadioAbility"); + topAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // move mission to end + stackManager_->MoveMissionToEnd(musicAbility->GetToken(), false); + + // attach radio ability + EXPECT_CALL(*mockScheduler_, ScheduleRestoreAbilityState(_)).Times(1); + stackManager_->AttachAbilityThread(mockScheduler_, radioSAbility->GetToken()); + radioSAbility->SetScheduler(nullptr); +} + +/* + * Feature: AaFwk + * Function: MoveMissionToEnd + * SubFunction: NA + * FunctionPoints: Resume mission record + * EnvConditions: NA + * CaseDescription: 1. start radio ability standard + * 2. start music ability singleton + * 3. radio ability died + * 4. move mission which at top to end + * 5. resume radio ability + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_031, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(_, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + // launcher ability + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto launcherAbility = stackManager_->GetCurrentTopAbility(); + launcherAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // radio ability standard + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto radioAbility = stackManager_->GetCurrentTopAbility(); + radioAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // music ability singleton + auto musicSAbilityRequest = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicSAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicSAbility = stackManager_->GetCurrentTopAbility(); + musicSAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // set mock scheduler + EXPECT_CALL(*mockScheduler_, AsObject()).WillRepeatedly(Return(nullptr)); + radioAbility->SetScheduler(mockScheduler_); + + // radio ability die + stackManager_->OnAbilityDied(radioAbility); + + // set top ability active + auto topAbility = stackManager_->GetCurrentTopAbility(); + EXPECT_NE(topAbility->GetAbilityInfo().name, "RadioAbility"); + topAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // move mission to end + stackManager_->MoveMissionToEnd(musicSAbility->GetToken(), false); + + // attach radio ability + EXPECT_CALL(*mockScheduler_, ScheduleRestoreAbilityState(_)).Times(1); + stackManager_->AttachAbilityThread(mockScheduler_, radioAbility->GetToken()); + radioAbility->SetScheduler(nullptr); +} + +/* + * Feature: AaFwk + * Function: MoveMissionToEnd + * SubFunction: NA + * FunctionPoints: Floating window and full screen movement + * EnvConditions: NA + * CaseDescription: When a full screen application and a floating window application are displayed, move the floating + * window application to the background + */ + +HWTEST_F(AbilityStackModuleTest, ability_stack_test_032, TestSize.Level1) +{ + OHOS::sptr scheduler(new MockAbilityScheduler()); + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topMissionRecord1 = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord1 = stackManager_->GetCurrentTopAbility(); + topAbilityRecord1->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto musicAbilityRequest_ = GenerateAbilityRequest("device", "Music", "launcher", "com.ix.hiMusic"); + // start float ability + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + + musicAbilityRequest_.startSetting = abilityStartSetting; + ref = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, ref); + auto topMissionRecord2 = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord2 = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topMissionRecord2); + EXPECT_TRUE(topAbilityRecord2); + topAbilityRecord2->SetAbilityState(OHOS::AAFwk::ACTIVE); + + stackManager_->isMultiWinMoving_ = false; + // test case + EXPECT_EQ(topMissionRecord1->GetMissionStack()->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); + EXPECT_EQ(topMissionRecord2->GetMissionStack()->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + topAbilityRecord2->SetScheduler(scheduler); + // EXPECT_CALL(*scheduler, AsObject()).Times(testing::AtLeast(1)); + // Notify application executionon ConfigurationUpdated + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)).Times(testing::AtLeast(1)); + auto focusChangeFlag = [](bool flag) { EXPECT_TRUE(flag); }; + + EXPECT_CALL(*scheduler, NotifyTopActiveAbilityChanged(testing::_)) + .Times(testing::AtLeast(1)) + .WillOnce(testing::Invoke(focusChangeFlag)); + // test fun + ref = stackManager_->MoveMissionToEnd(topAbilityRecord2->GetToken(), true); + EXPECT_EQ(ERR_OK, ref); +} + +/* + * Feature: AaFwk + * Function: MoveMissionToEnd + * SubFunction: NA + * FunctionPoints: Floating window and full screen movement + * EnvConditions: NA + * CaseDescription: When a full screen application and a floating window application are displayed, move the floating + * window application to the background + */ + +HWTEST_F(AbilityStackModuleTest, ability_stack_test_033, TestSize.Level1) +{ + OHOS::sptr scheduler(new MockAbilityScheduler()); + OHOS::sptr schedulerRadio(new MockAbilityScheduler()); + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topMissionRecord1 = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord1 = stackManager_->GetCurrentTopAbility(); + topAbilityRecord1->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // radio ability standard + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topMissionRecordRadio = stackManager_->GetTopMissionRecord(); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topMissionRecordRadio); + EXPECT_TRUE(topAbilityRecordRadio); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto musicAbilityRequest_ = GenerateAbilityRequest("device", "Music", "launcher", "com.ix.hiMusic"); + // start float ability + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + + musicAbilityRequest_.startSetting = abilityStartSetting; + ref = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, ref); + auto topMissionRecord2 = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord2 = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topMissionRecord2); + EXPECT_TRUE(topAbilityRecord2); + topAbilityRecord2->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // test case + EXPECT_EQ(topMissionRecord1->GetMissionStack()->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); + EXPECT_EQ(topMissionRecordRadio->GetMissionStack()->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + EXPECT_EQ(topMissionRecord2->GetMissionStack()->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + stackManager_->isMultiWinMoving_ = false; + + // Music anility scheduler + topAbilityRecord2->SetScheduler(scheduler); + EXPECT_CALL(*scheduler, AsObject()).Times(testing::AtLeast(1)); + // Notify application executionon ConfigurationUpdated + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)).Times(testing::AtLeast(1)); + + auto focusChangeFlag = [](bool flag) { EXPECT_TRUE(flag); }; + + EXPECT_CALL(*scheduler, NotifyTopActiveAbilityChanged(testing::_)) + .Times(testing::AtLeast(1)) + .WillOnce(testing::Invoke(focusChangeFlag)); + + // test fun + ref = stackManager_->MoveMissionToEnd(topAbilityRecord2->GetToken(), true); + EXPECT_EQ(ERR_OK, ref); +} + +/* + * Feature: AaFwk + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: StartAbility by setting info, satrt a Split screen or floating window + * EnvConditions: NA + * CaseDescription: Start a floating window in singleton mode? + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_034, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord1 = stackManager_->GetCurrentTopAbility(); + topAbilityRecord1->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // singleton ability + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topMissionRecordRadio = stackManager_->GetTopMissionRecord(); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topMissionRecordRadio); + EXPECT_TRUE(topAbilityRecordRadio); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topMissionRecordRadio->GetMissionStack()->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + EXPECT_FALSE(stackManager_->isMultiWinMoving_); +} + +/* + * Feature: AaFwk + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: StartAbility by setting info, satrt a Split screen or floating window + * EnvConditions: NA + * CaseDescription: Start a normal full screen stack when the top of the stack is a floating window + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_035, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord1 = stackManager_->GetCurrentTopAbility(); + topAbilityRecord1->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // singleton ability + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioTopAbility", "radio", "com.ix.hiRadio"); + + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topMissionRecordRadio = stackManager_->GetTopMissionRecord(); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topMissionRecordRadio); + EXPECT_TRUE(topAbilityRecordRadio); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // start defult ability, put in float stack + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + + auto musicAbility = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(musicAbility); + musicAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + EXPECT_EQ(musicAbility->GetMissionStackId(), FLOATING_MISSION_STACK_ID); +} + +/* + * Feature: AaFwk + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: StartAbility by setting info, satrt a Split screen or floating window + * EnvConditions: NA + * CaseDescription: Start a singleton full screen stack when the top of the stack is a floating window + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_036, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord1 = stackManager_->GetCurrentTopAbility(); + topAbilityRecord1->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // singleton ability + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioTopAbility", "radio", "com.ix.hiRadio"); + + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topMissionRecordRadio = stackManager_->GetTopMissionRecord(); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topMissionRecordRadio); + EXPECT_TRUE(topAbilityRecordRadio); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // start defult singleton ability, put in float stack + auto musicTonAbilityRequest = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicTonAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicTonMissionRecord = stackManager_->GetTopMissionRecord(); + auto musicTonAbility = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(musicTonMissionRecord); + EXPECT_TRUE(musicTonAbility); + musicTonAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(musicTonMissionRecord->GetMissionStack()->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); +} + +/* + * Feature: AaFwk + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: StartAbility by setting info, satrt a Split screen or floating window + * EnvConditions: NA + * CaseDescription: Start a floating window based on a single column full screen stack + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_037, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord1 = stackManager_->GetCurrentTopAbility(); + topAbilityRecord1->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // start defult singleton ability, put in float stack + auto musicTonAbilityRequest = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicTonAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicTonMissionRecord = stackManager_->GetTopMissionRecord(); + auto musicTonAbility = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(musicTonMissionRecord); + EXPECT_TRUE(musicTonAbility); + musicTonAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // singleton ability + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topMissionRecordRadio = stackManager_->GetTopMissionRecord(); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topMissionRecordRadio); + EXPECT_TRUE(topAbilityRecordRadio); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topMissionRecordRadio->GetMissionStack()->GetMissionStackId(), FLOATING_MISSION_STACK_ID); +} + +/* + * Feature: AaFwk + * Function: MoveMissionToFloatingStack + * SubFunction: Try moving other applications to the floating window stack + * FunctionPoints: + * EnvConditions: NA + * CaseDescription: Move the luncher to the floating window stack + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_038, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord = stackManager_->GetCurrentTopAbility(); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); + + // move luncher, will fail + MissionOption missionOption; + missionOption.missionId = topAbilityRecord->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; + ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, MOVE_MISSION_TO_STACK_NOT_SUPPORT_MULTI_WIN); + + EXPECT_NE(topAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); +} + +/* + * Feature: AaFwk + * Function: MoveMissionToFloatingStack + * SubFunction: Try moving other applications to the floating window stack + * FunctionPoints: + * EnvConditions: NA + * CaseDescription: Move the defult ability to the floating window stack + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_039, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto musicTonAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + auto ref = stackManager_->StartAbility(musicTonAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + + MissionOption missionOption; + missionOption.missionId = topAbilityRecord->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; + ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, ERR_OK); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // Starting another normal application should start on the floating window stack + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(musicTonAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto radioAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(radioAbilityRecord); + radioAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(radioAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); +} + +/* + * Feature: AaFwk + * Function: MoveMissionToFloatingStack + * SubFunction: Try moving other applications to the floating window stack + * FunctionPoints: + * EnvConditions: NA + * CaseDescription: Move a single instance of the common application to the floating window stack + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_040, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto musicTonAbilityRequest = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + auto ref = stackManager_->StartAbility(musicTonAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + + MissionOption missionOption; + missionOption.missionId = topAbilityRecord->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; + ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, ERR_OK); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // Starting another singletop application should start on the floating window stack + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicTopAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto radioAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(radioAbilityRecord); + radioAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // To be discussed + EXPECT_EQ(radioAbilityRecord->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); +} + +/* + * Feature: AaFwk + * Function: MoveMissionToFloatingStack + * SubFunction: Try moving other applications to the floating window stack + * FunctionPoints: + * EnvConditions: NA + * CaseDescription: Move a floating window to the floating window stack + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_041, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord1 = stackManager_->GetCurrentTopAbility(); + topAbilityRecord1->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // singleton ability + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioTopAbility", "radio", "com.ix.hiRadio"); + + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordRadio); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + EXPECT_EQ(topAbilityRecordRadio->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // move float window + MissionOption missionOption; + missionOption.missionId = topAbilityRecordRadio->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; + ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, MOVE_MISSION_TO_STACK_NOT_EXIST_MISSION); +} + +/* + * Feature: AaFwk + * Function: MinimizeMultiWindow and MaximizeMultiWindow + * SubFunction: moving other applications to the floating window stack or Full screen stack + * FunctionPoints: + * EnvConditions: NA + * CaseDescription: Move the luncher to the floating window stack + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_042, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord = stackManager_->GetCurrentTopAbility(); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // try move luncher to float stack + ref = stackManager_->MinimizeMultiWindow(topAbilityRecord->GetMissionRecordId()); + EXPECT_EQ(MINIMIZE_MULTI_WINDOW_FAILED, ref); + ref = stackManager_->MaximizeMultiWindow(topAbilityRecord->GetMissionRecordId()); + EXPECT_EQ(MAXIMIZE_MULTIWINDOW_NOT_EXIST, ref); +} + +/* + * Feature: AaFwk + * Function: MinimizeMultiWindow and MaximizeMultiWindow + * SubFunction: moving other applications to the floating window stack or Full screen stack + * FunctionPoints: + * EnvConditions: NA + * CaseDescription: Move the singleton ability to the floating window stack + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_043, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordlauncher = stackManager_->GetCurrentTopAbility(); + topAbilityRecordlauncher->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto musicTonAbilityRequest = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicTonAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + MissionOption missionOption; + missionOption.missionId = topAbilityRecord->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; + ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, ERR_OK); + + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + stackManager_->isMultiWinMoving_ = false; + + // SetScheduler + OHOS::sptr scheduler(new MockAbilityScheduler()); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); + topAbilityRecord->SetScheduler(scheduler); + + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)).Times(1); + + OHOS::sptr schedulerluncher(new MockAbilityScheduler()); + EXPECT_CALL(*schedulerluncher, AsObject()).WillRepeatedly(Return(nullptr)); + topAbilityRecordlauncher->SetScheduler(schedulerluncher); + + auto getFocusChangeFlag = [](bool flag) { EXPECT_TRUE(flag); }; + auto loseFocusChangeFlag = [](bool flag) { EXPECT_FALSE(flag); }; + + EXPECT_CALL(*schedulerluncher, NotifyTopActiveAbilityChanged(testing::_)) + .Times(testing::AtLeast(1)) + .WillOnce(testing::Invoke(getFocusChangeFlag)); + + EXPECT_CALL(*scheduler, NotifyTopActiveAbilityChanged(testing::_)) + .Times(testing::AtLeast(1)) + .WillOnce(testing::Invoke(loseFocusChangeFlag)); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + EXPECT_FALSE(topAbilityRecord->IsToEnd()); + + ref = stackManager_->MinimizeMultiWindow(topAbilityRecord->GetMissionRecordId()); + EXPECT_EQ(ERR_OK, ref); + + EXPECT_TRUE(topAbilityRecord->IsToEnd()); +} + +/* + * Feature: AaFwk + * Function: MinimizeMultiWindow and MaximizeMultiWindow + * SubFunction: moving other applications to the floating window stack or Full screen stack + * FunctionPoints: + * EnvConditions: NA + * CaseDescription: Move the float ability to the defult stack + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_044, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto musicTonAbilityRequest = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + auto ref = stackManager_->StartAbility(musicTonAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + + MissionOption missionOption; + missionOption.missionId = topAbilityRecord->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; + ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, ERR_OK); + + // SetScheduler + OHOS::sptr scheduler(new MockAbilityScheduler()); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); + topAbilityRecord->SetScheduler(scheduler); + + EXPECT_CALL(*scheduler, NotifyMultiWinModeChanged(testing::_, testing::_)).Times(1); + EXPECT_CALL(*scheduler, NotifyTopActiveAbilityChanged(testing::_)).Times(2); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + ref = stackManager_->MaximizeMultiWindow(topAbilityRecord->GetMissionRecordId()); + EXPECT_EQ(ERR_OK, ref); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); +} + +/* + * Feature: AaFwk + * Function: MinimizeMultiWindow and MaximizeMultiWindow + * SubFunction: moving other applications to the floating window stack or Full screen stack + * FunctionPoints: + * EnvConditions: NA + * CaseDescription: Operate when there are two floating window + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_045, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(3)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord1 = stackManager_->GetCurrentTopAbility(); + topAbilityRecord1->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto radioAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(radioAbilityRecord); + radioAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(radioAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(musicAbilityRecord); + musicAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + radioAbilityRecord->SetAbilityState(OHOS::AAFwk::BACKGROUND); + + EXPECT_EQ(musicAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // SetScheduler + OHOS::sptr scheduler(new MockAbilityScheduler()); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); + radioAbilityRecord->SetScheduler(scheduler); + + // top float ability move to defult stack + ref = stackManager_->MaximizeMultiWindow(radioAbilityRecord->GetMissionRecordId()); + EXPECT_EQ(ERR_OK, ref); + + EXPECT_EQ(musicAbilityRecord->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); +} + +/* + * Feature: AaFwk + * Function: MinimizeMultiWindow and MaximizeMultiWindow + * SubFunction: moving other applications to the floating window stack or Full screen stack + * FunctionPoints: + * EnvConditions: NA + * CaseDescription: When the floating window application calls MinimizeMultiWindow, it will switch to the background + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_046, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(3)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordlauncher = stackManager_->GetCurrentTopAbility(); + topAbilityRecordlauncher->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto radioAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(radioAbilityRecord); + radioAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(radioAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(musicAbilityRecord); + musicAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + radioAbilityRecord->SetAbilityState(OHOS::AAFwk::BACKGROUND); + + EXPECT_EQ(musicAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // SetScheduler + OHOS::sptr scheduler(new MockAbilityScheduler()); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); + musicAbilityRecord->SetScheduler(scheduler); + + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)).Times(1); + + OHOS::sptr schedulerluncher(new MockAbilityScheduler()); + EXPECT_CALL(*schedulerluncher, AsObject()).WillRepeatedly(Return(nullptr)); + topAbilityRecordlauncher->SetScheduler(schedulerluncher); + + auto getFocusChangeFlag = [](bool flag) { EXPECT_TRUE(flag); }; + auto loseFocusChangeFlag = [](bool flag) { EXPECT_FALSE(flag); }; + + EXPECT_CALL(*schedulerluncher, NotifyTopActiveAbilityChanged(testing::_)) + .Times(testing::AtLeast(1)) + .WillOnce(testing::Invoke(getFocusChangeFlag)); + + EXPECT_CALL(*scheduler, NotifyTopActiveAbilityChanged(testing::_)) + .Times(testing::AtLeast(1)) + .WillOnce(testing::Invoke(loseFocusChangeFlag)); + + EXPECT_FALSE(musicAbilityRecord->IsToEnd()); + + ref = stackManager_->MinimizeMultiWindow(radioAbilityRecord->GetMissionRecordId()); + EXPECT_EQ(ERR_OK, ref); + + EXPECT_TRUE(musicAbilityRecord->IsToEnd()); +} + +/* + * Feature: AaFwk + * Function:ChangeFocusAbility + * SubFunction: Change the focus state of two active states + * FunctionPoints: + * EnvConditions: NA + * CaseDescription:Switch from the focus of the floating window to the luncher + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_047, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordLuncher = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordLuncher); + stackManager_->CompleteActive(topAbilityRecordLuncher); + + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordRadio); + stackManager_->CompleteActive(topAbilityRecordRadio); + + // set luncher scheduler + OHOS::sptr schedulerluncher(new MockAbilityScheduler()); + EXPECT_CALL(*schedulerluncher, AsObject()).WillRepeatedly(Return(nullptr)); + topAbilityRecordLuncher->SetScheduler(schedulerluncher); + + auto getFocusChangeFlag = [](bool flag) { EXPECT_TRUE(flag); }; + auto loseFocusChangeFlag = [](bool flag) { EXPECT_FALSE(flag); }; + + EXPECT_CALL(*schedulerluncher, NotifyTopActiveAbilityChanged(testing::_)) + .Times(testing::AtLeast(1)) + .WillOnce(testing::Invoke(getFocusChangeFlag)); + + // set float windows scheduler + OHOS::sptr scheduler(new MockAbilityScheduler()); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); + topAbilityRecordRadio->SetScheduler(scheduler); + + EXPECT_CALL(*scheduler, NotifyTopActiveAbilityChanged(testing::_)) + .Times(testing::AtLeast(1)) + .WillOnce(testing::Invoke(loseFocusChangeFlag)); + + // make sure both are active + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::ACTIVE); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + // luncher get the focus + ref = stackManager_->ChangeFocusAbility(topAbilityRecordRadio->GetToken(), topAbilityRecordLuncher->GetToken()); + EXPECT_EQ(ERR_OK, ref); +} + +/* + * Feature: AaFwk + * Function:ChangeFocusAbility + * SubFunction: Change the focus state of two active states + * FunctionPoints: + * EnvConditions: NA + * CaseDescription:Switch focus between two floating windows + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_048, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordLuncher = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordLuncher); + stackManager_->CompleteActive(topAbilityRecordLuncher); + + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordRadio); + stackManager_->CompleteActive(topAbilityRecordRadio); + + // in float stact + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(musicAbilityRecord); + stackManager_->CompleteActive(musicAbilityRecord); + + // Make sure to start in the floating window stack + EXPECT_EQ(musicAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + EXPECT_EQ(topAbilityRecordRadio->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // set MusicAbility scheduler + OHOS::sptr schedulerMusic(new MockAbilityScheduler()); + EXPECT_CALL(*schedulerMusic, AsObject()).WillRepeatedly(Return(nullptr)); + musicAbilityRecord->SetScheduler(schedulerMusic); + + auto loseFocusChangeFlag = [](bool flag) { EXPECT_FALSE(flag); }; + auto getFocusChangeFlag = [](bool flag) { EXPECT_TRUE(flag); }; + + EXPECT_CALL(*schedulerMusic, NotifyTopActiveAbilityChanged(testing::_)) + .Times(testing::AtLeast(1)) + .WillOnce(testing::Invoke(loseFocusChangeFlag)); + + // set RadioAbility scheduler + OHOS::sptr scheduler(new MockAbilityScheduler()); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); + topAbilityRecordRadio->SetScheduler(scheduler); + + EXPECT_CALL(*scheduler, NotifyTopActiveAbilityChanged(testing::_)) + .Times(testing::AtLeast(1)) + .WillOnce(testing::Invoke(getFocusChangeFlag)); + + // make sure both are active + musicAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + // RadioAbility get the focus + ref = stackManager_->ChangeFocusAbility(musicAbilityRecord->GetToken(), topAbilityRecordRadio->GetToken()); + EXPECT_EQ(ERR_OK, ref); +} + +/* + * Feature: AaFwk + * Function:ChangeFocusAbility + * SubFunction: Change the focus state of two active states + * FunctionPoints: + * EnvConditions: NA + * CaseDescription:The application of floating window gets the focus + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_049, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordLuncher = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordLuncher); + stackManager_->CompleteActive(topAbilityRecordLuncher); + + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordRadio); + stackManager_->CompleteActive(topAbilityRecordRadio); + + // set luncher scheduler + OHOS::sptr schedulerluncher(new MockAbilityScheduler()); + EXPECT_CALL(*schedulerluncher, AsObject()).WillRepeatedly(Return(nullptr)); + topAbilityRecordLuncher->SetScheduler(schedulerluncher); + + auto getFocusChangeFlag = [](bool flag) { EXPECT_TRUE(flag); }; + auto loseFocusChangeFlag = [](bool flag) { EXPECT_FALSE(flag); }; + + EXPECT_CALL(*schedulerluncher, NotifyTopActiveAbilityChanged(testing::_)) + .Times(testing::AtLeast(1)) + .WillOnce(testing::Invoke(getFocusChangeFlag)) + .WillOnce(testing::Invoke(loseFocusChangeFlag)); + + // set float windows scheduler + OHOS::sptr scheduler(new MockAbilityScheduler()); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); + topAbilityRecordRadio->SetScheduler(scheduler); + + EXPECT_CALL(*scheduler, NotifyTopActiveAbilityChanged(testing::_)) + .Times(testing::AtLeast(1)) + .WillOnce(testing::Invoke(loseFocusChangeFlag)) + .WillOnce(testing::Invoke(getFocusChangeFlag)); + + // make sure both are active + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::ACTIVE); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + // luncher get the focus + ref = stackManager_->ChangeFocusAbility(topAbilityRecordRadio->GetToken(), topAbilityRecordLuncher->GetToken()); + EXPECT_EQ(ERR_OK, ref); + + // make sure both are active + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::ACTIVE); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + // Click the floating window again to get the focus + ref = stackManager_->ChangeFocusAbility(topAbilityRecordLuncher->GetToken(), topAbilityRecordRadio->GetToken()); + EXPECT_EQ(ERR_OK, ref); +} + +/* + * Feature: AaFwk + * Function:GetFloatingMissions + * SubFunction: Get the information of floating window application + * FunctionPoints: + * EnvConditions: NA + * CaseDescription:Get the information of floating window application.. + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_050, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + auto ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + + MissionOption missionOption; + missionOption.missionId = topAbilityRecord->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; + ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, ERR_OK); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // Starting another singletop application should start on the floating window stack + auto musicTopAbilityRequest = GenerateAbilityRequest("device", "MusicTopAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicTopAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(musicAbilityRecord); + musicAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(musicAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // get missions + std::vector list; + stackManager_->GetFloatingMissions(list); + int size = list.size(); + EXPECT_EQ(size, 1); + + AbilityMissionInfo info = list.front(); + EXPECT_EQ(info.baseAbility.abilityName_, "MusicAbility"); + EXPECT_EQ(info.topAbility.abilityName_, "MusicTopAbility"); +} + +/* + * Feature: AaFwk + * Function:GetFloatingMissions + * SubFunction: Get the information of floating window application + * FunctionPoints: + * EnvConditions: NA + * CaseDescription:Get the information of floating window application + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_051, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto musicTonAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + auto ref = stackManager_->StartAbility(musicTonAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + + MissionOption missionOption; + missionOption.missionId = topAbilityRecord->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; + ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, ERR_OK); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // Starting another singletop application should start on the floating window stack + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicTopAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(musicAbilityRecord); + musicAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(musicAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + std::vector list; + stackManager_->GetFloatingMissions(list); + int size = list.size(); + EXPECT_EQ(size, 1); + + AbilityMissionInfo info = list.front(); + EXPECT_EQ(info.baseAbility.abilityName_, "MusicAbility"); + EXPECT_EQ(info.topAbility.abilityName_, "MusicTopAbility"); +} + +/* + * Feature: AaFwk + * Function:GetFloatingMissions + * SubFunction: Get the information of floating window application + * FunctionPoints: + * EnvConditions: NA + * CaseDescription:Get the information of floating window application + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_052, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto musicTonAbilityRequest = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + auto ref = stackManager_->StartAbility(musicTonAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + + MissionOption missionOption; + missionOption.missionId = topAbilityRecord->GetMissionRecordId(); + missionOption.winModeKey = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING; + ref = stackManager_->MoveMissionToFloatingStack(missionOption); + EXPECT_EQ(ref, ERR_OK); + + EXPECT_EQ(topAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // Starting another singletop application should start on the floating window stack + auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicTopAbility", "music", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto musicAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(musicAbilityRecord); + musicAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(musicAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto radioAbilityRecord = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(radioAbilityRecord); + radioAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(radioAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + std::vector list; + stackManager_->GetFloatingMissions(list); + int size = list.size(); + EXPECT_EQ(size, 1); + + AbilityMissionInfo info = list.front(); + EXPECT_EQ(info.baseAbility.abilityName_, "MusicAbility"); + EXPECT_EQ(info.topAbility.abilityName_, "RadioAbility"); +} + +/* + * Feature: AaFwk + * Function:GetFloatingMissions + * SubFunction: Get the information of floating window application + * FunctionPoints: + * EnvConditions: NA + * CaseDescription:Get the information of floating window application + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_053, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordLuncher = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordLuncher); + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordRadio); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + + std::vector list; + stackManager_->GetFloatingMissions(list); + int size = list.size(); + EXPECT_EQ(size, 1); + + AbilityMissionInfo info = list.front(); + EXPECT_EQ(info.topAbility.abilityName_, "RadioAbility"); + EXPECT_EQ(info.baseAbility.abilityName_, "RadioAbility"); +} + +/* + * Feature: AaFwk + * Function:RemoveMissionById + * SubFunction: delete mission by id + * FunctionPoints: + * EnvConditions: NA + * CaseDescription: 01 + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_054, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordLuncher = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordLuncher); + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto music1AbilityRequest_ = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(music1AbilityRequest_); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto music2AbilityRequest_ = GenerateAbilityRequest("device", "MusicAbility2", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(music2AbilityRequest_); + auto secondTopAbility = stackManager_->GetCurrentTopAbility(); + secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioSAbility", "radio", "com.ix.hiRadio"); + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordRadio); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + + GTEST_LOG_(INFO) << "firstTopAbility :" << firstTopAbility->GetMissionRecordId(); + GTEST_LOG_(INFO) << "secondTopAbility :" << secondTopAbility->GetMissionRecordId(); + GTEST_LOG_(INFO) << "topAbilityRecordRadio :" << topAbilityRecordRadio->GetMissionRecordId(); + + EXPECT_EQ(topAbilityRecordLuncher->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); + EXPECT_EQ(firstTopAbility->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + EXPECT_EQ(secondTopAbility->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + EXPECT_EQ(topAbilityRecordRadio->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + auto missionID = firstTopAbility->GetMissionRecordId(); + ref = stackManager_->RemoveMissionById(missionID); + EXPECT_EQ(ERR_OK, ref); + + auto missionRecord = stackManager_->GetMissionRecordById(missionID); + EXPECT_TRUE(missionRecord == nullptr); + + // luncher stack move to top + auto currentStack = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(currentStack != nullptr); + EXPECT_EQ(currentStack->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); +} + +/* + * Feature: AaFwk + * Function:OnAbilityDied + * SubFunction: ability died + * FunctionPoints: + * EnvConditions: NA + * CaseDescription:02 + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_055, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordLuncher = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordLuncher); + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto music1AbilityRequest_ = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(music1AbilityRequest_); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto music2AbilityRequest_ = GenerateAbilityRequest("device", "MusicAbility2", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(music2AbilityRequest_); + auto secondTopAbility = stackManager_->GetCurrentTopAbility(); + secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioSAbility", "radio", "com.ix.hiRadio"); + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordRadio); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + + GTEST_LOG_(INFO) << "firstTopAbility :" << firstTopAbility->GetMissionRecordId(); + GTEST_LOG_(INFO) << "secondTopAbility :" << secondTopAbility->GetMissionRecordId(); + GTEST_LOG_(INFO) << "topAbilityRecordRadio :" << topAbilityRecordRadio->GetMissionRecordId(); + + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::BACKGROUND); + firstTopAbility->SetAbilityState(OHOS::AAFwk::BACKGROUND); + secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topAbilityRecordLuncher->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); + EXPECT_EQ(firstTopAbility->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + EXPECT_EQ(secondTopAbility->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + EXPECT_EQ(topAbilityRecordRadio->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + // let ability died + stackManager_->OnAbilityDied(firstTopAbility); + + EXPECT_TRUE(secondTopAbility != nullptr); + EXPECT_EQ(firstTopAbility->GetAbilityState(), OHOS::AAFwk::INITIAL); +} + +/* + * Feature: AaFwk + * Function:OnAbilityDied + * SubFunction: ability died + * FunctionPoints: + * EnvConditions: NA + * CaseDescription:03 Delete the defult stack and pull it up again + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_056, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordLuncher = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordLuncher); + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto music1AbilityRequest_ = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(music1AbilityRequest_); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto music2AbilityRequest_ = GenerateAbilityRequest("device", "MusicAbility2", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(music2AbilityRequest_); + auto secondTopAbility = stackManager_->GetCurrentTopAbility(); + secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioSAbility", "radio", "com.ix.hiRadio"); + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordRadio); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + + GTEST_LOG_(INFO) << "firstTopAbility :" << firstTopAbility->GetMissionRecordId(); + GTEST_LOG_(INFO) << "secondTopAbility :" << secondTopAbility->GetMissionRecordId(); + GTEST_LOG_(INFO) << "topAbilityRecordRadio :" << topAbilityRecordRadio->GetMissionRecordId(); + + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::BACKGROUND); + firstTopAbility->SetAbilityState(OHOS::AAFwk::BACKGROUND); + secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topAbilityRecordLuncher->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); + EXPECT_EQ(firstTopAbility->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + EXPECT_EQ(secondTopAbility->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + EXPECT_EQ(topAbilityRecordRadio->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + + OHOS::sptr scheduler(new MockAbilityScheduler()); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); + firstTopAbility->SetScheduler(scheduler); + + EXPECT_CALL(*scheduler, ScheduleRestoreAbilityState(testing::_)).Times(testing::AtLeast(1)); + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)).Times(1); + // let ability died + stackManager_->OnAbilityDied(firstTopAbility); + + EXPECT_TRUE(secondTopAbility != nullptr); + EXPECT_EQ(firstTopAbility->GetAbilityState(), OHOS::AAFwk::INITIAL); + + // restart + ref = stackManager_->StartAbility(music1AbilityRequest_); + EXPECT_EQ(ERR_OK, ref); +} + +/* + * Feature: AaFwk + * Function:RemoveMissionById + * SubFunction: delete mission by id + * FunctionPoints: + * EnvConditions: NA + * CaseDescription: 04 remove radioAbility mission. + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_057, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordLuncher = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordLuncher); + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordRadio); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto music1AbilityRequest_ = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(music1AbilityRequest_); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::BACKGROUND); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topAbilityRecordLuncher->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); + EXPECT_EQ(topAbilityRecordRadio->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + EXPECT_EQ(firstTopAbility->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + + auto missionID = topAbilityRecordRadio->GetMissionRecordId(); + ref = stackManager_->RemoveMissionById(missionID); + EXPECT_EQ(ERR_OK, ref); + + auto missionRecord = stackManager_->GetMissionRecordById(missionID); + EXPECT_TRUE(missionRecord == nullptr); + + auto currentStack = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(currentStack != nullptr); + EXPECT_EQ(currentStack->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); +} + +/* + * Feature: AaFwk + * Function:RemoveMissionById + * SubFunction: delete mission by id + * FunctionPoints: + * EnvConditions: NA + * CaseDescription: 05 ability died RadioAbility. + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_058, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(2)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordLuncher = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordLuncher); + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordRadio); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto music1AbilityRequest_ = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(music1AbilityRequest_); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::BACKGROUND); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topAbilityRecordLuncher->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); + EXPECT_EQ(topAbilityRecordRadio->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + EXPECT_EQ(firstTopAbility->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + + // let ability died + stackManager_->OnAbilityDied(topAbilityRecordRadio); + + EXPECT_EQ(topAbilityRecordRadio->GetAbilityState(), OHOS::AAFwk::INITIAL); +} + +/* + * Feature: AaFwk + * Function:RemoveMissionById + * SubFunction: delete mission by id + * FunctionPoints: + * EnvConditions: NA + * CaseDescription: 06 restart RadioAbility, it will be call onrestore + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_059, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(3)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordLuncher = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordLuncher); + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); + // float flag + auto abilityStartSetting = AbilityStartSetting::GetEmptySetting(); + EXPECT_TRUE(abilityStartSetting); + abilityStartSetting->AddProperty(AbilityStartSetting::WINDOW_MODE_KEY, + std::to_string(AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING)); + radioAbilityRequest.startSetting = abilityStartSetting; + + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); + auto topAbilityRecordRadio = stackManager_->GetCurrentTopAbility(); + EXPECT_TRUE(topAbilityRecordRadio); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto music1AbilityRequest_ = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(music1AbilityRequest_); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + topAbilityRecordLuncher->SetAbilityState(OHOS::AAFwk::BACKGROUND); + topAbilityRecordRadio->SetAbilityState(OHOS::AAFwk::ACTIVE); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + EXPECT_EQ(topAbilityRecordLuncher->GetMissionStackId(), LAUNCHER_MISSION_STACK_ID); + EXPECT_EQ(topAbilityRecordRadio->GetMissionStackId(), FLOATING_MISSION_STACK_ID); + EXPECT_EQ(firstTopAbility->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + + OHOS::sptr scheduler(new MockAbilityScheduler()); + EXPECT_CALL(*scheduler, AsObject()).WillRepeatedly(Return(nullptr)); + topAbilityRecordRadio->SetScheduler(scheduler); + + EXPECT_CALL(*scheduler, ScheduleRestoreAbilityState(testing::_)).Times(testing::AtLeast(1)); + + // let ability died + stackManager_->OnAbilityDied(topAbilityRecordRadio); + + auto currentStack = stackManager_->GetCurrentMissionStack(); + EXPECT_TRUE(currentStack != nullptr); + EXPECT_EQ(currentStack->GetMissionStackId(), DEFAULT_MISSION_STACK_ID); + + EXPECT_EQ(topAbilityRecordRadio->GetAbilityState(), OHOS::AAFwk::INITIAL); + + // restart + ref = stackManager_->StartAbility(radioAbilityRequest); + EXPECT_EQ(ERR_OK, ref); } } // namespace AAFwk diff --git a/services/test/moduletest/dump_module_test/BUILD.gn b/services/test/moduletest/dump_module_test/BUILD.gn index 2385abbf276..12f748c226c 100644 --- a/services/test/moduletest/dump_module_test/BUILD.gn +++ b/services/test/moduletest/dump_module_test/BUILD.gn @@ -22,14 +22,13 @@ ohos_moduletest("dump_module_test") { "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/aafwk/standard/services/test/moduletest/module_test_dump_util/", + "//foundation/aafwk/standard/services/test/mock/include", ] sources = [ "${services_path}/abilitymgr/test/unittest/phone/ability_with_applications_test/mock_ability_scheduler.cpp", "//foundation/aafwk/standard/services/test/moduletest/module_test_dump_util/module_test_dump_util.cpp", "dump_module_test.cpp", - - #"${services_path}/abilitymgr/test/unittest/phone/ability_dump_test/mock_app_manager.cpp", ] configs = [ diff --git a/services/test/moduletest/dump_module_test/dump_module_test.cpp b/services/test/moduletest/dump_module_test/dump_module_test.cpp index 240181e551b..7dc60020da0 100755 --- a/services/test/moduletest/dump_module_test/dump_module_test.cpp +++ b/services/test/moduletest/dump_module_test/dump_module_test.cpp @@ -27,7 +27,7 @@ #undef protected #include "ability_manager_errors.h" #include "gtest/gtest.h" -#include "mock_bundle_manager.h" +#include "mock_bundle_mgr.h" #include "want.h" #include "sa_mgr_client.h" #include "appmgr_test_service.h" @@ -496,11 +496,11 @@ HWTEST_F(DumpModuleTest, dump_module_test_008, TestSize.Level2) std::vector dumpInfo; std::vector abilityNames; - ASSERT_TRUE(g_abilityMs); + EXPECT_TRUE(g_abilityMs); auto stackMgr = g_abilityMs->GetStackManager(); - ASSERT_TRUE(stackMgr); + EXPECT_TRUE(stackMgr); auto missionRecord = stackMgr->GetTopMissionRecord(); - ASSERT_TRUE(missionRecord); + EXPECT_TRUE(missionRecord); int id = missionRecord->GetMissionRecordId(); args += " "; args += std::to_string(id); @@ -639,7 +639,7 @@ HWTEST_F(DumpModuleTest, dump_module_test_011, TestSize.Level2) g_abilityMs->DumpState(args, result); auto stackMgr = g_abilityMs->GetStackManager(); - ASSERT_TRUE(stackMgr); + EXPECT_TRUE(stackMgr); g_abilityMs->DumpWaittingAbilityQueue(waitingQueueResult); ASSERT_EQ(waitingQueueResult, expectResult); @@ -655,7 +655,7 @@ HWTEST_F(DumpModuleTest, dump_module_test_011, TestSize.Level2) EXPECT_EQ(refwant2, START_ABILITY_WAITING); g_abilityMs->DumpState(args, result); - ASSERT_TRUE(stackMgr); + EXPECT_TRUE(stackMgr); stackMgr->DumpWaittingAbilityQueue(waitingQueueResult); EXPECT_NE(std::string::npos, waitingQueueResult.find("com.ix.hiRadio")); } diff --git a/services/test/moduletest/ipc_ability_mgr_test/BUILD.gn b/services/test/moduletest/ipc_ability_mgr_test/BUILD.gn old mode 100644 new mode 100755 index ae3b9685ae7..a07b9f281d4 --- a/services/test/moduletest/ipc_ability_mgr_test/BUILD.gn +++ b/services/test/moduletest/ipc_ability_mgr_test/BUILD.gn @@ -18,7 +18,7 @@ module_output_path = "aafwk_standard/mstabilitymgrservice" ohos_moduletest("IpcAbilityMgrServiceModuleTest") { module_out_path = module_output_path - + include_dirs = [ "//third_party/jsoncpp/include" ] sources = [ "ipc_ability_mgr_module_test.cpp" ] configs = [ @@ -38,6 +38,7 @@ ohos_moduletest("IpcAbilityMgrServiceModuleTest") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/services/test/moduletest/ipc_ability_mgr_test/ipc_ability_mgr_module_test.cpp b/services/test/moduletest/ipc_ability_mgr_test/ipc_ability_mgr_module_test.cpp index 509a4e52dc8..bea7a9e12ba 100644 --- a/services/test/moduletest/ipc_ability_mgr_test/ipc_ability_mgr_module_test.cpp +++ b/services/test/moduletest/ipc_ability_mgr_test/ipc_ability_mgr_module_test.cpp @@ -124,7 +124,7 @@ HWTEST_F(IpcAbilityMgrModuleTest, AbilityMgrService_IPC_002, TestSize.Level1) std::string bundleName = "com.ix.aafwk.moduletest"; auto abilityRequest = CreateAbilityRequest(abilityName, bundleName); auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - ASSERT_TRUE(abilityRecord); + EXPECT_TRUE(abilityRecord); for (int i = 0; i < COUNT; i++) { sptr mockAbilityMgr(new MockAbilityMgrService()); sptr abilityMgrClient = iface_cast(mockAbilityMgr); diff --git a/services/test/moduletest/ipc_ability_scheduler_test/BUILD.gn b/services/test/moduletest/ipc_ability_scheduler_test/BUILD.gn old mode 100644 new mode 100755 index e7d2016550d..f66b7c28b32 --- a/services/test/moduletest/ipc_ability_scheduler_test/BUILD.gn +++ b/services/test/moduletest/ipc_ability_scheduler_test/BUILD.gn @@ -19,6 +19,8 @@ module_output_path = "aafwk_standard/mstabilitymgrservice" ohos_moduletest("IpcAbilitySchedulerModuleTest") { module_out_path = module_output_path + include_dirs = [ "//third_party/jsoncpp/include" ] + sources = [ "${services_path}/abilitymgr/src/ability_scheduler_proxy.cpp", "${services_path}/abilitymgr/src/ability_scheduler_stub.cpp", @@ -47,6 +49,7 @@ ohos_moduletest("IpcAbilitySchedulerModuleTest") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] diff --git a/services/test/moduletest/panding_want_manager_test/BUILD.gn b/services/test/moduletest/panding_want_manager_test/BUILD.gn old mode 100644 new mode 100755 index c8c2df23dae..078092bf133 --- a/services/test/moduletest/panding_want_manager_test/BUILD.gn +++ b/services/test/moduletest/panding_want_manager_test/BUILD.gn @@ -26,6 +26,8 @@ ohos_moduletest("PandingWantMgrTest") { "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmg", "//foundation/appexecfwk/standard/kits/appkit/native/app/include", + "//base/notification/ns_standard/interfaces/innerkits/wantagent/include", + "//third_party/jsoncpp/include", "//base/notification/ans_standard/interfaces/innerkits/wantagent/include", ] @@ -40,6 +42,7 @@ ohos_moduletest("PandingWantMgrTest") { "//base/notification/ans_standard/frameworks/wantagent/src/want_agent_log_wrapper.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_client.cpp", "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/sa_mgr/src/sa_mgr_client_mock.cpp", + "//foundation/aafwk/standard/services/test/mock/src/mock_app_mgr_client.cpp", "//foundation/aafwk/standard/services/test/mock/src/mock_bundle_mgr.cpp", "//foundation/appexecfwk/standard/common/log/src/app_log_wrapper.cpp", "panding_want_manager_test.cpp", @@ -63,6 +66,7 @@ ohos_moduletest("PandingWantMgrTest") { "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/services/test/moduletest/panding_want_manager_test/panding_want_manager_test.cpp b/services/test/moduletest/panding_want_manager_test/panding_want_manager_test.cpp index dd03a1bb924..7d580121a24 100644 --- a/services/test/moduletest/panding_want_manager_test/panding_want_manager_test.cpp +++ b/services/test/moduletest/panding_want_manager_test/panding_want_manager_test.cpp @@ -452,6 +452,7 @@ HWTEST_F(PandingWantMgrTest, pending_want_mgr_test_003, TestSize.Level1) EXPECT_TRUE(serviceRecord); Want serviceWant = serviceRecord->GetWant(); ElementName element = serviceWant.GetElement(); + EXPECT_EQ(element.GetAbilityName(), "hiService"); EXPECT_EQ(element.GetBundleName(), "com.ix.hiService"); } diff --git a/tools/BUILD.gn b/tools/BUILD.gn old mode 100644 new mode 100755 diff --git a/tools/aa/BUILD.gn b/tools/aa/BUILD.gn old mode 100644 new mode 100755 index e7b0da5f53a..dd5e7b0ca58 --- a/tools/aa/BUILD.gn +++ b/tools/aa/BUILD.gn @@ -19,6 +19,7 @@ config("ability_command_config") { "include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "//utils/system/safwk/native/include", + "//third_party/jsoncpp/include", ] } diff --git a/tools/test/mock/mock_ability_manager_stub.h b/tools/test/mock/mock_ability_manager_stub.h index a389a832015..c5e8b4506b8 100644 --- a/tools/test/mock/mock_ability_manager_stub.h +++ b/tools/test/mock/mock_ability_manager_stub.h @@ -98,6 +98,19 @@ public: MOCK_METHOD1(UnlockMission, int(int)); MOCK_METHOD2(SetMissionDescriptionInfo, int(const sptr &token, const MissionDescriptionInfo &info)); MOCK_METHOD0(GetMissionLockModeState, int()); + MOCK_METHOD1(UpdateConfiguration, int(const DummyConfiguration &)); + MOCK_METHOD4(StartAbility, int(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode)); + MOCK_METHOD1(MoveMissionToFloatingStack, int(const MissionOption &missionOption)); + MOCK_METHOD1(MoveMissionToSplitScreenStack, int(const MissionOption &missionOption)); + MOCK_METHOD2( + ChangeFocusAbility, int(const sptr &lostFocusToken, const sptr &getFocusToken)); + MOCK_METHOD1(MinimizeMultiWindow, int(int missionId)); + MOCK_METHOD1(MaximizeMultiWindow, int(int missionId)); + MOCK_METHOD1(GetFloatingMissions, int(std::vector &list)); + MOCK_METHOD1(CloseMultiWindow, int(int missionId)); + MOCK_METHOD1(SetMissionStackSetting, int(const StackSetting &stackSetting)); + MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id)); public: std::string powerState_; diff --git a/tools/test/systemtest/aa/BUILD.gn b/tools/test/systemtest/aa/BUILD.gn old mode 100644 new mode 100755 index 87f139d870e..f1db856675e --- a/tools/test/systemtest/aa/BUILD.gn +++ b/tools/test/systemtest/aa/BUILD.gn @@ -19,6 +19,8 @@ module_output_path = "aafwk_standard/tools" ohos_systemtest("ability_command_start_system_test") { module_out_path = module_output_path + include_dirs = [ "//third_party/jsoncpp/include" ] + sources = [ "ability_command_start_system_test.cpp", "tool_system_test.cpp", @@ -34,6 +36,7 @@ ohos_systemtest("ability_command_start_system_test") { deps = [ "${aafwk_path}/tools/aa:tools_aa_source_set", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", ] external_deps = [ @@ -61,6 +64,7 @@ ohos_systemtest("ability_command_stop_service_system_test") { deps = [ "${aafwk_path}/tools/aa:tools_aa_source_set", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", ] external_deps = [ @@ -73,6 +77,8 @@ ohos_systemtest("ability_command_stop_service_system_test") { ohos_systemtest("ability_command_dump_system_test") { module_out_path = module_output_path + include_dirs = [ "//third_party/jsoncpp/include" ] + sources = [ "ability_command_dump_system_test.cpp", "tool_system_test.cpp", @@ -88,6 +94,7 @@ ohos_systemtest("ability_command_dump_system_test") { deps = [ "${aafwk_path}/tools/aa:tools_aa_source_set", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", ] external_deps = [ -- Gitee