1 /*
2  * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef OHOS_ABILITY_RUNTIME_JS_UI_ABILITY_H
17 #define OHOS_ABILITY_RUNTIME_JS_UI_ABILITY_H
18 
19 #include "ability_delegator_infos.h"
20 #include "freeze_util.h"
21 #include "js_embeddable_ui_ability_context.h"
22 #include "ui_ability.h"
23 
24 class NativeReference;
25 
26 namespace OHOS {
27 namespace AbilityRuntime {
28 class JsRuntime;
29 struct InsightIntentExecutorInfo;
30 using AbilityHandler = AppExecFwk::AbilityHandler;
31 using AbilityInfo = AppExecFwk::AbilityInfo;
32 using OHOSApplication = AppExecFwk::OHOSApplication;
33 using Want = AppExecFwk::Want;
34 using AbilityStartSetting = AppExecFwk::AbilityStartSetting;
35 using Configuration = AppExecFwk::Configuration;
36 using InsightIntentExecuteResult = AppExecFwk::InsightIntentExecuteResult;
37 using InsightIntentExecuteParam = AppExecFwk::InsightIntentExecuteParam;
38 using InsightIntentExecutorAsyncCallback = AppExecFwk::InsightIntentExecutorAsyncCallback;
39 
40 class JsUIAbility : public UIAbility {
41 public:
42     /**
43      * @brief Create a JsUIAbility instance through the singleton pattern
44      * @param runtime The runtime of the ability
45      * @return Returns the JsUIability Instance point
46      */
47     static UIAbility *Create(const std::unique_ptr<Runtime> &runtime);
48 
49     explicit JsUIAbility(JsRuntime &jsRuntime);
50     ~JsUIAbility() override;
51 
52     /**
53      * @brief Init the UIability
54      * @param abilityInfo Indicate the Ability information
55      * @param application Indicates the main process
56      * @param handler the UIability EventHandler object
57      * @param token the remote token
58      */
59     void Init(std::shared_ptr<AppExecFwk::AbilityLocalRecord> record,
60         const std::shared_ptr<OHOSApplication> application,
61         std::shared_ptr<AbilityHandler> &handler, const sptr<IRemoteObject> &token) override;
62 
63     /**
64      * @brief OnStart,Start JsUIability
65      * @param want Indicates the {@link Want} structure containing startup information about the ability
66      * @param sessionInfo Indicates the sessionInfo
67      */
68     void OnStart(const Want &want, sptr<AAFwk::SessionInfo> sessionInfo = nullptr) override;
69 
70     /**
71      * @brief Called when this ability enters the <b>STATE_STOP</b> state.
72      * The ability in the <b>STATE_STOP</b> is being destroyed.
73      * You can override this function to implement your own processing logic.
74      */
75     void OnStop() override;
76 
77     /**
78      * @brief Called when this ability enters the <b>STATE_STOP</b> state.
79      * The ability in the <b>STATE_STOP</b> is being destroyed.
80      * You can override this function to implement your own processing logic.
81      * @param callbackInfo Indicates the lifecycle transaction callback information
82      * @param isAsyncCallback Indicates whether it is an asynchronous lifecycle callback
83      */
84     void OnStop(AppExecFwk::AbilityTransactionCallbackInfo<> *callbackInfo, bool &isAsyncCallback) override;
85 
86     /**
87      * @brief The callback of OnStop.
88      */
89     void OnStopCallback() override;
90 
91     /**
92      * @brief Prepare user data of local Ability.
93      * @param wantParams Indicates the user data to be saved.
94      * @return If the ability is willing to continue and data saved successfully, it returns 0;
95      * otherwise, it returns errcode.
96      */
97     int32_t OnContinue(WantParams &wantParams) override;
98 
99     /**
100      * @brief Update configuration
101      * @param configuration Indicates the updated configuration information.
102      */
103     void OnConfigurationUpdated(const Configuration &configuration) override;
104 
105     /**
106      * @brief Update Contextconfiguration
107      */
108     void UpdateContextConfiguration() override;
109 
110     /**
111      * @brief Called when the system configuration is updated.
112      * @param level Indicates the memory trim level, which shows the current memory usage status.
113      */
114     void OnMemoryLevel(int level) override;
115 
116     /**
117      * @brief Called when the launch mode of an ability is set to singleInstance. This happens when you re-launch an
118      * ability that has been at the top of the ability stack.
119      * @param want Indicates the new Want containing information about the ability.
120      */
121     void OnNewWant(const Want &want) override;
122 
123     /**
124      * @brief Prepare user data of local Ability.
125      * @param reason the reason why framework invoke this function
126      * @param wantParams Indicates the user data to be saved.
127      * @return result code defined in abilityConstants
128      */
129     int32_t OnSaveState(int32_t reason, WantParams &wantParams) override;
130 
131     /**
132      * @brief Called when startAbilityForResult(ohos.aafwk.content.Want,int) is called to start an ability and the
133      * result is returned. This method is called only on Page abilities. You can start a new ability to perform some
134      * calculations and use setResult (int,ohos.aafwk.content.Want) to return the calculation result. Then the system
135      * calls back the current method to use the returned data to execute its own logic.
136      * @param requestCode Indicates the request code returned after the ability is started. You can define the request
137      * code to identify the results returned by abilities. The value ranges from 0 to 65535.
138      * @param resultCode Indicates the result code returned after the ability is started. You can define the result code
139      * to identify an error.
140      * @param want Indicates the data returned after the ability is started. You can define the data returned. The
141      * value can be null.
142      */
143     void OnAbilityResult(int requestCode, int resultCode, const Want &resultData) override;
144 
145     /**
146      * @brief request a remote object of callee from this ability.
147      * @return Returns the remote object of callee.
148      */
149     sptr<IRemoteObject> CallRequest() override;
150 
151     /**
152      * @brief dump ability info
153      * @param params dump params that indicate different dump targets
154      * @param info dump ability info
155      */
156     void Dump(const std::vector<std::string> &params, std::vector<std::string> &info) override;
157 
158     /**
159      * @brief Get JsAbility
160      * @return Return the JsAbility
161      */
162     std::shared_ptr<NativeReference> GetJsAbility();
163 
164     /**
165      * @brief Callback when the ability is shared.You can override this function to implement your own sharing logic.
166      * @param wantParams Indicates the user data to be saved.
167      * @return the result of OnShare
168      */
169     int32_t OnShare(WantParams &wantParams) override;
170 
171 #ifdef SUPPORT_GRAPHICS
172 public:
173     /**
174      * @brief Called after instantiating WindowScene.
175      * You can override this function to implement your own processing logic.
176      */
177     void OnSceneCreated() override;
178 
179     /**
180      * @brief Called after ability stoped.
181      * You can override this function to implement your own processing logic.
182      */
183     void OnSceneWillDestroy() override;
184 
185     /**
186      * @brief Called after ability stoped.
187      * You can override this function to implement your own processing logic.
188      */
189     void onSceneDestroyed() override;
190 
191     /**
192      * @brief Called after ability restored.
193      * You can override this function to implement your own processing logic.
194      */
195     void OnSceneRestored() override;
196 
197     /**
198      * @brief Called when this ability enters the <b>STATE_FOREGROUND</b> state.
199      * The ability in the <b>STATE_FOREGROUND</b> state is visible.
200      * You can override this function to implement your own processing logic.
201      */
202     void OnForeground(const Want &want) override;
203 
204     /**
205      * @brief Call "onForeground" js function barely.
206      *
207      * @param want Want
208      */
209     void CallOnForegroundFunc(const Want &want) override;
210 
211     /**
212      * @brief Request focus for current window, can be override.
213      *
214      * @param want Want
215      */
216     void RequestFocus(const Want &want) override;
217 
218     /**
219      * @brief Called when this ability enters the <b>STATE_BACKGROUND</b> state.
220      * The ability in the <b>STATE_BACKGROUND</b> state is invisible.
221      * You can override this function to implement your own processing logic.
222      */
223     void OnBackground() override;
224 
225     /**
226      * Called when back press is dispatched.
227      * Return true if ability will be moved to background; return false if will be terminated
228      */
229     bool OnBackPress() override;
230 
231     /**
232      * @brief Called when ability prepare terminate.
233      * @return Return true if ability need to stop terminating; return false if ability need to terminate.
234      */
235     bool OnPrepareTerminate() override;
236 
237     /**
238      * @brief Get JsWindow Stage
239      * @return Returns the current NativeReference
240      */
241     std::shared_ptr<NativeReference> GetJsWindowStage();
242 
243     /**
244      * @brief Get JsRuntime
245      * @return Returns the current JsRuntime
246      */
247     const JsRuntime &GetJsRuntime();
248 
249     /**
250      * @brief Execute insight intent when an ability is in foreground, schedule it to foreground repeatly.
251      *
252      * @param want Want.
253      * @param executeParam insight intent execute param.
254      * @param callback insight intent async callback.
255      */
256     void ExecuteInsightIntentRepeateForeground(const Want &want,
257         const std::shared_ptr<InsightIntentExecuteParam> &executeParam,
258         std::unique_ptr<InsightIntentExecutorAsyncCallback> callback) override;
259 
260     /**
261      * @brief Execute insight intent when an ability didn't started or in background, schedule it to foreground.
262      *
263      * @param want Want.
264      * @param executeParam insight intent execute param.
265      * @param callback insight intent async callback.
266      */
267     void ExecuteInsightIntentMoveToForeground(const Want &want,
268         const std::shared_ptr<InsightIntentExecuteParam> &executeParam,
269         std::unique_ptr<InsightIntentExecutorAsyncCallback> callback) override;
270 
271     /**
272      * @brief Execute insight intent when an ability didn't started, schedule it to background.
273      *
274      * @param want Want.
275      * @param executeParam insight intent execute param.
276      * @param callback insight intent async callback.
277      */
278     virtual void ExecuteInsightIntentBackground(const AAFwk::Want &want,
279         const std::shared_ptr<InsightIntentExecuteParam> &executeParam,
280         std::unique_ptr<InsightIntentExecutorAsyncCallback> callback) override;
281 
282 protected:
283     void DoOnForeground(const Want &want) override;
284     void ContinuationRestore(const Want &want) override;
285 
286 private:
287     bool IsRestorePageStack(const Want &want);
288     void RestorePageStack(const Want &want);
289     void GetPageStackFromWant(const Want &want, std::string &pageStack);
290     void AbilityContinuationOrRecover(const Want &want);
291     void UpdateJsWindowStage(napi_value windowStage);
292     inline bool GetInsightIntentExecutorInfo(const Want &want,
293         const std::shared_ptr<InsightIntentExecuteParam> &executeParam,
294         InsightIntentExecutorInfo& executeInfo);
295 
296     std::shared_ptr<NativeReference> jsWindowStageObj_;
297     int32_t windowMode_ = 0;
298 #endif
299 
300 private:
301     napi_value CallObjectMethod(const char *name, napi_value const *argv = nullptr, size_t argc = 0,
302         bool withResult = false, bool showMethodNotFoundLog = true);
303     bool CheckPromise(napi_value result);
304     bool CallPromise(napi_value result, AppExecFwk::AbilityTransactionCallbackInfo<> *callbackInfo);
305     bool CallPromise(napi_value result, int32_t &onContinueRes);
306     std::unique_ptr<NativeReference> CreateAppWindowStage();
307     std::shared_ptr<AppExecFwk::ADelegatorAbilityProperty> CreateADelegatorAbilityProperty();
308     sptr<IRemoteObject> SetNewRuleFlagToCallee(napi_env env, napi_value remoteJsObj);
309     void SetAbilityContext(std::shared_ptr<AbilityInfo> abilityInfo,
310         std::shared_ptr<AAFwk::Want> want, const std::string &moduleName, const std::string &srcPath);
311     void DoOnForegroundForSceneIsNull(const Want &want);
312     void GetDumpInfo(
313         napi_env env, napi_value dumpInfo, napi_value onDumpInfo, std::vector<std::string> &info);
314     void AddLifecycleEventBeforeJSCall(FreezeUtil::TimeoutState state, const std::string &methodName) const;
315     void AddLifecycleEventAfterJSCall(FreezeUtil::TimeoutState state, const std::string &methodName) const;
316     void CreateJSContext(napi_env env, napi_value &contextObj, int32_t screenMode);
317     bool CheckSatisfyTargetAPIVersion(int32_t targetAPIVersion);
318     bool BackPressDefaultValue();
319     void UpdateAbilityObj(std::shared_ptr<AbilityInfo> abilityInfo,
320         const std::string &moduleName, const std::string &srcPath);
321 
322     JsRuntime &jsRuntime_;
323     std::shared_ptr<NativeReference> shellContextRef_;
324     std::shared_ptr<NativeReference> jsAbilityObj_;
325     std::shared_ptr<int32_t> screenModePtr_;
326     sptr<IRemoteObject> remoteCallee_;
327 };
328 } // namespace AbilityRuntime
329 } // namespace OHOS
330 #endif // OHOS_ABILITY_RUNTIME_JS_UI_ABILITY_H
331