diff --git a/bundle.json b/bundle.json index 41f016c6..b427b7ff 100644 --- a/bundle.json +++ b/bundle.json @@ -41,7 +41,6 @@ "input", "multimedia_image_standard", "os_account", - "power_manager_native", "safwk", "samgr_standard", "utils_base" diff --git a/form_runtime/BUILD.gn b/form_runtime/BUILD.gn index a86164a2..72f8d47b 100644 --- a/form_runtime/BUILD.gn +++ b/form_runtime/BUILD.gn @@ -100,7 +100,6 @@ ohos_shared_library("libfms") { "form_runtime:form_manager", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "power_manager_native:powermgr_client", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "time_native:time_service", @@ -115,6 +114,12 @@ ohos_shared_library("libfms") { ] } + defines = [] + if (ability_runtime_power) { + defines = [ "SUPPORT_POWER" ] + external_deps += [ "power_manager_native:powermgr_client" ] + } + subsystem_name = "aafwk" part_name = "form_runtime" } diff --git a/form_runtime/services/src/form_mgr_adapter.cpp b/form_runtime/services/src/form_mgr_adapter.cpp index 36838336..e04c4377 100644 --- a/form_runtime/services/src/form_mgr_adapter.cpp +++ b/form_runtime/services/src/form_mgr_adapter.cpp @@ -48,7 +48,6 @@ #include "ipc_skeleton.h" #include "iservice_registry.h" #include "ohos_account_kits.h" -#include "power_mgr_client.h" #include "system_ability_definition.h" namespace OHOS { diff --git a/form_runtime/services/src/form_provider_mgr.cpp b/form_runtime/services/src/form_provider_mgr.cpp index c3ed1deb..0b0c6c9c 100644 --- a/form_runtime/services/src/form_provider_mgr.cpp +++ b/form_runtime/services/src/form_provider_mgr.cpp @@ -29,8 +29,9 @@ #include "form_refresh_connection.h" #include "form_timer_mgr.h" #include "hilog_wrapper.h" +#ifdef SUPPORT_POWER #include "power_mgr_client.h" - +#endif namespace OHOS { namespace AppExecFwk { FormProviderMgr::FormProviderMgr(){} @@ -133,12 +134,14 @@ ErrCode FormProviderMgr::RefreshForm(const int64_t formId, const Want &want, boo FormDataMgr::GetInstance().SetCountTimerRefresh(formId, true); } +#ifdef SUPPORT_POWER bool screenOnFlag = PowerMgr::PowerMgrClient::GetInstance().IsScreenOn(); if (!screenOnFlag) { FormDataMgr::GetInstance().SetNeedRefresh(formId, true); HILOG_ERROR("%{public}s fail, screen off, set refresh flag, do not refresh now", __func__); return ERR_OK; } +#endif bool needRefresh = IsNeedToFresh(record, formId, isVisibleToFresh); if (!needRefresh) { @@ -313,6 +316,7 @@ ErrCode FormProviderMgr::UpdateForm(const int64_t formId, // update form for host clients FormDataMgr::GetInstance().UpdateHostNeedRefresh(formId, true); +#ifdef SUPPORT_POWER bool screenOnFlag = PowerMgr::PowerMgrClient::GetInstance().IsScreenOn(); if (screenOnFlag) { if (FormDataMgr::GetInstance().UpdateHostForm(formId, formRecord)) { @@ -320,9 +324,13 @@ ErrCode FormProviderMgr::UpdateForm(const int64_t formId, formRecord.formProviderInfo.SetUpgradeFlg(false); } } + + HILOG_DEBUG("%{public}s screenOn:%{public}d.", __func__, screenOnFlag); +#endif + // check if cache data size is less than 1k or not std::string jsonData = formRecord.formProviderInfo.GetFormDataString(); // get json data - HILOG_DEBUG("%{public}s screenOn:%{public}d jsonData:%{public}s.", __func__, screenOnFlag, jsonData.c_str()); + HILOG_DEBUG("%{public}s jsonData:%{public}s.", __func__, jsonData.c_str()); std::map, int32_t>> imageDataMap = formProviderData.GetImageDataMap(); // check if cache data size is less than 1k or not @@ -347,11 +355,13 @@ int FormProviderMgr::MessageEvent(const int64_t formId, const FormRecord &record { HILOG_INFO("%{public}s called, formId:%{public}" PRId64 ".", __func__, formId); +#ifdef SUPPORT_POWER bool screenOnFlag = PowerMgr::PowerMgrClient::GetInstance().IsScreenOn(); if (!screenOnFlag) { HILOG_WARN("%{public}s fail, screen off now", __func__); return ERR_APPEXECFWK_FORM_COMMON_CODE; } +#endif sptr formMsgEventConnection = new FormMsgEventConnection(formId, want, record.bundleName, record.abilityName); diff --git a/form_runtime/test/unittest/fms_form_mgr_message_event_test/BUILD.gn b/form_runtime/test/unittest/fms_form_mgr_message_event_test/BUILD.gn index db5e6950..d1b5c9dd 100644 --- a/form_runtime/test/unittest/fms_form_mgr_message_event_test/BUILD.gn +++ b/form_runtime/test/unittest/fms_form_mgr_message_event_test/BUILD.gn @@ -12,6 +12,7 @@ # limitations under the License. import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") import("//foundation/aafwk/standard/form_runtime/form_runtime.gni") module_output_path = "form_runtime/formmgrservice" @@ -71,8 +72,12 @@ ohos_unittest("FmsFormMgrMessageEventTest") { "form_runtime:form_manager", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "power_manager_native:powermgr_client", ] + + if (ability_runtime_power) { + defines = [ "SUPPORT_POWER" ] + external_deps += [ "power_manager_native:powermgr_client" ] + } } group("unittest") { diff --git a/form_runtime/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp b/form_runtime/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp index f1a039be..49c0adcc 100644 --- a/form_runtime/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp +++ b/form_runtime/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp @@ -32,7 +32,9 @@ #include "mock_ability_manager.h" #include "mock_bundle_manager.h" #include "mock_form_host_client.h" +#ifdef SUPPORT_POWER #include "power_mgr_client.h" +#endif #include "running_process_info.h" #include "system_ability_definition.h" @@ -133,13 +135,14 @@ HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_001, TestSize.Level0) want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); +#ifdef SUPPORT_POWER bool screenOnFlag = PowerMgr::PowerMgrClient::GetInstance().IsScreenOn(); if (!screenOnFlag) { EXPECT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, FormMgr::GetInstance().MessageEvent(formId, want, token_)); } else { EXPECT_EQ(ERR_OK, FormMgr::GetInstance().MessageEvent(formId, want, token_)); } - +#endif GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_001 end"; } diff --git a/form_runtime/test/unittest/fms_form_provider_mgr_test/BUILD.gn b/form_runtime/test/unittest/fms_form_provider_mgr_test/BUILD.gn index d4538e70..1a65e4f8 100644 --- a/form_runtime/test/unittest/fms_form_provider_mgr_test/BUILD.gn +++ b/form_runtime/test/unittest/fms_form_provider_mgr_test/BUILD.gn @@ -12,6 +12,7 @@ # limitations under the License. import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") import("//foundation/aafwk/standard/form_runtime/form_runtime.gni") module_output_path = "form_runtime/formmgrservice" @@ -71,8 +72,12 @@ ohos_unittest("FmsFormProviderMgrTest") { "form_runtime:form_manager", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "power_manager_native:powermgr_client", ] + + if (ability_runtime_power) { + defines = [ "SUPPORT_POWER" ] + external_deps += [ "power_manager_native:powermgr_client" ] + } } group("unittest") { diff --git a/form_runtime/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp b/form_runtime/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp index 75077c03..140fa49d 100644 --- a/form_runtime/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp +++ b/form_runtime/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp @@ -34,7 +34,9 @@ #include "mock_ability_manager.h" #include "mock_bundle_manager.h" #include "mock_form_host_client.h" +#ifdef SUPPORT_POWER #include "power_mgr_client.h" +#endif #include "running_process_info.h" #include "system_ability_definition.h" @@ -213,6 +215,7 @@ HWTEST_F(FmsFormProviderMgrTest, RefreshForm_002, TestSize.Level0) FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); +#ifdef SUPPORT_POWER bool screenOnFlag = PowerMgr::PowerMgrClient::GetInstance().IsScreenOn(); if (!screenOnFlag) { EXPECT_EQ(ERR_OK, FormProviderMgr::GetInstance().RefreshForm(formId, want, true)); @@ -220,6 +223,7 @@ HWTEST_F(FmsFormProviderMgrTest, RefreshForm_002, TestSize.Level0) EXPECT_EQ(ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL, FormProviderMgr::GetInstance().RefreshForm(formId, want, true)); } +#endif GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_005 end"; } diff --git a/frameworks/kits/ability/ability_runtime/include/ability_context.h b/frameworks/kits/ability/ability_runtime/include/ability_context.h index 46b36b71..2f5fae32 100644 --- a/frameworks/kits/ability/ability_runtime/include/ability_context.h +++ b/frameworks/kits/ability/ability_runtime/include/ability_context.h @@ -230,24 +230,6 @@ public: */ virtual ErrCode ReleaseAbility(const std::shared_ptr &callback) = 0; - /** - * @brief Set mission label of this ability. - * - * @param label the label of this ability. - * @return Returns ERR_OK if success. - */ - virtual ErrCode SetMissionLabel(const std::string &label) = 0; - -#ifdef SUPPORT_GRAPHICS - /** - * @brief Set mission icon of this ability. - * - * @param icon the icon of this ability. - * @return Returns ERR_OK if success. - */ - virtual ErrCode SetMissionIcon(const std::shared_ptr &icon) = 0; -#endif - /** * @brief Get LocalCallContainer. * @@ -258,7 +240,24 @@ public: virtual void SetConfiguration(const std::shared_ptr &config) = 0; virtual void RegisterAbilityCallback(std::weak_ptr abilityCallback) = 0; + #ifdef SUPPORT_GRAPHICS + /** + * @brief Set mission label of this ability. + * + * @param label the label of this ability. + * @return Returns ERR_OK if success. + */ + virtual ErrCode SetMissionLabel(const std::string &label) = 0; + + /** + * @brief Set mission icon of this ability. + * + * @param icon the icon of this ability. + * @return Returns ERR_OK if success. + */ + virtual ErrCode SetMissionIcon(const std::shared_ptr &icon) = 0; + virtual int GetCurrentWindowMode() = 0; #endif virtual bool IsTerminating() = 0; diff --git a/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h b/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h index a5181d4b..b61c1696 100644 --- a/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h +++ b/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h @@ -86,24 +86,6 @@ public: ErrCode RestoreWindowStage(NativeEngine& engine, NativeValue* contentStorage) override; - /** - * @brief Set mission label of this ability. - * - * @param label the label of this ability. - * @return Returns ERR_OK if success. - */ - ErrCode SetMissionLabel(const std::string &label) override; - -#ifdef SUPPORT_GRAPHICS - /** - * @brief Set mission icon of this ability. - * - * @param icon the icon of this ability. - * @return Returns ERR_OK if success. - */ - ErrCode SetMissionIcon(const std::shared_ptr &icon) override; -#endif - void SetStageContext(const std::shared_ptr &stageContext); /** @@ -183,6 +165,22 @@ public: } #ifdef SUPPORT_GRAPHICS + /** + * @brief Set mission label of this ability. + * + * @param label the label of this ability. + * @return Returns ERR_OK if success. + */ + ErrCode SetMissionLabel(const std::string &label) override; + + /** + * @brief Set mission icon of this ability. + * + * @param icon the icon of this ability. + * @return Returns ERR_OK if success. + */ + ErrCode SetMissionIcon(const std::shared_ptr &icon) override; + /** * get current window mode */ diff --git a/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp b/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp index 39f4ed41..4a8f9867 100644 --- a/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp +++ b/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp @@ -455,6 +455,13 @@ ErrCode AbilityContextImpl::ReleaseAbility(const std::shared_ptr return localCallContainer_->Release(callback); } +void AbilityContextImpl::RegisterAbilityCallback(std::weak_ptr abilityCallback) +{ + HILOG_INFO("%{public}s called.", __func__); + abilityCallback_ = abilityCallback; +} + +#ifdef SUPPORT_GRAPHICS ErrCode AbilityContextImpl::SetMissionLabel(const std::string &label) { HILOG_INFO("%{public}s begin. label = %{public}s", __func__, label.c_str()); @@ -465,7 +472,6 @@ ErrCode AbilityContextImpl::SetMissionLabel(const std::string &label) return err; } -#ifdef SUPPORT_GRAPHICS ErrCode AbilityContextImpl::SetMissionIcon(const std::shared_ptr &icon) { HILOG_INFO("%{public}s begin.", __func__); @@ -475,15 +481,7 @@ ErrCode AbilityContextImpl::SetMissionIcon(const std::shared_ptr abilityCallback) -{ - HILOG_INFO("%{public}s called.", __func__); - abilityCallback_ = abilityCallback; -} - -#ifdef SUPPORT_GRAPHICS int AbilityContextImpl::GetCurrentWindowMode() { HILOG_INFO("%{public}s called.", __func__); diff --git a/frameworks/kits/ability/native/include/ability.h b/frameworks/kits/ability/native/include/ability.h index b69199e6..bf3301da 100644 --- a/frameworks/kits/ability/native/include/ability.h +++ b/frameworks/kits/ability/native/include/ability.h @@ -25,21 +25,24 @@ #include "ability_event_interface.h" #include "ability_lifecycle_executor.h" #include "ability_lifecycle_interface.h" -#ifdef SUPPORT_GRAPHICS -#include "ability_window.h" -#endif #include "appexecfwk_errors.h" #include "configuration.h" #include "context.h" #include "continuation_handler.h" #include "continuation_state.h" -#ifdef SUPPORT_GRAPHICS -#include "display_manager.h" -#endif #include "dummy_ability_package.h" #include "dummy_component_container.h" #include "dummy_notification_request.h" +#include "iability_callback.h" +#include "iremote_object.h" +#include "pac_map.h" +#include "want.h" +#include "want_agent.h" +#include "../../ability_runtime/include/ability_context.h" + #ifdef SUPPORT_GRAPHICS +#include "ability_window.h" +#include "display_manager.h" #include "form_callback_interface.h" #include "form_constants.h" #include "form_death_callback.h" @@ -48,21 +51,11 @@ #include "form_state_info.h" #include "foundation/multimodalinput/input/interfaces/native/innerkits/event/include/key_event.h" #include "foundation/multimodalinput/input/interfaces/native/innerkits/event/include/pointer_event.h" -#endif -#include "iability_callback.h" -#include "iremote_object.h" -#include "pac_map.h" -#include "want.h" -#include "want_agent.h" -#ifdef SUPPORT_GRAPHICS #include "window_option.h" #include "window_scene.h" #include "wm_common.h" -#endif -#ifndef SUPPORT_GRAPHICS #include "inttypes.h" #endif -#include "../../ability_runtime/include/ability_context.h" using Uri = OHOS::Uri; @@ -102,9 +95,6 @@ class Ability : public IAbilityEvent, public IAbilityCallback, public std::enable_shared_from_this { public: -#ifdef SUPPORT_GRAPHICS - friend class PageAbilityImpl; -#endif friend class NewAbilityImpl; static Ability* Create(const std::unique_ptr& runtime); @@ -144,21 +134,6 @@ public: */ virtual void AddActionRoute(const std::string &action, const std::string &entry) final; -#ifdef SUPPORT_GRAPHICS - /** - * @brief Sets the background color of the window in RGB color mode. - * - * @param red The value ranges from 0 to 255. - * - * @param green The value ranges from 0 to 255. - * - * @param blue The value ranges from 0 to 255. - * - * @return Returns the result of SetWindowBackgroundColor - */ - virtual int SetWindowBackgroundColor(int red, int green, int blue) final; -#endif - /** * @brief Destroys this Page or Service ability. * After a Page or Service ability performs all operations, it can use this method to destroy itself @@ -189,30 +164,6 @@ public: */ bool IsUpdatingConfigurations() override; -#ifdef SUPPORT_GRAPHICS - /** - * @brief Informs the system of the time required for drawing this Page ability. - * - * @return Returns the notification is successful or fail - */ - bool PrintDrawnCompleted() override; - - /** - * @brief Inflates UI controls by using ComponentContainer. - * You can create a ComponentContainer instance that contains multiple components. - * - * @param componentContainer Indicates a set of customized components. - */ - virtual void SetUIContent(const ComponentContainer &componentContainer); - - /** - * @brief Inflates layout resources by using the layout resource ID. - * - * @param layoutRes Indicates the layout resource ID, which cannot be a negative number. - */ - virtual void SetUIContent(int layoutRes) final; -#endif - /** * Start other ability for result. * @@ -297,86 +248,6 @@ public: */ virtual void OnInactive(); -#ifdef SUPPORT_GRAPHICS - /** - * @brief Called after instantiating WindowScene. - * - * - * You can override this function to implement your own processing logic. - */ - virtual void OnSceneCreated(); - - /** - * @brief Called after ability stoped. - * - * - * You can override this function to implement your own processing logic. - */ - virtual void onSceneDestroyed(); - - /** - * @brief Called after ability restored. - * - * - * You can override this function to implement your own processing logic. - */ - virtual void OnSceneRestored(); - - /** - * @brief Called when this ability enters the STATE_FOREGROUND state. - * - * - * The ability in the STATE_FOREGROUND state is visible. - * You can override this function to implement your own processing logic. - */ - virtual void OnForeground(const Want &want); - - /** - * @brief Called when this ability enters the STATE_BACKGROUND state. - * - * - * The ability in the STATE_BACKGROUND state is invisible. - * You can override this function to implement your own processing logic. - */ - virtual void OnBackground(); - - /** - * @brief Called when a key is pressed. When any component in the Ability gains focus, the key-down event for - * the component will be handled first. This callback will not be invoked if the callback triggered for the - * key-down event of the component returns true. The default implementation of this callback does nothing - * and returns false. - * - * @param keyEvent Indicates the key-down event. - * - * @return Returns true if this event is handled and will not be passed further; returns false if this event - * is not handled and should be passed to other handlers. - */ - virtual void OnKeyDown(const std::shared_ptr& keyEvent); - - /** - * @brief Called when a key is released. When any component in the Ability gains focus, the key-up event for - * the component will be handled first. This callback will not be invoked if the callback triggered for the - * key-up event of the component returns true. The default implementation of this callback does nothing and - * returns false. - * - * @param keyEvent Indicates the key-up event. - * - * @return Returns true if this event is handled and will not be passed further; returns false if this event - * is not handled and should be passed to other handlers. - */ - virtual void OnKeyUp(const std::shared_ptr& keyEvent); - - /** - * @brief Called when a touch event is dispatched to this ability. The default implementation of this callback - * does nothing and returns false. - * - * @param event Indicates information about the touch event. - * - * @return Returns true if the event is handled; returns false otherwise. - */ - virtual void OnPointerEvent(std::shared_ptr& pointerEvent); -#endif - /** * @brief Called when this Service ability is connected for the first time. * @@ -395,105 +266,6 @@ public: */ virtual void OnDisconnect(const Want &want); -#ifdef SUPPORT_GRAPHICS - /** - * @brief Inflates UI controls by using ComponentContainer. - * You can create a ComponentContainer instance that contains multiple components. - * - * @param componentContainer Indicates the component layout defined by the user. - * @param context Indicates the context to use. - * @param typeFlag Indicates the window type. - */ - virtual void SetUIContent( - const ComponentContainer &componentContainer, std::shared_ptr &context, int typeFlag); - - /** - * @brief Inflates layout resources by using the layout resource ID. - * - * @param layoutRes Indicates the layout resource ID, which cannot be a negative number. - * @param context Indicates the context to use. - * @param typeFlag Indicates the window type. - */ - virtual void SetUIContent(int layoutRes, std::shared_ptr &context, int typeFlag); - - /** - * @brief Called when this ability gains or loses window focus. - * - * @param hasFocus Specifies whether this ability has focus. - */ - virtual void OnWindowFocusChanged(bool hasFocus); - - /** - * @brief Called when this ability is moved to or removed from the top of the stack. - * - * @param topActive Specifies whether this ability is moved to or removed from the top of the stack. The value true - * indicates that it is moved to the top, and false indicates that it is removed from the top of the stack. - */ - virtual void OnTopActiveAbilityChanged(bool topActive); - - /** - * @brief Inflates UI controls by using windowOption. - * - * @param windowOption Indicates the window option defined by the user. - */ - virtual void InitWindow(Rosen::WindowType winType, int32_t displayId, sptr option); - - /** - * @brief Get the window belong to the ability. - * - * @return Returns a Window object pointer. - */ - virtual const sptr GetWindow(); - - /** - * @brief get the scene belong to the ability. - * - * @return Returns a WindowScene object pointer. - */ - std::shared_ptr GetScene(); - - /** - * @brief Checks whether the main window of this ability has window focus. - * - * @return Returns true if this ability currently has window focus; returns false otherwise. - */ - bool HasWindowFocus(); - - void SetShowOnLockScreen(bool showOnLockScreen); - - /** - * @brief When the ability starts, set whether to wake up the screen. - * - * @param wakeUp Set true to wake up, false to not wake up. - */ - void SetWakeUpScreen(bool wakeUp); - - /** - * @brief Set the display orientation of the main window. - * - * @param orientation Indicates the display orientation of the window. - */ - void SetDisplayOrientation(int orientation); - - /** - * @brief Get the display orientation of the main window. - * - * @return Returns the display orientation of the window. - */ - int GetDisplayOrientation() override; - - /** - * @brief Called when a key is lone pressed. - * - * @param keyCode Indicates the code of the key long pressed. - * @param keyEvent Indicates the key-long-press event. - * - * @return Returns true if this event is handled and will not be passed further; returns false if this event - * is not handled and should be passed to other handlers. - */ - virtual bool OnKeyPressAndHold(int keyCode, const std::shared_ptr &keyEvent); -#endif - /** * @brief Called back after permissions are requested by using * AbilityContext.requestPermissionsFromUser(java.lang.String[],int). @@ -510,15 +282,6 @@ public: virtual void OnRequestPermissionsFromUserResult( int requestCode, const std::vector &permissions, const std::vector &grantResults); -#ifdef SUPPORT_GRAPHICS - /** - * @brief Called when this ability is about to leave the foreground and enter the background due to a user - * operation, for example, when the user touches the Home key. - * - */ - virtual void OnLeaveForeground(); -#endif - /** * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG. @@ -713,15 +476,6 @@ public: */ virtual void SetResult(int resultCode, const Want &resultData) final; -#ifdef SUPPORT_GRAPHICS - /** - * @brief Sets the type of audio whose volume will be adjusted by the volume button. - * - * @param volumeType Indicates the AudioManager.AudioVolumeType to set. - */ - virtual void SetVolumeTypeAdjustedByKey(int volumeType); -#endif - /** * @brief Called back when Service is started. * This method can be called only by Service. You can use the StartAbility(ohos.aafwk.content.Want) method to start @@ -917,15 +671,6 @@ public: */ virtual int BatchInsert(const Uri &uri, const std::vector &values); -#ifdef SUPPORT_GRAPHICS - /** - * @brief Obtains the type of audio whose volume is adjusted by the volume button. - * - * @return Returns the AudioManager.AudioVolumeType. - */ - int GetVolumeTypeAdjustedByKey(); -#endif - /** * @brief Obtains the lifecycle state of this ability. * @@ -1017,7 +762,376 @@ public: */ std::shared_ptr CreatePostEventTimeouter(std::string taskstr); + /** + * @brief Keep this Service ability in the background and displays a notification bar. + * + * @param wantAgent Indicates which ability to start when user click the notification bar. + * @return the method result code, 0 means succeed + */ + virtual int StartBackgroundRunning(const AbilityRuntime::WantAgent::WantAgent &wantAgent) final; + + /** + * @brief Cancel background running of this ability to free up system memory. + * + * @return the method result code, 0 means succeed + */ + virtual int StopBackgroundRunning() final; + + /** + * @brief Get the error message by error code. + * @param errorCode the error code return form fms. + * @return Returns the error message detail. + */ + std::string GetErrorMsg(const ErrCode errorCode); + + /** + * @brief Acquire a bundle manager, if it not existed, + * @return returns the bundle manager ipc object, or nullptr for failed. + */ + sptr GetBundleMgr(); + + /** + * @brief Add the bundle manager instance for debug. + * @param bundleManager the bundle manager ipc object. + */ + void SetBundleManager(const sptr &bundleManager); + + /** + * @brief You can use the IContinuationRegisterManager object to interact with the Device+ control center, + * including registering and unregistering the ability to migrate, updating the device connection state, and + * showing the list of devices that can be selected for ability migration. + * + * @return Returns true if the migration request is successful; returns false otherwise. + */ + std::weak_ptr GetContinuationRegisterManager(); + + /** + * @brief Prepare user data of local Ability. + * + * @param wantParams Indicates the user data to be saved. + * @return If the ability is willing to continue and data saved successfully, it returns 0; + * otherwise, it returns errcode. + */ + virtual int32_t OnContinue(WantParams &wantParams); + + /** + * @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. + * @param versionCode Target bundle version. + */ + virtual void ContinueAbilityWithStack(const std::string &deviceId, uint32_t versionCode) 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 Performs batch operations on the database. + * + * @param operations Indicates a list of database operations on the database. + * @return Returns the result of each operation, in array. + */ + virtual std::vector> ExecuteBatch( + const std::vector> &operations); + + /** + * @brief Executes an operation among the batch operations to be executed. + * + * @param operation Indicates the operation to execute. + * @param results Indicates a set of results of the batch operations. + * @param index Indicates the index of the current operation result in the batch operation results. + */ + void ExecuteOperation(std::shared_ptr &operation, + std::vector> &results, int index); + + /** + * @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; + + /** + * @brief request a remote object of callee from this ability. + * @return Returns the remote object of callee. + */ + virtual sptr CallRequest(); + #ifdef SUPPORT_GRAPHICS +public: + friend class PageAbilityImpl; + uint32_t sceneFlag_ = 0; + + /** + * @brief Sets the background color of the window in RGB color mode. + * + * @param red The value ranges from 0 to 255. + * + * @param green The value ranges from 0 to 255. + * + * @param blue The value ranges from 0 to 255. + * + * @return Returns the result of SetWindowBackgroundColor + */ + virtual int SetWindowBackgroundColor(int red, int green, int blue) final; + + /** + * @brief Informs the system of the time required for drawing this Page ability. + * + * @return Returns the notification is successful or fail + */ + bool PrintDrawnCompleted() override; + + /** + * @brief Inflates UI controls by using ComponentContainer. + * You can create a ComponentContainer instance that contains multiple components. + * + * @param componentContainer Indicates a set of customized components. + */ + virtual void SetUIContent(const ComponentContainer &componentContainer); + + /** + * @brief Inflates layout resources by using the layout resource ID. + * + * @param layoutRes Indicates the layout resource ID, which cannot be a negative number. + */ + virtual void SetUIContent(int layoutRes) final; + + /** + * @brief Called after instantiating WindowScene. + * + * + * You can override this function to implement your own processing logic. + */ + virtual void OnSceneCreated(); + + /** + * @brief Called after ability stoped. + * + * + * You can override this function to implement your own processing logic. + */ + virtual void onSceneDestroyed(); + + /** + * @brief Called after ability restored. + * + * + * You can override this function to implement your own processing logic. + */ + virtual void OnSceneRestored(); + + /** + * @brief Called when this ability enters the STATE_FOREGROUND state. + * + * + * The ability in the STATE_FOREGROUND state is visible. + * You can override this function to implement your own processing logic. + */ + virtual void OnForeground(const Want &want); + + /** + * @brief Called when this ability enters the STATE_BACKGROUND state. + * + * + * The ability in the STATE_BACKGROUND state is invisible. + * You can override this function to implement your own processing logic. + */ + virtual void OnBackground(); + + /** + * @brief Called when a key is pressed. When any component in the Ability gains focus, the key-down event for + * the component will be handled first. This callback will not be invoked if the callback triggered for the + * key-down event of the component returns true. The default implementation of this callback does nothing + * and returns false. + * + * @param keyEvent Indicates the key-down event. + * + * @return Returns true if this event is handled and will not be passed further; returns false if this event + * is not handled and should be passed to other handlers. + */ + virtual void OnKeyDown(const std::shared_ptr& keyEvent); + + /** + * @brief Called when a key is released. When any component in the Ability gains focus, the key-up event for + * the component will be handled first. This callback will not be invoked if the callback triggered for the + * key-up event of the component returns true. The default implementation of this callback does nothing and + * returns false. + * + * @param keyEvent Indicates the key-up event. + * + * @return Returns true if this event is handled and will not be passed further; returns false if this event + * is not handled and should be passed to other handlers. + */ + virtual void OnKeyUp(const std::shared_ptr& keyEvent); + + /** + * @brief Called when a touch event is dispatched to this ability. The default implementation of this callback + * does nothing and returns false. + * + * @param event Indicates information about the touch event. + * + * @return Returns true if the event is handled; returns false otherwise. + */ + virtual void OnPointerEvent(std::shared_ptr& pointerEvent); + + /** + * @brief Inflates UI controls by using ComponentContainer. + * You can create a ComponentContainer instance that contains multiple components. + * + * @param componentContainer Indicates the component layout defined by the user. + * @param context Indicates the context to use. + * @param typeFlag Indicates the window type. + */ + virtual void SetUIContent( + const ComponentContainer &componentContainer, std::shared_ptr &context, int typeFlag); + + /** + * @brief Inflates layout resources by using the layout resource ID. + * + * @param layoutRes Indicates the layout resource ID, which cannot be a negative number. + * @param context Indicates the context to use. + * @param typeFlag Indicates the window type. + */ + virtual void SetUIContent(int layoutRes, std::shared_ptr &context, int typeFlag); + + /** + * @brief Called when this ability gains or loses window focus. + * + * @param hasFocus Specifies whether this ability has focus. + */ + virtual void OnWindowFocusChanged(bool hasFocus); + + /** + * @brief Called when this ability is moved to or removed from the top of the stack. + * + * @param topActive Specifies whether this ability is moved to or removed from the top of the stack. The value true + * indicates that it is moved to the top, and false indicates that it is removed from the top of the stack. + */ + virtual void OnTopActiveAbilityChanged(bool topActive); + + /** + * @brief Inflates UI controls by using windowOption. + * + * @param windowOption Indicates the window option defined by the user. + */ + virtual void InitWindow(Rosen::WindowType winType, int32_t displayId, sptr option); + + /** + * @brief Get the window belong to the ability. + * + * @return Returns a Window object pointer. + */ + virtual const sptr GetWindow(); + + /** + * @brief get the scene belong to the ability. + * + * @return Returns a WindowScene object pointer. + */ + std::shared_ptr GetScene(); + + /** + * @brief Checks whether the main window of this ability has window focus. + * + * @return Returns true if this ability currently has window focus; returns false otherwise. + */ + bool HasWindowFocus(); + + void SetShowOnLockScreen(bool showOnLockScreen); + + /** + * @brief When the ability starts, set whether to wake up the screen. + * + * @param wakeUp Set true to wake up, false to not wake up. + */ + void SetWakeUpScreen(bool wakeUp); + + /** + * @brief Set the display orientation of the main window. + * + * @param orientation Indicates the display orientation of the window. + */ + void SetDisplayOrientation(int orientation); + + /** + * @brief Get the display orientation of the main window. + * + * @return Returns the display orientation of the window. + */ + int GetDisplayOrientation() override; + + /** + * @brief Called when a key is lone pressed. + * + * @param keyCode Indicates the code of the key long pressed. + * @param keyEvent Indicates the key-long-press event. + * + * @return Returns true if this event is handled and will not be passed further; returns false if this event + * is not handled and should be passed to other handlers. + */ + virtual bool OnKeyPressAndHold(int keyCode, const std::shared_ptr &keyEvent); + + /** + * @brief Called when this ability is about to leave the foreground and enter the background due to a user + * operation, for example, when the user touches the Home key. + * + */ + virtual void OnLeaveForeground(); + + /** + * @brief Sets the type of audio whose volume will be adjusted by the volume button. + * + * @param volumeType Indicates the AudioManager.AudioVolumeType to set. + */ + virtual void SetVolumeTypeAdjustedByKey(int volumeType); + + /** + * @brief Obtains the type of audio whose volume is adjusted by the volume button. + * + * @return Returns the AudioManager.AudioVolumeType. + */ + int GetVolumeTypeAdjustedByKey(); + /** * Releases an obtained form by its ID. * @@ -1083,24 +1197,7 @@ public: * */ ErrCode DeleteForm(const int64_t formId); -#endif - /** - * @brief Keep this Service ability in the background and displays a notification bar. - * - * @param wantAgent Indicates which ability to start when user click the notification bar. - * @return the method result code, 0 means succeed - */ - virtual int StartBackgroundRunning(const AbilityRuntime::WantAgent::WantAgent &wantAgent) final; - - /** - * @brief Cancel background running of this ability to free up system memory. - * - * @return the method result code, 0 means succeed - */ - virtual int StopBackgroundRunning() final; - -#ifdef SUPPORT_GRAPHICS /** * @brief The form callback. */ @@ -1409,130 +1506,14 @@ public: * @return Returns true if the request is successfully initiated; returns false otherwise. */ ErrCode GetFormsInfoByModule(std::string &bundleName, std::string &moduleName, std::vector &formInfos); -#endif - /** - * @brief Get the error message by error code. - * @param errorCode the error code return form fms. - * @return Returns the error message detail. - */ - std::string GetErrorMsg(const ErrCode errorCode); - /** - * @brief Acquire a bundle manager, if it not existed, - * @return returns the bundle manager ipc object, or nullptr for failed. - */ - sptr GetBundleMgr(); - - /** - * @brief Add the bundle manager instance for debug. - * @param bundleManager the bundle manager ipc object. - */ - void SetBundleManager(const sptr &bundleManager); - - /** - * @brief You can use the IContinuationRegisterManager object to interact with the Device+ control center, - * including registering and unregistering the ability to migrate, updating the device connection state, and - * showing the list of devices that can be selected for ability migration. - * - * @return Returns true if the migration request is successful; returns false otherwise. - */ - std::weak_ptr GetContinuationRegisterManager(); - - /** - * @brief Prepare user data of local Ability. - * - * @param wantParams Indicates the user data to be saved. - * @return If the ability is willing to continue and data saved successfully, it returns 0; - * otherwise, it returns errcode. - */ - virtual int32_t OnContinue(WantParams &wantParams); - -#ifdef SUPPORT_GRAPHICS /** * @brief Get page ability stack info. * * @return A string represents page ability stack info, empty if failed; */ virtual std::string GetContentInfo(); -#endif - /** - * @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. - * @param versionCode Target bundle version. - */ - virtual void ContinueAbilityWithStack(const std::string &deviceId, uint32_t versionCode) 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 Performs batch operations on the database. - * - * @param operations Indicates a list of database operations on the database. - * @return Returns the result of each operation, in array. - */ - virtual std::vector> ExecuteBatch( - const std::vector> &operations); - - /** - * @brief Executes an operation among the batch operations to be executed. - * - * @param operation Indicates the operation to execute. - * @param results Indicates a set of results of the batch operations. - * @param index Indicates the index of the current operation result in the batch operation results. - */ - void ExecuteOperation(std::shared_ptr &operation, - std::vector> &results, int index); - - /** - * @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; - -#ifdef SUPPORT_GRAPHICS /** * @brief Set WindowScene listener * @@ -1540,81 +1521,13 @@ public: * @return None. */ void SetSceneListener(const sptr &listener); -#endif - /** - * @brief request a remote object of callee from this ability. - * @return Returns the remote object of callee. - */ - virtual sptr CallRequest(); - -#ifdef SUPPORT_GRAPHICS /** * @brief Called back at ability context. */ virtual int GetCurrentWindowMode() override; - uint32_t sceneFlag_ = 0; -#endif protected: -#ifdef SUPPORT_GRAPHICS - /** - * @brief Acquire a form provider remote object. - * @return Returns form provider remote object. - */ - sptr GetFormRemoteObject(); -#endif - - /** - * @brief Acquire the launch parameter. - * @return launch parameter. - */ - const AAFwk::LaunchParam& GetLaunchParam() const; - -#ifdef SUPPORT_GRAPHICS - /** - * @brief process when foreground executed. - * - * You can override this function to implement your own processing logic - */ - virtual void DoOnForeground(const Want& want); - - /** - * @brief requeset focus for current window. - * - * You can override this function to implement your own processing logic - */ - virtual void RequsetFocus(const Want &want); - - /** - * @brief Acquire the window option. - * @return window option. - */ - sptr GetWindowOption(const Want &want); -#endif - - /** - * @brief judge where invoke resoreWindowStage in continuation - * @return true if invoked resoreWindowStage in continuation. - */ - bool IsRestoredInContinuation() const; - - /** - * @brief wait for distributed object to complete sync - * - * @param want the want param. - */ - void WaitingDistributedObjectSyncComplete(const Want& want); - - /** - * @brief Notify continuation - * - * @param want the want param. - * @param success whether continuation success. - */ - void NotityContinuationResult(const Want& want, bool success); - -#ifdef SUPPORT_GRAPHICS class AbilityDisplayListener : public OHOS::Rosen::DisplayManager::IDisplayListener { public: AbilityDisplayListener(const std::weak_ptr& ability) @@ -1683,17 +1596,71 @@ protected: * @param to the displayId after display move */ void OnDisplayMove(Rosen::DisplayId from, Rosen::DisplayId to); -#endif -protected: - std::shared_ptr abilityContext_ = nullptr; - std::shared_ptr setting_ = nullptr; - LaunchParam launchParam_; -#ifdef SUPPORT_GRAPHICS + + /** + * @brief Acquire a form provider remote object. + * @return Returns form provider remote object. + */ + sptr GetFormRemoteObject(); + + /** + * @brief process when foreground executed. + * + * You can override this function to implement your own processing logic + */ + virtual void DoOnForeground(const Want& want); + + /** + * @brief requeset focus for current window. + * + * You can override this function to implement your own processing logic + */ + virtual void RequsetFocus(const Want &want); + + /** + * @brief Acquire the window option. + * @return window option. + */ + sptr GetWindowOption(const Want &want); + std::shared_ptr scene_ = nullptr; sptr sceneListener_ = nullptr; sptr abilityDisplayListener_ = nullptr; sptr abilityDisplayMoveListener_ = nullptr; #endif + +protected: + /** + * @brief Acquire the launch parameter. + * @return launch parameter. + */ + const AAFwk::LaunchParam& GetLaunchParam() const; + + /** + * @brief judge where invoke resoreWindowStage in continuation + * @return true if invoked resoreWindowStage in continuation. + */ + bool IsRestoredInContinuation() const; + + /** + * @brief wait for distributed object to complete sync + * + * @param want the want param. + */ + void WaitingDistributedObjectSyncComplete(const Want& want); + + /** + * @brief Notify continuation + * + * @param want the want param. + * @param success whether continuation success. + */ + void NotityContinuationResult(const Want& want, bool success); + + std::shared_ptr abilityContext_ = nullptr; + std::shared_ptr setting_ = nullptr; + LaunchParam launchParam_; + private: std::shared_ptr ParsePredictionArgsReference( std::vector> &results, std::shared_ptr &operation, @@ -1727,7 +1694,6 @@ private: */ void SetLaunchParam(const AAFwk::LaunchParam &launchParam); -private: std::shared_ptr continuationHandler_ = nullptr; std::shared_ptr continuationManager_ = nullptr; std::shared_ptr continuationRegisterManager_ = nullptr; @@ -1738,15 +1704,8 @@ private: std::shared_ptr application_ = nullptr; std::vector types_; std::map resultCallbacks_; -#ifdef SUPPORT_GRAPHICS - std::shared_ptr abilityWindow_ = nullptr; -#endif std::shared_ptr setWant_ = nullptr; sptr reverseContinuationSchedulerReplica_ = nullptr; -#ifdef SUPPORT_GRAPHICS - bool bWindowFocus_ = false; - bool showOnLockScreen_ = false; -#endif static const std::string SYSTEM_UI; static const std::string STATUS_BAR; @@ -1761,26 +1720,12 @@ private: // If session id cannot get from want, assign it as default. static const int DEFAULT_DMS_SESSION_ID; -#ifdef SUPPORT_GRAPHICS - std::vector lostedByReconnectTempForms_; - std::map> appCallbacks_; -#endif std::map userReqParams_; sptr iBundleMgr_; -#ifdef SUPPORT_GRAPHICS - 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; -#endif static const int64_t MIN_NEXT_TIME = 5; -private: #ifdef SUPPORT_GRAPHICS +private: /** * @brief Delete or release form with formId. * @@ -1856,6 +1801,20 @@ private: * @return Returns true if the request is successfully initiated; returns false otherwise. */ bool ReAcquireForm(const int64_t formId, const Want &want); + + std::shared_ptr abilityWindow_ = nullptr; + bool bWindowFocus_ = false; + bool showOnLockScreen_ = false; + std::vector lostedByReconnectTempForms_; + std::map> appCallbacks_; + 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; #endif }; } // namespace AppExecFwk diff --git a/frameworks/kits/ability/native/include/ability_impl.h b/frameworks/kits/ability/native/include/ability_impl.h index fbd05319..ba6a9115 100644 --- a/frameworks/kits/ability/native/include/ability_impl.h +++ b/frameworks/kits/ability/native/include/ability_impl.h @@ -97,38 +97,6 @@ public: // Page Service Ability has different AbilityTransaction virtual void HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState); -#ifdef SUPPORT_GRAPHICS - /** - * @brief Execution the KeyDown callback of the ability - * @param keyEvent Indicates the key-down event. - * - * @return Returns true if this event is handled and will not be passed further; returns false if this event is - * not handled and should be passed to other handlers. - * - */ - virtual void DoKeyDown(const std::shared_ptr& keyEvent); - - /** - * @brief Execution the KeyUp callback of the ability - * @param keyEvent Indicates the key-up event. - * - * @return Returns true if this event is handled and will not be passed further; returns false if this event is - * not handled and should be passed to other handlers. - * - */ - virtual void DoKeyUp(const std::shared_ptr& keyEvent); - - /** - * @brief Called when a touch event is dispatched to this ability. The default implementation of this callback - * does nothing and returns false. - * @param touchEvent Indicates information about the touch event. - * - * @return Returns true if the event is handled; returns false otherwise. - * - */ - virtual void DoPointerEvent(std::shared_ptr& pointerEvent); -#endif - /** * @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) @@ -345,9 +313,57 @@ public: bool IsStageBasedModel() const; #ifdef SUPPORT_GRAPHICS +public: + /** + * @brief Execution the KeyDown callback of the ability + * @param keyEvent Indicates the key-down event. + * + * @return Returns true if this event is handled and will not be passed further; returns false if this event is + * not handled and should be passed to other handlers. + * + */ + virtual void DoKeyDown(const std::shared_ptr& keyEvent); + + /** + * @brief Execution the KeyUp callback of the ability + * @param keyEvent Indicates the key-up event. + * + * @return Returns true if this event is handled and will not be passed further; returns false if this event is + * not handled and should be passed to other handlers. + * + */ + virtual void DoKeyUp(const std::shared_ptr& keyEvent); + + /** + * @brief Called when a touch event is dispatched to this ability. The default implementation of this callback + * does nothing and returns false. + * @param touchEvent Indicates information about the touch event. + * + * @return Returns true if the event is handled; returns false otherwise. + * + */ + virtual void DoPointerEvent(std::shared_ptr& pointerEvent); + void AfterUnFocused(); void AfterFocused(); + +protected: + /** + * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application + * that it belongs to of the lifecycle status. + * + * @param want The Want object to switch the life cycle. + */ + void Foreground(const Want &want); + + /** + * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_BACKGROUND. And notifies the + * application that it belongs to of the lifecycle status. + * + */ + void Background(); #endif + protected: /** * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application @@ -378,23 +394,6 @@ protected: */ void Inactive(); -#ifdef SUPPORT_GRAPHICS - /** - * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application - * that it belongs to of the lifecycle status. - * - * @param want The Want object to switch the life cycle. - */ - void Foreground(const Want &want); - - /** - * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_BACKGROUND. And notifies the - * application that it belongs to of the lifecycle status. - * - */ - void Background(); -#endif - /** * @brief SerUriString */ @@ -430,7 +429,24 @@ protected: std::shared_ptr handler_; private: + typedef enum { + START, + INACTIVE, + ACTIVE, + BACKGROUND, + FOREGROUND, + STOP, + } Action; + + std::shared_ptr abilityLifecycleCallbacks_; + std::shared_ptr applicationImpl_; + std::shared_ptr contextDeal_; + bool hasSaveData_ = false; + bool needSaveDate_ = false; + PacMap restoreData_; + #ifdef SUPPORT_GRAPHICS +private: class WindowLifeCycleImpl : public Rosen::IWindowLifeCycle { public: WindowLifeCycleImpl(const sptr& token, const std::shared_ptr& owner) @@ -456,23 +472,6 @@ private: std::shared_ptr abilityImpl_; }; #endif - typedef enum { - START, - INACTIVE, - ACTIVE, - BACKGROUND, - FOREGROUND, - STOP, - } Action; - - std::shared_ptr abilityLifecycleCallbacks_; - std::shared_ptr applicationImpl_; - std::shared_ptr contextDeal_; - -private: - bool hasSaveData_ = false; - bool needSaveDate_ = false; - PacMap restoreData_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/include/ability_runtime/js_ability.h b/frameworks/kits/ability/native/include/ability_runtime/js_ability.h index e914f53a..108d399b 100644 --- a/frameworks/kits/ability/native/include/ability_runtime/js_ability.h +++ b/frameworks/kits/ability/native/include/ability_runtime/js_ability.h @@ -46,14 +46,6 @@ public: void OnStart(const Want &want) override; void OnStop() override; -#ifdef SUPPORT_GRAPHICS - void OnSceneCreated() override; - void onSceneDestroyed() override; - void OnSceneRestored() override; - - void OnForeground(const Want &want) override; - void OnBackground() override; -#endif int32_t OnContinue(WantParams &wantParams) override; void OnConfigurationUpdated(const Configuration &configuration) override; void UpdateContextConfiguration() override; @@ -73,17 +65,26 @@ public: */ virtual void Dump(const std::vector ¶ms, std::vector &info) override; -protected: #ifdef SUPPORT_GRAPHICS +public: + void OnSceneCreated() override; + void onSceneDestroyed() override; + void OnSceneRestored() override; + + void OnForeground(const Want &want) override; + void OnBackground() override; + +protected: void DoOnForeground(const Want &want) override; void RequsetFocus(const Want &want) override; + +private: + void GetPageStackFromWant(const Want &want, std::string &pageStack); #endif + private: void CallObjectMethod(const char *name, NativeValue *const *argv = nullptr, size_t argc = 0); std::unique_ptr CreateAppWindowStage(); -#ifdef SUPPORT_GRAPHICS - void GetPageStackFromWant(const Want &want, std::string &pageStack); -#endif std::shared_ptr CreateADelegatorAbilityProperty(); JsRuntime &jsRuntime_; diff --git a/frameworks/kits/ability/native/include/ability_runtime/js_ability_context.h b/frameworks/kits/ability/native/include/ability_runtime/js_ability_context.h index c5c0f2cf..e1e07ae2 100644 --- a/frameworks/kits/ability/native/include/ability_runtime/js_ability_context.h +++ b/frameworks/kits/ability/native/include/ability_runtime/js_ability_context.h @@ -54,13 +54,8 @@ public: static NativeValue* TerminateSelfWithResult(NativeEngine* engine, NativeCallbackInfo* info); static NativeValue* RequestPermissionsFromUser(NativeEngine* engine, NativeCallbackInfo* info); static NativeValue* RestoreWindowStage(NativeEngine* engine, NativeCallbackInfo* info); - static NativeValue* SetMissionLabel(NativeEngine* engine, NativeCallbackInfo* info); static NativeValue* IsTerminating(NativeEngine* engine, NativeCallbackInfo* info); -#ifdef SUPPORT_GRAPHICS - static NativeValue* SetMissionIcon(NativeEngine* engine, NativeCallbackInfo* info); -#endif - static void ConfigurationUpdated(NativeEngine* engine, std::shared_ptr &jsContext, const std::shared_ptr &config); @@ -69,6 +64,16 @@ public: return context_.lock(); } +#ifdef SUPPORT_GRAPHICS +public: + static NativeValue* SetMissionLabel(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* SetMissionIcon(NativeEngine* engine, NativeCallbackInfo* info); + +private: + NativeValue* OnSetMissionLabel(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnSetMissionIcon(NativeEngine& engine, NativeCallbackInfo& info); +#endif + private: NativeValue* OnStartAbility(NativeEngine& engine, NativeCallbackInfo& info); NativeValue* OnStartAbilityWithAccount(NativeEngine& engine, NativeCallbackInfo& info); @@ -86,13 +91,8 @@ private: NativeValue* OnTerminateSelf(NativeEngine& engine, NativeCallbackInfo& info); NativeValue* OnRequestPermissionsFromUser(NativeEngine& engine, NativeCallbackInfo& info); NativeValue* OnRestoreWindowStage(NativeEngine& engine, NativeCallbackInfo& info); - NativeValue* OnSetMissionLabel(NativeEngine& engine, NativeCallbackInfo& info); NativeValue* OnIsTerminating(NativeEngine& engine, NativeCallbackInfo& info); -#ifdef SUPPORT_GRAPHICS - NativeValue* OnSetMissionIcon(NativeEngine& engine, NativeCallbackInfo& info); -#endif - static bool UnWrapWant(NativeEngine& engine, NativeValue* argv, AAFwk::Want& want); static NativeValue* WrapWant(NativeEngine& engine, const AAFwk::Want& want); static bool UnWrapAbilityResult(NativeEngine& engine, NativeValue* argv, int& resultCode, AAFwk::Want& want); diff --git a/frameworks/kits/ability/native/src/ability.cpp b/frameworks/kits/ability/native/src/ability.cpp index e75754a6..4361d1d1 100644 --- a/frameworks/kits/ability/native/src/ability.cpp +++ b/frameworks/kits/ability/native/src/ability.cpp @@ -42,19 +42,9 @@ #include "data_uri_utils.h" #include "distributed_objectstore.h" #include "hilog_wrapper.h" -#ifdef SUPPORT_GRAPHICS -#include "display_type.h" -#include "form_host_client.h" -#include "form_mgr.h" -#include "form_mgr_errors.h" -#include "form_provider_client.h" -#endif #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" -#ifdef SUPPORT_GRAPHICS -#include "key_event.h" -#endif #include "ohos_application.h" #include "reverse_continuation_scheduler_primary.h" #include "reverse_continuation_scheduler_replica.h" @@ -65,6 +55,15 @@ #include "task_handler_client.h" #include "values_bucket.h" +#ifdef SUPPORT_GRAPHICS +#include "display_type.h" +#include "form_host_client.h" +#include "form_mgr.h" +#include "form_mgr_errors.h" +#include "form_provider_client.h" +#include "key_event.h" +#endif + namespace OHOS { namespace AppExecFwk { // REGISTER_AA(Ability) @@ -82,12 +81,6 @@ const std::string LAUNCHER_BUNDLE_NAME = "com.ohos.launcher"; const std::string LAUNCHER_ABILITY_NAME = "com.ohos.launcher.MainAbility"; const std::string SHOW_ON_LOCK_SCREEN = "ShowOnLockScreen"; -#ifdef SUPPORT_GRAPHICS -static std::mutex formLock; - -constexpr int64_t SEC_TO_MILLISEC = 1000; -constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; -#endif #ifdef DISTRIBUTED_DATA_OBJECT_ENABLE constexpr int32_t DISTRIBUTED_OBJECT_TIMEOUT = 10000; #endif @@ -190,18 +183,6 @@ bool Ability::IsUpdatingConfigurations() return AbilityContext::IsUpdatingConfigurations(); } -#ifdef SUPPORT_GRAPHICS -/** - * @brief Informs the system of the time required for drawing this Page ability. - * - * @return Returns the notification is successful or fail - */ -bool Ability::PrintDrawnCompleted() -{ - return AbilityContext::PrintDrawnCompleted(); -} -#endif - void Ability::OnStart(const Want &want) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); @@ -426,57 +407,6 @@ void Ability::OnInactive() HILOG_INFO("%{public}s end", __func__); } -#ifdef SUPPORT_GRAPHICS -/** - * @brief Called after instantiating WindowScene. - * - * - * You can override this function to implement your own processing logic. - */ -void Ability::OnSceneCreated() -{ - HILOG_INFO("%{public}s called.", __func__); -} - -/** - * @brief Called after restore WindowScene. - * - * - * You can override this function to implement your own processing logic. - */ -void Ability::OnSceneRestored() -{ - HILOG_INFO("%{public}s called.", __func__); -} - -/** - * @brief Called after ability stoped. - * - * - * You can override this function to implement your own processing logic. - */ -void Ability::onSceneDestroyed() -{ - HILOG_INFO("%{public}s called.", __func__); -} - -/** - * @brief Called when this ability enters the STATE_FOREGROUND state. - * - * - * The ability in the STATE_FOREGROUND state is visible. - * You can override this function to implement your own processing logic. - */ -void Ability::OnForeground(const Want &want) -{ - HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - DoOnForeground(want); - DispatchLifecycleOnForeground(want); - HILOG_INFO("%{public}s end.", __func__); -} -#endif - bool Ability::IsRestoredInContinuation() const { if (abilityContext_ == nullptr) { @@ -549,56 +479,6 @@ void Ability::NotityContinuationResult(const Want& want, bool success) originDeviceId, sessionId, success, reverseContinuationSchedulerReplica_); } -#ifdef SUPPORT_GRAPHICS -/** - * @brief Called when this ability enters the STATE_BACKGROUND state. - * - * - * The ability in the STATE_BACKGROUND state is invisible. - * You can override this function to implement your own processing logic. - */ -void Ability::OnBackground() -{ - HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { - if (abilityInfo_->isStageBasedModel) { - if (scene_ == nullptr) { - HILOG_ERROR("Ability::OnBackground error. scene_ == nullptr."); - return; - } - HILOG_INFO("GoBackground sceneFlag:%{public}d.", sceneFlag_); - scene_->GoBackground(sceneFlag_); - } else { - if (abilityWindow_ == nullptr) { - HILOG_ERROR("Ability::OnBackground error. abilityWindow_ == nullptr."); - return; - } - HILOG_INFO("OnPostAbilityBackground sceneFlag:%{public}d.", sceneFlag_); - abilityWindow_->OnPostAbilityBackground(sceneFlag_); - } - } - - if (abilityLifecycleExecutor_ == nullptr) { - HILOG_ERROR("Ability::OnBackground error. abilityLifecycleExecutor_ == nullptr."); - return; - } - - if (abilityInfo_->isStageBasedModel) { - abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::BACKGROUND_NEW); - } else { - abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::BACKGROUND); - } - - if (lifecycle_ == nullptr) { - HILOG_ERROR("Ability::OnBackground error. lifecycle_ == nullptr."); - return; - } - lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND); - HILOG_INFO("%{public}s end", __func__); -} -#endif - /** * @brief Called when this Service ability is connected for the first time. * @@ -722,196 +602,6 @@ ErrCode Ability::StartAbility(const Want &want, AbilityStartSetting abilityStart return err; } -#ifdef SUPPORT_GRAPHICS -/** - * @brief Called when a key is pressed. When any component in the Ability gains focus, the key-down event for - * the component will be handled first. This callback will not be invoked if the callback triggered for the - * key-down event of the component returns true. The default implementation of this callback does nothing - * and returns false. - * - * @param keyEvent Indicates the key-down event. - * - * @return Returns true if this event is handled and will not be passed further; returns false if this event - * is not handled and should be passed to other handlers. - */ -void Ability::OnKeyDown(const std::shared_ptr& keyEvent) -{ - HILOG_INFO("Ability::OnKeyDown called"); -} - -/** - * @brief Called when a key is released. When any component in the Ability gains focus, the key-up event for - * the component will be handled first. This callback will not be invoked if the callback triggered for the - * key-up event of the component returns true. The default implementation of this callback does nothing and - * returns false. - * - * @param keyEvent Indicates the key-up event. - * - * @return Returns true if this event is handled and will not be passed further; returns false if this event - * is not handled and should be passed to other handlers. - */ -void Ability::OnKeyUp(const std::shared_ptr& keyEvent) -{ - HILOG_INFO("Ability::OnKeyUp called"); - auto code = keyEvent->GetKeyCode(); - if (code == MMI::KeyEvent::KEYCODE_BACK) { - HILOG_INFO("Ability::OnKey Back key pressed."); - OnBackPressed(); - } -} - -/** - * @brief Called when a touch event is dispatched to this ability. The default implementation of this callback - * does nothing and returns false. - * - * @param event Indicates information about the touch event. - * - * @return Returns true if the event is handled; returns false otherwise. - */ -void Ability::OnPointerEvent(std::shared_ptr& pointerEvent) -{ - HILOG_INFO("Ability::OnTouchEvent called"); -} - -/** - * @brief Inflates UI controls by using ComponentContainer. - * You can create a ComponentContainer instance that contains multiple components. - * - * @param componentContainer Indicates a set of customized components. - */ -void Ability::SetUIContent(const ComponentContainer &componentContainer) -{} - -/** - * @brief Inflates layout resources by using the layout resource ID. - * - * @param layoutRes Indicates the layout resource ID, which cannot be a negative number. - */ -void Ability::SetUIContent(int layoutRes) -{} - -/** - * @brief Inflates UI controls by using ComponentContainer. - * You can create a ComponentContainer instance that contains multiple components. - * - * @param componentContainer Indicates the component layout defined by the user. - * @param context Indicates the context to use. - * @param typeFlag Indicates the window type. - */ -void Ability::SetUIContent( - const ComponentContainer &componentContainer, std::shared_ptr &context, int typeFlag) -{} - -/** - * @brief Inflates layout resources by using the layout resource ID. - * - * @param layoutRes Indicates the layout resource ID, which cannot be a negative number. - * @param context Indicates the context to use. - * @param typeFlag Indicates the window type. - */ -void Ability::SetUIContent(int layoutRes, std::shared_ptr &context, int typeFlag) -{} - -/** - * @brief Inflates UI controls by using WindowOption. - * - * @param windowOption Indicates the window option defined by the user. - */ -void Ability::InitWindow(Rosen::WindowType winType, int32_t displayId, sptr option) -{ - if (abilityWindow_ == nullptr) { - HILOG_ERROR("Ability::InitWindow abilityWindow_ is nullptr"); - return; - } - abilityWindow_->InitWindow(winType, abilityContext_, sceneListener_, displayId, option); -} - -/** - * @brief Get the window belong to the ability. - * - * @return Returns a IWindowsManager object pointer. - */ -const sptr Ability::GetWindow() -{ - if (abilityWindow_ != nullptr) { - return abilityWindow_->GetWindow(); - } else { - HILOG_INFO("%{public}s abilityWindow_ is nullptr.", __func__); - return nullptr; - } -} - -/** - * @brief get the scene belong to the ability. - * - * @return Returns a WindowScene object pointer. - */ -std::shared_ptr Ability::GetScene() -{ - return scene_; -} - -/** - * @brief Obtains the type of audio whose volume is adjusted by the volume button. - * - * @return Returns the AudioManager.AudioVolumeType. - */ -int Ability::GetVolumeTypeAdjustedByKey() -{ - return 0; -} - -/** - * @brief Checks whether the main window of this ability has window focus. - * - * @return Returns true if this ability currently has window focus; returns false otherwise. - */ -bool Ability::HasWindowFocus() -{ - if (abilityInfo_ == nullptr) { - HILOG_INFO("Ability::HasWindowFocus abilityInfo_ == nullptr"); - return false; - } - - if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { - return bWindowFocus_; - } - - return false; -} - -void Ability::SetShowOnLockScreen(bool showOnLockScreen) -{ - HILOG_INFO("SetShowOnLockScreen come, showOnLockScreen is %{public}d", showOnLockScreen); - showOnLockScreen_ = showOnLockScreen; - sptr window = nullptr; - if (abilityWindow_ == nullptr || (window = abilityWindow_->GetWindow()) == nullptr) { - HILOG_INFO("SetShowOnLockScreen come, window is null"); - return; - } - HILOG_INFO("SetShowOnLockScreen come, addWindowFlag, showOnLockScreen is %{public}d", showOnLockScreen); - if (showOnLockScreen) { - window->AddWindowFlag(Rosen::WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED); - } else { - window->RemoveWindowFlag(Rosen::WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED); - } -} - -/** - * @brief Called when a key is lone pressed. - * - * @param keyCode Indicates the code of the key long pressed. - * @param keyEvent Indicates the key-long-press event. - * - * @return Returns true if this event is handled and will not be passed further; returns false if this event - * is not handled and should be passed to other handlers. - */ -bool Ability::OnKeyPressAndHold(int keyCode, const std::shared_ptr &keyEvent) -{ - return false; -} -#endif - /** * @brief Called back after permissions are requested by using * AbilityContext.requestPermissionsFromUser(java.lang.String[],int). @@ -929,16 +619,6 @@ void Ability::OnRequestPermissionsFromUserResult( int requestCode, const std::vector &permissions, const std::vector &grantResults) {} -#ifdef SUPPORT_GRAPHICS -/** - * @brief Called when this ability is about to leave the foreground and enter the background due to a user - * operation, for example, when the user touches the Home key. - * - */ -void Ability::OnLeaveForeground() -{} -#endif - /** * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG. @@ -1257,16 +937,6 @@ void Ability::SetResult(int resultCode, const Want &resultData) HILOG_INFO("%{public}s end.", __func__); } -#ifdef SUPPORT_GRAPHICS -/** - * @brief Sets the type of audio whose volume will be adjusted by the volume button. - * - * @param volumeType Indicates the AudioManager.AudioVolumeType to set. - */ -void Ability::SetVolumeTypeAdjustedByKey(int volumeType) -{} -#endif - /** * @brief Called back when Service is started. * This method can be called only by Service. You can use the StartAbility(ohos.aafwk.content.Want) method to start @@ -1669,24 +1339,6 @@ void Ability::SetMainRoute(const std::string &entry) void Ability::AddActionRoute(const std::string &action, const std::string &entry) {} -#ifdef SUPPORT_GRAPHICS -/** - * @brief Sets the background color of the window in RGB color mode. - * - * @param red The value ranges from 0 to 255. - * - * @param green The value ranges from 0 to 255. - * - * @param blue The value ranges from 0 to 255. - * - * @return Returns the result of SetWindowBackgroundColor - */ -int Ability::SetWindowBackgroundColor(int red, int green, int blue) -{ - return -1; -} -#endif - /** * @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template. * @@ -1780,21 +1432,6 @@ int32_t Ability::OnContinue(WantParams &wantParams) return ContinuationManager::OnContinueResult::Reject; } -#ifdef SUPPORT_GRAPHICS -/** - * @brief Get page ability stack info. - * - * @return A string represents page ability stack info, empty if failed; - */ -std::string Ability::GetContentInfo() -{ - if (scene_ == nullptr) { - return ""; - } - return scene_->GetContentInfo(); -} -#endif - /** * @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. @@ -1959,25 +1596,6 @@ bool Ability::IsFlagExists(unsigned int flag, unsigned int flagSet) return (flag & flagSet) == flag; } -#ifdef SUPPORT_GRAPHICS -/** - * @brief Called when this ability gains or loses window focus. - * - * @param hasFocus Specifies whether this ability has focus. - */ -void Ability::OnWindowFocusChanged(bool hasFocus) -{} - -/** - * @brief Called when this ability is moved to or removed from the top of the stack. - * - * @param topActive Specifies whether this ability is moved to or removed from the top of the stack. The value true - * indicates that it is moved to the top, and false indicates that it is removed from the top of the stack. - */ -void Ability::OnTopActiveAbilityChanged(bool topActive) -{} -#endif - /** * @brief Called to set caller information for the application. The default implementation returns null. * @@ -1998,7 +1616,844 @@ std::shared_ptr Ability::CreatePostEventTimeouter(std:: return std::make_shared(taskstr, handler_); } +/** + * @brief Keep this Service ability in the background and displays a notification bar. + * + * @param wantAgent Indicates which ability to start when user click the notification bar. + * @return the method result code, 0 means succeed + */ +int Ability::StartBackgroundRunning(const AbilityRuntime::WantAgent::WantAgent &wantAgent) +{ +#ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE + uint32_t defaultBgMode = 0; + BackgroundTaskMgr::ContinuousTaskParam taskParam = BackgroundTaskMgr::ContinuousTaskParam(false, defaultBgMode, + std::make_shared(wantAgent), abilityInfo_->name, GetToken()); + return BackgroundTaskMgr::BackgroundTaskMgrHelper::RequestStartBackgroundRunning(taskParam); +#else + return ERR_INVALID_OPERATION; +#endif +} + +/** + * @brief Cancel background running of this ability to free up system memory. + * + * @return the method result code, 0 means succeed + */ +int Ability::StopBackgroundRunning() +{ +#ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE + return BackgroundTaskMgr::BackgroundTaskMgrHelper::RequestStopBackgroundRunning(abilityInfo_->name, GetToken()); +#else + return ERR_INVALID_OPERATION; +#endif +} + +/** + * @brief Get the error message by error code. + * @param errorCode the error code return form fms. + * @return Returns the error message detail. + */ +std::string Ability::GetErrorMsg(const ErrCode errorCode) +{ #ifdef SUPPORT_GRAPHICS + return FormMgr::GetInstance().GetErrorMessage(errorCode); +#else + return nullptr; +#endif +} + +/** + * @brief Acquire a bundle manager, if it not existed. + * @return returns the bundle manager ipc object, or nullptr for failed. + */ +sptr Ability::GetBundleMgr() +{ + HILOG_INFO("%{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) { + HILOG_ERROR("%{public}s error, failed to get bundle manager service.", __func__); + return nullptr; + } + + iBundleMgr_ = iface_cast(remoteObject); + if (iBundleMgr_ == nullptr) { + HILOG_ERROR("%{public}s error, failed to get bundle manager service", __func__); + return nullptr; + } + } + + return iBundleMgr_; +} + +/** + * @brief Add the bundle manager instance for debug. + * @param bundleManager the bundle manager ipc object. + */ +void Ability::SetBundleManager(const sptr &bundleManager) +{ + HILOG_INFO("%{public}s called.", __func__); + + iBundleMgr_ = bundleManager; +} + +/** + * @brief Set the start ability setting. + * @param setting the start ability setting. + */ +void Ability::SetStartAbilitySetting(std::shared_ptr setting) +{ + HILOG_INFO("%{public}s called.", __func__); + setting_ = setting; +} + +/** + * @brief Set the launch param. + * + * @param launchParam the launch param. + */ +void Ability::SetLaunchParam(const AAFwk::LaunchParam &launchParam) +{ + HILOG_INFO("%{public}s called.", __func__); + launchParam_ = launchParam; +} + +const AAFwk::LaunchParam& Ability::GetLaunchParam() const +{ + return launchParam_; +} + +std::vector> Ability::ExecuteBatch( + const std::vector> &operations) +{ + HILOG_INFO("Ability::ExecuteBatch start"); + std::vector> results; + if (abilityInfo_ == nullptr) { + HILOG_ERROR("Ability::ExecuteBatch abilityInfo is nullptr"); + return results; + } + if (abilityInfo_->type != AppExecFwk::AbilityType::DATA) { + HILOG_ERROR("Ability::ExecuteBatch data ability type failed, current type: %{public}d", abilityInfo_->type); + return results; + } + size_t len = operations.size(); + HILOG_INFO("Ability::ExecuteBatch operation is nullptr, len %{public}zu", len); + for (size_t i = 0; i < len; i++) { + std::shared_ptr operation = operations[i]; + if (operation == nullptr) { + HILOG_INFO("Ability::ExecuteBatch operation is nullptr, create DataAbilityResult"); + results.push_back(std::make_shared(0)); + continue; + } + ExecuteOperation(operation, results, i); + } + HILOG_INFO("Ability::ExecuteBatch end, %{public}zu", results.size()); + return results; +} +void Ability::ExecuteOperation(std::shared_ptr &operation, + std::vector> &results, int index) +{ + HILOG_INFO("Ability::ExecuteOperation start, index=%{public}d", index); + if (abilityInfo_->type != AppExecFwk::AbilityType::DATA) { + HILOG_ERROR("Ability::ExecuteOperation data ability type failed, current type: %{public}d", abilityInfo_->type); + return; + } + if (index < 0) { + HILOG_ERROR( + "Ability::ExecuteOperation operation result index should not below zero, current index: %{public}d", index); + return; + } + if (operation == nullptr) { + HILOG_INFO("Ability::ExecuteOperation operation is nullptr, create DataAbilityResult"); + results.push_back(std::make_shared(0)); + return; + } + + int numRows = 0; + std::shared_ptr valuesBucket = ParseValuesBucketReference(results, operation, index); + std::shared_ptr predicates = + ParsePredictionArgsReference(results, operation, index); + if (operation->IsInsertOperation()) { + HILOG_INFO("Ability::ExecuteOperation IsInsertOperation"); + numRows = Insert(*(operation->GetUri().get()), *valuesBucket); + } else if (operation->IsDeleteOperation() && predicates) { + HILOG_INFO("Ability::ExecuteOperation IsDeleteOperation"); + numRows = Delete(*(operation->GetUri().get()), *predicates); + } else if (operation->IsUpdateOperation() && predicates) { + HILOG_INFO("Ability::ExecuteOperation IsUpdateOperation"); + numRows = Update(*(operation->GetUri().get()), *valuesBucket, *predicates); + } else if (operation->IsAssertOperation() && predicates) { + HILOG_INFO("Ability::ExecuteOperation IsAssertOperation"); + std::vector columns; + std::shared_ptr queryResult = + Query(*(operation->GetUri().get()), columns, *predicates); + if (queryResult == nullptr) { + HILOG_ERROR("Ability::ExecuteOperation Query retval is nullptr"); + results.push_back(std::make_shared(0)); + return; + } + if (queryResult->GetRowCount(numRows) != 0) { + HILOG_ERROR("Ability::ExecuteOperation queryResult->GetRowCount(numRows) != E_OK"); + } + if (!CheckAssertQueryResult(queryResult, operation->GetValuesBucket())) { + if (queryResult != nullptr) { + queryResult->Close(); + } + HILOG_ERROR("Query Result is not equal to expected value."); + } + + if (queryResult != nullptr) { + queryResult->Close(); + } + } else { + HILOG_ERROR("Ability::ExecuteOperation Expected bad type %{public}d", operation->GetType()); + } + if (operation->GetExpectedCount() != numRows) { + HILOG_ERROR("Ability::ExecuteOperation Expected %{public}d rows but actual %{public}d", + operation->GetExpectedCount(), + numRows); + } else { + if (operation->GetUri() != nullptr) { + results.push_back(std::make_shared(*operation->GetUri(), numRows)); + } else { + results.push_back(std::make_shared(Uri(std::string("")), numRows)); + } + } +} + +std::shared_ptr Ability::ParsePredictionArgsReference( + std::vector> &results, std::shared_ptr &operation, + int numRefs) +{ + if (operation == nullptr) { + HILOG_ERROR("Ability::ParsePredictionArgsReference intpur is nullptr"); + return nullptr; + } + + std::map predicatesBackReferencesMap = operation->GetDataAbilityPredicatesBackReferences(); + if (predicatesBackReferencesMap.empty()) { + return operation->GetDataAbilityPredicates(); + } + + std::vector strPredicatesList; + strPredicatesList.clear(); + std::shared_ptr predicates = operation->GetDataAbilityPredicates(); + if (predicates == nullptr) { + HILOG_INFO("Ability::ParsePredictionArgsReference operation->GetDataAbilityPredicates is nullptr"); + } else { + HILOG_INFO("Ability::ParsePredictionArgsReference operation->GetDataAbilityPredicates isn`t nullptr"); + strPredicatesList = predicates->GetWhereArgs(); + } + + if (strPredicatesList.empty()) { + HILOG_ERROR("Ability::ParsePredictionArgsReference operation->GetDataAbilityPredicates()->GetWhereArgs()" + "error strList is empty()"); + } + + for (auto iterMap : predicatesBackReferencesMap) { + HILOG_INFO( + "Ability::ParsePredictionArgsReference predicatesBackReferencesMap first:%{public}d second:%{public}d", + iterMap.first, + iterMap.second); + int tempCount = ChangeRef2Value(results, numRefs, iterMap.second); + if (tempCount < 0) { + HILOG_ERROR("Ability::ParsePredictionArgsReference tempCount:%{public}d", tempCount); + continue; + } + std::string strPredicates = std::to_string(tempCount); + HILOG_INFO("Ability::ParsePredictionArgsReference strPredicates:%{public}s", strPredicates.c_str()); + strPredicatesList.push_back(strPredicates); + HILOG_INFO("Ability::ParsePredictionArgsReference push_back done"); + } + + if (predicates) { + predicates->SetWhereArgs(strPredicatesList); + } + + return predicates; +} + +std::shared_ptr Ability::ParseValuesBucketReference( + std::vector> &results, std::shared_ptr &operation, + int numRefs) +{ + NativeRdb::ValuesBucket retValueBucket; + if (operation == nullptr) { + HILOG_ERROR("Ability::ParseValuesBucketReference intpur is nullptr"); + return nullptr; + } + + if (operation->GetValuesBucketReferences() == nullptr) { + return operation->GetValuesBucket(); + } + + retValueBucket.Clear(); + if (operation->GetValuesBucket() == nullptr) { + HILOG_INFO("Ability::ParseValuesBucketReference operation->GetValuesBucket is nullptr"); + } else { + HILOG_INFO("Ability::ParseValuesBucketReference operation->GetValuesBucket is nullptr"); + retValueBucket = *operation->GetValuesBucket(); + } + + std::map valuesMapReferences; + operation->GetValuesBucketReferences()->GetAll(valuesMapReferences); + + for (auto itermap : valuesMapReferences) { + std::string key = itermap.first; + NativeRdb::ValueObject obj; + if (!operation->GetValuesBucketReferences()->GetObject(key, obj)) { + HILOG_ERROR("Ability::ParseValuesBucketReference operation->GetValuesBucketReferences()->GetObject error"); + continue; + } + switch (obj.GetType()) { + case NativeRdb::ValueObjectType::TYPE_INT: { + int val = 0; + if (obj.GetInt(val) != 0) { + HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetInt() error"); + break; + } + HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutInt(%{public}s, %{public}d)", + key.c_str(), + val); + retValueBucket.PutInt(key, val); + } break; + case NativeRdb::ValueObjectType::TYPE_DOUBLE: { + double val = 0.0; + if (obj.GetDouble(val) != 0) { + HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetDouble() error"); + break; + } + HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutDouble(%{public}s, %{public}f)", + key.c_str(), + val); + retValueBucket.PutDouble(key, val); + } break; + case NativeRdb::ValueObjectType::TYPE_STRING: { + std::string val = ""; + if (obj.GetString(val) != 0) { + HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetString() error"); + break; + } + HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutString(%{public}s, %{public}s)", + key.c_str(), + val.c_str()); + retValueBucket.PutString(key, val); + } break; + case NativeRdb::ValueObjectType::TYPE_BLOB: { + std::vector val; + if (obj.GetBlob(val) != 0) { + HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetBlob() error"); + break; + } + HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutBlob(%{public}s, %{public}zu)", + key.c_str(), + val.size()); + retValueBucket.PutBlob(key, val); + } break; + case NativeRdb::ValueObjectType::TYPE_BOOL: { + bool val = false; + if (obj.GetBool(val) != 0) { + HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetBool() error"); + break; + } + HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutBool(%{public}s, %{public}s)", + key.c_str(), + val ? "true" : "false"); + retValueBucket.PutBool(key, val); + } break; + default: { + HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutNull(%{public}s)", key.c_str()); + retValueBucket.PutNull(key); + } break; + } + } + + std::map valuesMap; + retValueBucket.GetAll(valuesMap); + + return std::make_shared(valuesMap); +} + +int Ability::ChangeRef2Value(std::vector> &results, int numRefs, int index) +{ + int retval = -1; + if (index >= numRefs) { + HILOG_ERROR("Ability::ChangeRef2Value index >= numRefs"); + return retval; + } + + if (index >= static_cast(results.size())) { + HILOG_ERROR("Ability::ChangeRef2Value index:%{public}d >= results.size():%{public}zu", index, results.size()); + return retval; + } + + std::shared_ptr refResult = results[index]; + if (refResult == nullptr) { + HILOG_ERROR("Ability::ChangeRef2Value No.%{public}d refResult is null", index); + return retval; + } + + if (refResult->GetUri().ToString().empty()) { + retval = refResult->GetCount(); + } else { + retval = DataUriUtils::GetId(refResult->GetUri()); + } + + return retval; +} + +bool Ability::CheckAssertQueryResult(std::shared_ptr &queryResult, + std::shared_ptr &&valuesBucket) +{ + if (queryResult == nullptr) { + HILOG_ERROR("Ability::CheckAssertQueryResult intput queryResult is null"); + return true; + } + + if (valuesBucket == nullptr) { + HILOG_ERROR("Ability::CheckAssertQueryResult intput valuesBucket is null"); + return true; + } + + std::map valuesMap; + valuesBucket->GetAll(valuesMap); + if (valuesMap.empty()) { + HILOG_ERROR("Ability::CheckAssertQueryResult valuesMap is empty"); + return true; + } + int count = 0; + if (queryResult->GetRowCount(count) != 0) { + HILOG_ERROR("Ability::CheckAssertQueryResult GetRowCount is 0"); + return true; + } + + for (auto iterMap : valuesMap) { + std::string strObject; + if (iterMap.second.GetString(strObject) != 0) { + HILOG_ERROR("Ability::CheckAssertQueryResult GetString strObject is error"); + continue; + } + if (strObject.empty()) { + HILOG_ERROR("Ability::CheckAssertQueryResult strObject is empty"); + continue; + } + for (int i = 0; i < count; ++i) { + std::string strName; + if (queryResult->GetString(i, strName) != 0) { + HILOG_ERROR("Ability::CheckAssertQueryResult GetString strName is error"); + continue; + } + if (strName.empty()) { + HILOG_ERROR("Ability::CheckAssertQueryResult strName is empty"); + continue; + } + if (strName == strObject) { + HILOG_ERROR("Ability::CheckAssertQueryResult strName same to strObject"); + continue; + } + + return false; + } + } + + return true; +} + +/** + * @brief request a remote object of callee from this ability. + * @return Returns the remote object of callee. + */ +sptr Ability::CallRequest() +{ + return nullptr; +} + +ErrCode Ability::StartFeatureAbilityForResult(const Want &want, int requestCode, FeatureAbilityTask &&task) +{ + HILOG_DEBUG("%{public}s begin.", __func__); + resultCallbacks_.insert(make_pair(requestCode, std::move(task))); + ErrCode err = StartAbilityForResult(want, requestCode); + HILOG_INFO("%{public}s end. ret=%{public}d", __func__, err); + return err; +} + +void Ability::OnFeatureAbilityResult(int requestCode, int resultCode, const Want &want) +{ + HILOG_DEBUG("%{public}s begin.", __func__); + auto callback = resultCallbacks_.find(requestCode); + if (callback != resultCallbacks_.end()) { + if (callback->second) { + callback->second(resultCode, want); + } + resultCallbacks_.erase(requestCode); + } + HILOG_INFO("%{public}s end.", __func__); +} + +#ifdef SUPPORT_GRAPHICS +static std::mutex formLock; +constexpr int64_t SEC_TO_MILLISEC = 1000; +constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; + +/** + * @brief Informs the system of the time required for drawing this Page ability. + * + * @return Returns the notification is successful or fail + */ +bool Ability::PrintDrawnCompleted() +{ + return AbilityContext::PrintDrawnCompleted(); +} + +/** + * @brief Called after instantiating WindowScene. + * + * + * You can override this function to implement your own processing logic. + */ +void Ability::OnSceneCreated() +{ + HILOG_INFO("%{public}s called.", __func__); +} + +/** + * @brief Called after restore WindowScene. + * + * + * You can override this function to implement your own processing logic. + */ +void Ability::OnSceneRestored() +{ + HILOG_INFO("%{public}s called.", __func__); +} + +/** + * @brief Called after ability stoped. + * + * + * You can override this function to implement your own processing logic. + */ +void Ability::onSceneDestroyed() +{ + HILOG_INFO("%{public}s called.", __func__); +} + +/** + * @brief Called when this ability enters the STATE_FOREGROUND state. + * + * + * The ability in the STATE_FOREGROUND state is visible. + * You can override this function to implement your own processing logic. + */ +void Ability::OnForeground(const Want &want) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + HILOG_INFO("%{public}s begin.", __func__); + DoOnForeground(want); + DispatchLifecycleOnForeground(want); + HILOG_INFO("%{public}s end.", __func__); +} + +/** + * @brief Called when this ability enters the STATE_BACKGROUND state. + * + * + * The ability in the STATE_BACKGROUND state is invisible. + * You can override this function to implement your own processing logic. + */ +void Ability::OnBackground() +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + HILOG_INFO("%{public}s begin.", __func__); + if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { + if (abilityInfo_->isStageBasedModel) { + if (scene_ == nullptr) { + HILOG_ERROR("Ability::OnBackground error. scene_ == nullptr."); + return; + } + HILOG_INFO("GoBackground sceneFlag:%{public}d.", sceneFlag_); + scene_->GoBackground(sceneFlag_); + } else { + if (abilityWindow_ == nullptr) { + HILOG_ERROR("Ability::OnBackground error. abilityWindow_ == nullptr."); + return; + } + HILOG_INFO("OnPostAbilityBackground sceneFlag:%{public}d.", sceneFlag_); + abilityWindow_->OnPostAbilityBackground(sceneFlag_); + } + } + + if (abilityLifecycleExecutor_ == nullptr) { + HILOG_ERROR("Ability::OnBackground error. abilityLifecycleExecutor_ == nullptr."); + return; + } + + if (abilityInfo_->isStageBasedModel) { + abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::BACKGROUND_NEW); + } else { + abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::BACKGROUND); + } + + if (lifecycle_ == nullptr) { + HILOG_ERROR("Ability::OnBackground error. lifecycle_ == nullptr."); + return; + } + lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND); + HILOG_INFO("%{public}s end", __func__); +} + +/** + * @brief Called when a key is pressed. When any component in the Ability gains focus, the key-down event for + * the component will be handled first. This callback will not be invoked if the callback triggered for the + * key-down event of the component returns true. The default implementation of this callback does nothing + * and returns false. + * + * @param keyEvent Indicates the key-down event. + * + * @return Returns true if this event is handled and will not be passed further; returns false if this event + * is not handled and should be passed to other handlers. + */ +void Ability::OnKeyDown(const std::shared_ptr& keyEvent) +{ + HILOG_INFO("Ability::OnKeyDown called"); +} + +/** + * @brief Called when a key is released. When any component in the Ability gains focus, the key-up event for + * the component will be handled first. This callback will not be invoked if the callback triggered for the + * key-up event of the component returns true. The default implementation of this callback does nothing and + * returns false. + * + * @param keyEvent Indicates the key-up event. + * + * @return Returns true if this event is handled and will not be passed further; returns false if this event + * is not handled and should be passed to other handlers. + */ +void Ability::OnKeyUp(const std::shared_ptr& keyEvent) +{ + HILOG_INFO("Ability::OnKeyUp called"); + auto code = keyEvent->GetKeyCode(); + if (code == MMI::KeyEvent::KEYCODE_BACK) { + HILOG_INFO("Ability::OnKey Back key pressed."); + OnBackPressed(); + } +} + +/** + * @brief Called when a touch event is dispatched to this ability. The default implementation of this callback + * does nothing and returns false. + * + * @param event Indicates information about the touch event. + * + * @return Returns true if the event is handled; returns false otherwise. + */ +void Ability::OnPointerEvent(std::shared_ptr& pointerEvent) +{ + HILOG_INFO("Ability::OnTouchEvent called"); +} + +/** + * @brief Inflates UI controls by using ComponentContainer. + * You can create a ComponentContainer instance that contains multiple components. + * + * @param componentContainer Indicates a set of customized components. + */ +void Ability::SetUIContent(const ComponentContainer &componentContainer) +{} + +/** + * @brief Inflates layout resources by using the layout resource ID. + * + * @param layoutRes Indicates the layout resource ID, which cannot be a negative number. + */ +void Ability::SetUIContent(int layoutRes) +{} + +/** + * @brief Inflates UI controls by using ComponentContainer. + * You can create a ComponentContainer instance that contains multiple components. + * + * @param componentContainer Indicates the component layout defined by the user. + * @param context Indicates the context to use. + * @param typeFlag Indicates the window type. + */ +void Ability::SetUIContent( + const ComponentContainer &componentContainer, std::shared_ptr &context, int typeFlag) +{} + +/** + * @brief Inflates layout resources by using the layout resource ID. + * + * @param layoutRes Indicates the layout resource ID, which cannot be a negative number. + * @param context Indicates the context to use. + * @param typeFlag Indicates the window type. + */ +void Ability::SetUIContent(int layoutRes, std::shared_ptr &context, int typeFlag) +{} + +/** + * @brief Inflates UI controls by using WindowOption. + * + * @param windowOption Indicates the window option defined by the user. + */ +void Ability::InitWindow(Rosen::WindowType winType, int32_t displayId, sptr option) +{ + if (abilityWindow_ == nullptr) { + HILOG_ERROR("Ability::InitWindow abilityWindow_ is nullptr"); + return; + } + abilityWindow_->InitWindow(winType, abilityContext_, sceneListener_, displayId, option); +} + +/** + * @brief Get the window belong to the ability. + * + * @return Returns a IWindowsManager object pointer. + */ +const sptr Ability::GetWindow() +{ + if (abilityWindow_ != nullptr) { + return abilityWindow_->GetWindow(); + } else { + HILOG_INFO("%{public}s abilityWindow_ is nullptr.", __func__); + return nullptr; + } +} + +/** + * @brief get the scene belong to the ability. + * + * @return Returns a WindowScene object pointer. + */ +std::shared_ptr Ability::GetScene() +{ + return scene_; +} + +/** + * @brief Obtains the type of audio whose volume is adjusted by the volume button. + * + * @return Returns the AudioManager.AudioVolumeType. + */ +int Ability::GetVolumeTypeAdjustedByKey() +{ + return 0; +} + +/** + * @brief Checks whether the main window of this ability has window focus. + * + * @return Returns true if this ability currently has window focus; returns false otherwise. + */ +bool Ability::HasWindowFocus() +{ + if (abilityInfo_ == nullptr) { + HILOG_INFO("Ability::HasWindowFocus abilityInfo_ == nullptr"); + return false; + } + + if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { + return bWindowFocus_; + } + + return false; +} + +void Ability::SetShowOnLockScreen(bool showOnLockScreen) +{ + HILOG_INFO("SetShowOnLockScreen come, showOnLockScreen is %{public}d", showOnLockScreen); + showOnLockScreen_ = showOnLockScreen; + sptr window = nullptr; + if (abilityWindow_ == nullptr || (window = abilityWindow_->GetWindow()) == nullptr) { + HILOG_INFO("SetShowOnLockScreen come, window is null"); + return; + } + HILOG_INFO("SetShowOnLockScreen come, addWindowFlag, showOnLockScreen is %{public}d", showOnLockScreen); + if (showOnLockScreen) { + window->AddWindowFlag(Rosen::WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED); + } else { + window->RemoveWindowFlag(Rosen::WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED); + } +} + +/** + * @brief Called when a key is lone pressed. + * + * @param keyCode Indicates the code of the key long pressed. + * @param keyEvent Indicates the key-long-press event. + * + * @return Returns true if this event is handled and will not be passed further; returns false if this event + * is not handled and should be passed to other handlers. + */ +bool Ability::OnKeyPressAndHold(int keyCode, const std::shared_ptr &keyEvent) +{ + return false; +} + +/** + * @brief Called when this ability is about to leave the foreground and enter the background due to a user + * operation, for example, when the user touches the Home key. + * + */ +void Ability::OnLeaveForeground() +{} + +/** + * @brief Sets the type of audio whose volume will be adjusted by the volume button. + * + * @param volumeType Indicates the AudioManager.AudioVolumeType to set. + */ +void Ability::SetVolumeTypeAdjustedByKey(int volumeType) +{} + +/** + * @brief Sets the background color of the window in RGB color mode. + * + * @param red The value ranges from 0 to 255. + * + * @param green The value ranges from 0 to 255. + * + * @param blue The value ranges from 0 to 255. + * + * @return Returns the result of SetWindowBackgroundColor + */ +int Ability::SetWindowBackgroundColor(int red, int green, int blue) +{ + return -1; +} + +/** + * @brief Get page ability stack info. + * + * @return A string represents page ability stack info, empty if failed; + */ +std::string Ability::GetContentInfo() +{ + if (scene_ == nullptr) { + return ""; + } + return scene_->GetContentInfo(); +} + +/** + * @brief Called when this ability gains or loses window focus. + * + * @param hasFocus Specifies whether this ability has focus. + */ +void Ability::OnWindowFocusChanged(bool hasFocus) +{} + +/** + * @brief Called when this ability is moved to or removed from the top of the stack. + * + * @param topActive Specifies whether this ability is moved to or removed from the top of the stack. The value true + * indicates that it is moved to the top, and false indicates that it is removed from the top of the stack. + */ +void Ability::OnTopActiveAbilityChanged(bool topActive) +{} + /** * Releases an obtained form by its ID. * @@ -2079,41 +2534,7 @@ ErrCode Ability::DeleteForm(const int64_t formId) // delete form with formId return DeleteForm(formId, DELETE_FORM); } -#endif -/** - * @brief Keep this Service ability in the background and displays a notification bar. - * - * @param wantAgent Indicates which ability to start when user click the notification bar. - * @return the method result code, 0 means succeed - */ -int Ability::StartBackgroundRunning(const AbilityRuntime::WantAgent::WantAgent &wantAgent) -{ -#ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE - uint32_t defaultBgMode = 0; - BackgroundTaskMgr::ContinuousTaskParam taskParam = BackgroundTaskMgr::ContinuousTaskParam(false, defaultBgMode, - std::make_shared(wantAgent), abilityInfo_->name, GetToken()); - return BackgroundTaskMgr::BackgroundTaskMgrHelper::RequestStartBackgroundRunning(taskParam); -#else - return ERR_INVALID_OPERATION; -#endif -} - -/** - * @brief Cancel background running of this ability to free up system memory. - * - * @return the method result code, 0 means succeed - */ -int Ability::StopBackgroundRunning() -{ -#ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE - return BackgroundTaskMgr::BackgroundTaskMgrHelper::RequestStopBackgroundRunning(abilityInfo_->name, GetToken()); -#else - return ERR_INVALID_OPERATION; -#endif -} - -#ifdef SUPPORT_GRAPHICS /** * @brief Cast temp form with formId. * @@ -3078,60 +3499,7 @@ ErrCode Ability::GetFormsInfoByModule(std::string &bundleName, std::string &modu // GetFormsInfoByModule request to fms return FormMgr::GetInstance().GetFormsInfoByModule(bundleName, moduleName, formInfos); } -#endif -/** - * @brief Get the error message by error code. - * @param errorCode the error code return form fms. - * @return Returns the error message detail. - */ -std::string Ability::GetErrorMsg(const ErrCode errorCode) -{ -#ifdef SUPPORT_GRAPHICS - return FormMgr::GetInstance().GetErrorMessage(errorCode); -#else - return nullptr; -#endif -} - -/** - * @brief Acquire a bundle manager, if it not existed. - * @return returns the bundle manager ipc object, or nullptr for failed. - */ -sptr Ability::GetBundleMgr() -{ - HILOG_INFO("%{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) { - HILOG_ERROR("%{public}s error, failed to get bundle manager service.", __func__); - return nullptr; - } - - iBundleMgr_ = iface_cast(remoteObject); - if (iBundleMgr_ == nullptr) { - HILOG_ERROR("%{public}s error, failed to get bundle manager service", __func__); - return nullptr; - } - } - - return iBundleMgr_; -} - -/** - * @brief Add the bundle manager instance for debug. - * @param bundleManager the bundle manager ipc object. - */ -void Ability::SetBundleManager(const sptr &bundleManager) -{ - HILOG_INFO("%{public}s called.", __func__); - - iBundleMgr_ = bundleManager; -} - -#ifdef SUPPORT_GRAPHICS /** * @brief Acquire a form provider remote object. * @return Returns form provider remote object. @@ -3151,378 +3519,12 @@ sptr Ability::GetFormRemoteObject() HILOG_INFO("%{public}s end", __func__); return providerRemoteObject_; } -#endif -/** - * @brief Set the start ability setting. - * @param setting the start ability setting. - */ -void Ability::SetStartAbilitySetting(std::shared_ptr setting) -{ - HILOG_INFO("%{public}s called.", __func__); - setting_ = setting; -} - -/** - * @brief Set the launch param. - * - * @param launchParam the launch param. - */ -void Ability::SetLaunchParam(const AAFwk::LaunchParam &launchParam) -{ - HILOG_INFO("%{public}s called.", __func__); - launchParam_ = launchParam; -} - -const AAFwk::LaunchParam& Ability::GetLaunchParam() const -{ - return launchParam_; -} - -#ifdef SUPPORT_GRAPHICS void Ability::SetSceneListener(const sptr &listener) { sceneListener_ = listener; } -#endif -std::vector> Ability::ExecuteBatch( - const std::vector> &operations) -{ - HILOG_INFO("Ability::ExecuteBatch start"); - std::vector> results; - if (abilityInfo_ == nullptr) { - HILOG_ERROR("Ability::ExecuteBatch abilityInfo is nullptr"); - return results; - } - if (abilityInfo_->type != AppExecFwk::AbilityType::DATA) { - HILOG_ERROR("Ability::ExecuteBatch data ability type failed, current type: %{public}d", abilityInfo_->type); - return results; - } - size_t len = operations.size(); - HILOG_INFO("Ability::ExecuteBatch operation is nullptr, len %{public}zu", len); - for (size_t i = 0; i < len; i++) { - std::shared_ptr operation = operations[i]; - if (operation == nullptr) { - HILOG_INFO("Ability::ExecuteBatch operation is nullptr, create DataAbilityResult"); - results.push_back(std::make_shared(0)); - continue; - } - ExecuteOperation(operation, results, i); - } - HILOG_INFO("Ability::ExecuteBatch end, %{public}zu", results.size()); - return results; -} -void Ability::ExecuteOperation(std::shared_ptr &operation, - std::vector> &results, int index) -{ - HILOG_INFO("Ability::ExecuteOperation start, index=%{public}d", index); - if (abilityInfo_->type != AppExecFwk::AbilityType::DATA) { - HILOG_ERROR("Ability::ExecuteOperation data ability type failed, current type: %{public}d", abilityInfo_->type); - return; - } - if (index < 0) { - HILOG_ERROR( - "Ability::ExecuteOperation operation result index should not below zero, current index: %{public}d", index); - return; - } - if (operation == nullptr) { - HILOG_INFO("Ability::ExecuteOperation operation is nullptr, create DataAbilityResult"); - results.push_back(std::make_shared(0)); - return; - } - - int numRows = 0; - std::shared_ptr valuesBucket = ParseValuesBucketReference(results, operation, index); - std::shared_ptr predicates = - ParsePredictionArgsReference(results, operation, index); - if (operation->IsInsertOperation()) { - HILOG_INFO("Ability::ExecuteOperation IsInsertOperation"); - numRows = Insert(*(operation->GetUri().get()), *valuesBucket); - } else if (operation->IsDeleteOperation() && predicates) { - HILOG_INFO("Ability::ExecuteOperation IsDeleteOperation"); - numRows = Delete(*(operation->GetUri().get()), *predicates); - } else if (operation->IsUpdateOperation() && predicates) { - HILOG_INFO("Ability::ExecuteOperation IsUpdateOperation"); - numRows = Update(*(operation->GetUri().get()), *valuesBucket, *predicates); - } else if (operation->IsAssertOperation() && predicates) { - HILOG_INFO("Ability::ExecuteOperation IsAssertOperation"); - std::vector columns; - std::shared_ptr queryResult = - Query(*(operation->GetUri().get()), columns, *predicates); - if (queryResult == nullptr) { - HILOG_ERROR("Ability::ExecuteOperation Query retval is nullptr"); - results.push_back(std::make_shared(0)); - return; - } - if (queryResult->GetRowCount(numRows) != 0) { - HILOG_ERROR("Ability::ExecuteOperation queryResult->GetRowCount(numRows) != E_OK"); - } - if (!CheckAssertQueryResult(queryResult, operation->GetValuesBucket())) { - if (queryResult != nullptr) { - queryResult->Close(); - } - HILOG_ERROR("Query Result is not equal to expected value."); - } - - if (queryResult != nullptr) { - queryResult->Close(); - } - } else { - HILOG_ERROR("Ability::ExecuteOperation Expected bad type %{public}d", operation->GetType()); - } - if (operation->GetExpectedCount() != numRows) { - HILOG_ERROR("Ability::ExecuteOperation Expected %{public}d rows but actual %{public}d", - operation->GetExpectedCount(), - numRows); - } else { - if (operation->GetUri() != nullptr) { - results.push_back(std::make_shared(*operation->GetUri(), numRows)); - } else { - results.push_back(std::make_shared(Uri(std::string("")), numRows)); - } - } -} - -std::shared_ptr Ability::ParsePredictionArgsReference( - std::vector> &results, std::shared_ptr &operation, - int numRefs) -{ - if (operation == nullptr) { - HILOG_ERROR("Ability::ParsePredictionArgsReference intpur is nullptr"); - return nullptr; - } - - std::map predicatesBackReferencesMap = operation->GetDataAbilityPredicatesBackReferences(); - if (predicatesBackReferencesMap.empty()) { - return operation->GetDataAbilityPredicates(); - } - - std::vector strPredicatesList; - strPredicatesList.clear(); - std::shared_ptr predicates = operation->GetDataAbilityPredicates(); - if (predicates == nullptr) { - HILOG_INFO("Ability::ParsePredictionArgsReference operation->GetDataAbilityPredicates is nullptr"); - } else { - HILOG_INFO("Ability::ParsePredictionArgsReference operation->GetDataAbilityPredicates isn`t nullptr"); - strPredicatesList = predicates->GetWhereArgs(); - } - - if (strPredicatesList.empty()) { - HILOG_ERROR("Ability::ParsePredictionArgsReference operation->GetDataAbilityPredicates()->GetWhereArgs()" - "error strList is empty()"); - } - - for (auto iterMap : predicatesBackReferencesMap) { - HILOG_INFO( - "Ability::ParsePredictionArgsReference predicatesBackReferencesMap first:%{public}d second:%{public}d", - iterMap.first, - iterMap.second); - int tempCount = ChangeRef2Value(results, numRefs, iterMap.second); - if (tempCount < 0) { - HILOG_ERROR("Ability::ParsePredictionArgsReference tempCount:%{public}d", tempCount); - continue; - } - std::string strPredicates = std::to_string(tempCount); - HILOG_INFO("Ability::ParsePredictionArgsReference strPredicates:%{public}s", strPredicates.c_str()); - strPredicatesList.push_back(strPredicates); - HILOG_INFO("Ability::ParsePredictionArgsReference push_back done"); - } - - if (predicates) { - predicates->SetWhereArgs(strPredicatesList); - } - - return predicates; -} - -std::shared_ptr Ability::ParseValuesBucketReference( - std::vector> &results, std::shared_ptr &operation, - int numRefs) -{ - NativeRdb::ValuesBucket retValueBucket; - if (operation == nullptr) { - HILOG_ERROR("Ability::ParseValuesBucketReference intpur is nullptr"); - return nullptr; - } - - if (operation->GetValuesBucketReferences() == nullptr) { - return operation->GetValuesBucket(); - } - - retValueBucket.Clear(); - if (operation->GetValuesBucket() == nullptr) { - HILOG_INFO("Ability::ParseValuesBucketReference operation->GetValuesBucket is nullptr"); - } else { - HILOG_INFO("Ability::ParseValuesBucketReference operation->GetValuesBucket is nullptr"); - retValueBucket = *operation->GetValuesBucket(); - } - - std::map valuesMapReferences; - operation->GetValuesBucketReferences()->GetAll(valuesMapReferences); - - for (auto itermap : valuesMapReferences) { - std::string key = itermap.first; - NativeRdb::ValueObject obj; - if (!operation->GetValuesBucketReferences()->GetObject(key, obj)) { - HILOG_ERROR("Ability::ParseValuesBucketReference operation->GetValuesBucketReferences()->GetObject error"); - continue; - } - switch (obj.GetType()) { - case NativeRdb::ValueObjectType::TYPE_INT: { - int val = 0; - if (obj.GetInt(val) != 0) { - HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetInt() error"); - break; - } - HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutInt(%{public}s, %{public}d)", - key.c_str(), - val); - retValueBucket.PutInt(key, val); - } break; - case NativeRdb::ValueObjectType::TYPE_DOUBLE: { - double val = 0.0; - if (obj.GetDouble(val) != 0) { - HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetDouble() error"); - break; - } - HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutDouble(%{public}s, %{public}f)", - key.c_str(), - val); - retValueBucket.PutDouble(key, val); - } break; - case NativeRdb::ValueObjectType::TYPE_STRING: { - std::string val = ""; - if (obj.GetString(val) != 0) { - HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetString() error"); - break; - } - HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutString(%{public}s, %{public}s)", - key.c_str(), - val.c_str()); - retValueBucket.PutString(key, val); - } break; - case NativeRdb::ValueObjectType::TYPE_BLOB: { - std::vector val; - if (obj.GetBlob(val) != 0) { - HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetBlob() error"); - break; - } - HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutBlob(%{public}s, %{public}zu)", - key.c_str(), - val.size()); - retValueBucket.PutBlob(key, val); - } break; - case NativeRdb::ValueObjectType::TYPE_BOOL: { - bool val = false; - if (obj.GetBool(val) != 0) { - HILOG_ERROR("Ability::ParseValuesBucketReference ValueObject->GetBool() error"); - break; - } - HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutBool(%{public}s, %{public}s)", - key.c_str(), - val ? "true" : "false"); - retValueBucket.PutBool(key, val); - } break; - default: { - HILOG_INFO("Ability::ParseValuesBucketReference retValueBucket->PutNull(%{public}s)", key.c_str()); - retValueBucket.PutNull(key); - } break; - } - } - - std::map valuesMap; - retValueBucket.GetAll(valuesMap); - - return std::make_shared(valuesMap); -} - -int Ability::ChangeRef2Value(std::vector> &results, int numRefs, int index) -{ - int retval = -1; - if (index >= numRefs) { - HILOG_ERROR("Ability::ChangeRef2Value index >= numRefs"); - return retval; - } - - if (index >= static_cast(results.size())) { - HILOG_ERROR("Ability::ChangeRef2Value index:%{public}d >= results.size():%{public}zu", index, results.size()); - return retval; - } - - std::shared_ptr refResult = results[index]; - if (refResult == nullptr) { - HILOG_ERROR("Ability::ChangeRef2Value No.%{public}d refResult is null", index); - return retval; - } - - if (refResult->GetUri().ToString().empty()) { - retval = refResult->GetCount(); - } else { - retval = DataUriUtils::GetId(refResult->GetUri()); - } - - return retval; -} - -bool Ability::CheckAssertQueryResult(std::shared_ptr &queryResult, - std::shared_ptr &&valuesBucket) -{ - if (queryResult == nullptr) { - HILOG_ERROR("Ability::CheckAssertQueryResult intput queryResult is null"); - return true; - } - - if (valuesBucket == nullptr) { - HILOG_ERROR("Ability::CheckAssertQueryResult intput valuesBucket is null"); - return true; - } - - std::map valuesMap; - valuesBucket->GetAll(valuesMap); - if (valuesMap.empty()) { - HILOG_ERROR("Ability::CheckAssertQueryResult valuesMap is empty"); - return true; - } - int count = 0; - if (queryResult->GetRowCount(count) != 0) { - HILOG_ERROR("Ability::CheckAssertQueryResult GetRowCount is 0"); - return true; - } - - for (auto iterMap : valuesMap) { - std::string strObject; - if (iterMap.second.GetString(strObject) != 0) { - HILOG_ERROR("Ability::CheckAssertQueryResult GetString strObject is error"); - continue; - } - if (strObject.empty()) { - HILOG_ERROR("Ability::CheckAssertQueryResult strObject is empty"); - continue; - } - for (int i = 0; i < count; ++i) { - std::string strName; - if (queryResult->GetString(i, strName) != 0) { - HILOG_ERROR("Ability::CheckAssertQueryResult GetString strName is error"); - continue; - } - if (strName.empty()) { - HILOG_ERROR("Ability::CheckAssertQueryResult strName is empty"); - continue; - } - if (strName == strObject) { - HILOG_ERROR("Ability::CheckAssertQueryResult strName same to strObject"); - continue; - } - - return false; - } - } - - return true; -} - -#ifdef SUPPORT_GRAPHICS sptr Ability::GetWindowOption(const Want &want) { sptr option = new Rosen::WindowOption(); @@ -3575,18 +3577,7 @@ void Ability::DoOnForeground(const Want& want) } } -#endif -/** - * @brief request a remote object of callee from this ability. - * @return Returns the remote object of callee. - */ -sptr Ability::CallRequest() -{ - return nullptr; -} - -#ifdef SUPPORT_GRAPHICS int Ability::GetCurrentWindowMode() { HILOG_INFO("%{public}s start", __func__); @@ -3808,27 +3799,5 @@ int Ability::GetDisplayOrientation() return 0; } #endif - -ErrCode Ability::StartFeatureAbilityForResult(const Want &want, int requestCode, FeatureAbilityTask &&task) -{ - HILOG_DEBUG("%{public}s begin.", __func__); - resultCallbacks_.insert(make_pair(requestCode, std::move(task))); - ErrCode err = StartAbilityForResult(want, requestCode); - HILOG_INFO("%{public}s end. ret=%{public}d", __func__, err); - return err; -} - -void Ability::OnFeatureAbilityResult(int requestCode, int resultCode, const Want &want) -{ - HILOG_DEBUG("%{public}s begin.", __func__); - auto callback = resultCallbacks_.find(requestCode); - if (callback != resultCallbacks_.end()) { - if (callback->second) { - callback->second(resultCode, want); - } - resultCallbacks_.erase(requestCode); - } - HILOG_INFO("%{public}s end.", __func__); -} } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/src/ability_impl.cpp b/frameworks/kits/ability/native/src/ability_impl.cpp index 7501b929..a881cb3b 100644 --- a/frameworks/kits/ability/native/src/ability_impl.cpp +++ b/frameworks/kits/ability/native/src/ability_impl.cpp @@ -182,160 +182,6 @@ bool AbilityImpl::IsStageBasedModel() const return isStageBasedModel_; } -#ifdef SUPPORT_GRAPHICS -void AbilityImpl::AfterUnFocused() -{ - HILOG_INFO("%{public}s begin.", __func__); - if (!ability_ || !ability_->GetAbilityInfo() || !contextDeal_ || !handler_) { - HILOG_ERROR("AbilityImpl::AfterUnFocused failed"); - return; - } - - if (ability_->GetAbilityInfo()->isStageBasedModel) { - HILOG_INFO("new version ability, do nothing when after unfocused."); - return; - } - - HILOG_INFO("old version ability, window after unfocused."); - auto task = [abilityImpl = shared_from_this(), ability = ability_, contextDeal = contextDeal_]() { - auto info = contextDeal->GetLifeCycleStateInfo(); - info.state = AbilityLifeCycleState::ABILITY_STATE_INACTIVE; - info.isNewWant = false; - Want want(*(ability->GetWant())); - abilityImpl->HandleAbilityTransaction(want, info); - }; - handler_->PostTask(task); - HILOG_INFO("%{public}s end.", __func__); -} - -void AbilityImpl::AfterFocused() -{ - HILOG_INFO("%{public}s begin.", __func__); - if (!ability_ || !ability_->GetAbilityInfo() || !contextDeal_ || !handler_) { - HILOG_ERROR("AbilityImpl::AfterFocused failed"); - return; - } - - if (ability_->GetAbilityInfo()->isStageBasedModel) { - HILOG_INFO("new version ability, do nothing when after focused."); - return; - } - - HILOG_INFO("fa mode ability, window after focused."); - auto task = [abilityImpl = shared_from_this(), ability = ability_, contextDeal = contextDeal_]() { - auto info = contextDeal->GetLifeCycleStateInfo(); - info.state = AbilityLifeCycleState::ABILITY_STATE_ACTIVE; - info.isNewWant = false; - Want want(*(ability->GetWant())); - abilityImpl->HandleAbilityTransaction(want, info); - }; - handler_->PostTask(task); - HILOG_INFO("%{public}s end.", __func__); -} - -void AbilityImpl::WindowLifeCycleImpl::AfterForeground() -{ - HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - auto owner = owner_.lock(); - if (owner && !owner->IsStageBasedModel()) { - return; - } - - HILOG_INFO("Stage mode ability, window after foreground, notify ability manager service."); - PacMap restoreData; - AbilityManagerClient::GetInstance()->AbilityTransitionDone(token_, - AbilityLifeCycleState::ABILITY_STATE_FOREGROUND_NEW, restoreData); -} - -void AbilityImpl::WindowLifeCycleImpl::AfterBackground() -{ - HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - auto owner = owner_.lock(); - if (owner && !owner->IsStageBasedModel()) { - return; - } - - HILOG_INFO("new version ability, window after background."); - PacMap restoreData; - AbilityManagerClient::GetInstance()->AbilityTransitionDone(token_, - AbilityLifeCycleState::ABILITY_STATE_BACKGROUND_NEW, restoreData); -} - -void AbilityImpl::WindowLifeCycleImpl::AfterFocused() -{ - HILOG_INFO("%{public}s begin.", __func__); - auto owner = owner_.lock(); - if (owner) { - owner->AfterFocused(); - } - HILOG_INFO("%{public}s end.", __func__); -} - -void AbilityImpl::WindowLifeCycleImpl::AfterUnfocused() -{ - HILOG_INFO("%{public}s begin.", __func__); - auto owner = owner_.lock(); - if (owner) { - owner->AfterUnFocused(); - } - HILOG_INFO("%{public}s end.", __func__); -} - -/** - * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application - * that it belongs to of the lifecycle status. - * - * @param want The Want object to switch the life cycle. - */ -void AbilityImpl::Foreground(const Want &want) -{ - HILOG_INFO("%{public}s begin.", __func__); - if (ability_ == nullptr || ability_->GetAbilityInfo() == nullptr || abilityLifecycleCallbacks_ == nullptr) { - HILOG_ERROR("AbilityImpl::Foreground ability_ or abilityLifecycleCallbacks_ is nullptr"); - return; - } - - HILOG_INFO("AbilityImpl::Foreground"); - ability_->OnForeground(want); - if ((ability_->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE) && - (ability_->GetAbilityInfo()->isStageBasedModel)) { - lifecycleState_ = AAFwk::ABILITY_STATE_FOREGROUND_NEW; - } else { - lifecycleState_ = AAFwk::ABILITY_STATE_INACTIVE; - } - abilityLifecycleCallbacks_->OnAbilityForeground(ability_); - HILOG_INFO("%{public}s end.", __func__); -} - -/** - * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_BACKGROUND. And notifies the application - * that it belongs to of the lifecycle status. - * - */ -void AbilityImpl::Background() -{ - HILOG_INFO("%{public}s begin.", __func__); - if (ability_ == nullptr || ability_->GetAbilityInfo() == nullptr || abilityLifecycleCallbacks_ == nullptr) { - HILOG_ERROR("AbilityImpl::Background ability_ or abilityLifecycleCallbacks_ is nullptr"); - return; - } - - HILOG_INFO("AbilityImpl::Background"); - ability_->OnLeaveForeground(); - ability_->OnBackground(); - if ((ability_->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE) && - (ability_->GetAbilityInfo()->isStageBasedModel)) { - lifecycleState_ = AAFwk::ABILITY_STATE_BACKGROUND_NEW; - } else { - lifecycleState_ = AAFwk::ABILITY_STATE_BACKGROUND; - } - abilityLifecycleCallbacks_->OnAbilityBackground(ability_); - HILOG_INFO("%{public}s end.", __func__); -} -#endif - /** * @brief Save data and states of an ability when it is restored by the system. and Calling information back to Ability. * This method should be implemented by a Page ability. @@ -450,47 +296,6 @@ int AbilityImpl::GetCurrentState() return lifecycleState_; } -#ifdef SUPPORT_GRAPHICS -/** - * @brief Execution the KeyDown callback of the ability - * @param keyEvent Indicates the key-down event. - * - * @return Returns true if this event is handled and will not be passed further; returns false if this event is - * not handled and should be passed to other handlers. - * - */ -void AbilityImpl::DoKeyDown(const std::shared_ptr& keyEvent) -{ - HILOG_INFO("AbilityImpl::DoKeyDown called"); -} - -/** - * @brief Execution the KeyUp callback of the ability - * @param keyEvent Indicates the key-up event. - * - * @return Returns true if this event is handled and will not be passed further; returns false if this event is - * not handled and should be passed to other handlers. - * - */ -void AbilityImpl::DoKeyUp(const std::shared_ptr& keyEvent) -{ - HILOG_INFO("AbilityImpl::DoKeyUp called"); -} - -/** - * @brief Called when a touch event is dispatched to this ability. The default implementation of this callback - * does nothing and returns false. - * @param touchEvent Indicates information about the touch event. - * - * @return Returns true if the event is handled; returns false otherwise. - * - */ -void AbilityImpl::DoPointerEvent(std::shared_ptr& pointerEvent) -{ - HILOG_INFO("AbilityImpl::DoPointerEvent called"); -} -#endif - /** * @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 @@ -861,26 +666,6 @@ void AbilityImpl::ScheduleUpdateConfiguration(const Configuration &config) HILOG_INFO("%{public}s end.", __func__); } -#ifdef SUPPORT_GRAPHICS -void AbilityImpl::InputEventConsumerImpl::OnInputEvent(std::shared_ptr keyEvent) const -{ - int32_t code = keyEvent->GetKeyAction(); - if (code == MMI::KeyEvent::KEY_ACTION_DOWN) { - abilityImpl_->DoKeyDown(keyEvent); - HILOG_INFO("AbilityImpl::OnKeyDown keyAction: %{public}d.", code); - } else if (code == MMI::KeyEvent::KEY_ACTION_UP) { - abilityImpl_->DoKeyUp(keyEvent); - HILOG_INFO("AbilityImpl::DoKeyUp keyAction: %{public}d.", code); - } -} - -void AbilityImpl::InputEventConsumerImpl::OnInputEvent(std::shared_ptr pointerEvent) const -{ - HILOG_INFO("AbilityImpl::DoPointerEvent called."); - abilityImpl_->DoPointerEvent(pointerEvent); -} -#endif - /** * @brief Create a PostEvent timeout task. The default delay is 5000ms * @@ -921,5 +706,216 @@ void AbilityImpl::NotifyContinuationResult(int32_t result) } ability_->OnCompleteContinuation(result); } + +#ifdef SUPPORT_GRAPHICS +void AbilityImpl::AfterUnFocused() +{ + HILOG_INFO("%{public}s begin.", __func__); + if (!ability_ || !ability_->GetAbilityInfo() || !contextDeal_ || !handler_) { + HILOG_ERROR("AbilityImpl::AfterUnFocused failed"); + return; + } + + if (ability_->GetAbilityInfo()->isStageBasedModel) { + HILOG_INFO("new version ability, do nothing when after unfocused."); + return; + } + + HILOG_INFO("old version ability, window after unfocused."); + auto task = [abilityImpl = shared_from_this(), ability = ability_, contextDeal = contextDeal_]() { + auto info = contextDeal->GetLifeCycleStateInfo(); + info.state = AbilityLifeCycleState::ABILITY_STATE_INACTIVE; + info.isNewWant = false; + Want want(*(ability->GetWant())); + abilityImpl->HandleAbilityTransaction(want, info); + }; + handler_->PostTask(task); + HILOG_INFO("%{public}s end.", __func__); +} + +void AbilityImpl::AfterFocused() +{ + HILOG_INFO("%{public}s begin.", __func__); + if (!ability_ || !ability_->GetAbilityInfo() || !contextDeal_ || !handler_) { + HILOG_ERROR("AbilityImpl::AfterFocused failed"); + return; + } + + if (ability_->GetAbilityInfo()->isStageBasedModel) { + HILOG_INFO("new version ability, do nothing when after focused."); + return; + } + + HILOG_INFO("fa mode ability, window after focused."); + auto task = [abilityImpl = shared_from_this(), ability = ability_, contextDeal = contextDeal_]() { + auto info = contextDeal->GetLifeCycleStateInfo(); + info.state = AbilityLifeCycleState::ABILITY_STATE_ACTIVE; + info.isNewWant = false; + Want want(*(ability->GetWant())); + abilityImpl->HandleAbilityTransaction(want, info); + }; + handler_->PostTask(task); + HILOG_INFO("%{public}s end.", __func__); +} + +void AbilityImpl::WindowLifeCycleImpl::AfterForeground() +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + HILOG_INFO("%{public}s begin.", __func__); + auto owner = owner_.lock(); + if (owner && !owner->IsStageBasedModel()) { + return; + } + + HILOG_INFO("Stage mode ability, window after foreground, notify ability manager service."); + PacMap restoreData; + AbilityManagerClient::GetInstance()->AbilityTransitionDone(token_, + AbilityLifeCycleState::ABILITY_STATE_FOREGROUND_NEW, restoreData); +} + +void AbilityImpl::WindowLifeCycleImpl::AfterBackground() +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + HILOG_INFO("%{public}s begin.", __func__); + auto owner = owner_.lock(); + if (owner && !owner->IsStageBasedModel()) { + return; + } + + HILOG_INFO("new version ability, window after background."); + PacMap restoreData; + AbilityManagerClient::GetInstance()->AbilityTransitionDone(token_, + AbilityLifeCycleState::ABILITY_STATE_BACKGROUND_NEW, restoreData); +} + +void AbilityImpl::WindowLifeCycleImpl::AfterFocused() +{ + HILOG_INFO("%{public}s begin.", __func__); + auto owner = owner_.lock(); + if (owner) { + owner->AfterFocused(); + } + HILOG_INFO("%{public}s end.", __func__); +} + +void AbilityImpl::WindowLifeCycleImpl::AfterUnfocused() +{ + HILOG_INFO("%{public}s begin.", __func__); + auto owner = owner_.lock(); + if (owner) { + owner->AfterUnFocused(); + } + HILOG_INFO("%{public}s end.", __func__); +} + +/** + * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application + * that it belongs to of the lifecycle status. + * + * @param want The Want object to switch the life cycle. + */ +void AbilityImpl::Foreground(const Want &want) +{ + HILOG_INFO("%{public}s begin.", __func__); + if (ability_ == nullptr || ability_->GetAbilityInfo() == nullptr || abilityLifecycleCallbacks_ == nullptr) { + HILOG_ERROR("AbilityImpl::Foreground ability_ or abilityLifecycleCallbacks_ is nullptr"); + return; + } + + HILOG_INFO("AbilityImpl::Foreground"); + ability_->OnForeground(want); + if ((ability_->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE) && + (ability_->GetAbilityInfo()->isStageBasedModel)) { + lifecycleState_ = AAFwk::ABILITY_STATE_FOREGROUND_NEW; + } else { + lifecycleState_ = AAFwk::ABILITY_STATE_INACTIVE; + } + abilityLifecycleCallbacks_->OnAbilityForeground(ability_); + HILOG_INFO("%{public}s end.", __func__); +} + +/** + * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_BACKGROUND. And notifies the application + * that it belongs to of the lifecycle status. + * + */ +void AbilityImpl::Background() +{ + HILOG_INFO("%{public}s begin.", __func__); + if (ability_ == nullptr || ability_->GetAbilityInfo() == nullptr || abilityLifecycleCallbacks_ == nullptr) { + HILOG_ERROR("AbilityImpl::Background ability_ or abilityLifecycleCallbacks_ is nullptr"); + return; + } + + HILOG_INFO("AbilityImpl::Background"); + ability_->OnLeaveForeground(); + ability_->OnBackground(); + if ((ability_->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE) && + (ability_->GetAbilityInfo()->isStageBasedModel)) { + lifecycleState_ = AAFwk::ABILITY_STATE_BACKGROUND_NEW; + } else { + lifecycleState_ = AAFwk::ABILITY_STATE_BACKGROUND; + } + abilityLifecycleCallbacks_->OnAbilityBackground(ability_); + HILOG_INFO("%{public}s end.", __func__); +} + +/** + * @brief Execution the KeyDown callback of the ability + * @param keyEvent Indicates the key-down event. + * + * @return Returns true if this event is handled and will not be passed further; returns false if this event is + * not handled and should be passed to other handlers. + * + */ +void AbilityImpl::DoKeyDown(const std::shared_ptr& keyEvent) +{ + HILOG_INFO("AbilityImpl::DoKeyDown called"); +} + +/** + * @brief Execution the KeyUp callback of the ability + * @param keyEvent Indicates the key-up event. + * + * @return Returns true if this event is handled and will not be passed further; returns false if this event is + * not handled and should be passed to other handlers. + * + */ +void AbilityImpl::DoKeyUp(const std::shared_ptr& keyEvent) +{ + HILOG_INFO("AbilityImpl::DoKeyUp called"); +} + +/** + * @brief Called when a touch event is dispatched to this ability. The default implementation of this callback + * does nothing and returns false. + * @param touchEvent Indicates information about the touch event. + * + * @return Returns true if the event is handled; returns false otherwise. + * + */ +void AbilityImpl::DoPointerEvent(std::shared_ptr& pointerEvent) +{ + HILOG_INFO("AbilityImpl::DoPointerEvent called"); +} + +void AbilityImpl::InputEventConsumerImpl::OnInputEvent(std::shared_ptr keyEvent) const +{ + int32_t code = keyEvent->GetKeyAction(); + if (code == MMI::KeyEvent::KEY_ACTION_DOWN) { + abilityImpl_->DoKeyDown(keyEvent); + HILOG_INFO("AbilityImpl::OnKeyDown keyAction: %{public}d.", code); + } else if (code == MMI::KeyEvent::KEY_ACTION_UP) { + abilityImpl_->DoKeyUp(keyEvent); + HILOG_INFO("AbilityImpl::DoKeyUp keyAction: %{public}d.", code); + } +} + +void AbilityImpl::InputEventConsumerImpl::OnInputEvent(std::shared_ptr pointerEvent) const +{ + HILOG_INFO("AbilityImpl::DoPointerEvent called."); + abilityImpl_->DoPointerEvent(pointerEvent); +} +#endif } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/src/ability_lifecycle_observer.cpp b/frameworks/kits/ability/native/src/ability_lifecycle_observer.cpp index 129b017b..f616973b 100644 --- a/frameworks/kits/ability/native/src/ability_lifecycle_observer.cpp +++ b/frameworks/kits/ability/native/src/ability_lifecycle_observer.cpp @@ -24,28 +24,6 @@ namespace AppExecFwk { void LifecycleObserver::OnActive() {} -#ifdef SUPPORT_GRAPHICS -/** - * @brief Called back in response to an ON_BACKGROUND event. - * When an ON_BACKGROUND event is received, the ability or ability slice is invisible. You are advised to - * suspend the threads related to this ability or ability slice and clear resources for more system memory. - * - */ -void LifecycleObserver::OnBackground() -{} - -/** - * @brief Called back in response to an ON_FOREGROUND event, where information for the - * ability or ability slice to go back to the ACTIVE state is carried in the want parameter. - * When an ON_FOREGROUND event is received, the ability or ability slice returns to the foreground. You can use - * this method to implement re-initialization or adjust the UI display by using the want parameter. - * - * @param want Indicates the information for the ability or ability slice to go back to the ACTIVE state. - */ -void LifecycleObserver::OnForeground(const Want &want) -{} -#endif - /** * @brief Called back in response to an ON_INACTIVE event. * When an ON_INACTIVE event is received, the ability or ability slice is in the INACTIVE state. INACTIVE is an @@ -95,5 +73,27 @@ void LifecycleObserver::OnStateChanged(Lifecycle::Event event, const Want &want) */ virtual void LifecycleObserver::OnStateChanged(LifeCycle::Event event) {} + +#ifdef SUPPORT_GRAPHICS +/** + * @brief Called back in response to an ON_BACKGROUND event. + * When an ON_BACKGROUND event is received, the ability or ability slice is invisible. You are advised to + * suspend the threads related to this ability or ability slice and clear resources for more system memory. + * + */ +void LifecycleObserver::OnBackground() +{} + +/** + * @brief Called back in response to an ON_FOREGROUND event, where information for the + * ability or ability slice to go back to the ACTIVE state is carried in the want parameter. + * When an ON_FOREGROUND event is received, the ability or ability slice returns to the foreground. You can use + * this method to implement re-initialization or adjust the UI display by using the want parameter. + * + * @param want Indicates the information for the ability or ability slice to go back to the ACTIVE state. + */ +void LifecycleObserver::OnForeground(const Want &want) +{} +#endif } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp b/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp index 4f8e7433..89faea3a 100644 --- a/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp +++ b/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp @@ -37,9 +37,6 @@ namespace OHOS { namespace AbilityRuntime { -#ifdef SUPPORT_GRAPHICS -const std::string PAGE_STACK_PROPERTY_NAME = "pageStack"; -#endif Ability *JsAbility::Create(const std::unique_ptr &runtime) { return new JsAbility(static_cast(*runtime)); @@ -189,6 +186,8 @@ void JsAbility::OnStop() } #ifdef SUPPORT_GRAPHICS +const std::string PAGE_STACK_PROPERTY_NAME = "pageStack"; + void JsAbility::OnSceneCreated() { HILOG_INFO("OnSceneCreated begin, ability is %{public}s.", GetAbilityName().c_str()); @@ -306,6 +305,116 @@ void JsAbility::OnBackground() applicationContext->DispatchOnAbilityBackground(jsAbilityObj_); } } + +std::unique_ptr JsAbility::CreateAppWindowStage() +{ + HandleScope handleScope(jsRuntime_); + auto &engine = jsRuntime_.GetNativeEngine(); + NativeValue *jsWindowStage = Rosen::CreateJsWindowStage(engine, GetScene()); + if (jsWindowStage == nullptr) { + HILOG_ERROR("Failed to create jsWindowSatge object"); + return nullptr; + } + return jsRuntime_.LoadSystemModule("application.WindowStage", &jsWindowStage, 1); +} + +void JsAbility::GetPageStackFromWant(const Want &want, std::string &pageStack) +{ + auto stringObj = AAFwk::IString::Query(want.GetParams().GetParam(PAGE_STACK_PROPERTY_NAME)); + if (stringObj != nullptr) { + pageStack = AAFwk::String::Unbox(stringObj); + } +} + +void JsAbility::DoOnForeground(const Want &want) +{ + if (scene_ == nullptr) { + if ((abilityContext_ == nullptr) || (sceneListener_ == nullptr)) { + HILOG_ERROR("Ability::OnForeground error. abilityContext_ or sceneListener_ is nullptr!"); + return; + } + scene_ = std::make_shared(); + if (scene_ == nullptr) { + HILOG_ERROR("%{public}s error. failed to create WindowScene instance!", __func__); + return; + } + int32_t displayId = Rosen::WindowScene::DEFAULT_DISPLAY_ID; + if (setting_ != nullptr) { + std::string strDisplayId = + setting_->GetProperty(OHOS::AppExecFwk::AbilityStartSetting::WINDOW_DISPLAY_ID_KEY); + std::regex formatRegex("[0-9]{0,9}$"); + std::smatch sm; + bool flag = std::regex_match(strDisplayId, sm, formatRegex); + if (flag && !strDisplayId.empty()) { + displayId = std::stoi(strDisplayId); + HILOG_INFO("%{public}s success. displayId is %{public}d", __func__, displayId); + } else { + HILOG_INFO("%{public}s failed to formatRegex:[%{public}s]", __func__, strDisplayId.c_str()); + } + } + auto option = GetWindowOption(want); + Rosen::WMError ret = scene_->Init(displayId, abilityContext_, sceneListener_, option); + if (ret != Rosen::WMError::WM_OK) { + HILOG_ERROR("%{public}s error. failed to init window scene!", __func__); + return; + } + + // multi-instance ability continuation + HILOG_INFO("lauch reason = %{public}d", launchParam_.launchReason); + if (IsRestoredInContinuation()) { + std::string pageStack; + GetPageStackFromWant(want, pageStack); + HandleScope handleScope(jsRuntime_); + auto &engine = jsRuntime_.GetNativeEngine(); + if (abilityContext_->GetContentStorage()) { + scene_->GetMainWindow()->SetUIContent(pageStack, &engine, + abilityContext_->GetContentStorage()->Get(), true); + } else { + HILOG_ERROR("restore: content storage is nullptr"); + } + OnSceneRestored(); + WaitingDistributedObjectSyncComplete(want); + } else { + OnSceneCreated(); + } + } else { + auto window = scene_->GetMainWindow(); + if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) { + auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, + AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED); + window->SetWindowMode(static_cast(windowMode)); + HILOG_INFO("set window mode = %{public}d.", windowMode); + } + } + + auto window = scene_->GetMainWindow(); + if (window) { + HILOG_INFO("Call RegisterDisplayMoveListener, windowId: %{public}d", window->GetWindowId()); + std::weak_ptr weakAbility = shared_from_this(); + abilityDisplayMoveListener_ = new AbilityDisplayMoveListener(weakAbility); + window->RegisterDisplayMoveListener(abilityDisplayMoveListener_); + } + + HILOG_INFO("%{public}s begin scene_->GoForeground, sceneFlag_:%{public}d.", __func__, Ability::sceneFlag_); + scene_->GoForeground(Ability::sceneFlag_); + HILOG_INFO("%{public}s end scene_->GoForeground.", __func__); +} + +void JsAbility::RequsetFocus(const Want &want) +{ + HILOG_INFO("%{public}s called.", __func__); + if (scene_ == nullptr) { + return; + } + auto window = scene_->GetMainWindow(); + if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) { + auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, + AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED); + window->SetWindowMode(static_cast(windowMode)); + HILOG_INFO("set window mode = %{public}d.", windowMode); + } + scene_->GoForeground(Ability::sceneFlag_); +} #endif int32_t JsAbility::OnContinue(WantParams &wantParams) @@ -509,102 +618,6 @@ void JsAbility::CallObjectMethod(const char *name, NativeValue *const *argv, siz nativeEngine.CallFunction(value, methodOnCreate, argv, argc); } -#ifdef SUPPORT_GRAPHICS -std::unique_ptr JsAbility::CreateAppWindowStage() -{ - HandleScope handleScope(jsRuntime_); - auto &engine = jsRuntime_.GetNativeEngine(); - NativeValue *jsWindowStage = Rosen::CreateJsWindowStage(engine, GetScene()); - if (jsWindowStage == nullptr) { - HILOG_ERROR("Failed to create jsWindowSatge object"); - return nullptr; - } - return jsRuntime_.LoadSystemModule("application.WindowStage", &jsWindowStage, 1); -} - -void JsAbility::GetPageStackFromWant(const Want &want, std::string &pageStack) -{ - auto stringObj = AAFwk::IString::Query(want.GetParams().GetParam(PAGE_STACK_PROPERTY_NAME)); - if (stringObj != nullptr) { - pageStack = AAFwk::String::Unbox(stringObj); - } -} - -void JsAbility::DoOnForeground(const Want &want) -{ - if (scene_ == nullptr) { - if ((abilityContext_ == nullptr) || (sceneListener_ == nullptr)) { - HILOG_ERROR("Ability::OnForeground error. abilityContext_ or sceneListener_ is nullptr!"); - return; - } - scene_ = std::make_shared(); - if (scene_ == nullptr) { - HILOG_ERROR("%{public}s error. failed to create WindowScene instance!", __func__); - return; - } - int32_t displayId = Rosen::WindowScene::DEFAULT_DISPLAY_ID; - if (setting_ != nullptr) { - std::string strDisplayId = - setting_->GetProperty(OHOS::AppExecFwk::AbilityStartSetting::WINDOW_DISPLAY_ID_KEY); - std::regex formatRegex("[0-9]{0,9}$"); - std::smatch sm; - bool flag = std::regex_match(strDisplayId, sm, formatRegex); - if (flag && !strDisplayId.empty()) { - displayId = std::stoi(strDisplayId); - HILOG_INFO("%{public}s success. displayId is %{public}d", __func__, displayId); - } else { - HILOG_INFO("%{public}s failed to formatRegex:[%{public}s]", __func__, strDisplayId.c_str()); - } - } - auto option = GetWindowOption(want); - Rosen::WMError ret = scene_->Init(displayId, abilityContext_, sceneListener_, option); - if (ret != Rosen::WMError::WM_OK) { - HILOG_ERROR("%{public}s error. failed to init window scene!", __func__); - return; - } - - // multi-instance ability continuation - HILOG_INFO("lauch reason = %{public}d", launchParam_.launchReason); - if (IsRestoredInContinuation()) { - std::string pageStack; - GetPageStackFromWant(want, pageStack); - HandleScope handleScope(jsRuntime_); - auto &engine = jsRuntime_.GetNativeEngine(); - if (abilityContext_->GetContentStorage()) { - scene_->GetMainWindow()->SetUIContent(pageStack, &engine, - abilityContext_->GetContentStorage()->Get(), true); - } else { - HILOG_ERROR("restore: content storage is nullptr"); - } - OnSceneRestored(); - WaitingDistributedObjectSyncComplete(want); - } else { - OnSceneCreated(); - } - } else { - auto window = scene_->GetMainWindow(); - if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) { - auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, - AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED); - window->SetWindowMode(static_cast(windowMode)); - HILOG_INFO("set window mode = %{public}d.", windowMode); - } - } - - auto window = scene_->GetMainWindow(); - if (window) { - HILOG_INFO("Call RegisterDisplayMoveListener, windowId: %{public}d", window->GetWindowId()); - std::weak_ptr weakAbility = shared_from_this(); - abilityDisplayMoveListener_ = new AbilityDisplayMoveListener(weakAbility); - window->RegisterDisplayMoveListener(abilityDisplayMoveListener_); - } - - HILOG_INFO("%{public}s begin scene_->GoForeground, sceneFlag_:%{public}d.", __func__, Ability::sceneFlag_); - scene_->GoForeground(Ability::sceneFlag_); - HILOG_INFO("%{public}s end scene_->GoForeground.", __func__); -} -#endif - std::shared_ptr JsAbility::CreateADelegatorAbilityProperty() { auto property = std::make_shared(); @@ -616,24 +629,6 @@ std::shared_ptr JsAbility::CreateADelegat return property; } -#ifdef SUPPORT_GRAPHICS -void JsAbility::RequsetFocus(const Want &want) -{ - HILOG_INFO("%{public}s called.", __func__); - if (scene_ == nullptr) { - return; - } - auto window = scene_->GetMainWindow(); - if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) { - auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, - AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED); - window->SetWindowMode(static_cast(windowMode)); - HILOG_INFO("set window mode = %{public}d.", windowMode); - } - scene_->GoForeground(Ability::sceneFlag_); -} -#endif - void JsAbility::Dump(const std::vector ¶ms, std::vector &info) { Ability::Dump(params, info); diff --git a/frameworks/kits/ability/native/src/ability_runtime/js_ability_context.cpp b/frameworks/kits/ability/native/src/ability_runtime/js_ability_context.cpp index 2b57f8d1..1889ed66 100644 --- a/frameworks/kits/ability/native/src/ability_runtime/js_ability_context.cpp +++ b/frameworks/kits/ability/native/src/ability_runtime/js_ability_context.cpp @@ -158,26 +158,12 @@ NativeValue* JsAbilityContext::RestoreWindowStage(NativeEngine* engine, NativeCa return (me != nullptr) ? me->OnRestoreWindowStage(*engine, *info) : nullptr; } -NativeValue* JsAbilityContext::SetMissionLabel(NativeEngine* engine, NativeCallbackInfo* info) -{ - JsAbilityContext* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnSetMissionLabel(*engine, *info) : nullptr; -} - NativeValue* JsAbilityContext::IsTerminating(NativeEngine* engine, NativeCallbackInfo* info) { JsAbilityContext* me = CheckParamsAndGetThis(engine, info); return (me != nullptr) ? me->OnIsTerminating(*engine, *info) : nullptr; } -#ifdef SUPPORT_GRAPHICS -NativeValue* JsAbilityContext::SetMissionIcon(NativeEngine* engine, NativeCallbackInfo* info) -{ - JsAbilityContext* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnSetMissionIcon(*engine, *info) : nullptr; -} -#endif - NativeValue* JsAbilityContext::OnStartAbility(NativeEngine& engine, NativeCallbackInfo& info) { HILOG_INFO("OnStartAbility is called."); @@ -987,50 +973,6 @@ NativeValue* JsAbilityContext::OnRestoreWindowStage(NativeEngine& engine, Native return engine.CreateUndefined(); } -NativeValue* JsAbilityContext::OnSetMissionLabel(NativeEngine& engine, NativeCallbackInfo& info) -{ - HILOG_INFO("OnSetMissionLabel is called, argc = %{public}d", static_cast(info.argc)); - if (info.argc < ARGC_ONE) { - HILOG_ERROR("OnSetMissionLabel, Not enough params"); - return engine.CreateUndefined(); - } - - int32_t errorCode = 0; - std::string label; - if (!ConvertFromJsValue(engine, info.argv[0], label)) { - HILOG_ERROR("OnSetMissionLabel, parse label failed."); - errorCode = ERR_NOT_OK; - } - - AsyncTask::CompleteCallback complete = - [weak = context_, label, errorCode](NativeEngine& engine, AsyncTask& task, int32_t status) { - if (errorCode != 0) { - task.Reject(engine, CreateJsError(engine, errorCode, "Invalidate params.")); - return; - } - - auto context = weak.lock(); - if (!context) { - HILOG_WARN("context is released"); - task.Reject(engine, CreateJsError(engine, 1, "Context is released")); - return; - } - - auto errcode = context->SetMissionLabel(label); - if (errcode == 0) { - task.Resolve(engine, engine.CreateUndefined()); - } else { - task.Reject(engine, CreateJsError(engine, errcode, "SetMissionLabel failed.")); - } - }; - - NativeValue* lastParam = (info.argc == ARGC_ONE) ? nullptr : info.argv[1]; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return result; -} - NativeValue* JsAbilityContext::OnIsTerminating(NativeEngine& engine, NativeCallbackInfo& info) { HILOG_INFO("OnIsTerminating is called"); @@ -1042,53 +984,6 @@ NativeValue* JsAbilityContext::OnIsTerminating(NativeEngine& engine, NativeCallb return engine.CreateBoolean(context->IsTerminating()); } -#ifdef SUPPORT_GRAPHICS -NativeValue* JsAbilityContext::OnSetMissionIcon(NativeEngine& engine, NativeCallbackInfo& info) -{ - HILOG_INFO("OnSetMissionIcon is called, argc = %{public}d", static_cast(info.argc)); - if (info.argc < ARGC_ONE) { - HILOG_ERROR("OnSetMissionIcon, Not enough params"); - return engine.CreateUndefined(); - } - - int32_t errorCode = 0; - auto icon = OHOS::Media::PixelMapNapi::GetPixelMap(reinterpret_cast(&engine), - reinterpret_cast(info.argv[0])); - if (!icon) { - HILOG_ERROR("OnSetMissionIcon, parse icon failed."); - errorCode = ERR_NOT_OK; - } - - AsyncTask::CompleteCallback complete = - [weak = context_, icon, errorCode](NativeEngine& engine, AsyncTask& task, int32_t status) { - if (errorCode != 0) { - task.Reject(engine, CreateJsError(engine, errorCode, "Invalidate params.")); - return; - } - - auto context = weak.lock(); - if (!context) { - HILOG_WARN("context is released when set mission icon"); - task.Reject(engine, CreateJsError(engine, -1, "Context is released")); - return; - } - - auto errcode = context->SetMissionIcon(icon); - if (errcode == 0) { - task.Resolve(engine, engine.CreateUndefined()); - } else { - task.Reject(engine, CreateJsError(engine, errcode, "SetMissionIcon failed.")); - } - }; - - NativeValue* lastParam = (info.argc == ARGC_ONE) ? nullptr : info.argv[1]; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return result; -} -#endif - bool JsAbilityContext::UnWrapWant(NativeEngine& engine, NativeValue* argv, AAFwk::Want& want) { if (argv == nullptr) { @@ -1241,10 +1136,10 @@ NativeValue* CreateJsAbilityContext(NativeEngine& engine, std::shared_ptr(engine_.CreateReference(jsConnectionObject, 1)); } + +#ifdef SUPPORT_GRAPHICS +NativeValue* JsAbilityContext::SetMissionLabel(NativeEngine* engine, NativeCallbackInfo* info) +{ + JsAbilityContext* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnSetMissionLabel(*engine, *info) : nullptr; +} + +NativeValue* JsAbilityContext::SetMissionIcon(NativeEngine* engine, NativeCallbackInfo* info) +{ + JsAbilityContext* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnSetMissionIcon(*engine, *info) : nullptr; +} + +NativeValue* JsAbilityContext::OnSetMissionLabel(NativeEngine& engine, NativeCallbackInfo& info) +{ + HILOG_INFO("OnSetMissionLabel is called, argc = %{public}d", static_cast(info.argc)); + if (info.argc < ARGC_ONE) { + HILOG_ERROR("OnSetMissionLabel, Not enough params"); + return engine.CreateUndefined(); + } + + int32_t errorCode = 0; + std::string label; + if (!ConvertFromJsValue(engine, info.argv[0], label)) { + HILOG_ERROR("OnSetMissionLabel, parse label failed."); + errorCode = ERR_NOT_OK; + } + + AsyncTask::CompleteCallback complete = + [weak = context_, label, errorCode](NativeEngine& engine, AsyncTask& task, int32_t status) { + if (errorCode != 0) { + task.Reject(engine, CreateJsError(engine, errorCode, "Invalidate params.")); + return; + } + + auto context = weak.lock(); + if (!context) { + HILOG_WARN("context is released"); + task.Reject(engine, CreateJsError(engine, 1, "Context is released")); + return; + } + + auto errcode = context->SetMissionLabel(label); + if (errcode == 0) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "SetMissionLabel failed.")); + } + }; + + NativeValue* lastParam = (info.argc == ARGC_ONE) ? nullptr : info.argv[1]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +NativeValue* JsAbilityContext::OnSetMissionIcon(NativeEngine& engine, NativeCallbackInfo& info) +{ + HILOG_INFO("OnSetMissionIcon is called, argc = %{public}d", static_cast(info.argc)); + if (info.argc < ARGC_ONE) { + HILOG_ERROR("OnSetMissionIcon, Not enough params"); + return engine.CreateUndefined(); + } + + int32_t errorCode = 0; + auto icon = OHOS::Media::PixelMapNapi::GetPixelMap(reinterpret_cast(&engine), + reinterpret_cast(info.argv[0])); + if (!icon) { + HILOG_ERROR("OnSetMissionIcon, parse icon failed."); + errorCode = ERR_NOT_OK; + } + + AsyncTask::CompleteCallback complete = + [weak = context_, icon, errorCode](NativeEngine& engine, AsyncTask& task, int32_t status) { + if (errorCode != 0) { + task.Reject(engine, CreateJsError(engine, errorCode, "Invalidate params.")); + return; + } + + auto context = weak.lock(); + if (!context) { + HILOG_WARN("context is released when set mission icon"); + task.Reject(engine, CreateJsError(engine, -1, "Context is released")); + return; + } + + auto errcode = context->SetMissionIcon(icon); + if (errcode == 0) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "SetMissionIcon failed.")); + } + }; + + NativeValue* lastParam = (info.argc == ARGC_ONE) ? nullptr : info.argv[1]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} +#endif } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability.cpp b/frameworks/kits/ability/native/test/mock/include/mock_ability.cpp index dc1fb5f1..911a50e2 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability.cpp +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability.cpp @@ -67,18 +67,6 @@ void Ability::OnActive() void Ability::OnInactive() {} -#ifdef SUPPORT_GRAPHICS -void Ability::OnForeground(const Want &want) -{ - return; -} - -void Ability::OnBackground() -{ - return; -} -#endif - sptr Ability::OnConnect(const Want &want) { return nullptr; @@ -102,100 +90,12 @@ void Ability::StartAbility(const Want &want, AbilityStartSetting abilityStartSet return; } -#ifdef SUPPORT_GRAPHICS -bool Ability::OnKeyDown(int keyCode, const KeyEvent &keyEvent) -{ - return false; -} - -bool Ability::OnKeyUp(int keyCode, const KeyEvent &keyEvent) -{ - return false; -} - -bool Ability::OnTouchEvent(const TouchEvent &touchEvent) -{ - return false; -} - -void Ability::SetUIContent(const ComponentContainer &componentContainer) -{ - return; -} - -void Ability::SetUIContent(int layoutRes) -{ - return; -} // namespace AppExecFwk - -void Ability::SetUIContent( - const ComponentContainer &componentContainer, std::shared_ptr &context, int typeFlag) -{ - return; -} - -void Ability::SetUIContent(int layoutRes, std::shared_ptr &context, int typeFlag) -{ - return; -} - -/** - * @brief Inflates UI controls by using WindowConfig. - * - * @param config Indicates the window config defined by the user. - */ -void Ability::SetUIContent(const WindowConfig &config) -{ - if (abilityWindow_ == nullptr) { - HILOG_ERROR("Ability::SetUIContent abilityWindow_ is nullptr"); - return; - } - - HILOG_INFO("Ability::SetUIContent called"); - abilityWindow_->SetWindowConfig(config); -} - -/** - * @brief Get the window belong to the ability. - * - * @return Returns a IWindowsManager object pointer. - */ -std::unique_ptr &Ability::GetWindow(int windowID) -{ - HILOG_INFO("Ability::GetWindow called windowID = %d.", windowID); - - return abilityWindow_->GetWindow(windowID); -} - -int Ability::GetVolumeTypeAdjustedByKey() -{ - return 0; -} - -bool Ability::HasWindowFocus() -{ - return false; -} - -bool Ability::OnKeyPressAndHold(int keyCode, const std::shared_ptr &keyEvent) -{ - return false; -} -#endif - void Ability::OnRequestPermissionsFromUserResult( int requestCode, const std::vector &permissions, const std::vector &grantResults) { return; } -#ifdef SUPPORT_GRAPHICS -void Ability::OnLeaveForeground() -{ - return; -} -#endif - std::string Ability::GetType(const Uri &uri) { std::string value("\nullptr"); @@ -272,13 +172,6 @@ void Ability::OnEventDispatch() return; } -#ifdef SUPPORT_GRAPHICS -void Ability::OnWindowFocusChanged(bool hasFocus) -{ - return; -} -#endif - void Ability::SetWant(const AAFwk::Want &want) { setWant_ = std::make_shared(want); @@ -302,13 +195,6 @@ void Ability::SetResult(int resultCode, const Want &resultData) } } -#ifdef SUPPORT_GRAPHICS -void Ability::SetVolumeTypeAdjustedByKey(int volumeType) -{ - return; -} -#endif - void Ability::OnCommand(const AAFwk::Want &want, bool restart, int startId) { return; @@ -442,6 +328,110 @@ void Ability::AddActionRoute(const std::string &action, const std::string &entry } #ifdef SUPPORT_GRAPHICS +void Ability::OnForeground(const Want &want) +{ + return; +} + +void Ability::OnBackground() +{ + return; +} + +bool Ability::OnKeyDown(int keyCode, const KeyEvent &keyEvent) +{ + return false; +} + +bool Ability::OnKeyUp(int keyCode, const KeyEvent &keyEvent) +{ + return false; +} + +bool Ability::OnTouchEvent(const TouchEvent &touchEvent) +{ + return false; +} + +void Ability::SetUIContent(const ComponentContainer &componentContainer) +{ + return; +} + +void Ability::SetUIContent(int layoutRes) +{ + return; +} // namespace AppExecFwk + +void Ability::SetUIContent( + const ComponentContainer &componentContainer, std::shared_ptr &context, int typeFlag) +{ + return; +} + +void Ability::SetUIContent(int layoutRes, std::shared_ptr &context, int typeFlag) +{ + return; +} + +/** + * @brief Inflates UI controls by using WindowConfig. + * + * @param config Indicates the window config defined by the user. + */ +void Ability::SetUIContent(const WindowConfig &config) +{ + if (abilityWindow_ == nullptr) { + HILOG_ERROR("Ability::SetUIContent abilityWindow_ is nullptr"); + return; + } + + HILOG_INFO("Ability::SetUIContent called"); + abilityWindow_->SetWindowConfig(config); +} + +/** + * @brief Get the window belong to the ability. + * + * @return Returns a IWindowsManager object pointer. + */ +std::unique_ptr &Ability::GetWindow(int windowID) +{ + HILOG_INFO("Ability::GetWindow called windowID = %d.", windowID); + + return abilityWindow_->GetWindow(windowID); +} + +int Ability::GetVolumeTypeAdjustedByKey() +{ + return 0; +} + +bool Ability::HasWindowFocus() +{ + return false; +} + +bool Ability::OnKeyPressAndHold(int keyCode, const std::shared_ptr &keyEvent) +{ + return false; +} + +void Ability::OnLeaveForeground() +{ + return; +} + +void Ability::OnWindowFocusChanged(bool hasFocus) +{ + return; +} + +void Ability::SetVolumeTypeAdjustedByKey(int volumeType) +{ + return; +} + int Ability::SetWindowBackgroundColor(int red, int green, int blue) { return -1; diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_impl.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_impl.h index 2c8adc7c..3246489e 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_impl.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_impl.h @@ -49,18 +49,6 @@ public: this->Inactive(); } -#ifdef SUPPORT_GRAPHICS - void ImplForeground(const Want &want) - { - this->Foreground(want); - } - - void ImplBackground() - { - this->Background(); - } -#endif - void SetlifecycleState(int state) { this->lifecycleState_ = state; @@ -93,6 +81,18 @@ public: return AbilityImpl::CheckAndRestore(); } +#ifdef SUPPORT_GRAPHICS + void ImplForeground(const Want &want) + { + this->Foreground(want); + } + + void ImplBackground() + { + this->Background(); + } +#endif + private: AbilityImpl AbilityImpl_; }; diff --git a/frameworks/kits/ability/native/test/mock/include/mock_lifecycle_observer.h b/frameworks/kits/ability/native/test/mock/include/mock_lifecycle_observer.h index 67f7c832..ee95fd1a 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_lifecycle_observer.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_lifecycle_observer.h @@ -38,34 +38,6 @@ public: GTEST_LOG_(INFO) << "MockLifecycleObserver::OnActive called"; } -#ifdef SUPPORT_GRAPHICS - /** - * Called back in response to an ON_BACKGROUND event. - * When an ON_BACKGROUND event is received, the ability or ability slice is invisible. You are advised to - * suspend the threads related to this ability or ability slice and clear resources for more system memory. - * - */ - - virtual void OnBackground() - { - GTEST_LOG_(INFO) << "MockLifecycleObserver::OnBackground called"; - } - - /** - * Called back in response to an ON_FOREGROUND event, where information for the - * ability or ability slice to go back to the ACTIVE state is carried in the want parameter. - * When an ON_FOREGROUND event is received, the ability or ability slice returns to the foreground. You can use - * this method to implement re-initialization or adjust the UI display by using the want parameter. - * - * @param want Indicates the information for the ability or ability slice to go back to the ACTIVE state. - */ - virtual void OnForeground(const Want &want) - { - (void)want; - GTEST_LOG_(INFO) << "MockLifecycleObserver::OnForeground called"; - } -#endif - /** * Called back in response to an ON_INACTIVE event. * When an ON_INACTIVE event is received, the ability or ability slice is in the INACTIVE state. INACTIVE is an @@ -129,6 +101,34 @@ public: (void)event; GTEST_LOG_(INFO) << "MockLifecycleObserver::OnStateChanged called"; } + +#ifdef SUPPORT_GRAPHICS + /** + * Called back in response to an ON_BACKGROUND event. + * When an ON_BACKGROUND event is received, the ability or ability slice is invisible. You are advised to + * suspend the threads related to this ability or ability slice and clear resources for more system memory. + * + */ + + virtual void OnBackground() + { + GTEST_LOG_(INFO) << "MockLifecycleObserver::OnBackground called"; + } + + /** + * Called back in response to an ON_FOREGROUND event, where information for the + * ability or ability slice to go back to the ACTIVE state is carried in the want parameter. + * When an ON_FOREGROUND event is received, the ability or ability slice returns to the foreground. You can use + * this method to implement re-initialization or adjust the UI display by using the want parameter. + * + * @param want Indicates the information for the ability or ability slice to go back to the ACTIVE state. + */ + virtual void OnForeground(const Want &want) + { + (void)want; + GTEST_LOG_(INFO) << "MockLifecycleObserver::OnForeground called"; + } +#endif }; } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp b/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp index 31b4b824..ac6713a2 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp +++ b/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp @@ -86,18 +86,6 @@ void AbilityImpl::Inactive() GTEST_LOG_(INFO) << "Mock AbilityImpl::Inactive called"; } -#ifdef SUPPORT_GRAPHICS -void AbilityImpl::Foreground(const Want &want) -{ - GTEST_LOG_(INFO) << "Mock AbilityImpl::Foreground called"; -} - -void AbilityImpl::Background() -{ - GTEST_LOG_(INFO) << "Mock AbilityImpl::Background called"; -} -#endif - void AbilityImpl::DispatchSaveAbilityState() { GTEST_LOG_(INFO) << "Mock AbilityImpl::DispatchSaveAbilityState called"; @@ -134,14 +122,6 @@ int AbilityImpl::GetCurrentState() return lifecycleState_; } -#ifdef SUPPORT_GRAPHICS -void AbilityImpl::DoKeyDown(const std::shared_ptr& keyEvent) {} - -void AbilityImpl::DoKeyUp(const std::shared_ptr& keyEvent) {} - -void AbilityImpl::DoPointerEvent(std::shared_ptr& pointerEvent) {} -#endif - void AbilityImpl::SendResult(int requestCode, int resultCode, const Want &resultData) { GTEST_LOG_(INFO) << "Mock AbilityImpl::SendResult called"; @@ -195,5 +175,23 @@ std::string AbilityImpl::GetType(const Uri &uri) GTEST_LOG_(INFO) << "Mock AbilityImpl::GetType called"; return ""; } + +#ifdef SUPPORT_GRAPHICS +void AbilityImpl::Foreground(const Want &want) +{ + GTEST_LOG_(INFO) << "Mock AbilityImpl::Foreground called"; +} + +void AbilityImpl::Background() +{ + GTEST_LOG_(INFO) << "Mock AbilityImpl::Background called"; +} + +void AbilityImpl::DoKeyDown(const std::shared_ptr& keyEvent) {} + +void AbilityImpl::DoKeyUp(const std::shared_ptr& keyEvent) {} + +void AbilityImpl::DoPointerEvent(std::shared_ptr& pointerEvent) {} +#endif } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator.h b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator.h index 0ce0d28d..016704a6 100644 --- a/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator.h +++ b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator.h @@ -27,6 +27,7 @@ #ifndef SUPPORT_GRAPHICS #include "inttypes.h" #endif + #include "ability_delegator_infos.h" #include "iability_monitor.h" #include "delegator_thread.h" diff --git a/frameworks/kits/appkit/native/test/mock/ability_delegator/mock_ability_delegator_stub.cpp b/frameworks/kits/appkit/native/test/mock/ability_delegator/mock_ability_delegator_stub.cpp index c7db95bb..24685296 100644 --- a/frameworks/kits/appkit/native/test/mock/ability_delegator/mock_ability_delegator_stub.cpp +++ b/frameworks/kits/appkit/native/test/mock/ability_delegator/mock_ability_delegator_stub.cpp @@ -199,26 +199,6 @@ int MockAbilityDelegatorStub::BlockAppService() return 0; } -#ifdef ABILITY_COMMAND_FOR_TEST -int MockAbilityDelegatorStub::ForceTimeoutForTest(const std::string &abilityName, const std::string &state) -{ - return 0; -} -#endif - -#ifdef SUPPORT_GRAPHICS -int MockAbilityDelegatorStub::SetMissionIcon( - const sptr &token, const std::shared_ptr &icon) -{ - return 0; -} - -int MockAbilityDelegatorStub::RegisterWindowManagerServiceHandler(const sptr& handler) -{ - return 0; -} -#endif - bool MockAbilityDelegatorStub2::finishFlag_ = false; MockAbilityDelegatorStub2::MockAbilityDelegatorStub2() @@ -396,6 +376,11 @@ int MockAbilityDelegatorStub2::BlockAppService() } #ifdef ABILITY_COMMAND_FOR_TEST +int MockAbilityDelegatorStub::ForceTimeoutForTest(const std::string &abilityName, const std::string &state) +{ + return 0; +} + int MockAbilityDelegatorStub2::ForceTimeoutForTest(const std::string &abilityName, const std::string &state) { return 0; @@ -403,6 +388,17 @@ int MockAbilityDelegatorStub2::ForceTimeoutForTest(const std::string &abilityNam #endif #ifdef SUPPORT_GRAPHICS +int MockAbilityDelegatorStub::SetMissionIcon( + const sptr &token, const std::shared_ptr &icon) +{ + return 0; +} + +int MockAbilityDelegatorStub::RegisterWindowManagerServiceHandler(const sptr& handler) +{ + return 0; +} + int MockAbilityDelegatorStub2::SetMissionIcon( const sptr &token, const std::shared_ptr &icon) { diff --git a/frameworks/kits/appkit/native/test/mock/ability_delegator/mock_ability_delegator_stub.h b/frameworks/kits/appkit/native/test/mock/ability_delegator/mock_ability_delegator_stub.h index 3afd9bb3..f8e39c0f 100644 --- a/frameworks/kits/appkit/native/test/mock/ability_delegator/mock_ability_delegator_stub.h +++ b/frameworks/kits/appkit/native/test/mock/ability_delegator/mock_ability_delegator_stub.h @@ -110,7 +110,6 @@ public: MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); - MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD1(ClearUpApplicationData, int(const std::string &)); MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); @@ -152,6 +151,7 @@ public: virtual int ForceTimeoutForTest(const std::string &abilityName, const std::string &state) override; #endif #ifdef SUPPORT_GRAPHICS + MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); virtual int SetMissionIcon( const sptr &token, const std::shared_ptr &icon) override; virtual int RegisterWindowManagerServiceHandler(const sptr& handler); @@ -247,7 +247,6 @@ public: MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); - MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD1(ClearUpApplicationData, int(const std::string &)); MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); @@ -289,6 +288,7 @@ public: virtual int ForceTimeoutForTest(const std::string &abilityName, const std::string &state) override; #endif #ifdef SUPPORT_GRAPHICS + MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); virtual int SetMissionIcon( const sptr &token, const std::shared_ptr &icon) override; virtual int RegisterWindowManagerServiceHandler(const sptr& handler); diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_client.h b/interfaces/innerkits/ability_manager/include/ability_manager_client.h index 7cf30b62..929e6bdb 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_client.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_client.h @@ -589,6 +589,7 @@ public: */ ErrCode RegisterSnapshotHandler(const sptr& handler); +#ifdef SUPPORT_GRAPHICS /** * Set mission label of this ability. * @@ -598,7 +599,6 @@ public: */ ErrCode SetMissionLabel(const sptr &abilityToken, const std::string &label); -#ifdef SUPPORT_GRAPHICS /** * Set mission icon of this ability. * diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h index a487b355..834f4134 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h @@ -466,9 +466,9 @@ public: virtual int StopUser(int userId, const sptr &callback) = 0; +#ifdef SUPPORT_GRAPHICS virtual int SetMissionLabel(const sptr &abilityToken, const std::string &label) = 0; -#ifdef SUPPORT_GRAPHICS virtual int SetMissionIcon(const sptr &token, const std::shared_ptr &icon) = 0; diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp b/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp index 0b98a816..edeb9a3e 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp @@ -181,8 +181,265 @@ napi_value SetShowOnLockScreenPromise(napi_env env, ShowOnLockScreenCB *cbData) HILOG_INFO("%{public}s, promise end.", __func__); return promise; } -#endif +napi_value NAPI_SetDisplayOrientationWrap(napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) +{ + HILOG_DEBUG("%{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 (!UnwrapSetDisplayOrientation(env, argc, args, asyncCallbackInfo)) { + HILOG_INFO("%{public}s called. Invoke UnwrapSetDisplayOrientation fail", __func__); + return nullptr; + } + + AsyncParamEx asyncParamEx; + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + HILOG_INFO("%{public}s called. asyncCallback.", __func__); + asyncParamEx.resource = "NAPI_SetDisplayOrientationCallback"; + asyncParamEx.execute = SetDisplayOrientationExecuteCallbackWork; + asyncParamEx.complete = CompleteAsyncCallbackWork; + + return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } else { + HILOG_INFO("%{public}s called. promise.", __func__); + asyncParamEx.resource = "NAPI_SetDisplayOrientationPromise"; + asyncParamEx.execute = SetDisplayOrientationExecuteCallbackWork; + asyncParamEx.complete = CompletePromiseCallbackWork; + + return ExecutePromiseCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } +} + +void SetDisplayOrientationExecuteCallbackWork(napi_env env, void *data) +{ + HILOG_DEBUG("%{public}s called.", __func__); + AsyncJSCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called. asyncCallbackInfo is null", __func__); + return; + } + + asyncCallbackInfo->error_code = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->native_data.data_type = NVT_NONE; + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->error_code = NAPI_ERR_ACE_ABILITY; + return; + } + + int orientation = asyncCallbackInfo->param.paramArgs.GetIntValue("orientation"); + asyncCallbackInfo->ability->SetDisplayOrientation(orientation); + asyncCallbackInfo->native_data.data_type = NVT_INT32; + asyncCallbackInfo->native_data.int32_value = 1; +} + +bool UnwrapSetDisplayOrientation(napi_env env, size_t argc, napi_value *argv, AsyncJSCallbackInfo *asyncCallbackInfo) +{ + HILOG_DEBUG("%{public}s called, argc=%{public}zu", __func__, argc); + + const size_t argcMax = 2; + if (argc > argcMax || argc < argcMax - 1) { + HILOG_ERROR("%{public}s called, Params is invalid.", __func__); + return false; + } + + if (argc == argcMax) { + if (!CreateAsyncCallback(env, argv[PARAM1], asyncCallbackInfo)) { + HILOG_DEBUG("%{public}s called, the second parameter is invalid.", __func__); + return false; + } + } + + int orientation = 0; + if (!UnwrapInt32FromJS2(env, argv[PARAM0], orientation)) { + HILOG_ERROR("%{public}s called, the parameter is invalid.", __func__); + return false; + } + + int maxRange = 3; + if (orientation < 0 || orientation > maxRange) { + HILOG_ERROR("%{public}s called, wrong parameter range.", __func__); + return false; + } + + asyncCallbackInfo->param.paramArgs.PutIntValue("orientation", orientation); + return true; +} + +static void SetWakeUpScreenAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("%{public}s,called", __func__); + SetWakeUpScreenCB *setWakeUpScreenCB = static_cast(data); + if (setWakeUpScreenCB == nullptr) { + HILOG_ERROR("%{public}s, input param is nullptr", __func__); + return; + } + + do { + setWakeUpScreenCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + if (setWakeUpScreenCB->cbBase.ability == nullptr) { + HILOG_ERROR("%{public}s, input param is nullptr", __func__); + setWakeUpScreenCB->cbBase.errCode = NAPI_ERR_ACE_ABILITY; + break; + } + + setWakeUpScreenCB->cbBase.ability->SetWakeUpScreen(setWakeUpScreenCB->wakeUp); + } while (false); + + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value callResult = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_get_undefined(env, &undefined); + result[PARAM0] = GetCallbackErrorValue(env, setWakeUpScreenCB->cbBase.errCode); + napi_get_null(env, &result[PARAM1]); + napi_get_reference_value(env, setWakeUpScreenCB->cbBase.cbInfo.callback, &callback); + napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); + + if (setWakeUpScreenCB->cbBase.cbInfo.callback != nullptr) { + napi_delete_reference(env, setWakeUpScreenCB->cbBase.cbInfo.callback); + } + napi_delete_async_work(env, setWakeUpScreenCB->cbBase.asyncWork); + delete setWakeUpScreenCB; + setWakeUpScreenCB = nullptr; + + HILOG_INFO("%{public}s,called end", __func__); +} + +static napi_value SetWakeUpScreenAsync(napi_env env, napi_value *args, SetWakeUpScreenCB *cbData) +{ + HILOG_INFO("%{public}s,called", __func__); + if (cbData == nullptr || args == nullptr) { + HILOG_ERROR("%{public}s, input param is nullptr", __func__); + return nullptr; + } + + napi_valuetype valuetypeParam0 = napi_undefined; + napi_valuetype valuetypeParam1 = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetypeParam0)); + NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetypeParam1)); + if (valuetypeParam0 != napi_boolean || valuetypeParam1 != napi_function) { + HILOG_ERROR("%{public}s, Params is error type", __func__); + return nullptr; + } + NAPI_CALL(env, napi_create_reference(env, args[PARAM1], 1, &cbData->cbBase.cbInfo.callback)); + + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + NAPI_CALL(env, + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { HILOG_INFO("NAPI_SetWakeUpScreenScreen, worker pool thread execute."); }, + SetWakeUpScreenAsyncCompleteCB, + (void *)cbData, + &cbData->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, cbData->cbBase.asyncWork)); + napi_value result = nullptr; + NAPI_CALL(env, napi_get_null(env, &result)); + + HILOG_INFO("%{public}s,called end", __func__); + return result; +} + +napi_value SetWakeUpScreenPromise(napi_env env, SetWakeUpScreenCB *cbData) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (cbData == 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); + cbData->cbBase.deferred = deferred; + + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { HILOG_INFO("NAPI_SetWakeUpScreenScreen, worker pool thread execute."); }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("SetWakeUpScreenPromise, main event thread complete."); + SetWakeUpScreenCB *setWakeUpScreenCB = static_cast(data); + setWakeUpScreenCB->cbBase.errCode = NO_ERROR; + if (setWakeUpScreenCB->cbBase.ability == nullptr) { + HILOG_ERROR("%{public}s, input param is nullptr", __func__); + setWakeUpScreenCB->cbBase.errCode = NAPI_ERR_ACE_ABILITY; + } + + setWakeUpScreenCB->cbBase.ability->SetWakeUpScreen(setWakeUpScreenCB->wakeUp); + napi_value result = GetCallbackErrorValue(env, setWakeUpScreenCB->cbBase.errCode); + if (setWakeUpScreenCB->cbBase.errCode == NO_ERROR) { + napi_resolve_deferred(env, setWakeUpScreenCB->cbBase.deferred, result); + } else { + napi_reject_deferred(env, setWakeUpScreenCB->cbBase.deferred, result); + } + + napi_delete_async_work(env, setWakeUpScreenCB->cbBase.asyncWork); + delete setWakeUpScreenCB; + setWakeUpScreenCB = nullptr; + HILOG_INFO("SetWakeUpScreenPromise, main event thread complete end."); + }, + (void *)cbData, + &cbData->cbBase.asyncWork); + napi_queue_async_work(env, cbData->cbBase.asyncWork); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +static napi_value SetWakeUpScreenWrap(napi_env env, napi_callback_info info, SetWakeUpScreenCB *cbData) +{ + HILOG_INFO("%{public}s,called", __func__); + if (cbData == nullptr) { + HILOG_ERROR("%{public}s, input param cbData is nullptr", __func__); + return nullptr; + } + + size_t argcAsync = 2; + const size_t argStdValue = 2; + const size_t argPromise = 1; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); + if (argcAsync != argStdValue && argcAsync != argPromise) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + if (!UnwrapBoolFromJS2(env, args[PARAM0], cbData->wakeUp)) { + HILOG_ERROR("%{public}s, UnwrapBoolFromJS2(wakeUp) run error", __func__); + return nullptr; + } + + 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)); + + cbData->cbBase.ability = ability; + napi_value ret = nullptr; + if (argcAsync == argStdValue) { + ret = SetWakeUpScreenAsync(env, args, cbData); + } else { + ret = SetWakeUpScreenPromise(env, cbData); + } + HILOG_INFO("%{public}s,called end", __func__); + return ret; +} +#endif napi_value NAPI_SetShowOnLockScreen(napi_env env, napi_callback_info info) { @@ -2470,96 +2727,6 @@ napi_value NAPI_SetDisplayOrientation(napi_env env, napi_callback_info info) #endif } -#ifdef SUPPORT_GRAPHICS -napi_value NAPI_SetDisplayOrientationWrap(napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) -{ - HILOG_DEBUG("%{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 (!UnwrapSetDisplayOrientation(env, argc, args, asyncCallbackInfo)) { - HILOG_INFO("%{public}s called. Invoke UnwrapSetDisplayOrientation fail", __func__); - return nullptr; - } - - AsyncParamEx asyncParamEx; - if (asyncCallbackInfo->cbInfo.callback != nullptr) { - HILOG_INFO("%{public}s called. asyncCallback.", __func__); - asyncParamEx.resource = "NAPI_SetDisplayOrientationCallback"; - asyncParamEx.execute = SetDisplayOrientationExecuteCallbackWork; - asyncParamEx.complete = CompleteAsyncCallbackWork; - - return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); - } else { - HILOG_INFO("%{public}s called. promise.", __func__); - asyncParamEx.resource = "NAPI_SetDisplayOrientationPromise"; - asyncParamEx.execute = SetDisplayOrientationExecuteCallbackWork; - asyncParamEx.complete = CompletePromiseCallbackWork; - - return ExecutePromiseCallbackWork(env, asyncCallbackInfo, &asyncParamEx); - } -} - -void SetDisplayOrientationExecuteCallbackWork(napi_env env, void *data) -{ - HILOG_DEBUG("%{public}s called.", __func__); - AsyncJSCallbackInfo *asyncCallbackInfo = static_cast(data); - if (asyncCallbackInfo == nullptr) { - HILOG_INFO("%{public}s called. asyncCallbackInfo is null", __func__); - return; - } - - asyncCallbackInfo->error_code = NAPI_ERR_NO_ERROR; - asyncCallbackInfo->native_data.data_type = NVT_NONE; - if (asyncCallbackInfo->ability == nullptr) { - asyncCallbackInfo->error_code = NAPI_ERR_ACE_ABILITY; - return; - } - - int orientation = asyncCallbackInfo->param.paramArgs.GetIntValue("orientation"); - asyncCallbackInfo->ability->SetDisplayOrientation(orientation); - asyncCallbackInfo->native_data.data_type = NVT_INT32; - asyncCallbackInfo->native_data.int32_value = 1; -} - -bool UnwrapSetDisplayOrientation(napi_env env, size_t argc, napi_value *argv, AsyncJSCallbackInfo *asyncCallbackInfo) -{ - HILOG_DEBUG("%{public}s called, argc=%{public}zu", __func__, argc); - - const size_t argcMax = 2; - if (argc > argcMax || argc < argcMax - 1) { - HILOG_ERROR("%{public}s called, Params is invalid.", __func__); - return false; - } - - if (argc == argcMax) { - if (!CreateAsyncCallback(env, argv[PARAM1], asyncCallbackInfo)) { - HILOG_DEBUG("%{public}s called, the second parameter is invalid.", __func__); - return false; - } - } - - int orientation = 0; - if (!UnwrapInt32FromJS2(env, argv[PARAM0], orientation)) { - HILOG_ERROR("%{public}s called, the parameter is invalid.", __func__); - return false; - } - - int maxRange = 3; - if (orientation < 0 || orientation > maxRange) { - HILOG_ERROR("%{public}s called, wrong parameter range.", __func__); - return false; - } - - asyncCallbackInfo->param.paramArgs.PutIntValue("orientation", orientation); - return true; -} -#endif - napi_value NAPI_GetDisplayOrientation(napi_env env, napi_callback_info info) { #ifdef SUPPORT_GRAPHICS @@ -2616,178 +2783,6 @@ napi_value ContextPermissionInit(napi_env env, napi_value exports) return exports; } -#ifdef SUPPORT_GRAPHICS -static void SetWakeUpScreenAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("%{public}s,called", __func__); - SetWakeUpScreenCB *setWakeUpScreenCB = static_cast(data); - if (setWakeUpScreenCB == nullptr) { - HILOG_ERROR("%{public}s, input param is nullptr", __func__); - return; - } - - do { - setWakeUpScreenCB->cbBase.errCode = NAPI_ERR_NO_ERROR; - if (setWakeUpScreenCB->cbBase.ability == nullptr) { - HILOG_ERROR("%{public}s, input param is nullptr", __func__); - setWakeUpScreenCB->cbBase.errCode = NAPI_ERR_ACE_ABILITY; - break; - } - - setWakeUpScreenCB->cbBase.ability->SetWakeUpScreen(setWakeUpScreenCB->wakeUp); - } while (false); - - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value callResult = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_get_undefined(env, &undefined); - result[PARAM0] = GetCallbackErrorValue(env, setWakeUpScreenCB->cbBase.errCode); - napi_get_null(env, &result[PARAM1]); - napi_get_reference_value(env, setWakeUpScreenCB->cbBase.cbInfo.callback, &callback); - napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); - - if (setWakeUpScreenCB->cbBase.cbInfo.callback != nullptr) { - napi_delete_reference(env, setWakeUpScreenCB->cbBase.cbInfo.callback); - } - napi_delete_async_work(env, setWakeUpScreenCB->cbBase.asyncWork); - delete setWakeUpScreenCB; - setWakeUpScreenCB = nullptr; - - HILOG_INFO("%{public}s,called end", __func__); -} - -static napi_value SetWakeUpScreenAsync(napi_env env, napi_value *args, SetWakeUpScreenCB *cbData) -{ - HILOG_INFO("%{public}s,called", __func__); - if (cbData == nullptr || args == nullptr) { - HILOG_ERROR("%{public}s, input param is nullptr", __func__); - return nullptr; - } - - napi_valuetype valuetypeParam0 = napi_undefined; - napi_valuetype valuetypeParam1 = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetypeParam0)); - NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetypeParam1)); - if (valuetypeParam0 != napi_boolean || valuetypeParam1 != napi_function) { - HILOG_ERROR("%{public}s, Params is error type", __func__); - return nullptr; - } - NAPI_CALL(env, napi_create_reference(env, args[PARAM1], 1, &cbData->cbBase.cbInfo.callback)); - - napi_value resourceName = nullptr; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - NAPI_CALL(env, - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { HILOG_INFO("NAPI_SetWakeUpScreenScreen, worker pool thread execute."); }, - SetWakeUpScreenAsyncCompleteCB, - (void *)cbData, - &cbData->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, cbData->cbBase.asyncWork)); - napi_value result = nullptr; - NAPI_CALL(env, napi_get_null(env, &result)); - - HILOG_INFO("%{public}s,called end", __func__); - return result; -} - -napi_value SetWakeUpScreenPromise(napi_env env, SetWakeUpScreenCB *cbData) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (cbData == 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); - cbData->cbBase.deferred = deferred; - - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { HILOG_INFO("NAPI_SetWakeUpScreenScreen, worker pool thread execute."); }, - [](napi_env env, napi_status status, void *data) { - HILOG_INFO("SetWakeUpScreenPromise, main event thread complete."); - SetWakeUpScreenCB *setWakeUpScreenCB = static_cast(data); - setWakeUpScreenCB->cbBase.errCode = NO_ERROR; - if (setWakeUpScreenCB->cbBase.ability == nullptr) { - HILOG_ERROR("%{public}s, input param is nullptr", __func__); - setWakeUpScreenCB->cbBase.errCode = NAPI_ERR_ACE_ABILITY; - } - - setWakeUpScreenCB->cbBase.ability->SetWakeUpScreen(setWakeUpScreenCB->wakeUp); - napi_value result = GetCallbackErrorValue(env, setWakeUpScreenCB->cbBase.errCode); - if (setWakeUpScreenCB->cbBase.errCode == NO_ERROR) { - napi_resolve_deferred(env, setWakeUpScreenCB->cbBase.deferred, result); - } else { - napi_reject_deferred(env, setWakeUpScreenCB->cbBase.deferred, result); - } - - napi_delete_async_work(env, setWakeUpScreenCB->cbBase.asyncWork); - delete setWakeUpScreenCB; - setWakeUpScreenCB = nullptr; - HILOG_INFO("SetWakeUpScreenPromise, main event thread complete end."); - }, - (void *)cbData, - &cbData->cbBase.asyncWork); - napi_queue_async_work(env, cbData->cbBase.asyncWork); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -static napi_value SetWakeUpScreenWrap(napi_env env, napi_callback_info info, SetWakeUpScreenCB *cbData) -{ - HILOG_INFO("%{public}s,called", __func__); - if (cbData == nullptr) { - HILOG_ERROR("%{public}s, input param cbData is nullptr", __func__); - return nullptr; - } - - size_t argcAsync = 2; - const size_t argStdValue = 2; - const size_t argPromise = 1; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, nullptr, nullptr)); - if (argcAsync != argStdValue && argcAsync != argPromise) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - if (!UnwrapBoolFromJS2(env, args[PARAM0], cbData->wakeUp)) { - HILOG_ERROR("%{public}s, UnwrapBoolFromJS2(wakeUp) run error", __func__); - return nullptr; - } - - 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)); - - cbData->cbBase.ability = ability; - napi_value ret = nullptr; - if (argcAsync == argStdValue) { - ret = SetWakeUpScreenAsync(env, args, cbData); - } else { - ret = SetWakeUpScreenPromise(env, cbData); - } - HILOG_INFO("%{public}s,called end", __func__); - return ret; -} -#endif - napi_value NAPI_SetWakeUpScreen(napi_env env, napi_callback_info info) { #ifdef SUPPORT_GRAPHICS diff --git a/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.cpp b/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.cpp index 94109a1d..ba95ddae 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.cpp +++ b/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.cpp @@ -44,33 +44,6 @@ void JsMissionListener::OnMissionMovedToFront(int32_t missionId) CallJsMethod("onMissionMovedToFront", missionId); } -#ifdef SUPPORT_GRAPHICS -void JsMissionListener::OnMissionIconUpdated(int32_t missionId, const std::shared_ptr &icon) -{ - HILOG_INFO("OnMissionIconUpdated, missionId = %{public}d", missionId); - if (engine_ == nullptr) { - HILOG_ERROR("engine_ is nullptr"); - return; - } - - if (missionId <= 0 || !icon) { - HILOG_ERROR("missionId or icon is invalid, missionId:%{public}d", missionId); - return; - } - - // js callback must run in js thread - std::unique_ptr complete = std::make_unique - ([jsMissionListener = this, missionId, icon](NativeEngine &engine, AsyncTask &task, int32_t status) { - if (jsMissionListener) { - jsMissionListener->CallJsMissionIconUpdated(missionId, icon); - } - }); - NativeReference* callback = nullptr; - std::unique_ptr execute = nullptr; - AsyncTask::Schedule(*engine_, std::make_unique(callback, std::move(execute), std::move(complete))); -} -#endif - void JsMissionListener::AddJsListenerObject(int32_t listenerId, NativeValue* jsListenerObject) { jsListenerObjectMap_.emplace( @@ -134,6 +107,31 @@ void JsMissionListener::CallJsMethodInner(const std::string &methodName, int32_t } #ifdef SUPPORT_GRAPHICS +void JsMissionListener::OnMissionIconUpdated(int32_t missionId, const std::shared_ptr &icon) +{ + HILOG_INFO("OnMissionIconUpdated, missionId = %{public}d", missionId); + if (engine_ == nullptr) { + HILOG_ERROR("engine_ is nullptr"); + return; + } + + if (missionId <= 0 || !icon) { + HILOG_ERROR("missionId or icon is invalid, missionId:%{public}d", missionId); + return; + } + + // js callback must run in js thread + std::unique_ptr complete = std::make_unique + ([jsMissionListener = this, missionId, icon](NativeEngine &engine, AsyncTask &task, int32_t status) { + if (jsMissionListener) { + jsMissionListener->CallJsMissionIconUpdated(missionId, icon); + } + }); + NativeReference* callback = nullptr; + std::unique_ptr execute = nullptr; + AsyncTask::Schedule(*engine_, std::make_unique(callback, std::move(execute), std::move(complete))); +} + void JsMissionListener::CallJsMissionIconUpdated(int32_t missionId, const std::shared_ptr &icon) { if (engine_ == nullptr) { diff --git a/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.h b/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.h index 2294a36a..e0546cc1 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.h +++ b/interfaces/kits/napi/aafwk/mission_manager/js_mission_listener.h @@ -35,22 +35,22 @@ public: void OnMissionSnapshotChanged(int32_t missionId) override; void OnMissionMovedToFront(int32_t missionId) override; -#ifdef SUPPORT_GRAPHICS - void OnMissionIconUpdated(int32_t missionId, const std::shared_ptr &icon) override; -#endif - void AddJsListenerObject(int32_t listenerId, NativeValue* jsListenerObject); bool RemoveJsListenerObject(int32_t listenerId); bool IsEmpty(); +#ifdef SUPPORT_GRAPHICS +public: + void OnMissionIconUpdated(int32_t missionId, const std::shared_ptr &icon) override; + +private: + void CallJsMissionIconUpdated(int32_t missionId, const std::shared_ptr &icon); +#endif + private: void CallJsMethod(const std::string &methodName, int32_t missionId); void CallJsMethodInner(const std::string &methodName, int32_t missionId); -#ifdef SUPPORT_GRAPHICS - void CallJsMissionIconUpdated(int32_t missionId, const std::shared_ptr &icon); -#endif - NativeEngine* engine_ = nullptr; std::map> jsListenerObjectMap_; std::shared_ptr mainHandler_; diff --git a/services/abilitymgr/include/ability_manager_proxy.h b/services/abilitymgr/include/ability_manager_proxy.h index 0a856ae0..6dd4e12b 100644 --- a/services/abilitymgr/include/ability_manager_proxy.h +++ b/services/abilitymgr/include/ability_manager_proxy.h @@ -431,9 +431,9 @@ public: virtual int StopUser(int userId, const sptr &callback) override; +#ifdef SUPPORT_GRAPHICS virtual int SetMissionLabel(const sptr &abilityToken, const std::string &label) override; -#ifdef SUPPORT_GRAPHICS virtual int SetMissionIcon(const sptr &token, const std::shared_ptr &icon) override; diff --git a/services/abilitymgr/include/ability_manager_service.h b/services/abilitymgr/include/ability_manager_service.h index aa4a6bf9..6d6755f8 100644 --- a/services/abilitymgr/include/ability_manager_service.h +++ b/services/abilitymgr/include/ability_manager_service.h @@ -595,8 +595,6 @@ public: virtual int StopUser(int userId, const sptr &callback) override; - virtual int SetMissionLabel(const sptr &abilityToken, const std::string &label) override; - /** * Called when client complete dump. * @@ -607,6 +605,8 @@ public: virtual int DumpAbilityInfoDone(std::vector &infos, const sptr &callerToken) override; #ifdef SUPPORT_GRAPHICS + virtual int SetMissionLabel(const sptr &abilityToken, const std::string &label) override; + virtual int SetMissionIcon(const sptr &token, const std::shared_ptr &icon) override; @@ -949,9 +949,6 @@ private: int32_t InitAbilityInfoFromExtension(AppExecFwk::ExtensionAbilityInfo &extensionInfo, AppExecFwk::AbilityInfo &abilityInfo); -#ifdef SUPPORT_GRAPHICS - int32_t ShowPickerDialog(const Want& want, int32_t userId); -#endif // multi user void StartFreezingScreen(); @@ -1041,9 +1038,7 @@ private: std::unordered_map> missionListManagers_; std::shared_ptr currentMissionListManager_; -#ifdef SUPPORT_GRAPHICS - sptr wmsHandler_; -#endif + std::shared_ptr userController_; sptr abilityController_ = nullptr; bool controllerIsAStabilityTest_ = false; @@ -1053,6 +1048,12 @@ private: std::multimap timeoutMap_; static sptr instance_; + +#ifdef SUPPORT_GRAPHICS + int32_t ShowPickerDialog(const Want& want, int32_t userId); + + sptr wmsHandler_; +#endif }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/ability_manager_stub.h b/services/abilitymgr/include/ability_manager_stub.h index 8937ed3c..db59956e 100644 --- a/services/abilitymgr/include/ability_manager_stub.h +++ b/services/abilitymgr/include/ability_manager_stub.h @@ -129,8 +129,6 @@ private: int ReleaseInner(MessageParcel &data, MessageParcel &reply); int StartUserInner(MessageParcel &data, MessageParcel &reply); int StopUserInner(MessageParcel &data, MessageParcel &reply); - int SetMissionLabelInner(MessageParcel &data, MessageParcel &reply); - int SetMissionIconInner(MessageParcel &data, MessageParcel &reply); int GetAbilityRunningInfosInner(MessageParcel &data, MessageParcel &reply); int GetExtensionRunningInfosInner(MessageParcel &data, MessageParcel &reply); int GetProcessRunningInfosInner(MessageParcel &data, MessageParcel &reply); @@ -155,6 +153,8 @@ private: int MoveMissionToFrontByOptionsInner(MessageParcel &data, MessageParcel &reply); #ifdef SUPPORT_GRAPHICS + int SetMissionLabelInner(MessageParcel &data, MessageParcel &reply); + int SetMissionIconInner(MessageParcel &data, MessageParcel &reply); int RegisterWindowManagerServiceHandlerInner(MessageParcel &data, MessageParcel &reply); int CompleteFirstFrameDrawingInner(MessageParcel &data, MessageParcel &reply); #endif diff --git a/services/abilitymgr/include/mission_data_storage.h b/services/abilitymgr/include/mission_data_storage.h index de277b1f..af9f5cab 100644 --- a/services/abilitymgr/include/mission_data_storage.h +++ b/services/abilitymgr/include/mission_data_storage.h @@ -71,15 +71,6 @@ public: */ void DeleteMissionSnapshot(int32_t missionId); -#ifdef SUPPORT_GRAPHICS - /** - * @brief Get the Snapshot object - * @param missionId Indicates this mission id. - * @return Returns PixelMap of snapshot. - */ - sptr GetSnapshot(int missionId) const; -#endif - /** * @brief Get the Mission Snapshot object * @param missionId @@ -88,6 +79,21 @@ public: */ bool GetMissionSnapshot(int32_t missionId, MissionSnapshot& missionSnapshot); +#ifdef SUPPORT_GRAPHICS +public: + /** + * @brief Get the Snapshot object + * @param missionId Indicates this mission id. + * @return Returns PixelMap of snapshot. + */ + sptr GetSnapshot(int missionId) const; + + std::unique_ptr GetPixelMap(int missionId) const; + +private: + std::map> cachedPixelMap_; +#endif + private: std::string GetMissionDataDirPath() const; @@ -107,17 +113,9 @@ private: void SaveSnapshotFile(int32_t missionId, const MissionSnapshot& missionSnapshot); -#ifdef SUPPORT_GRAPHICS - std::unique_ptr GetPixelMap(int missionId) const; -#endif - -private: int userId_ = 0; std::shared_ptr handler_; std::mutex cachedPixelMapMutex_; -#ifdef SUPPORT_GRAPHICS - std::map> cachedPixelMap_; -#endif }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/mission_list_manager.h b/services/abilitymgr/include/mission_list_manager.h index 2c041018..fc919e3c 100644 --- a/services/abilitymgr/include/mission_list_manager.h +++ b/services/abilitymgr/include/mission_list_manager.h @@ -256,28 +256,6 @@ public: */ sptr GetAbilityTokenByMissionId(int32_t missionId); - /** - * Set mission label of this ability. - * - * @param abilityToken target ability token. - * @param label target label. - * @return Retun 0 if success. - */ - int SetMissionLabel(const sptr &abilityToken, const std::string &label); - -#ifdef SUPPORT_GRAPHICS - /** - * Set mission icon of this ability. - * - * @param token target ability token. - * @param icon target label. - * @return Retun 0 if success. - */ - int SetMissionIcon(const sptr &token, const std::shared_ptr &icon); - - void CompleteFirstFrameDrawing(const sptr &abilityToken) const; -#endif - /** * @brief dump all abilities * @@ -364,6 +342,62 @@ public: bool IsStarted(); void PauseManager(); void ResumeManager(); + +#ifdef SUPPORT_GRAPHICS +public: + /** + * Set mission label of this ability. + * + * @param abilityToken target ability token. + * @param label target label. + * @return Retun 0 if success. + */ + int SetMissionLabel(const sptr &abilityToken, const std::string &label); + + /** + * Set mission icon of this ability. + * + * @param token target ability token. + * @param icon target label. + * @return Retun 0 if success. + */ + int SetMissionIcon(const sptr &token, const std::shared_ptr &icon); + + void CompleteFirstFrameDrawing(const sptr &abilityToken) const; + +private: + void NotifyAnimationFromRecentTask(const std::shared_ptr &abilityRecord, + const std::shared_ptr &startOptions, const Want &want) const; + void NotifyAnimationFromStartingAbility(const std::shared_ptr &callerAbility, + const AbilityRequest &abilityRequest, const sptr abilityToken) const; + void SetShowWhenLocked(const AppExecFwk::AbilityInfo &abilityInfo, sptr &info) const; + void SetAbilityTransitionInfo(const AppExecFwk::AbilityInfo &abilityInfo, sptr &info) const; + void SetWindowModeAndDisplayId(sptr &info, const Want &want) const; + + sptr GetWMSHandler() const; + + void StartingWindowCold(const std::shared_ptr &abilityRecord, + const std::shared_ptr &startOptions, const Want &want, + const AbilityRequest &abilityRequest) const; + void StartingWindowHot(const std::shared_ptr &abilityRecord, + const std::shared_ptr &startOptions, const Want &want, const AbilityRequest &abilityRequest, + int32_t missionId) const; + std::shared_ptr CreateResourceManager( + const AppExecFwk::AbilityInfo &abilityInfo) const; + sptr GetPixelMap(const uint32_t windowIconId, + std::shared_ptr resourceManager) const; + sptr CreateAbilityTransitionInfo(const sptr abilityToken, + const std::shared_ptr &startOptions, const Want &want) const; + sptr CreateAbilityTransitionInfo(const AbilityRequest &abilityRequest, + const sptr abilityToken) const; + void CancelStartingWindow(const sptr abilityToken, bool isDelay) const; + void NotifyStartingWindow(bool isCold, const std::shared_ptr &targetMission, + const std::shared_ptr &targetAbilityRecord, const AbilityRequest &abilityRequest, + const std::shared_ptr &callerAbility); + void NotifyStartingWindow(bool isCold, const std::shared_ptr &targetAbilityRecord, + std::shared_ptr &startOptions, int32_t missionId); +#endif + private: int StartAbilityLocked(const std::shared_ptr ¤tTopAbility, const std::shared_ptr &callerAbility, const AbilityRequest &abilityRequest); @@ -430,40 +464,6 @@ private: void AddUninstallTags(const std::string &bundleName, int32_t uid); void RemoveMissionLocked(int32_t missionId); -#ifdef SUPPORT_GRAPHICS - void NotifyAnimationFromRecentTask(const std::shared_ptr &abilityRecord, - const std::shared_ptr &startOptions, const Want &want) const; - void NotifyAnimationFromStartingAbility(const std::shared_ptr &callerAbility, - const AbilityRequest &abilityRequest, const sptr abilityToken) const; - void SetShowWhenLocked(const AppExecFwk::AbilityInfo &abilityInfo, sptr &info) const; - void SetAbilityTransitionInfo(const AppExecFwk::AbilityInfo &abilityInfo, sptr &info) const; - void SetWindowModeAndDisplayId(sptr &info, const Want &want) const; - - sptr GetWMSHandler() const; - - void StartingWindowCold(const std::shared_ptr &abilityRecord, - const std::shared_ptr &startOptions, const Want &want, - const AbilityRequest &abilityRequest) const; - void StartingWindowHot(const std::shared_ptr &abilityRecord, - const std::shared_ptr &startOptions, const Want &want, const AbilityRequest &abilityRequest, - int32_t missionId) const; - std::shared_ptr CreateResourceManager( - const AppExecFwk::AbilityInfo &abilityInfo) const; - sptr GetPixelMap(const uint32_t windowIconId, - std::shared_ptr resourceManager) const; - sptr CreateAbilityTransitionInfo(const sptr abilityToken, - const std::shared_ptr &startOptions, const Want &want) const; - sptr CreateAbilityTransitionInfo(const AbilityRequest &abilityRequest, - const sptr abilityToken) const; - void CancelStartingWindow(const sptr abilityToken, bool isDelay) const; - void NotifyStartingWindow(bool isCold, const std::shared_ptr &targetMission, - const std::shared_ptr &targetAbilityRecord, const AbilityRequest &abilityRequest, - const std::shared_ptr &callerAbility); - void NotifyStartingWindow(bool isCold, const std::shared_ptr &targetAbilityRecord, - std::shared_ptr &startOptions, int32_t missionId); -#endif - -private: int userId_; mutable std::recursive_mutex managerLock_; // launcher list is also in currentMissionLists_ @@ -479,14 +479,12 @@ private: std::shared_ptr listenerController_; bool isPC_ = false; -private: -class MissionDmInitCallback : public DistributedHardware::DmInitCallback { -public: - void OnRemoteDied() override; + class MissionDmInitCallback : public DistributedHardware::DmInitCallback { + public: + void OnRemoteDied() override; -public: - static bool isInit_; -}; + static bool isInit_; + }; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/screenshot_handler.h b/services/abilitymgr/include/screenshot_handler.h index c5e21804..3d293cf0 100644 --- a/services/abilitymgr/include/screenshot_handler.h +++ b/services/abilitymgr/include/screenshot_handler.h @@ -34,13 +34,14 @@ public: virtual ~ScreenshotHandler() = default; void StartScreenshot(int32_t missionId, int32_t winId); -#ifdef SUPPORT_GRAPHICS - OHOS::WMImageInfo GetImageInfo(int32_t missionId); -#endif + void RemoveImageInfo(int32_t missionId); -private: #ifdef SUPPORT_GRAPHICS +public: + OHOS::WMImageInfo GetImageInfo(int32_t missionId); + +private: std::map screenShot_; sptr windowMS_; #endif diff --git a/services/abilitymgr/include/screenshot_response.h b/services/abilitymgr/include/screenshot_response.h index f8f321c6..5c92384b 100644 --- a/services/abilitymgr/include/screenshot_response.h +++ b/services/abilitymgr/include/screenshot_response.h @@ -32,18 +32,20 @@ class ScreenShotResponse { public: ScreenShotResponse() = default; virtual ~ScreenShotResponse() = default; + #ifdef SUPPORT_GRAPHICS +public: void OnWindowShot(const OHOS::WMImageInfo &info); OHOS::WMImageInfo GetImageInfo(); + +private: + std::shared_ptr info_; #endif private: static constexpr int TIME_OUT = 200 * 1000; std::mutex mutex_; std::condition_variable condition_; -#ifdef SUPPORT_GRAPHICS - std::shared_ptr info_; -#endif }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_client.cpp b/services/abilitymgr/src/ability_manager_client.cpp index f2a70b6d..33f9169a 100644 --- a/services/abilitymgr/src/ability_manager_client.cpp +++ b/services/abilitymgr/src/ability_manager_client.cpp @@ -759,6 +759,7 @@ ErrCode AbilityManagerClient::DelegatorDoAbilityBackground(const sptrDelegatorDoAbilityBackground(token); } +#ifdef SUPPORT_GRAPHICS ErrCode AbilityManagerClient::SetMissionLabel(const sptr &token, const std::string& label) { auto abms = GetAbilityManager(); @@ -766,7 +767,6 @@ ErrCode AbilityManagerClient::SetMissionLabel(const sptr &token, return abms->SetMissionLabel(token, label); } -#ifdef SUPPORT_GRAPHICS ErrCode AbilityManagerClient::SetMissionIcon( const sptr &abilityToken, const std::shared_ptr &icon) { diff --git a/services/abilitymgr/src/ability_manager_proxy.cpp b/services/abilitymgr/src/ability_manager_proxy.cpp index 1fb00f64..7c781f8d 100644 --- a/services/abilitymgr/src/ability_manager_proxy.cpp +++ b/services/abilitymgr/src/ability_manager_proxy.cpp @@ -1791,6 +1791,7 @@ int AbilityManagerProxy::StopUser(int userId, const sptr &cal return reply.ReadInt32(); } +#ifdef SUPPORT_GRAPHICS int AbilityManagerProxy::SetMissionLabel(const sptr &token, const std::string &label) { MessageParcel data; @@ -1815,7 +1816,6 @@ int AbilityManagerProxy::SetMissionLabel(const sptr &token, const return reply.ReadInt32(); } -#ifdef SUPPORT_GRAPHICS int AbilityManagerProxy::SetMissionIcon(const sptr &token, const std::shared_ptr &icon) { diff --git a/services/abilitymgr/src/ability_manager_service.cpp b/services/abilitymgr/src/ability_manager_service.cpp index 3b5e1b77..4a73e2ec 100644 --- a/services/abilitymgr/src/ability_manager_service.cpp +++ b/services/abilitymgr/src/ability_manager_service.cpp @@ -35,9 +35,6 @@ #include "ability_util.h" #include "hitrace_meter.h" #include "bundle_mgr_client.h" -#ifdef SUPPORT_GRAPHICS -#include "display_manager.h" -#endif #include "distributed_client.h" #include "free_install_manager.h" #include "hilog_wrapper.h" @@ -46,11 +43,6 @@ #include "ipc_skeleton.h" #include "iservice_registry.h" #include "itest_observer.h" -#ifdef SUPPORT_GRAPHICS -#include "png.h" -#include "ui_service_mgr_client.h" -#include "locale_config.h" -#endif #include "mission_info_mgr.h" #include "permission_constants.h" #include "permission_verification.h" @@ -65,6 +57,13 @@ #include "xcollie/watchdog.h" #include "parameter.h" +#ifdef SUPPORT_GRAPHICS +#include "display_manager.h" +#include "png.h" +#include "ui_service_mgr_client.h" +#include "locale_config.h" +#endif + using OHOS::AppExecFwk::ElementName; using OHOS::Security::AccessToken::AccessTokenKit; @@ -3321,73 +3320,6 @@ int AbilityManagerService::CheckCallPermissions(const AbilityRequest &abilityReq return ERR_OK; } -int AbilityManagerService::SetMissionLabel(const sptr &token, const std::string &label) -{ - HILOG_DEBUG("%{public}s", __func__); - auto missionListManager = currentMissionListManager_; - if (missionListManager) { - missionListManager->SetMissionLabel(token, label); - } - return 0; -} - -#ifdef SUPPORT_GRAPHICS -int AbilityManagerService::SetMissionIcon(const sptr &token, - const std::shared_ptr &icon) -{ - HILOG_DEBUG("%{public}s", __func__); - auto abilityRecord = Token::GetAbilityRecordByToken(token); - if (!abilityRecord) { - HILOG_ERROR("no such ability record"); - return -1; - } - - auto callingUid = IPCSkeleton::GetCallingUid(); - auto recordUid = abilityRecord->GetUid(); - if (callingUid != recordUid) { - HILOG_ERROR("not self, callingUid:%{public}d, recordUid:%{public}d", callingUid, recordUid); - return -1; - } - - auto userId = callingUid / BASE_USER_RANGE; - auto missionListManager = GetListManagerByUserId(userId); - if (!missionListManager) { - HILOG_ERROR("failed to find mission list manager."); - return -1; - } - - return missionListManager->SetMissionIcon(token, icon); -} - -int AbilityManagerService::RegisterWindowManagerServiceHandler(const sptr &handler) -{ - auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); - if (!isSaCall) { - HILOG_ERROR("%{public}s: Permission verification failed", __func__); - return CHECK_PERMISSION_FAILED; - } - wmsHandler_ = handler; - HILOG_DEBUG("%{public}s: WMS handler registered successfully.", __func__); - return ERR_OK; -} - -sptr AbilityManagerService::GetWMSHandler() const -{ - return wmsHandler_; -} - -void AbilityManagerService::CompleteFirstFrameDrawing(const sptr &abilityToken) -{ - HILOG_DEBUG("%{public}s is called.", __func__); - std::shared_lock lock(managersMutex_); - for (auto& item : missionListManagers_) { - if (item.second) { - item.second->CompleteFirstFrameDrawing(abilityToken); - } - } -} -#endif - int AbilityManagerService::StartUser(int userId) { HILOG_DEBUG("%{public}s, userId:%{public}d", __func__, userId); @@ -4007,21 +3939,6 @@ int AbilityManagerService::DelegatorMoveMissionToFront(int32_t missionId) return currentMissionListManager_->MoveMissionToFront(missionId); } -#ifdef SUPPORT_GRAPHICS -int32_t AbilityManagerService::ShowPickerDialog(const Want& want, int32_t userId) -{ - auto bms = GetBundleManager(); - CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED); - HILOG_INFO("share content: ShowPickerDialog, userId is %{public}d", userId); - std::vector abilityInfos; - IN_PROCESS_CALL_WITHOUT_RET( - bms->QueryAbilityInfos( - want, AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, userId, abilityInfos) - ); - return Ace::UIServiceMgrClient::GetInstance()->ShowAppPickerDialog(want, abilityInfos, userId); -} -#endif - void AbilityManagerService::UpdateCallerInfo(Want& want) { int32_t tokenId = (int32_t)IPCSkeleton::GetCallingTokenID(); @@ -4545,5 +4462,85 @@ int AbilityManagerService::DumpAbilityInfoDone(std::vector &infos, abilityRecord->DumpAbilityInfoDone(infos); return ERR_OK; } + +#ifdef SUPPORT_GRAPHICS +int AbilityManagerService::SetMissionLabel(const sptr &token, const std::string &label) +{ + HILOG_DEBUG("%{public}s", __func__); + auto missionListManager = currentMissionListManager_; + if (missionListManager) { + missionListManager->SetMissionLabel(token, label); + } + return 0; +} + +int AbilityManagerService::SetMissionIcon(const sptr &token, + const std::shared_ptr &icon) +{ + HILOG_DEBUG("%{public}s", __func__); + auto abilityRecord = Token::GetAbilityRecordByToken(token); + if (!abilityRecord) { + HILOG_ERROR("no such ability record"); + return -1; + } + + auto callingUid = IPCSkeleton::GetCallingUid(); + auto recordUid = abilityRecord->GetUid(); + if (callingUid != recordUid) { + HILOG_ERROR("not self, callingUid:%{public}d, recordUid:%{public}d", callingUid, recordUid); + return -1; + } + + auto userId = callingUid / BASE_USER_RANGE; + auto missionListManager = GetListManagerByUserId(userId); + if (!missionListManager) { + HILOG_ERROR("failed to find mission list manager."); + return -1; + } + + return missionListManager->SetMissionIcon(token, icon); +} + +int AbilityManagerService::RegisterWindowManagerServiceHandler(const sptr &handler) +{ + auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); + if (!isSaCall) { + HILOG_ERROR("%{public}s: Permission verification failed", __func__); + return CHECK_PERMISSION_FAILED; + } + wmsHandler_ = handler; + HILOG_DEBUG("%{public}s: WMS handler registered successfully.", __func__); + return ERR_OK; +} + +sptr AbilityManagerService::GetWMSHandler() const +{ + return wmsHandler_; +} + +void AbilityManagerService::CompleteFirstFrameDrawing(const sptr &abilityToken) +{ + HILOG_DEBUG("%{public}s is called.", __func__); + std::shared_lock lock(managersMutex_); + for (auto& item : missionListManagers_) { + if (item.second) { + item.second->CompleteFirstFrameDrawing(abilityToken); + } + } +} + +int32_t AbilityManagerService::ShowPickerDialog(const Want& want, int32_t userId) +{ + auto bms = GetBundleManager(); + CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED); + HILOG_INFO("share content: ShowPickerDialog, userId is %{public}d", userId); + std::vector abilityInfos; + IN_PROCESS_CALL_WITHOUT_RET( + bms->QueryAbilityInfos( + want, AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, userId, abilityInfos) + ); + return Ace::UIServiceMgrClient::GetInstance()->ShowAppPickerDialog(want, abilityInfos, userId); +} +#endif } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp index 6c2af258..9d9d6581 100644 --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -109,7 +109,6 @@ void AbilityManagerStub::SecondStepInit() requestFuncMap_[MOVE_MISSION_TO_FRONT_BY_OPTIONS] = &AbilityManagerStub::MoveMissionToFrontByOptionsInner; requestFuncMap_[START_CALL_ABILITY] = &AbilityManagerStub::StartAbilityByCallInner; requestFuncMap_[RELEASE_CALL_ABILITY] = &AbilityManagerStub::ReleaseInner; - requestFuncMap_[SET_MISSION_LABEL] = &AbilityManagerStub::SetMissionLabelInner; requestFuncMap_[START_USER] = &AbilityManagerStub::StartUserInner; requestFuncMap_[STOP_USER] = &AbilityManagerStub::StopUserInner; requestFuncMap_[GET_ABILITY_RUNNING_INFO] = &AbilityManagerStub::GetAbilityRunningInfosInner; @@ -137,11 +136,12 @@ void AbilityManagerStub::ThirdStepInit() requestFuncMap_[DO_ABILITY_BACKGROUND] = &AbilityManagerStub::DoAbilityBackgroundInner; requestFuncMap_[GET_MISSION_ID_BY_ABILITY_TOKEN] = &AbilityManagerStub::GetMissionIdByTokenInner; requestFuncMap_[GET_TOP_ABILITY] = &AbilityManagerStub::GetTopAbilityInner; - requestFuncMap_[SET_MISSION_ICON] = &AbilityManagerStub::SetMissionIconInner; requestFuncMap_[DUMP_ABILITY_INFO_DONE] = &AbilityManagerStub::DumpAbilityInfoDoneInner; requestFuncMap_[START_EXTENSION_ABILITY] = &AbilityManagerStub::StartExtensionAbilityInner; requestFuncMap_[STOP_EXTENSION_ABILITY] = &AbilityManagerStub::StopExtensionAbilityInner; #ifdef SUPPORT_GRAPHICS + requestFuncMap_[SET_MISSION_LABEL] = &AbilityManagerStub::SetMissionLabelInner; + requestFuncMap_[SET_MISSION_ICON] = &AbilityManagerStub::SetMissionIconInner; requestFuncMap_[REGISTER_WMS_HANDLER] = &AbilityManagerStub::RegisterWindowManagerServiceHandlerInner; requestFuncMap_[COMPLETEFIRSTFRAMEDRAWING] = &AbilityManagerStub::CompleteFirstFrameDrawingInner; #endif @@ -1065,50 +1065,6 @@ int AbilityManagerStub::StopUserInner(MessageParcel &data, MessageParcel &reply) return NO_ERROR; } -int AbilityManagerStub::SetMissionLabelInner(MessageParcel &data, MessageParcel &reply) -{ - sptr token = data.ReadRemoteObject(); - if (!token) { - HILOG_ERROR("SetMissionLabelInner read ability token failed."); - return ERR_NULL_OBJECT; - } - - std::string label = Str16ToStr8(data.ReadString16()); - int result = SetMissionLabel(token, label); - if (!reply.WriteInt32(result)) { - HILOG_ERROR("SetMissionLabel failed."); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -int AbilityManagerStub::SetMissionIconInner(MessageParcel &data, MessageParcel &reply) -{ -#ifdef SUPPORT_GRAPHICS - sptr token = data.ReadRemoteObject(); - if (!token) { - HILOG_ERROR("SetMissionIconInner read ability token failed."); - return ERR_NULL_OBJECT; - } - - std::shared_ptr icon(data.ReadParcelable()); - if (!icon) { - HILOG_ERROR("SetMissionIconInner read icon failed."); - return ERR_NULL_OBJECT; - } - - int result = SetMissionIcon(token, icon); - if (!reply.WriteInt32(result)) { - HILOG_ERROR("SetMissionIcon failed."); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -#else - HILOG_ERROR("do not support SetMissionIcon."); - return ERR_INVALID_VALUE; -#endif -} - int AbilityManagerStub::GetAbilityRunningInfosInner(MessageParcel &data, MessageParcel &reply) { std::vector abilityRunningInfos; @@ -1227,30 +1183,6 @@ int AbilityManagerStub::RegisterSnapshotHandlerInner(MessageParcel &data, Messag return result; } -#ifdef SUPPORT_GRAPHICS -int AbilityManagerStub::RegisterWindowManagerServiceHandlerInner(MessageParcel &data, MessageParcel &reply) -{ - sptr handler = iface_cast(data.ReadRemoteObject()); - if (handler == nullptr) { - HILOG_ERROR("%{public}s read WMS handler failed!", __func__); - return ERR_NULL_OBJECT; - } - return RegisterWindowManagerServiceHandler(handler); -} - -int AbilityManagerStub::CompleteFirstFrameDrawingInner(MessageParcel &data, MessageParcel &reply) -{ - HILOG_DEBUG("%{public}s is called.", __func__); - sptr abilityToken = data.ReadRemoteObject(); - if (abilityToken == nullptr) { - HILOG_ERROR("%{public}s read abilityToken failed!", __func__); - return ERR_NULL_OBJECT; - } - CompleteFirstFrameDrawing(abilityToken); - return 0; -} -#endif - int AbilityManagerStub::GetMissionSnapshotInfoInner(MessageParcel &data, MessageParcel &reply) { std::string deviceId = data.ReadString(); @@ -1473,5 +1405,68 @@ int AbilityManagerStub::DumpAbilityInfoDoneInner(MessageParcel &data, MessagePar } return NO_ERROR; } + +#ifdef SUPPORT_GRAPHICS +int AbilityManagerStub::SetMissionLabelInner(MessageParcel &data, MessageParcel &reply) +{ + sptr token = data.ReadRemoteObject(); + if (!token) { + HILOG_ERROR("SetMissionLabelInner read ability token failed."); + return ERR_NULL_OBJECT; + } + + std::string label = Str16ToStr8(data.ReadString16()); + int result = SetMissionLabel(token, label); + if (!reply.WriteInt32(result)) { + HILOG_ERROR("SetMissionLabel failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +int AbilityManagerStub::SetMissionIconInner(MessageParcel &data, MessageParcel &reply) +{ + sptr token = data.ReadRemoteObject(); + if (!token) { + HILOG_ERROR("SetMissionIconInner read ability token failed."); + return ERR_NULL_OBJECT; + } + + std::shared_ptr icon(data.ReadParcelable()); + if (!icon) { + HILOG_ERROR("SetMissionIconInner read icon failed."); + return ERR_NULL_OBJECT; + } + + int result = SetMissionIcon(token, icon); + if (!reply.WriteInt32(result)) { + HILOG_ERROR("SetMissionIcon failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +int AbilityManagerStub::RegisterWindowManagerServiceHandlerInner(MessageParcel &data, MessageParcel &reply) +{ + sptr handler = iface_cast(data.ReadRemoteObject()); + if (handler == nullptr) { + HILOG_ERROR("%{public}s read WMS handler failed!", __func__); + return ERR_NULL_OBJECT; + } + return RegisterWindowManagerServiceHandler(handler); +} + +int AbilityManagerStub::CompleteFirstFrameDrawingInner(MessageParcel &data, MessageParcel &reply) +{ + HILOG_DEBUG("%{public}s is called.", __func__); + sptr abilityToken = data.ReadRemoteObject(); + if (abilityToken == nullptr) { + HILOG_ERROR("%{public}s read abilityToken failed!", __func__); + return ERR_NULL_OBJECT; + } + CompleteFirstFrameDrawing(abilityToken); + return 0; +} +#endif } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/mission_list_manager.cpp b/services/abilitymgr/src/mission_list_manager.cpp index 916570dc..6b3d8fd2 100644 --- a/services/abilitymgr/src/mission_list_manager.cpp +++ b/services/abilitymgr/src/mission_list_manager.cpp @@ -1910,6 +1910,7 @@ void MissionListManager::BackToLauncher() launcherRootAbility->ProcessForegroundAbility(); } +#ifdef SUPPORT_GRAPHICS int MissionListManager::SetMissionLabel(const sptr &token, const std::string &label) { if (!token) { @@ -1926,7 +1927,6 @@ int MissionListManager::SetMissionLabel(const sptr &token, const return DelayedSingleton::GetInstance()->UpdateMissionLabel(missionId, label); } -#ifdef SUPPORT_GRAPHICS int MissionListManager::SetMissionIcon(const sptr &token, const std::shared_ptr &icon) { if (!token) { diff --git a/services/abilitymgr/test/mock/appmgr_test_service/BUILD.gn b/services/abilitymgr/test/mock/appmgr_test_service/BUILD.gn index c08be85f..77cd0e22 100644 --- a/services/abilitymgr/test/mock/appmgr_test_service/BUILD.gn +++ b/services/abilitymgr/test/mock/appmgr_test_service/BUILD.gn @@ -53,7 +53,6 @@ ohos_source_set("appmgr_test_service") { if (ability_runtime_graphics) { public_deps = [ "${graphic_path}:libwmservice" ] - defines = [ "SUPPORT_GRAPHICS" ] } external_deps = [ diff --git a/services/abilitymgr/test/mock/libs/aakit/BUILD.gn b/services/abilitymgr/test/mock/libs/aakit/BUILD.gn index b9b560c1..d6c0cde2 100644 --- a/services/abilitymgr/test/mock/libs/aakit/BUILD.gn +++ b/services/abilitymgr/test/mock/libs/aakit/BUILD.gn @@ -57,8 +57,4 @@ ohos_source_set("aakit_mock") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] - - if (ability_runtime_graphics) { - defines = [ "SUPPORT_GRAPHICS" ] - } } diff --git a/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn index f04b5d84..b4740a19 100644 --- a/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn @@ -60,10 +60,6 @@ ohos_unittest("ability_record_test") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] - - if (ability_runtime_graphics) { - defines = [ "SUPPORT_GRAPHICS" ] - } } ohos_unittest("ability_record_test_call") { diff --git a/services/test/moduletest/ability_record_test/BUILD.gn b/services/test/moduletest/ability_record_test/BUILD.gn index c98ec68b..936d4381 100644 --- a/services/test/moduletest/ability_record_test/BUILD.gn +++ b/services/test/moduletest/ability_record_test/BUILD.gn @@ -103,7 +103,6 @@ ohos_moduletest("AbilityRecordModuleTest") { "//foundation/arkui/ace_engine/interfaces/inner_api/ui_service_manager:ui_service_mgr", "//third_party/libpng:libpng", ] - defines = [ "SUPPORT_GRAPHICS" ] } external_deps = [ diff --git a/services/test/moduletest/ipc_ability_mgr_test/BUILD.gn b/services/test/moduletest/ipc_ability_mgr_test/BUILD.gn index 7c8a2c3d..ee0542e5 100644 --- a/services/test/moduletest/ipc_ability_mgr_test/BUILD.gn +++ b/services/test/moduletest/ipc_ability_mgr_test/BUILD.gn @@ -42,7 +42,6 @@ ohos_moduletest("IpcAbilityMgrServiceModuleTest") { if (ability_runtime_graphics) { deps += [ "//third_party/libpng:libpng" ] - defines = [ "SUPPORT_GRAPHICS" ] } external_deps = [ diff --git a/test/benchmarktest/mission_manager_test/BUILD.gn b/test/benchmarktest/mission_manager_test/BUILD.gn index d2af792a..909c9473 100644 --- a/test/benchmarktest/mission_manager_test/BUILD.gn +++ b/test/benchmarktest/mission_manager_test/BUILD.gn @@ -44,8 +44,10 @@ group("benchmarktest") { testonly = true deps = [] - deps += [ - # deps file - ":BenchmarkTestForMissionManager", - ] + if (ability_runtime_graphics) { + deps += [ + # deps file + ":BenchmarkTestForMissionManager", + ] + } } diff --git a/test/benchmarktest/mission_manager_test/mission_manager_test.cpp b/test/benchmarktest/mission_manager_test/mission_manager_test.cpp index b86c5bc5..1aa8ce8d 100644 --- a/test/benchmarktest/mission_manager_test/mission_manager_test.cpp +++ b/test/benchmarktest/mission_manager_test/mission_manager_test.cpp @@ -48,13 +48,9 @@ public: { } -#ifdef SUPPORT_GRAPHICS - void OnMissionIconUpdated(int32_t missionId, const std::shared_ptr &icon) override { } - -#endif }; class MissionManagerTest : public benchmark::Fixture {