• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 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_ABILITY_IMPL_H
17 #define OHOS_ABILITY_RUNTIME_ABILITY_IMPL_H
18 
19 #include "ability.h"
20 #include "iability_lifecycle_callback.h"
21 #include "context.h"
22 #include "application_impl.h"
23 #include "ability_local_record.h"
24 #include "ability_handler.h"
25 #include "ability_manager_client.h"
26 #include "ability_manager_interface.h"
27 #ifdef SUPPORT_GRAPHICS
28 #include "foundation/multimodalinput/input/interfaces/native/innerkits/event/include/i_input_event_consumer.h"
29 #endif
30 namespace OHOS {
31 namespace AppExecFwk {
32 class Ability;
33 class AbilityHandler;
34 class ApplicationImpl;
35 class AbilityLocalRecord;
36 class AbilityLifecycleCallbacks;
37 class OHOSApplication;
38 class AbilityImpl : public std::enable_shared_from_this<AbilityImpl> {
39 public:
40     AbilityImpl() = default;
41     virtual ~AbilityImpl() = default;
42     virtual void Init(std::shared_ptr<OHOSApplication> &application, const std::shared_ptr<AbilityLocalRecord> &record,
43         std::shared_ptr<Ability> &ability, std::shared_ptr<AbilityHandler> &handler, const sptr<IRemoteObject> &token);
44 
45     /**
46      * @brief Connect the ability. and Calling information back to Ability.
47      *
48      * @param want The Want object to connect to.
49      *
50      */
51     sptr<IRemoteObject> ConnectAbility(const Want &want);
52 
53     /**
54      * @brief Disconnects the connected object.
55      *
56      * @param want The Want object to disconnect to.
57      */
58     void DisconnectAbility(const Want &want);
59 
60     /**
61      * @brief Command the ability. and Calling information back to Ability.
62      *
63      * @param want The Want object to command to.
64      *
65      * * @param restart Indicates the startup mode. The value true indicates that Service is restarted after being
66      * destroyed, and the value false indicates a normal startup.
67      *
68      * @param startId Indicates the number of times the Service ability has been started. The startId is incremented
69      * by 1 every time the ability is started. For example, if the ability has been started for six times, the value
70      * of startId is 6.
71      */
72     void CommandAbility(const Want &want, bool restart, int startId);
73 
74     /**
75      * @brief Prepare terminate the ability.
76      *
77      * @return Return true if ability need be terminated; return false if ability need stop terminating.
78      */
79     bool PrepareTerminateAbility();
80 
81     /**
82      * @brief Gets the current Ability status.
83      *
84      */
85     int GetCurrentState();
86 
87     /**
88      * @brief Save data and states of an ability when it is restored by the system. and Calling information back to
89      * Ability. This method should be implemented by a Page ability.
90      *
91      */
92     void DispatchSaveAbilityState();
93 
94     /**
95      * @brief Restores data and states of an ability when it is restored by the system. and Calling information back
96      * to Ability. This method should be implemented by a Page ability.
97      * @param instate The Want object to connect to.
98      *
99      */
100     void DispatchRestoreAbilityState(const PacMap &inState);
101 
102     // Page Service Ability has different AbilityTransaction
103     virtual void HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState,
104         sptr<AAFwk::SessionInfo> sessionInfo = nullptr);
105 
106     /**
107      * @brief The life cycle callback.
108      * @param state The life cycle state to switch to.
109      */
110     virtual void AbilityTransactionCallback(const AbilityLifeCycleState &state);
111 
112     /**
113      * @brief Send the result code and data to be returned by this Page ability to the caller.
114      * When a Page ability is destroyed, the caller overrides the AbilitySlice#onAbilityResult(int, int, Want)
115      * method to receive the result set in the current method. This method can be called only after the ability has
116      * been initialized.
117      *
118      * @param requestCode Indicates the request code.
119      * @param resultCode Indicates the result code returned after the ability is destroyed. You can define the
120      * result code to identify an error.
121      * @param resultData Indicates the data returned after the ability is destroyed. You can define the data
122      * returned. This parameter can be null.
123      */
124     void SendResult(int requestCode, int resultCode, const Want &resultData);
125 
126     /**
127      * @brief Called when the launch mode of an ability is set to singleInstance. This happens when you re-launch
128      * an ability that has been at the top of the ability stack.
129      *
130      * @param want  Indicates the new Want containing information about the ability.
131      */
132     void NewWant(const Want &want);
133 
134     /**
135      * @brief Obtains the MIME types of files supported.
136      *
137      * @param uri Indicates the path of the files to obtain.
138      * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
139      *
140      * @return Returns the matched MIME types. If there is no match, null is returned.
141      */
142     virtual std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter);
143 
144     /**
145      * @brief Opens a file in a specified remote path.
146      *
147      * @param uri Indicates the path of the file to open.
148      * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
149      * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
150      * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
151      * data, or "rwt" for read and write access that truncates any existing file.
152      *
153      * @return Returns the file descriptor.
154      */
155     virtual int OpenFile(const Uri &uri, const std::string &mode);
156 
157     /**
158      * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets
159      * inside of their .hap.
160      *
161      * @param uri Indicates the path of the file to open.
162      * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
163      * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
164      * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
165      * data, or "rwt" for read and write access that truncates any existing file.
166      *
167      * @return Returns the RawFileDescriptor object containing file descriptor.
168      */
169     virtual int OpenRawFile(const Uri &uri, const std::string &mode);
170 
171     /**
172      * @brief Inserts a single data record into the database.
173      *
174      * @param uri Indicates the path of the data to operate.
175      * @param value  Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
176      *
177      * @return Returns the index of the inserted data record.
178      */
179     virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value);
180 
181     virtual std::shared_ptr<AppExecFwk::PacMap> Call(
182         const Uri &uri, const std::string &method, const std::string &arg, const AppExecFwk::PacMap &pacMap);
183 
184     /**
185      * @brief Updates data records in the database.
186      *
187      * @param uri Indicates the path of data to update.
188      * @param value Indicates the data to update. This parameter can be null.
189      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is
190      * null.
191      *
192      * @return Returns the number of data records updated.
193      */
194     virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value,
195         const NativeRdb::DataAbilityPredicates &predicates);
196 
197     /**
198      * @brief Deletes one or more data records from the database.
199      *
200      * @param uri Indicates the path of the data to operate.
201      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is
202      * null.
203      *
204      * @return Returns the number of data records deleted.
205      */
206     virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates);
207 
208     /**
209      * @brief Deletes one or more data records from the database.
210      *
211      * @param uri Indicates the path of data to query.
212      * @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
213      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is
214      * null.
215      *
216      * @return Returns the query result.
217      */
218     virtual std::shared_ptr<NativeRdb::AbsSharedResultSet> Query(
219         const Uri &uri, std::vector<std::string> &columns, const NativeRdb::DataAbilityPredicates &predicates);
220 
221     /**
222      * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should
223      * be implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
224      *
225      * @param uri Indicates the URI of the data.
226      *
227      * @return Returns the MIME type that matches the data specified by uri.
228      */
229     virtual std::string GetType(const Uri &uri);
230 
231     /**
232      * @brief Reloads data in the database.
233      *
234      * @param uri Indicates the position where the data is to reload. This parameter is mandatory.
235      * @param extras Indicates the PacMap object containing the additional parameters to be passed in this call.
236      * This parameter can be null. If a custom Sequenceable object is put in the PacMap object and will be
237      * transferred across processes, you must call BasePacMap.setClassLoader(ClassLoader) to set a class loader for
238      * the custom object.
239      *
240      * @return Returns true if the data is successfully reloaded; returns false otherwise.
241      */
242     virtual bool Reload(const Uri &uri, const PacMap &extras);
243 
244     /**
245      * @brief Inserts multiple data records into the database.
246      *
247      * @param uri Indicates the path of the data to operate.
248      * @param values Indicates the data records to insert.
249      *
250      * @return Returns the number of data records inserted.
251      */
252     virtual int BatchInsert(const Uri &uri, const std::vector<NativeRdb::ValuesBucket> &values);
253 
254     /**
255      * @brief Set deviceId/bundleName/abilityName of the calling ability
256      *
257      * @param deviceId deviceId of the calling ability
258      *
259      * @param deviceId bundleName of the calling ability
260      *
261      * @param deviceId abilityName of the calling ability
262      */
263     void SetCallingContext(const std::string &deviceId, const std::string &bundleName,
264         const std::string &abilityName, const std::string &moduleName);
265 
266     /**
267      * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used
268      * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the
269      * context has changed. If you implement URI normalization for a Data ability, you must also implement
270      * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to
271      * any method that is called on the Data ability must require normalization verification and denormalization. The
272      * default implementation of this method returns null, indicating that this Data ability does not support URI
273      * normalization.
274      *
275      * @param uri Indicates the Uri object to normalize.
276      *
277      * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise.
278      */
279     virtual Uri NormalizeUri(const Uri &uri);
280 
281     /**
282      * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one.
283      * The default implementation of this method returns the original URI passed to it.
284      *
285      * @param uri uri Indicates the Uri object to denormalize.
286      *
287      * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed
288      * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found
289      * in the current environment.
290      */
291     virtual Uri DenormalizeUri(const Uri &uri);
292 
293     /**
294      * @brief ScheduleUpdateConfiguration, scheduling update configuration.
295      */
296     void ScheduleUpdateConfiguration(const Configuration &config);
297 
298     /**
299      * @brief Create a PostEvent timeout task. The default delay is 5000ms
300      *
301      * @return Return a smart pointer to a timeout object
302      */
303     std::shared_ptr<AbilityPostEventTimeout> CreatePostEventTimeouter(std::string taskstr);
304 
305     virtual std::vector<std::shared_ptr<DataAbilityResult>> ExecuteBatch(
306         const std::vector<std::shared_ptr<DataAbilityOperation>> &operations);
307 
308     /**
309      * @brief continue ability to target device.
310      *
311      * @param deviceId target deviceId
312      * @param versionCode Target bundle version.
313      * @return
314      */
315     void ContinueAbility(const std::string& deviceId, uint32_t versionCode);
316 
317     /**
318      * @brief Notify continuation result to ability.
319      *
320      * @param result Continuaton result.
321      *
322      * @return
323      */
324     virtual void NotifyContinuationResult(int32_t result);
325 
326     /**
327      * @brief Notify current memory level to ability.
328      *
329      * @param level Current memory level.
330      *
331      * @return
332      */
333     virtual void NotifyMemoryLevel(int32_t level);
334 
335     bool IsStageBasedModel() const;
336 
337     /**
338      * @brief Provide operating system ShareData information to the observer
339      *
340      * @param uniqueId Indicates the Id of request
341      *
342      * @return
343      */
344     virtual void HandleShareData(const int32_t &uniqueId);
345 
346 #ifdef SUPPORT_GRAPHICS
347 public:
348     /**
349      * @brief Execution the KeyDown callback of the ability
350      * @param keyEvent Indicates the key-down event.
351      *
352      * @return Returns true if this event is handled and will not be passed further; returns false if this event is
353      * not handled and should be passed to other handlers.
354      *
355      */
356     virtual void DoKeyDown(const std::shared_ptr<MMI::KeyEvent>& keyEvent);
357 
358     /**
359      * @brief Execution the KeyUp callback of the ability
360      * @param keyEvent Indicates the key-up event.
361      *
362      * @return Returns true if this event is handled and will not be passed further; returns false if this event is
363      * not handled and should be passed to other handlers.
364      *
365      */
366     virtual void DoKeyUp(const std::shared_ptr<MMI::KeyEvent>& keyEvent);
367 
368     /**
369      * @brief Called when a touch event is dispatched to this ability. The default implementation of this callback
370      * does nothing and returns false.
371      * @param touchEvent Indicates information about the touch event.
372      *
373      * @return Returns true if the event is handled; returns false otherwise.
374      *
375      */
376     virtual void DoPointerEvent(std::shared_ptr<MMI::PointerEvent>& pointerEvent);
377 
378     void AfterUnFocused();
379     void AfterFocused();
380 
381 protected:
382     /**
383      * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application
384      * that it belongs to of the lifecycle status.
385      *
386      * @param want The Want object to switch the life cycle.
387      */
388     void Foreground(const Want &want);
389 
390     /**
391      * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_BACKGROUND. And notifies the
392      * application that it belongs to of the lifecycle status.
393      *
394      */
395     void Background();
396 #endif
397 
398 protected:
399     /**
400      * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application
401      * that it belongs to of the lifecycle status.
402      *
403      * @param want  The Want object to switch the life cycle.
404      * @param sessionInfo  Indicates the sessionInfo.
405      */
406     void Start(const Want &want, sptr<AAFwk::SessionInfo> sessionInfo = nullptr);
407 
408     /**
409      * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INITIAL. And notifies the application
410      * that it belongs to of the lifecycle status.
411      *
412      */
413     void Stop();
414 
415     /**
416      * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INITIAL. And notifies the application
417      * that it belongs to of the lifecycle status.
418      * @param isAsyncCallback Indicates whether it is an asynchronous lifecycle callback
419      */
420     void Stop(bool &isAsyncCallback);
421 
422     /**
423      * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INITIAL. And notifies the application
424      * that it belongs to of the lifecycle status.
425      */
426     void StopCallback();
427 
428     /**
429      * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_ACTIVE. And notifies the application
430      * that it belongs to of the lifecycle status.
431      *
432      */
433     void Active();
434 
435     /**
436      * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application
437      * that it belongs to of the lifecycle status.
438      *
439      */
440     void Inactive();
441 
442     /**
443      * @brief SetUriString
444      *
445      * @param uri the uri to set.
446      */
447     void SetUriString(const std::string &uri);
448 
449     /**
450      * @brief Set the LifeCycleStateInfo to the deal.
451      *
452      * @param info the info to set.
453      */
454     void SetLifeCycleStateInfo(const AAFwk::LifeCycleStateInfo &info);
455 
456     /**
457      * @brief Check if it needs to restore the data to the ability.
458      *
459      * @return Return true if success, otherwise return false.
460      */
461     bool CheckAndRestore();
462 
463     /**
464      * @brief Check if it needs to save the data to the ability.
465      *
466      * @return Return true if success, otherwise return false.
467      */
468     bool CheckAndSave();
469 
470     /**
471      * @brief Get share wantParam.
472      *
473      * @param WantParams
474      *
475      * @return Return the result of share.
476      */
477     int32_t Share(WantParams &wantParam);
478 
479     PacMap &GetRestoreData();
480 
481     bool isStageBasedModel_ = false;
482     int lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL;
483     sptr<IRemoteObject> token_;
484     std::shared_ptr<Ability> ability_;
485     std::shared_ptr<AbilityHandler> handler_;
486     bool notifyForegroundByWindow_ = false;
487     bool notifyForegroundByAbility_ = false;
488     std::mutex notifyForegroundLock_;
489 
490 private:
491     typedef enum {
492         START,
493         INACTIVE,
494         ACTIVE,
495         BACKGROUND,
496         FOREGROUND,
497         STOP,
498     } Action;
499 
500     std::shared_ptr<AbilityLifecycleCallbacks> abilityLifecycleCallbacks_;
501     std::shared_ptr<ApplicationImpl> applicationImpl_;
502     std::shared_ptr<ContextDeal> contextDeal_;
503     bool hasSaveData_ = false;
504     bool needSaveDate_ = false;
505     PacMap restoreData_;
506 
507 private:
508     void AfterFocusedCommon(bool isFocused);
509 
510 #ifdef SUPPORT_GRAPHICS
511 private:
512 class WindowLifeCycleImpl : public Rosen::IWindowLifeCycle {
513 public:
WindowLifeCycleImpl(const sptr<IRemoteObject> & token,const std::shared_ptr<AbilityImpl> & owner)514     WindowLifeCycleImpl(const sptr<IRemoteObject>& token, const std::shared_ptr<AbilityImpl>& owner)
515         : token_(token), owner_(owner) {}
~WindowLifeCycleImpl()516     virtual ~WindowLifeCycleImpl() {}
517     void AfterForeground() override;
518     void AfterBackground() override;
519     void AfterFocused() override;
520     void AfterUnfocused() override;
521     void ForegroundFailed(int32_t type) override;
522     void BackgroundFailed(int32_t type) override;
523 private:
524     sptr<IRemoteObject> token_ = nullptr;
525     std::weak_ptr<AbilityImpl> owner_;
526 };
527 
528 class InputEventConsumerImpl : public MMI::IInputEventConsumer {
529 public:
InputEventConsumerImpl(const std::shared_ptr<AbilityImpl> & abilityImpl)530     explicit InputEventConsumerImpl(const std::shared_ptr<AbilityImpl>& abilityImpl) : abilityImpl_(abilityImpl) {}
531     ~InputEventConsumerImpl() = default;
532     void OnInputEvent(std::shared_ptr<MMI::KeyEvent> keyEvent) const override;
533     void OnInputEvent(std::shared_ptr<MMI::PointerEvent> pointerEvent) const override;
OnInputEvent(std::shared_ptr<MMI::AxisEvent> axisEvent)534     void OnInputEvent(std::shared_ptr<MMI::AxisEvent> axisEvent) const override {}
535 private:
536     std::shared_ptr<AbilityImpl> abilityImpl_;
537 };
538 #endif
539 };
540 }  // namespace AppExecFwk
541 }  // namespace OHOS
542 #endif  // OHOS_ABILITY_RUNTIME_ABILITY_IMPL_H
543