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