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