1 /*
2  * Copyright (c) 2021-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 #include "ability.h"
17 
18 #include <cinttypes>
19 #include <thread>
20 
21 #include "ability_post_event_timeout.h"
22 #include "ability_runtime/js_ability.h"
23 #include "abs_shared_result_set.h"
24 #include "bundle_mgr_helper.h"
25 #include "configuration_convertor.h"
26 #include "connection_manager.h"
27 #include "continuation_manager.h"
28 #include "continuation_register_manager.h"
29 #include "continuation_register_manager_proxy.h"
30 #include "data_ability_operation.h"
31 #include "data_ability_predicates.h"
32 #include "data_ability_result.h"
33 #include "data_uri_utils.h"
34 #include "event_report.h"
35 #include "hilog_tag_wrapper.h"
36 #include "hitrace_meter.h"
37 #include "if_system_ability_manager.h"
38 #include "iservice_registry.h"
39 #include "ohos_application.h"
40 #include "reverse_continuation_scheduler_primary.h"
41 #include "reverse_continuation_scheduler_replica.h"
42 #include "reverse_continuation_scheduler_replica_handler_interface.h"
43 #include "runtime.h"
44 #include "scene_board_judgement.h"
45 #include "singleton.h"
46 #include "system_ability_definition.h"
47 #include "task_handler_client.h"
48 #include "values_bucket.h"
49 
50 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
51 #include "background_task_mgr_helper.h"
52 #include "continuous_task_param.h"
53 #endif
54 
55 #ifdef SUPPORT_GRAPHICS
56 #include "display_type.h"
57 #include "key_event.h"
58 #endif
59 
60 namespace OHOS {
61 namespace AppExecFwk {
62 const std::string Ability::SYSTEM_UI("com.ohos.systemui");
63 const std::string Ability::STATUS_BAR("com.ohos.systemui.statusbar.MainAbility");
64 const std::string Ability::NAVIGATION_BAR("com.ohos.systemui.navigationbar.MainAbility");
65 const std::string Ability::KEYGUARD("com.ohos.screenlock");
66 const std::string DEVICE_MANAGER_BUNDLE_NAME = "com.ohos.devicemanagerui";
67 const std::string DEVICE_MANAGER_NAME = "com.ohos.devicemanagerui.MainAbility";
68 const std::string Ability::DMS_SESSION_ID("sessionId");
69 const std::string Ability::DMS_ORIGIN_DEVICE_ID("deviceId");
70 const int Ability::DEFAULT_DMS_SESSION_ID(0);
71 const std::string LAUNCHER_BUNDLE_NAME = "com.ohos.launcher";
72 const std::string LAUNCHER_ABILITY_NAME = "com.ohos.launcher.MainAbility";
73 const std::string SHOW_ON_LOCK_SCREEN = "ShowOnLockScreen";
74 #ifdef WITH_DLP
75 const std::string DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag";
76 #endif // WITH_DLP
77 const std::string COMPONENT_STARTUP_NEW_RULES = "component.startup.newRules";
78 
Create(const std::unique_ptr<AbilityRuntime::Runtime> & runtime)79 Ability* Ability::Create(const std::unique_ptr<AbilityRuntime::Runtime>& runtime)
80 {
81     if (!runtime) {
82         return new Ability;
83     }
84 
85     switch (runtime->GetLanguage()) {
86         case AbilityRuntime::Runtime::Language::JS:
87             return AbilityRuntime::JsAbility::Create(runtime);
88 
89         default:
90             return new Ability();
91     }
92 }
93 
Init(const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<OHOSApplication> application,std::shared_ptr<AbilityHandler> & handler,const sptr<IRemoteObject> & token)94 void Ability::Init(const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<OHOSApplication> application,
95     std::shared_ptr<AbilityHandler> &handler, const sptr<IRemoteObject> &token)
96 {
97     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
98     TAG_LOGD(AAFwkTag::ABILITY, "called");
99     application_ = application;
100     abilityInfo_ = abilityInfo;
101     handler_ = handler;
102     AbilityContext::token_ = token;
103 
104 #ifdef SUPPORT_GRAPHICS
105     // page ability only.
106     if (abilityInfo_->type == AbilityType::PAGE) {
107         if (!abilityInfo_->isStageBasedModel) {
108             abilityWindow_ = std::make_shared<AbilityWindow>();
109             abilityWindow_->Init(handler_, shared_from_this());
110         }
111         continuationManager_ = std::make_shared<ContinuationManager>();
112         std::weak_ptr<Ability> ability = shared_from_this();
113         std::weak_ptr<ContinuationManager> continuationManager = continuationManager_;
114         continuationHandler_ = std::make_shared<ContinuationHandler>(continuationManager, ability);
115         if (!continuationManager_->Init(shared_from_this(), GetToken(), GetAbilityInfo(), continuationHandler_)) {
116             continuationManager_.reset();
117         } else {
118             std::weak_ptr<ContinuationHandler> continuationHandler = continuationHandler_;
119             sptr<ReverseContinuationSchedulerPrimary> primary = sptr<ReverseContinuationSchedulerPrimary>(
120                 new (std::nothrow) ReverseContinuationSchedulerPrimary(continuationHandler, handler_));
121             if (primary == nullptr) {
122                 TAG_LOGE(AAFwkTag::ABILITY, "create primary failed");
123             } else {
124                 continuationHandler_->SetPrimaryStub(primary);
125                 continuationHandler_->SetAbilityInfo(abilityInfo_);
126             }
127         }
128 
129         // register displayid change callback
130         TAG_LOGD(AAFwkTag::ABILITY, "Start RegisterDisplayListener");
131         abilityDisplayListener_ = new AbilityDisplayListener(ability);
132         Rosen::DisplayManager::GetInstance().RegisterDisplayListener(abilityDisplayListener_);
133     }
134 #endif
135     lifecycle_ = std::make_shared<LifeCycle>();
136     abilityLifecycleExecutor_ = std::make_shared<AbilityLifecycleExecutor>();
137     abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::INITIAL);
138 
139     if (abilityContext_ != nullptr) {
140         abilityContext_->RegisterAbilityCallback(weak_from_this());
141     }
142     TAG_LOGD(AAFwkTag::ABILITY, "end");
143 }
144 
AttachAbilityContext(const std::shared_ptr<AbilityRuntime::AbilityContext> & abilityContext)145 void Ability::AttachAbilityContext(const std::shared_ptr<AbilityRuntime::AbilityContext> &abilityContext)
146 {
147     abilityContext_ = abilityContext;
148 }
149 
GetResourceManager() const150 std::shared_ptr<Global::Resource::ResourceManager> Ability::GetResourceManager() const
151 {
152     return AbilityContext::GetResourceManager();
153 }
154 
IsUpdatingConfigurations()155 bool Ability::IsUpdatingConfigurations()
156 {
157     return AbilityContext::IsUpdatingConfigurations();
158 }
159 
OnStart(const Want & want,sptr<AAFwk::SessionInfo> sessionInfo)160 void Ability::OnStart(const Want &want, sptr<AAFwk::SessionInfo> sessionInfo)
161 {
162     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
163     if (abilityInfo_ == nullptr) {
164         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
165         return;
166     }
167 
168 #ifdef WITH_DLP
169     securityFlag_ = want.GetBoolParam(DLP_PARAMS_SECURITY_FLAG, false);
170     (const_cast<Want &>(want)).RemoveParam(DLP_PARAMS_SECURITY_FLAG);
171 #endif // WITH_DLP
172     SetWant(want);
173     if (sessionInfo != nullptr) {
174         SetSessionToken(sessionInfo->sessionToken);
175     }
176     TAG_LOGD(AAFwkTag::ABILITY, "ability:%{public}s", abilityInfo_->name.c_str());
177 #ifdef SUPPORT_GRAPHICS
178     if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) {
179         int32_t defualtDisplayId = static_cast<int32_t>(Rosen::DisplayManager::GetInstance().GetDefaultDisplayId());
180         int32_t displayId = want.GetIntParam(Want::PARAM_RESV_DISPLAY_ID, defualtDisplayId);
181         TAG_LOGD(AAFwkTag::ABILITY, "abilityName:%{public}s, displayId:%{public}d",
182             abilityInfo_->name.c_str(), displayId);
183         InitFAWindow(want, displayId);
184 
185         if (!UpdateResMgrAndConfiguration(displayId)) {
186             return;
187         }
188     }
189 #endif
190     if (abilityLifecycleExecutor_ == nullptr) {
191         TAG_LOGE(AAFwkTag::ABILITY, "null abilityLifecycleExecutor_");
192         return;
193     }
194     if (!abilityInfo_->isStageBasedModel) {
195         abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::INACTIVE);
196     } else {
197         abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::STARTED_NEW);
198     }
199 
200     if (lifecycle_ == nullptr) {
201         TAG_LOGE(AAFwkTag::ABILITY, "null lifecycle_");
202         return;
203     }
204     lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_START, want);
205     TAG_LOGD(AAFwkTag::ABILITY, "end");
206 }
207 
OnStop()208 void Ability::OnStop()
209 {
210     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
211     TAG_LOGD(AAFwkTag::ABILITY, "called");
212 #ifdef SUPPORT_GRAPHICS
213     (void)Rosen::DisplayManager::GetInstance().UnregisterDisplayListener(abilityDisplayListener_);
214     auto && window = GetWindow();
215     if (window != nullptr) {
216         TAG_LOGD(AAFwkTag::ABILITY, "unregisterDisplayMoveListener");
217         window->UnregisterDisplayMoveListener(abilityDisplayMoveListener_);
218     }
219     // Call JS Func(onWindowStageDestroy) and Release the scene.
220     if (scene_ != nullptr) {
221         scene_->GoDestroy();
222         onSceneDestroyed();
223     }
224 #endif
225     if (abilityLifecycleExecutor_ == nullptr) {
226         TAG_LOGE(AAFwkTag::ABILITY, "null abilityLifecycleExecutor_");
227         return;
228     }
229     abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::INITIAL);
230     if (lifecycle_ == nullptr) {
231         TAG_LOGE(AAFwkTag::ABILITY, "null lifecycle_");
232         return;
233     }
234     lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_STOP);
235     TAG_LOGD(AAFwkTag::ABILITY, "end");
236 }
237 
OnStop(AbilityTransactionCallbackInfo<> * callbackInfo,bool & isAsyncCallback)238 void Ability::OnStop(AbilityTransactionCallbackInfo<> *callbackInfo, bool &isAsyncCallback)
239 {
240     isAsyncCallback = false;
241     OnStop();
242 }
243 
OnStopCallback()244 void Ability::OnStopCallback()
245 {
246 }
247 
DestroyInstance()248 void Ability::DestroyInstance()
249 {
250     TAG_LOGD(AAFwkTag::ABILITY, "called");
251 #ifdef SUPPORT_GRAPHICS
252     // Release the window.
253     if (abilityWindow_ != nullptr && abilityInfo_->type == AppExecFwk::AbilityType::PAGE) {
254         abilityWindow_->OnPostAbilityStop(); // Ability instance will been released when window destroy.
255     }
256 #endif
257     TAG_LOGD(AAFwkTag::ABILITY, "end");
258 }
259 
OnActive()260 void Ability::OnActive()
261 {
262     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
263     TAG_LOGD(AAFwkTag::ABILITY, "called");
264 #ifdef SUPPORT_GRAPHICS
265     bWindowFocus_ = true;
266 #endif
267     if (abilityLifecycleExecutor_ == nullptr) {
268         TAG_LOGE(AAFwkTag::ABILITY, "null abilityLifecycleExecutor_");
269         return;
270     }
271     abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::ACTIVE);
272 
273     if (lifecycle_ == nullptr) {
274         TAG_LOGE(AAFwkTag::ABILITY, "null lifecycle_");
275         return;
276     }
277     lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE);
278     if (abilityInfo_ == nullptr) {
279         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
280         return;
281     }
282     AAFwk::EventInfo eventInfo;
283     eventInfo.bundleName = abilityInfo_->bundleName;
284     eventInfo.moduleName = abilityInfo_->moduleName;
285     eventInfo.abilityName = abilityInfo_->name;
286     eventInfo.abilityType = static_cast<int32_t>(abilityInfo_->type);
287     eventInfo.bundleType = static_cast<int32_t>(abilityInfo_->applicationInfo.bundleType);
288     if (setWant_ != nullptr) {
289         eventInfo.callerBundleName = setWant_->GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
290         TAG_LOGI(AAFwkTag::ABILITY, "caller:%{public}s", eventInfo.callerBundleName.c_str());
291     } else {
292         TAG_LOGE(AAFwkTag::ABILITY, "null setWant_");
293     }
294     AAFwk::EventReport::SendAbilityEvent(AAFwk::EventName::ABILITY_ONACTIVE,
295         HiSysEventType::BEHAVIOR, eventInfo);
296     TAG_LOGD(AAFwkTag::ABILITY, "end");
297 }
298 
OnInactive()299 void Ability::OnInactive()
300 {
301     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
302     TAG_LOGD(AAFwkTag::ABILITY, "called");
303 #ifdef SUPPORT_GRAPHICS
304     bWindowFocus_ = false;
305 #endif
306     if (abilityLifecycleExecutor_ == nullptr) {
307         TAG_LOGE(AAFwkTag::ABILITY, "null abilityLifecycleExecutor_");
308         return;
309     }
310     abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::INACTIVE);
311 
312     if (lifecycle_ == nullptr) {
313         TAG_LOGE(AAFwkTag::ABILITY, "null lifecycle_");
314         return;
315     }
316     lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_INACTIVE);
317     if (abilityInfo_ == nullptr) {
318         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
319         return;
320     }
321     AAFwk::EventInfo eventInfo;
322     eventInfo.bundleName = abilityInfo_->bundleName;
323     eventInfo.moduleName = abilityInfo_->moduleName;
324     eventInfo.abilityName = abilityInfo_->name;
325     eventInfo.bundleType = static_cast<int32_t>(abilityInfo_->applicationInfo.bundleType);
326     AAFwk::EventReport::SendAbilityEvent(AAFwk::EventName::ABILITY_ONINACTIVE,
327         HiSysEventType::BEHAVIOR, eventInfo);
328     TAG_LOGD(AAFwkTag::ABILITY, "end");
329 }
330 
IsRestoredInContinuation() const331 bool Ability::IsRestoredInContinuation() const
332 {
333     if (abilityContext_ == nullptr) {
334         TAG_LOGE(AAFwkTag::ABILITY, "null abilityContext_");
335         return false;
336     }
337 
338     if (launchParam_.launchReason != LaunchReason::LAUNCHREASON_CONTINUATION) {
339         TAG_LOGD(AAFwkTag::ABILITY, "launchReason:%{public}d", launchParam_.launchReason);
340         return false;
341     }
342 
343     TAG_LOGD(AAFwkTag::ABILITY, "restored In Continuation");
344     return true;
345 }
346 
ShouldRecoverState(const Want & want)347 bool Ability::ShouldRecoverState(const Want& want)
348 {
349     if (!want.GetBoolParam(Want::PARAM_ABILITY_RECOVERY_RESTART, false)) {
350         TAG_LOGI(AAFwkTag::ABILITY, "not recovery restart");
351         return false;
352     }
353 
354     if (abilityContext_ == nullptr) {
355         TAG_LOGW(AAFwkTag::ABILITY, "null abilityContext_");
356         return false;
357     }
358 
359     if (abilityContext_->GetContentStorage() == nullptr) {
360         TAG_LOGW(AAFwkTag::ABILITY, "null GetContentStorage");
361         return false;
362     }
363 
364     return true;
365 }
366 
NotifyContinuationResult(const Want & want,bool success)367 void Ability::NotifyContinuationResult(const Want& want, bool success)
368 {
369     TAG_LOGI(AAFwkTag::ABILITY, "called");
370 
371     int sessionId = want.GetIntParam(DMS_SESSION_ID, DEFAULT_DMS_SESSION_ID);
372     std::string originDeviceId = want.GetStringParam(DMS_ORIGIN_DEVICE_ID);
373     TAG_LOGD(AAFwkTag::ABILITY, "notify complete continuation");
374     continuationManager_->NotifyCompleteContinuation(
375         originDeviceId, sessionId, success, reverseContinuationSchedulerReplica_);
376 }
377 
OnConnect(const Want & want)378 sptr<IRemoteObject> Ability::OnConnect(const Want &want)
379 {
380     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
381     TAG_LOGD(AAFwkTag::ABILITY, "called");
382     if (abilityLifecycleExecutor_ == nullptr) {
383         TAG_LOGE(AAFwkTag::ABILITY, "null abilityLifecycleExecutor_");
384         return nullptr;
385     }
386     abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::ACTIVE);
387 
388     if (lifecycle_ == nullptr) {
389         TAG_LOGE(AAFwkTag::ABILITY, "null lifecycle_");
390         return nullptr;
391     }
392     lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE);
393     TAG_LOGD(AAFwkTag::ABILITY, "end");
394     return nullptr;
395 }
396 
OnDisconnect(const Want & want)397 void Ability::OnDisconnect(const Want &want)
398 {
399     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
400     TAG_LOGD(AAFwkTag::ABILITY, "called");
401 }
402 
StartAbilityForResult(const Want & want,int requestCode)403 ErrCode Ability::StartAbilityForResult(const Want &want, int requestCode)
404 {
405     TAG_LOGD(AAFwkTag::ABILITY, "start");
406     if (abilityInfo_ == nullptr) {
407         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
408         return ERR_NULL_OBJECT;
409     }
410     TAG_LOGD(AAFwkTag::ABILITY, "abilityType:%{public}d", abilityInfo_->type);
411     if (abilityInfo_->type != AppExecFwk::AbilityType::PAGE) {
412         TAG_LOGE(AAFwkTag::ABILITY, "abilityType:%{public}d mismatch", abilityInfo_->type);
413         return ERR_INVALID_VALUE;
414     }
415     ErrCode err = AbilityContext::StartAbility(want, requestCode);
416     TAG_LOGD(AAFwkTag::ABILITY, "end");
417     return err;
418 }
419 
StartAbilityForResult(const Want & want,int requestCode,AbilityStartSetting abilityStartSetting)420 ErrCode Ability::StartAbilityForResult(const Want &want, int requestCode, AbilityStartSetting abilityStartSetting)
421 {
422     TAG_LOGD(AAFwkTag::ABILITY, "called");
423     if (abilityInfo_ == nullptr) {
424         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
425         return ERR_NULL_OBJECT;
426     }
427     TAG_LOGD(AAFwkTag::ABILITY, "abilityType:%{public}d", abilityInfo_->type);
428     if (abilityInfo_->type != AppExecFwk::AbilityType::PAGE) {
429         TAG_LOGE(AAFwkTag::ABILITY, "abilityType:%{public}d", abilityInfo_->type);
430         return ERR_INVALID_VALUE;
431     }
432     ErrCode err = AbilityContext::StartAbility(want, requestCode, abilityStartSetting);
433     TAG_LOGD(AAFwkTag::ABILITY, "end");
434     return err;
435 }
436 
StartAbility(const Want & want,AbilityStartSetting abilityStartSetting)437 ErrCode Ability::StartAbility(const Want &want, AbilityStartSetting abilityStartSetting)
438 {
439     TAG_LOGD(AAFwkTag::ABILITY, "called");
440     if (abilityInfo_ == nullptr) {
441         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
442         return ERR_NULL_OBJECT;
443     }
444     TAG_LOGD(AAFwkTag::ABILITY, "abilityType:%{public}d", abilityInfo_->type);
445     if (abilityInfo_->type != AppExecFwk::AbilityType::PAGE && abilityInfo_->type != AppExecFwk::AbilityType::SERVICE) {
446         TAG_LOGE(AAFwkTag::ABILITY, "abilityType:%{public}d mismatch", abilityInfo_->type);
447         return ERR_INVALID_VALUE;
448     }
449     ErrCode err = AbilityContext::StartAbility(want, -1, abilityStartSetting);
450     TAG_LOGD(AAFwkTag::ABILITY, "end");
451     return err;
452 }
453 
AddFreeInstallObserver(const sptr<AbilityRuntime::IFreeInstallObserver> observer)454 ErrCode Ability::AddFreeInstallObserver(const sptr<AbilityRuntime::IFreeInstallObserver> observer)
455 {
456     return AbilityContext::AddFreeInstallObserver(observer);
457 }
458 
GetType(const Uri & uri)459 std::string Ability::GetType(const Uri &uri)
460 {
461     return "";
462 }
463 
Insert(const Uri & uri,const NativeRdb::ValuesBucket & value)464 int Ability::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value)
465 {
466     return 0;
467 }
468 
Call(const Uri & uri,const std::string & method,const std::string & arg,const AppExecFwk::PacMap & pacMap)469 std::shared_ptr<AppExecFwk::PacMap> Ability::Call(
470     const Uri &uri, const std::string &method, const std::string &arg, const AppExecFwk::PacMap &pacMap)
471 {
472     return nullptr;
473 }
474 
OnConfigurationUpdated(const Configuration & configuration)475 void Ability::OnConfigurationUpdated(const Configuration &configuration)
476 {
477     TAG_LOGD(AAFwkTag::ABILITY, "called");
478 }
479 
OnConfigurationUpdatedNotify(const Configuration & configuration)480 void Ability::OnConfigurationUpdatedNotify(const Configuration &configuration)
481 {
482     TAG_LOGD(AAFwkTag::ABILITY, "called");
483 
484     std::string language;
485     std::string colormode;
486     std::string hasPointerDevice;
487     InitConfigurationProperties(configuration, language, colormode, hasPointerDevice);
488     // Notify ResourceManager
489     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
490     if (resConfig == nullptr) {
491         TAG_LOGE(AAFwkTag::ABILITY, "null resConfig");
492         return;
493     }
494     auto resourceManager = GetResourceManager();
495     if (resourceManager != nullptr) {
496         resourceManager->GetResConfig(*resConfig);
497 #ifdef SUPPORT_GRAPHICS
498         if (!language.empty()) {
499             UErrorCode status = U_ZERO_ERROR;
500             icu::Locale locale = icu::Locale::forLanguageTag(language, status);
501             TAG_LOGD(AAFwkTag::ABILITY, "get forLanguageTag:%{public}d", static_cast<int>(status));
502             if (status == U_ZERO_ERROR) {
503                 resConfig->SetLocaleInfo(locale);
504             }
505         }
506 #endif
507         if (!colormode.empty()) {
508             resConfig->SetColorMode(ConvertColorMode(colormode));
509         }
510         if (!hasPointerDevice.empty()) {
511             resConfig->SetInputDevice(ConvertHasPointerDevice(hasPointerDevice));
512         }
513         resourceManager->UpdateResConfig(*resConfig);
514         TAG_LOGI(AAFwkTag::ABILITY,
515             "colorMode:%{public}d,hasPointerDevice:%{publis}d",
516             resConfig->GetColorMode(), resConfig->GetInputDevice());
517     }
518 
519     if (abilityContext_ != nullptr && application_ != nullptr) {
520         abilityContext_->SetConfiguration(application_->GetConfiguration());
521     }
522     // Notify Ability Subclass
523     OnConfigurationUpdated(configuration);
524 }
525 
InitConfigurationProperties(const Configuration & changeConfiguration,std::string & language,std::string & colormode,std::string & hasPointerDevice)526 void Ability::InitConfigurationProperties(const Configuration& changeConfiguration, std::string& language,
527     std::string& colormode, std::string& hasPointerDevice)
528 {
529     if (setting_) {
530         auto displayId = std::atoi(setting_->GetProperty(AbilityStartSetting::WINDOW_DISPLAY_ID_KEY).c_str());
531         language = changeConfiguration.GetItem(displayId, AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE);
532         colormode = changeConfiguration.GetItem(displayId, AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
533         hasPointerDevice = changeConfiguration.GetItem(displayId, AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE);
534         TAG_LOGI(AAFwkTag::ABILITY, "displayId: [%{public}d], language: [%{public}s], colormode: [%{public}s], "
535             "hasPointerDevice: [%{public}s]", displayId, language.c_str(), colormode.c_str(), hasPointerDevice.c_str());
536     } else {
537         language = changeConfiguration.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE);
538         colormode = changeConfiguration.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
539         hasPointerDevice = changeConfiguration.GetItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE);
540         TAG_LOGI(AAFwkTag::ABILITY, "language: [%{public}s], colormode: [%{public}s], hasPointerDevice: [%{public}s]",
541             language.c_str(), colormode.c_str(), hasPointerDevice.c_str());
542     }
543 }
544 
OnMemoryLevel(int level)545 void Ability::OnMemoryLevel(int level)
546 {
547     TAG_LOGD(AAFwkTag::ABILITY, "called");
548     if (scene_ == nullptr) {
549         TAG_LOGD(AAFwkTag::ABILITY, "null windowScene");
550         return;
551     }
552     scene_->NotifyMemoryLevel(level);
553 }
554 
OpenRawFile(const Uri & uri,const std::string & mode)555 int Ability::OpenRawFile(const Uri &uri, const std::string &mode)
556 {
557     return -1;
558 }
559 
Update(const Uri & uri,const NativeRdb::ValuesBucket & value,const NativeRdb::DataAbilityPredicates & predicates)560 int Ability::Update(
561     const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates)
562 {
563     return 0;
564 }
565 
GetApplication()566 std::shared_ptr<OHOSApplication> Ability::GetApplication()
567 {
568     TAG_LOGD(AAFwkTag::ABILITY, "called");
569     if (application_ == nullptr) {
570         TAG_LOGE(AAFwkTag::ABILITY, "null application_");
571         return nullptr;
572     }
573     TAG_LOGD(AAFwkTag::ABILITY, "end");
574     return application_;
575 }
576 
GetAbilityName()577 std::string Ability::GetAbilityName()
578 {
579     if (abilityInfo_ == nullptr) {
580         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
581         return "";
582     }
583 
584     return abilityInfo_->name;
585 }
586 
GetModuleName()587 std::string Ability::GetModuleName()
588 {
589     if (abilityInfo_ == nullptr) {
590         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
591         return "";
592     }
593 
594     return abilityInfo_->moduleName;
595 }
596 
IsTerminating()597 bool Ability::IsTerminating()
598 {
599     return false;
600 }
601 
OnAbilityResult(int requestCode,int resultCode,const Want & want)602 void Ability::OnAbilityResult(int requestCode, int resultCode, const Want &want)
603 {}
604 
OnBackPressed()605 void Ability::OnBackPressed()
606 {
607     TAG_LOGD(AAFwkTag::ABILITY, "called");
608     if (abilityInfo_ == nullptr) {
609         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
610         return;
611     }
612 
613     if (abilityInfo_->isLauncherAbility == false) {
614         TAG_LOGD(AAFwkTag::ABILITY, "not Launcher");
615         TerminateAbility();
616     }
617     TAG_LOGD(AAFwkTag::ABILITY, "end");
618 }
619 
OnNewWant(const Want & want)620 void Ability::OnNewWant(const Want &want)
621 {
622     TAG_LOGD(AAFwkTag::ABILITY, "called");
623 }
624 
OnRestoreAbilityState(const PacMap & inState)625 void Ability::OnRestoreAbilityState(const PacMap &inState)
626 {
627     TAG_LOGD(AAFwkTag::ABILITY, "called");
628 }
629 
OnSaveAbilityState(PacMap & outState)630 void Ability::OnSaveAbilityState(PacMap &outState)
631 {
632     TAG_LOGD(AAFwkTag::ABILITY, "called");
633 }
634 
OnEventDispatch()635 void Ability::OnEventDispatch()
636 {}
637 
SetWant(const AAFwk::Want & want)638 void Ability::SetWant(const AAFwk::Want &want)
639 {
640     setWant_ = std::make_shared<AAFwk::Want>(want);
641 }
642 
GetWant()643 std::shared_ptr<AAFwk::Want> Ability::GetWant()
644 {
645     return setWant_;
646 }
647 
SetResult(int resultCode,const Want & resultData)648 void Ability::SetResult(int resultCode, const Want &resultData)
649 {
650     TAG_LOGD(AAFwkTag::ABILITY, "called");
651     if (abilityInfo_ == nullptr) {
652         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
653         return;
654     }
655     TAG_LOGD(AAFwkTag::ABILITY, "abilityType:%{public}d", abilityInfo_->type);
656     if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) {
657         AbilityContext::resultWant_ = resultData;
658         AbilityContext::resultCode_ = resultCode;
659     }
660     TAG_LOGD(AAFwkTag::ABILITY, "end");
661 }
662 
OnCommand(const AAFwk::Want & want,bool restart,int startId)663 void Ability::OnCommand(const AAFwk::Want &want, bool restart, int startId)
664 {
665     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
666     TAG_LOGI(AAFwkTag::ABILITY, "restart:%{public}s, startId:%{public}d", restart ? "true" : "false", startId);
667     if (abilityLifecycleExecutor_ == nullptr) {
668         TAG_LOGE(AAFwkTag::ABILITY, "null abilityLifecycleExecutor_");
669         return;
670     }
671     abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::ACTIVE);
672 
673     if (lifecycle_ == nullptr) {
674         TAG_LOGE(AAFwkTag::ABILITY, "null lifecycle_");
675         return;
676     }
677     lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE);
678     TAG_LOGD(AAFwkTag::ABILITY, "end");
679 }
680 
Dump(const std::string & extra)681 void Ability::Dump(const std::string &extra)
682 {
683     TAG_LOGD(AAFwkTag::ABILITY, "called");
684     // abilityInfo
685     if (abilityInfo_ != nullptr) {
686         TAG_LOGD(AAFwkTag::ABILITY, "package:%{public}s", abilityInfo_->package.c_str());
687         TAG_LOGD(AAFwkTag::ABILITY, "name:%{public}s", abilityInfo_->name.c_str());
688         TAG_LOGD(AAFwkTag::ABILITY, "label:%{public}s", abilityInfo_->label.c_str());
689         TAG_LOGD(AAFwkTag::ABILITY, "description:%{public}s", abilityInfo_->description.c_str());
690         TAG_LOGD(AAFwkTag::ABILITY, "iconPath:%{public}s", abilityInfo_->iconPath.c_str());
691         TAG_LOGD(AAFwkTag::ABILITY, "visible:%{public}d", abilityInfo_->visible);
692         TAG_LOGD(AAFwkTag::ABILITY, "kind:%{public}s", abilityInfo_->kind.c_str());
693         TAG_LOGD(AAFwkTag::ABILITY, "type:%{public}d", abilityInfo_->type);
694         TAG_LOGD(AAFwkTag::ABILITY, "orientation:%{public}d", abilityInfo_->orientation);
695         TAG_LOGD(AAFwkTag::ABILITY, "launchMode:%{public}d", abilityInfo_->launchMode);
696         for (auto permission : abilityInfo_->permissions) {
697             TAG_LOGD(AAFwkTag::ABILITY, "permission:%{public}s", permission.c_str());
698         }
699         TAG_LOGD(AAFwkTag::ABILITY, "bundleName:%{public}s", abilityInfo_->bundleName.c_str());
700         TAG_LOGD(AAFwkTag::ABILITY, "applicationName:%{public}s", abilityInfo_->applicationName.c_str());
701     } else {
702         TAG_LOGD(AAFwkTag::ABILITY, "null abilityInfo");
703     }
704 
705     // lifecycle_Event
706     if (lifecycle_ != nullptr) {
707         TAG_LOGD(AAFwkTag::ABILITY, "lifecycle_Event:launchMode:%{public}d", lifecycle_->GetLifecycleState());
708     } else {
709         TAG_LOGD(AAFwkTag::ABILITY, "null lifecycle");
710     }
711 
712     // lifecycle_State
713     if (abilityLifecycleExecutor_ != nullptr) {
714         TAG_LOGD(AAFwkTag::ABILITY, "lifecycle_State:launchMode:%{public}d", abilityLifecycleExecutor_->GetState());
715     } else {
716         TAG_LOGD(AAFwkTag::ABILITY, "null abilityLifecycleExecutor");
717     }
718 
719     // applicationInfo
720     std::shared_ptr<ApplicationInfo> ApplicationInfoPtr = GetApplicationInfo();
721     if (ApplicationInfoPtr != nullptr) {
722         TAG_LOGD(AAFwkTag::ABILITY, "applicationInfo:name:%{public}s", ApplicationInfoPtr->name.c_str());
723         TAG_LOGD(AAFwkTag::ABILITY, "applicationInfo:bundleName:%{public}s", ApplicationInfoPtr->bundleName.c_str());
724     } else {
725         TAG_LOGD(AAFwkTag::ABILITY, "null ApplicationInfoPtr");
726     }
727 }
728 
Dump(const std::vector<std::string> & params,std::vector<std::string> & info)729 void Ability::Dump(const std::vector<std::string> &params, std::vector<std::string> &info)
730 {}
731 
KeepBackgroundRunning(int id,const NotificationRequest & notificationRequest)732 void Ability::KeepBackgroundRunning(int id, const NotificationRequest &notificationRequest)
733 {}
734 
CancelBackgroundRunning()735 void Ability::CancelBackgroundRunning()
736 {}
737 
NormalizeUri(const Uri & uri)738 Uri Ability::NormalizeUri(const Uri &uri)
739 {
740     return uri;
741 }
742 
Delete(const Uri & uri,const NativeRdb::DataAbilityPredicates & predicates)743 int Ability::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates)
744 {
745     return 0;
746 }
747 
GetFileTypes(const Uri & uri,const std::string & mimeTypeFilter)748 std::vector<std::string> Ability::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
749 {
750     return types_;
751 }
752 
OpenFile(const Uri & uri,const std::string & mode)753 int Ability::OpenFile(const Uri &uri, const std::string &mode)
754 {
755     return -1;
756 }
757 
Query(const Uri & uri,const std::vector<std::string> & columns,const NativeRdb::DataAbilityPredicates & predicates)758 std::shared_ptr<NativeRdb::AbsSharedResultSet> Ability::Query(
759     const Uri &uri, const std::vector<std::string> &columns, const NativeRdb::DataAbilityPredicates &predicates)
760 {
761     return nullptr;
762 }
763 
Reload(const Uri & uri,const PacMap & extras)764 bool Ability::Reload(const Uri &uri, const PacMap &extras)
765 {
766     return false;
767 }
768 
BatchInsert(const Uri & uri,const std::vector<NativeRdb::ValuesBucket> & values)769 int Ability::BatchInsert(const Uri &uri, const std::vector<NativeRdb::ValuesBucket> &values)
770 {
771     TAG_LOGD(AAFwkTag::ABILITY, "called");
772     int amount = 0;
773     for (auto it = values.begin(); it != values.end(); it++) {
774         if (Insert(uri, *it) >= 0) {
775             amount++;
776         }
777     }
778     TAG_LOGD(AAFwkTag::ABILITY, "insert amount:%{public}d", amount);
779     return amount;
780 }
781 
ContinueAbilityReversibly(const std::string & deviceId)782 void Ability::ContinueAbilityReversibly(const std::string &deviceId)
783 {
784     if (!VerifySupportForContinuation()) {
785         TAG_LOGE(AAFwkTag::ABILITY, "invalid continuation");
786         return;
787     }
788     continuationManager_->ContinueAbility(true, deviceId);
789 }
790 
GetOriginalDeviceId()791 std::string Ability::GetOriginalDeviceId()
792 {
793     return "";
794 }
795 
GetContinuationState()796 ContinuationState Ability::GetContinuationState()
797 {
798     if (!VerifySupportForContinuation()) {
799         TAG_LOGE(AAFwkTag::ABILITY, "invalid continuation");
800         return ContinuationState::LOCAL_RUNNING;
801     }
802     return continuationManager_->GetContinuationState();
803 }
804 
DenormalizeUri(const Uri & uri)805 Uri Ability::DenormalizeUri(const Uri &uri)
806 {
807     return uri;
808 }
809 
GetLifecycle()810 std::shared_ptr<LifeCycle> Ability::GetLifecycle()
811 {
812     TAG_LOGD(AAFwkTag::ABILITY, "called");
813     return lifecycle_;
814 }
815 
RegisterAbilityLifecycleObserver(const std::shared_ptr<ILifecycleObserver> & observer)816 void Ability::RegisterAbilityLifecycleObserver(const std::shared_ptr<ILifecycleObserver> &observer)
817 {
818     TAG_LOGD(AAFwkTag::ABILITY, "called");
819     if (observer == nullptr) {
820         TAG_LOGE(AAFwkTag::ABILITY, "null observer");
821         return;
822     }
823     if (lifecycle_ == nullptr) {
824         TAG_LOGE(AAFwkTag::ABILITY, "null lifecycle_");
825         return;
826     }
827     lifecycle_->AddObserver(observer);
828 }
829 
UnregisterAbilityLifecycleObserver(const std::shared_ptr<ILifecycleObserver> & observer)830 void Ability::UnregisterAbilityLifecycleObserver(const std::shared_ptr<ILifecycleObserver> &observer)
831 {
832     TAG_LOGD(AAFwkTag::ABILITY, "called");
833     if (observer == nullptr) {
834         TAG_LOGE(AAFwkTag::ABILITY, "null observer");
835         return;
836     }
837     if (lifecycle_ == nullptr) {
838         TAG_LOGE(AAFwkTag::ABILITY, "null lifecycle_");
839         return;
840     }
841     lifecycle_->RemoveObserver(observer);
842 }
843 
GetState()844 AbilityLifecycleExecutor::LifecycleState Ability::GetState()
845 {
846     TAG_LOGD(AAFwkTag::ABILITY, "called");
847 
848     if (abilityLifecycleExecutor_ == nullptr) {
849         TAG_LOGE(AAFwkTag::ABILITY, "null abilityLifecycleExecutor_");
850         return AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED;
851     }
852 
853     return (AbilityLifecycleExecutor::LifecycleState)abilityLifecycleExecutor_->GetState();
854 }
855 
StartAbility(const Want & want)856 ErrCode Ability::StartAbility(const Want &want)
857 {
858     TAG_LOGD(AAFwkTag::ABILITY, "called");
859     return AbilityContext::StartAbility(want, -1);
860 }
861 
PostTask(std::function<void ()> task,long delayTime)862 void Ability::PostTask(std::function<void()> task, long delayTime)
863 {
864     TAG_LOGD(AAFwkTag::ABILITY, "called");
865     TaskHandlerClient::GetInstance()->PostTask(task, delayTime);
866     TAG_LOGD(AAFwkTag::ABILITY, "end");
867 }
868 
OnContinue(WantParams & wantParams)869 int32_t Ability::OnContinue(WantParams &wantParams)
870 {
871     return ContinuationManager::OnContinueResult::REJECT;
872 }
873 
ContinueAbilityWithStack(const std::string & deviceId,uint32_t versionCode)874 void Ability::ContinueAbilityWithStack(const std::string &deviceId, uint32_t versionCode)
875 {
876     if (deviceId.empty()) {
877         TAG_LOGE(AAFwkTag::ABILITY, "empty deviceId");
878         return;
879     }
880 
881     if (!VerifySupportForContinuation()) {
882         TAG_LOGE(AAFwkTag::ABILITY, "invalid continuation");
883         return;
884     }
885     continuationManager_->ContinueAbilityWithStack(deviceId, versionCode);
886 }
887 
ContinueAbility(const std::string & deviceId)888 void Ability::ContinueAbility(const std::string &deviceId)
889 {
890     if (deviceId.empty()) {
891         TAG_LOGE(AAFwkTag::ABILITY, "empty deviceId");
892         return;
893     }
894 
895     if (!VerifySupportForContinuation()) {
896         TAG_LOGE(AAFwkTag::ABILITY, "invalid continuation");
897         return;
898     }
899     continuationManager_->ContinueAbility(false, deviceId);
900 }
901 
OnStartContinuation()902 bool Ability::OnStartContinuation()
903 {
904     return false;
905 }
906 
OnSaveData(WantParams & saveData)907 bool Ability::OnSaveData(WantParams &saveData)
908 {
909     return false;
910 }
911 
OnRestoreData(WantParams & restoreData)912 bool Ability::OnRestoreData(WantParams &restoreData)
913 {
914     return false;
915 }
916 
OnSaveState(int32_t reason,WantParams & wantParams)917 int32_t Ability::OnSaveState(int32_t reason, WantParams &wantParams)
918 {
919     return 0;
920 }
921 
OnCompleteContinuation(int result)922 void Ability::OnCompleteContinuation(int result)
923 {
924     TAG_LOGD(AAFwkTag::ABILITY, "initial");
925     if (continuationManager_ == nullptr) {
926         TAG_LOGE(AAFwkTag::ABILITY, "null Continuation manager_");
927         return;
928     }
929 
930     continuationManager_->ChangeProcessStateToInit();
931 }
932 
OnRemoteTerminated()933 void Ability::OnRemoteTerminated()
934 {}
935 
DispatchLifecycleOnForeground(const Want & want)936 void Ability::DispatchLifecycleOnForeground(const Want &want)
937 {
938     if (abilityLifecycleExecutor_ == nullptr) {
939         TAG_LOGE(AAFwkTag::ABILITY, "null abilityLifecycleExecutor_");
940         return;
941     }
942     if (abilityInfo_ != nullptr && abilityInfo_->isStageBasedModel) {
943         abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::FOREGROUND_NEW);
944     } else {
945         abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::INACTIVE);
946     }
947     if (lifecycle_ == nullptr) {
948         TAG_LOGE(AAFwkTag::ABILITY, "null lifecycle_");
949         return;
950     }
951     lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_FOREGROUND, want);
952 }
953 
VerifySupportForContinuation()954 bool Ability::VerifySupportForContinuation()
955 {
956     if (continuationManager_ == nullptr) {
957         TAG_LOGE(AAFwkTag::ABILITY, "null Continuation manager");
958         return false;
959     }
960     return true;
961 }
962 
HandleCreateAsContinuation(const Want & want)963 void Ability::HandleCreateAsContinuation(const Want &want)
964 {
965     if (!IsFlagExists(Want::FLAG_ABILITY_CONTINUATION, want.GetFlags())) {
966         TAG_LOGD(AAFwkTag::ABILITY, "not continuated ability");
967         return;
968     }
969 
970     // check whether it needs reversible
971     bool reversible = false;
972     reversible = IsFlagExists(Want::FLAG_ABILITY_CONTINUATION_REVERSIBLE, want.GetFlags());
973     if (!VerifySupportForContinuation()) {
974         TAG_LOGE(AAFwkTag::ABILITY, "invalid continuation");
975         return;
976     }
977     bool success = continuationManager_->RestoreData(
978         want.GetParams(), reversible, want.GetStringParam(ContinuationHandler::ORIGINAL_DEVICE_ID));
979     if (success && reversible) {
980         // Register this ability to receive reverse continuation callback.
981         std::weak_ptr<IReverseContinuationSchedulerReplicaHandler> ReplicaHandler = continuationHandler_;
982         reverseContinuationSchedulerReplica_ = sptr<ReverseContinuationSchedulerReplica>(
983             new (std::nothrow) ReverseContinuationSchedulerReplica(handler_, ReplicaHandler));
984 
985         if (reverseContinuationSchedulerReplica_ == nullptr) {
986             TAG_LOGE(AAFwkTag::ABILITY, "null reverseContinuationSchedulerReplica");
987             return;
988         }
989     }
990 
991     int sessionId = want.GetIntParam(DMS_SESSION_ID, DEFAULT_DMS_SESSION_ID);
992     std::string originDeviceId = want.GetStringParam(DMS_ORIGIN_DEVICE_ID);
993     TAG_LOGD(AAFwkTag::ABILITY, "notify complete continuation");
994     continuationManager_->NotifyCompleteContinuation(
995         originDeviceId, sessionId, success, reverseContinuationSchedulerReplica_);
996 }
997 
HandleCreateAsRecovery(const Want & want)998 void Ability::HandleCreateAsRecovery(const Want &want)
999 {
1000     TAG_LOGD(AAFwkTag::ABILITY, "called");
1001 }
1002 
IsFlagExists(unsigned int flag,unsigned int flagSet)1003 bool Ability::IsFlagExists(unsigned int flag, unsigned int flagSet)
1004 {
1005     return (flag & flagSet) == flag;
1006 }
1007 
OnSetCaller()1008 Uri Ability::OnSetCaller()
1009 {
1010     return Uri("");
1011 }
1012 
CreatePostEventTimeouter(std::string taskstr)1013 std::shared_ptr<AbilityPostEventTimeout> Ability::CreatePostEventTimeouter(std::string taskstr)
1014 {
1015     return std::make_shared<AbilityPostEventTimeout>(taskstr, handler_);
1016 }
1017 
StartBackgroundRunning(const AbilityRuntime::WantAgent::WantAgent & wantAgent)1018 int Ability::StartBackgroundRunning(const AbilityRuntime::WantAgent::WantAgent &wantAgent)
1019 {
1020 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
1021     auto bundleMgrHelper = DelayedSingleton<BundleMgrHelper>::GetInstance();
1022     if (bundleMgrHelper == nullptr) {
1023         TAG_LOGE(AAFwkTag::ABILITY, "bundleMgrHelper failed");
1024         return ERR_NULL_OBJECT;
1025     }
1026     if (abilityInfo_ == nullptr) {
1027         TAG_LOGE(AAFwkTag::ABILITY, "null ability info");
1028         return ERR_INVALID_VALUE;
1029     }
1030     Want want;
1031     want.SetAction("action.system.home");
1032     want.AddEntity("entity.system.home");
1033     want.SetElementName("", abilityInfo_->bundleName, "", "");
1034     AppExecFwk::AbilityInfo abilityInfo;
1035     bundleMgrHelper->QueryAbilityInfo(want, abilityInfo);
1036     std::string appName = bundleMgrHelper->GetAbilityLabel(abilityInfo_->bundleName, abilityInfo.name);
1037     uint32_t defaultBgMode = 0;
1038     BackgroundTaskMgr::ContinuousTaskParam taskParam = BackgroundTaskMgr::ContinuousTaskParam(false, defaultBgMode,
1039         std::make_shared<AbilityRuntime::WantAgent::WantAgent>(wantAgent), abilityInfo_->name, GetToken(), appName);
1040     return BackgroundTaskMgr::BackgroundTaskMgrHelper::RequestStartBackgroundRunning(taskParam);
1041 #else
1042     return ERR_INVALID_OPERATION;
1043 #endif
1044 }
1045 
StopBackgroundRunning()1046 int Ability::StopBackgroundRunning()
1047 {
1048 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
1049     return BackgroundTaskMgr::BackgroundTaskMgrHelper::RequestStopBackgroundRunning(abilityInfo_->name, GetToken());
1050 #else
1051     return ERR_INVALID_OPERATION;
1052 #endif
1053 }
1054 
SetStartAbilitySetting(std::shared_ptr<AbilityStartSetting> setting)1055 void Ability::SetStartAbilitySetting(std::shared_ptr<AbilityStartSetting> setting)
1056 {
1057     TAG_LOGD(AAFwkTag::ABILITY, "called");
1058     setting_ = setting;
1059 }
1060 
SetLaunchParam(const AAFwk::LaunchParam & launchParam)1061 void Ability::SetLaunchParam(const AAFwk::LaunchParam &launchParam)
1062 {
1063     TAG_LOGD(AAFwkTag::ABILITY, "called");
1064     launchParam_ = launchParam;
1065 }
1066 
GetLaunchParam() const1067 const AAFwk::LaunchParam& Ability::GetLaunchParam() const
1068 {
1069     return launchParam_;
1070 }
1071 
ExecuteBatch(const std::vector<std::shared_ptr<DataAbilityOperation>> & operations)1072 std::vector<std::shared_ptr<DataAbilityResult>> Ability::ExecuteBatch(
1073     const std::vector<std::shared_ptr<DataAbilityOperation>> &operations)
1074 {
1075     TAG_LOGD(AAFwkTag::ABILITY, "called");
1076     std::vector<std::shared_ptr<DataAbilityResult>> results;
1077     if (abilityInfo_ == nullptr) {
1078         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo");
1079         return results;
1080     }
1081     if (abilityInfo_->type != AppExecFwk::AbilityType::DATA) {
1082         TAG_LOGE(AAFwkTag::ABILITY, "failed,abilityType:%{public}d", abilityInfo_->type);
1083         return results;
1084     }
1085     size_t len = operations.size();
1086     TAG_LOGD(AAFwkTag::ABILITY, "null operation, len %{public}zu", len);
1087     for (size_t i = 0; i < len; i++) {
1088         std::shared_ptr<DataAbilityOperation> operation = operations[i];
1089         if (operation == nullptr) {
1090             TAG_LOGD(AAFwkTag::ABILITY, "null operation, create DataAbilityResult");
1091             results.push_back(std::make_shared<DataAbilityResult>(0));
1092             continue;
1093         }
1094         ExecuteOperation(operation, results, i);
1095     }
1096     TAG_LOGD(AAFwkTag::ABILITY, "end,%{public}zu", results.size());
1097     return results;
1098 }
ExecuteOperation(std::shared_ptr<DataAbilityOperation> & operation,std::vector<std::shared_ptr<DataAbilityResult>> & results,int index)1099 void Ability::ExecuteOperation(std::shared_ptr<DataAbilityOperation> &operation,
1100     std::vector<std::shared_ptr<DataAbilityResult>> &results, int index)
1101 {
1102     TAG_LOGD(AAFwkTag::ABILITY, "start, index=%{public}d", index);
1103     if (abilityInfo_->type != AppExecFwk::AbilityType::DATA) {
1104         TAG_LOGE(AAFwkTag::ABILITY, "failed,type:%{public}d", abilityInfo_->type);
1105         return;
1106     }
1107     if (index < 0) {
1108         TAG_LOGE(AAFwkTag::ABILITY, "invalid index:%{public}d", index);
1109         return;
1110     }
1111     if (operation == nullptr) {
1112         TAG_LOGW(AAFwkTag::ABILITY, "null operation");
1113         results.push_back(std::make_shared<DataAbilityResult>(0));
1114         return;
1115     }
1116 
1117     int numRows = 0;
1118     std::shared_ptr<NativeRdb::ValuesBucket> valuesBucket = ParseValuesBucketReference(results, operation, index);
1119     auto predicates = ParsePredictionArgsReference(results, operation, index);
1120     if (operation->IsInsertOperation()) {
1121         TAG_LOGD(AAFwkTag::ABILITY, "IsInsertOperation");
1122         numRows = Insert(*(operation->GetUri().get()), *valuesBucket);
1123     } else if (operation->IsDeleteOperation() && predicates) {
1124         TAG_LOGD(AAFwkTag::ABILITY, "IsDeleteOperation");
1125         numRows = Delete(*(operation->GetUri().get()), *predicates);
1126     } else if (operation->IsUpdateOperation() && predicates) {
1127         TAG_LOGD(AAFwkTag::ABILITY, "IsUpdateOperation");
1128         numRows = Update(*(operation->GetUri().get()), *valuesBucket, *predicates);
1129     } else if (operation->IsAssertOperation() && predicates) {
1130         TAG_LOGD(AAFwkTag::ABILITY, "IsAssertOperation");
1131         std::vector<std::string> columns;
1132         auto queryResult = Query(*(operation->GetUri().get()), columns, *predicates);
1133         if (queryResult == nullptr) {
1134             TAG_LOGE(AAFwkTag::ABILITY, "null queryResult");
1135             results.push_back(std::make_shared<DataAbilityResult>(0));
1136             return;
1137         }
1138         (void)CheckAssertQueryResult(queryResult, operation->GetValuesBucket());
1139         queryResult->Close();
1140     } else {
1141         TAG_LOGE(AAFwkTag::ABILITY, "bad type %{public}d", operation->GetType());
1142     }
1143     if (operation->GetExpectedCount() == numRows) {
1144         if (operation->GetUri() != nullptr) {
1145             results.push_back(std::make_shared<DataAbilityResult>(*operation->GetUri(), numRows));
1146         } else {
1147             results.push_back(std::make_shared<DataAbilityResult>(Uri(std::string("")), numRows));
1148         }
1149     }
1150 }
1151 
ParsePredictionArgsReference(std::vector<std::shared_ptr<DataAbilityResult>> & results,std::shared_ptr<DataAbilityOperation> & operation,int numRefs)1152 std::shared_ptr<NativeRdb::DataAbilityPredicates> Ability::ParsePredictionArgsReference(
1153     std::vector<std::shared_ptr<DataAbilityResult>> &results, std::shared_ptr<DataAbilityOperation> &operation,
1154     int numRefs)
1155 {
1156     if (operation == nullptr) {
1157         TAG_LOGE(AAFwkTag::ABILITY, "null intput");
1158         return nullptr;
1159     }
1160 
1161     std::map<int, int> predicatesBackReferencesMap = operation->GetDataAbilityPredicatesBackReferences();
1162     if (predicatesBackReferencesMap.empty()) {
1163         return operation->GetDataAbilityPredicates();
1164     }
1165 
1166     std::vector<std::string> strPredicatesList;
1167     strPredicatesList.clear();
1168     std::shared_ptr<NativeRdb::DataAbilityPredicates> predicates = operation->GetDataAbilityPredicates();
1169     if (predicates == nullptr) {
1170         TAG_LOGD(AAFwkTag::ABILITY, "null predicates");
1171     } else {
1172         TAG_LOGD(AAFwkTag::ABILITY, "operation->GetDataAbilityPredicates isn`t nullptr");
1173         strPredicatesList = predicates->GetWhereArgs();
1174     }
1175 
1176     if (strPredicatesList.empty()) {
1177         TAG_LOGE(AAFwkTag::ABILITY, "GetWhereArgs()"
1178                 "error strList empty");
1179     }
1180 
1181     for (auto iterMap : predicatesBackReferencesMap) {
1182         TAG_LOGD(AAFwkTag::ABILITY, "predicatesBackReferencesMap first:%{public}d second:%{public}d",
1183             iterMap.first,
1184             iterMap.second);
1185         int tempCount = ChangeRef2Value(results, numRefs, iterMap.second);
1186         if (tempCount < 0) {
1187             TAG_LOGE(AAFwkTag::ABILITY, "tempCount:%{public}d", tempCount);
1188             continue;
1189         }
1190         std::string strPredicates = std::to_string(tempCount);
1191         strPredicatesList.push_back(strPredicates);
1192     }
1193 
1194     if (predicates) {
1195         predicates->SetWhereArgs(strPredicatesList);
1196     }
1197 
1198     return predicates;
1199 }
1200 
ParseValuesBucketReference(std::vector<std::shared_ptr<DataAbilityResult>> & results,std::shared_ptr<DataAbilityOperation> & operation,int numRefs)1201 std::shared_ptr<NativeRdb::ValuesBucket> Ability::ParseValuesBucketReference(
1202     std::vector<std::shared_ptr<DataAbilityResult>> &results, std::shared_ptr<DataAbilityOperation> &operation,
1203     int numRefs)
1204 {
1205     if (operation == nullptr) {
1206         TAG_LOGE(AAFwkTag::ABILITY, "null intput");
1207         return nullptr;
1208     }
1209     if (operation->GetValuesBucketReferences() == nullptr) {
1210         return operation->GetValuesBucket();
1211     }
1212 
1213     NativeRdb::ValuesBucket retValueBucket;
1214     retValueBucket.Clear();
1215     if (operation->GetValuesBucket() != nullptr) {
1216         retValueBucket = *operation->GetValuesBucket();
1217     }
1218 
1219     std::map<std::string, NativeRdb::ValueObject> valuesMapReferences;
1220     operation->GetValuesBucketReferences()->GetAll(valuesMapReferences);
1221 
1222     for (auto itermap : valuesMapReferences) {
1223         std::string key = itermap.first;
1224         TAG_LOGD(AAFwkTag::ABILITY, "key:%{public}s", key.c_str());
1225         NativeRdb::ValueObject obj;
1226         if (!operation->GetValuesBucketReferences()->GetObject(key, obj)) {
1227             TAG_LOGE(AAFwkTag::ABILITY, "GetObject error");
1228             continue;
1229         }
1230         switch (obj.GetType()) {
1231             case NativeRdb::ValueObjectType::TYPE_INT:
1232                 ParseIntValue(obj, key, retValueBucket);
1233                 break;
1234             case NativeRdb::ValueObjectType::TYPE_DOUBLE:
1235                 ParseDoubleValue(obj, key, retValueBucket);
1236                 break;
1237             case NativeRdb::ValueObjectType::TYPE_STRING:
1238                 ParseStringValue(obj, key, retValueBucket);
1239                 break;
1240             case NativeRdb::ValueObjectType::TYPE_BLOB:
1241                 ParseBlobValue(obj, key, retValueBucket);
1242                 break;
1243             case NativeRdb::ValueObjectType::TYPE_BOOL:
1244                 ParseBoolValue(obj, key, retValueBucket);
1245                 break;
1246             default:
1247                 retValueBucket.PutNull(key);
1248                 break;
1249         }
1250     }
1251 
1252     std::map<std::string, NativeRdb::ValueObject> valuesMap;
1253     retValueBucket.GetAll(valuesMap);
1254     return std::make_shared<NativeRdb::ValuesBucket>(valuesMap);
1255 }
1256 
ParseIntValue(const NativeRdb::ValueObject & obj,const std::string & key,NativeRdb::ValuesBucket & retValueBucket) const1257 void Ability::ParseIntValue(const NativeRdb::ValueObject &obj, const std::string &key,
1258     NativeRdb::ValuesBucket &retValueBucket) const
1259 {
1260     int val = 0;
1261     if (obj.GetInt(val) != 0) {
1262         TAG_LOGE(AAFwkTag::ABILITY, "GetInt failed");
1263         return;
1264     }
1265     TAG_LOGD(AAFwkTag::ABILITY, "retValueBucket->PutInt(%{public}s, %{public}d)", key.c_str(), val);
1266     retValueBucket.PutInt(key, val);
1267 }
1268 
ParseDoubleValue(const NativeRdb::ValueObject & obj,const std::string & key,NativeRdb::ValuesBucket & retValueBucket) const1269 void Ability::ParseDoubleValue(const NativeRdb::ValueObject &obj, const std::string &key,
1270     NativeRdb::ValuesBucket &retValueBucket) const
1271 {
1272     double val = 0.0;
1273     if (obj.GetDouble(val) != 0) {
1274         TAG_LOGE(AAFwkTag::ABILITY, "GetDouble failed");
1275         return;
1276     }
1277     TAG_LOGD(AAFwkTag::ABILITY, "retValueBucket->PutDouble(%{public}s, %{public}f)", key.c_str(), val);
1278     retValueBucket.PutDouble(key, val);
1279 }
1280 
ParseStringValue(const NativeRdb::ValueObject & obj,const std::string & key,NativeRdb::ValuesBucket & retValueBucket) const1281 void Ability::ParseStringValue(const NativeRdb::ValueObject &obj, const std::string &key,
1282     NativeRdb::ValuesBucket &retValueBucket) const
1283 {
1284     std::string val = "";
1285     if (obj.GetString(val) != 0) {
1286         TAG_LOGE(AAFwkTag::ABILITY, "GetString failed");
1287         return;
1288     }
1289     TAG_LOGD(AAFwkTag::ABILITY, "retValueBucket->PutString(%{public}s, %{public}s)", key.c_str(), val.c_str());
1290     retValueBucket.PutString(key, val);
1291 }
1292 
ParseBlobValue(const NativeRdb::ValueObject & obj,const std::string & key,NativeRdb::ValuesBucket & retValueBucket) const1293 void Ability::ParseBlobValue(const NativeRdb::ValueObject &obj, const std::string &key,
1294     NativeRdb::ValuesBucket &retValueBucket) const
1295 {
1296     std::vector<uint8_t> val;
1297     if (obj.GetBlob(val) != 0) {
1298         TAG_LOGE(AAFwkTag::ABILITY, "GetBlob failed");
1299         return;
1300     }
1301     TAG_LOGD(AAFwkTag::ABILITY, "retValueBucket->PutBlob(%{public}s, %{public}zu)", key.c_str(), val.size());
1302     retValueBucket.PutBlob(key, val);
1303 }
1304 
ParseBoolValue(const NativeRdb::ValueObject & obj,const std::string & key,NativeRdb::ValuesBucket & retValueBucket) const1305 void Ability::ParseBoolValue(const NativeRdb::ValueObject &obj, const std::string &key,
1306     NativeRdb::ValuesBucket &retValueBucket) const
1307 {
1308     bool val = false;
1309     if (obj.GetBool(val) != 0) {
1310         TAG_LOGE(AAFwkTag::ABILITY, "GetBool failed");
1311         return;
1312     }
1313     TAG_LOGD(AAFwkTag::ABILITY, "retValueBucket->PutBool(%{public}s, %{public}s)", key.c_str(), val ? "true" : "false");
1314     retValueBucket.PutBool(key, val);
1315 }
1316 
ChangeRef2Value(std::vector<std::shared_ptr<DataAbilityResult>> & results,int numRefs,int index)1317 int Ability::ChangeRef2Value(std::vector<std::shared_ptr<DataAbilityResult>> &results, int numRefs, int index)
1318 {
1319     int retval = -1;
1320     if (index >= numRefs) {
1321         TAG_LOGE(AAFwkTag::ABILITY, "index >= numRefs");
1322         return retval;
1323     }
1324 
1325     if (index >= static_cast<int>(results.size())) {
1326         TAG_LOGE(AAFwkTag::ABILITY, "index:%{public}d >= results.size():%{public}zu",
1327             index, results.size());
1328         return retval;
1329     }
1330 
1331     std::shared_ptr<DataAbilityResult> refResult = results[index];
1332     if (refResult == nullptr) {
1333         TAG_LOGE(AAFwkTag::ABILITY, "No.%{public}d refResult", index);
1334         return retval;
1335     }
1336 
1337     if (refResult->GetUri().ToString().empty()) {
1338         retval = refResult->GetCount();
1339     } else {
1340         retval = DataUriUtils::GetId(refResult->GetUri());
1341     }
1342 
1343     return retval;
1344 }
1345 
CheckAssertQueryResult(std::shared_ptr<NativeRdb::AbsSharedResultSet> & queryResult,std::shared_ptr<NativeRdb::ValuesBucket> && valuesBucket)1346 bool Ability::CheckAssertQueryResult(std::shared_ptr<NativeRdb::AbsSharedResultSet> &queryResult,
1347     std::shared_ptr<NativeRdb::ValuesBucket> &&valuesBucket)
1348 {
1349     if (queryResult == nullptr) {
1350         TAG_LOGE(AAFwkTag::ABILITY, "intput queryResult");
1351         return true;
1352     }
1353 
1354     if (valuesBucket == nullptr) {
1355         TAG_LOGE(AAFwkTag::ABILITY, "intput valuesBucket");
1356         return true;
1357     }
1358 
1359     std::map<std::string, NativeRdb::ValueObject> valuesMap;
1360     valuesBucket->GetAll(valuesMap);
1361     if (valuesMap.empty()) {
1362         TAG_LOGE(AAFwkTag::ABILITY, "empty valuesMap");
1363         return true;
1364     }
1365     int count = 0;
1366     if (queryResult->GetRowCount(count) != 0) {
1367         TAG_LOGE(AAFwkTag::ABILITY, "getRowCount:0");
1368         return true;
1369     }
1370 
1371     for (auto iterMap : valuesMap) {
1372         std::string strObject;
1373         if (iterMap.second.GetString(strObject) != 0) {
1374             TAG_LOGE(AAFwkTag::ABILITY, "strObject failed");
1375             continue;
1376         }
1377         if (strObject.empty()) {
1378             TAG_LOGE(AAFwkTag::ABILITY, "empty strObject");
1379             continue;
1380         }
1381         for (int i = 0; i < count; ++i) {
1382             std::string strName;
1383             if (queryResult->GetString(i, strName) != 0) {
1384                 TAG_LOGE(AAFwkTag::ABILITY, "strName failed");
1385                 continue;
1386             }
1387             if (strName.empty()) {
1388                 TAG_LOGE(AAFwkTag::ABILITY, "empty strName");
1389                 continue;
1390             }
1391             if (strName == strObject) {
1392                 TAG_LOGE(AAFwkTag::ABILITY, "strName=strObject");
1393                 continue;
1394             }
1395 
1396             return false;
1397         }
1398     }
1399 
1400     return true;
1401 }
1402 
CallRequest()1403 sptr<IRemoteObject> Ability::CallRequest()
1404 {
1405     return nullptr;
1406 }
1407 
StartFeatureAbilityForResult(const Want & want,int requestCode,FeatureAbilityTask && task)1408 ErrCode Ability::StartFeatureAbilityForResult(const Want &want, int requestCode, FeatureAbilityTask &&task)
1409 {
1410     TAG_LOGD(AAFwkTag::ABILITY, "called");
1411     resultCallbacks_.insert(make_pair(requestCode, std::move(task)));
1412     ErrCode err = StartAbilityForResult(want, requestCode);
1413     TAG_LOGD(AAFwkTag::ABILITY, "ret:%{public}d", err);
1414     return err;
1415 }
1416 
OnFeatureAbilityResult(int requestCode,int resultCode,const Want & want)1417 void Ability::OnFeatureAbilityResult(int requestCode, int resultCode, const Want &want)
1418 {
1419     TAG_LOGD(AAFwkTag::ABILITY, "called");
1420     auto callback = resultCallbacks_.find(requestCode);
1421     if (callback != resultCallbacks_.end()) {
1422         if (callback->second) {
1423             callback->second(resultCode, want);
1424         }
1425         resultCallbacks_.erase(requestCode);
1426     }
1427     TAG_LOGD(AAFwkTag::ABILITY, "end");
1428 }
1429 
IsUseNewStartUpRule()1430 bool Ability::IsUseNewStartUpRule()
1431 {
1432     if (!isNewRuleFlagSetted_ && setWant_) {
1433         startUpNewRule_ = setWant_->GetBoolParam(COMPONENT_STARTUP_NEW_RULES, false);
1434         isNewRuleFlagSetted_ = true;
1435     }
1436     return startUpNewRule_;
1437 }
1438 
EnableAbilityRecovery(const std::shared_ptr<AbilityRecovery> & abilityRecovery)1439 void Ability::EnableAbilityRecovery(const std::shared_ptr<AbilityRecovery>& abilityRecovery)
1440 {
1441     TAG_LOGD(AAFwkTag::ABILITY, "called");
1442 }
1443 
OnShare(WantParams & wantParams)1444 int32_t Ability::OnShare(WantParams &wantParams)
1445 {
1446     return ERR_OK;
1447 }
1448 
1449 #ifdef SUPPORT_GRAPHICS
PrintDrawnCompleted()1450 bool Ability::PrintDrawnCompleted()
1451 {
1452     return AbilityContext::PrintDrawnCompleted();
1453 }
1454 
OnSceneCreated()1455 void Ability::OnSceneCreated()
1456 {
1457     TAG_LOGD(AAFwkTag::ABILITY, "called");
1458 }
1459 
OnSceneRestored()1460 void Ability::OnSceneRestored()
1461 {
1462     TAG_LOGD(AAFwkTag::ABILITY, "called");
1463 }
1464 
onSceneDestroyed()1465 void Ability::onSceneDestroyed()
1466 {
1467     TAG_LOGD(AAFwkTag::ABILITY, "called");
1468 }
1469 
OnForeground(const Want & want)1470 void Ability::OnForeground(const Want &want)
1471 {
1472     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1473     TAG_LOGD(AAFwkTag::ABILITY, "called");
1474     DoOnForeground(want);
1475     DispatchLifecycleOnForeground(want);
1476     TAG_LOGD(AAFwkTag::ABILITY, "end");
1477     AAFwk::EventInfo eventInfo;
1478     eventInfo.bundleName = want.GetElement().GetBundleName();
1479     eventInfo.moduleName = want.GetElement().GetModuleName();
1480     eventInfo.abilityName = want.GetElement().GetAbilityName();
1481     eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
1482     if (abilityInfo_ != nullptr) {
1483         eventInfo.bundleType = static_cast<int32_t>(abilityInfo_->applicationInfo.bundleType);
1484     } else {
1485         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
1486     }
1487     AAFwk::EventReport::SendAbilityEvent(AAFwk::EventName::ABILITY_ONFOREGROUND,
1488         HiSysEventType::BEHAVIOR, eventInfo);
1489 }
1490 
OnBackground()1491 void Ability::OnBackground()
1492 {
1493     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1494     TAG_LOGD(AAFwkTag::ABILITY, "called");
1495     if (abilityInfo_ == nullptr) {
1496         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
1497         return;
1498     }
1499     if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) {
1500         if (abilityInfo_->isStageBasedModel) {
1501             if (scene_ != nullptr) {
1502                 TAG_LOGD(AAFwkTag::ABILITY, "sceneFlag:%{public}d", sceneFlag_);
1503                 scene_->GoBackground(sceneFlag_);
1504             }
1505         } else {
1506             if (abilityWindow_ == nullptr) {
1507                 TAG_LOGE(AAFwkTag::ABILITY, "null abilityWindow_");
1508                 return;
1509             }
1510             TAG_LOGD(AAFwkTag::ABILITY, "sceneFlag:%{public}d", sceneFlag_);
1511             abilityWindow_->OnPostAbilityBackground(sceneFlag_);
1512         }
1513     }
1514 
1515     if (abilityLifecycleExecutor_ == nullptr) {
1516         TAG_LOGE(AAFwkTag::ABILITY, "null abilityLifecycleExecutor_");
1517         return;
1518     }
1519 
1520     if (abilityInfo_->isStageBasedModel) {
1521         abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::BACKGROUND_NEW);
1522     } else {
1523         abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::BACKGROUND);
1524     }
1525 
1526     if (lifecycle_ == nullptr) {
1527         TAG_LOGE(AAFwkTag::ABILITY, "null lifecycle_");
1528         return;
1529     }
1530     lifecycle_->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND);
1531     AAFwk::EventInfo eventInfo;
1532     eventInfo.bundleName = abilityInfo_->bundleName;
1533     eventInfo.moduleName = abilityInfo_->moduleName;
1534     eventInfo.abilityName = abilityInfo_->name;
1535     eventInfo.bundleType = static_cast<int32_t>(abilityInfo_->applicationInfo.bundleType);
1536     AAFwk::EventReport::SendAbilityEvent(AAFwk::EventName::ABILITY_ONBACKGROUND,
1537         HiSysEventType::BEHAVIOR, eventInfo);
1538 }
1539 
OnBackPress()1540 bool Ability::OnBackPress()
1541 {
1542     TAG_LOGD(AAFwkTag::ABILITY, "call");
1543     return false;
1544 }
1545 
OnPrepareTerminate()1546 bool Ability::OnPrepareTerminate()
1547 {
1548     TAG_LOGD(AAFwkTag::ABILITY, "call");
1549     return false;
1550 }
1551 
OnKeyDown(const std::shared_ptr<MMI::KeyEvent> & keyEvent)1552 void Ability::OnKeyDown(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
1553 {
1554     TAG_LOGD(AAFwkTag::ABILITY, "called");
1555 }
1556 
OnKeyUp(const std::shared_ptr<MMI::KeyEvent> & keyEvent)1557 void Ability::OnKeyUp(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
1558 {
1559     TAG_LOGD(AAFwkTag::ABILITY, "called");
1560     auto code = keyEvent->GetKeyCode();
1561     if (code == MMI::KeyEvent::KEYCODE_BACK) {
1562         TAG_LOGD(AAFwkTag::ABILITY, "back key pressed");
1563         OnBackPressed();
1564     }
1565 }
1566 
OnPointerEvent(std::shared_ptr<MMI::PointerEvent> & pointerEvent)1567 void Ability::OnPointerEvent(std::shared_ptr<MMI::PointerEvent>& pointerEvent)
1568 {
1569     TAG_LOGD(AAFwkTag::ABILITY, "called");
1570 }
1571 
InitWindow(int32_t displayId,sptr<Rosen::WindowOption> option)1572 void Ability::InitWindow(int32_t displayId, sptr<Rosen::WindowOption> option)
1573 {
1574     if (abilityWindow_ == nullptr) {
1575         TAG_LOGE(AAFwkTag::ABILITY, "null Ability window");
1576         return;
1577     }
1578     abilityWindow_->SetSessionToken(sessionToken_);
1579     abilityWindow_->InitWindow(abilityContext_, sceneListener_, displayId, option, securityFlag_);
1580 }
1581 
GetWindow()1582 const sptr<Rosen::Window> Ability::GetWindow()
1583 {
1584     if (abilityWindow_ == nullptr) {
1585         TAG_LOGD(AAFwkTag::ABILITY, "null Ability window");
1586         return nullptr;
1587     }
1588     return abilityWindow_->GetWindow();
1589 }
1590 
GetScene()1591 std::shared_ptr<Rosen::WindowScene> Ability::GetScene()
1592 {
1593     return scene_;
1594 }
1595 
HasWindowFocus()1596 bool Ability::HasWindowFocus()
1597 {
1598     if (abilityInfo_ == nullptr) {
1599         TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
1600         return false;
1601     }
1602 
1603     if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) {
1604         return bWindowFocus_;
1605     }
1606 
1607     return false;
1608 }
1609 
SetShowOnLockScreen(bool showOnLockScreen)1610 void Ability::SetShowOnLockScreen(bool showOnLockScreen)
1611 {
1612     TAG_LOGD(AAFwkTag::ABILITY, "showOnLockScreen:%{public}d", showOnLockScreen);
1613     showOnLockScreen_ = showOnLockScreen;
1614     sptr<Rosen::Window> window = nullptr;
1615     if (abilityWindow_ == nullptr || (window = abilityWindow_->GetWindow()) == nullptr) {
1616         TAG_LOGE(AAFwkTag::ABILITY, "window");
1617         return;
1618     }
1619     TAG_LOGD(AAFwkTag::ABILITY, "addWindowFlag, showOnLockScreen:%{public}d",
1620         showOnLockScreen);
1621     if (showOnLockScreen) {
1622         window->AddWindowFlag(Rosen::WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED);
1623         if (abilityInfo_ == nullptr) {
1624             TAG_LOGE(AAFwkTag::ABILITY, "null abilityInfo_");
1625             return;
1626         }
1627         AAFwk::EventInfo eventInfo;
1628         eventInfo.bundleName = abilityInfo_->bundleName;
1629         eventInfo.moduleName = abilityInfo_->moduleName;
1630         eventInfo.abilityName = abilityInfo_->name;
1631         AAFwk::EventReport::SendKeyEvent(AAFwk::EventName::FA_SHOW_ON_LOCK, HiSysEventType::BEHAVIOR, eventInfo);
1632     } else {
1633         window->RemoveWindowFlag(Rosen::WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED);
1634     }
1635 }
1636 
OnLeaveForeground()1637 void Ability::OnLeaveForeground()
1638 {}
1639 
SetVolumeTypeAdjustedByKey(int volumeType)1640 void Ability::SetVolumeTypeAdjustedByKey(int volumeType)
1641 {}
1642 
SetWindowBackgroundColor(int red,int green,int blue)1643 int Ability::SetWindowBackgroundColor(int red, int green, int blue)
1644 {
1645     return -1;
1646 }
1647 
GetContentInfo()1648 std::string Ability::GetContentInfo()
1649 {
1650     if (scene_ == nullptr) {
1651         return "";
1652     }
1653     return scene_->GetContentInfo(Rosen::BackupAndRestoreType::CONTINUATION);
1654 }
1655 
OnWindowFocusChanged(bool hasFocus)1656 void Ability::OnWindowFocusChanged(bool hasFocus)
1657 {}
1658 
OnTopActiveAbilityChanged(bool topActive)1659 void Ability::OnTopActiveAbilityChanged(bool topActive)
1660 {}
1661 
OnCreate(const Want & want)1662 FormProviderInfo Ability::OnCreate(const Want &want)
1663 {
1664     TAG_LOGD(AAFwkTag::ABILITY, "called");
1665     FormProviderInfo formProviderInfo;
1666     return formProviderInfo;
1667 }
1668 
OnShare(int64_t formId,AAFwk::WantParams & wantParams)1669 bool Ability::OnShare(int64_t formId, AAFwk::WantParams &wantParams)
1670 {
1671     TAG_LOGD(AAFwkTag::ABILITY, "called");
1672     return false;
1673 }
1674 
OnDelete(const int64_t formId)1675 void Ability::OnDelete(const int64_t formId)
1676 {}
1677 
OnUpdate(const int64_t formId,const AAFwk::WantParams & wantParams)1678 void Ability::OnUpdate(const int64_t formId, const AAFwk::WantParams &wantParams)
1679 {}
1680 
OnCastTemptoNormal(const int64_t formId)1681 void Ability::OnCastTemptoNormal(const int64_t formId)
1682 {}
1683 
OnVisibilityChanged(const std::map<int64_t,int32_t> & formEventsMap)1684 void Ability::OnVisibilityChanged(const std::map<int64_t, int32_t> &formEventsMap)
1685 {}
1686 
OnTriggerEvent(const int64_t formId,const std::string & message)1687 void Ability::OnTriggerEvent(const int64_t formId, const std::string &message)
1688 {}
1689 
OnAcquireFormState(const Want & want)1690 FormState Ability::OnAcquireFormState(const Want &want)
1691 {
1692     return FormState::DEFAULT;
1693 }
1694 
SetSceneListener(const sptr<Rosen::IWindowLifeCycle> & listener)1695 void Ability::SetSceneListener(const sptr<Rosen::IWindowLifeCycle> &listener)
1696 {
1697     sceneListener_ = listener;
1698 }
1699 
GetWindowOption(const Want & want)1700 sptr<Rosen::WindowOption> Ability::GetWindowOption(const Want &want)
1701 {
1702     sptr<Rosen::WindowOption> option = new Rosen::WindowOption();
1703     if (option == nullptr) {
1704         TAG_LOGE(AAFwkTag::ABILITY, "null option");
1705         return nullptr;
1706     }
1707     auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE,
1708         AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED);
1709     TAG_LOGD(AAFwkTag::ABILITY, "window mode:%{public}d", windowMode);
1710     option->SetWindowMode(static_cast<Rosen::WindowMode>(windowMode));
1711     bool showOnLockScreen = false;
1712     if (abilityInfo_) {
1713         std::vector<CustomizeData> datas = abilityInfo_->metaData.customizeData;
1714         for (CustomizeData data : datas) {
1715             if (data.name == SHOW_ON_LOCK_SCREEN) {
1716                 showOnLockScreen = true;
1717             }
1718         }
1719     }
1720     if (showOnLockScreen_ || showOnLockScreen) {
1721         TAG_LOGD(AAFwkTag::ABILITY, "add window flag WINDOW_FLAG_SHOW_WHEN_LOCKED");
1722         option->AddWindowFlag(Rosen::WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED);
1723     }
1724 
1725     if (want.GetElement().GetBundleName() == LAUNCHER_BUNDLE_NAME &&
1726         want.GetElement().GetAbilityName() == LAUNCHER_ABILITY_NAME) {
1727         TAG_LOGD(AAFwkTag::ABILITY, "set window type for launcher");
1728         option->SetWindowType(Rosen::WindowType::WINDOW_TYPE_DESKTOP);
1729     }
1730     return option;
1731 }
1732 
DoOnForeground(const Want & want)1733 void Ability::DoOnForeground(const Want& want)
1734 {
1735     if (abilityWindow_ == nullptr) {
1736         TAG_LOGD(AAFwkTag::ABILITY, "null Ability window");
1737         return;
1738     }
1739 
1740     TAG_LOGD(AAFwkTag::ABILITY, "sceneFlag:%{public}d", sceneFlag_);
1741     auto window = abilityWindow_->GetWindow();
1742     if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) {
1743         auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE,
1744             AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED);
1745         window->SetWindowMode(static_cast<Rosen::WindowMode>(windowMode));
1746         TAG_LOGD(AAFwkTag::ABILITY, "set window mode = %{public}d", windowMode);
1747     }
1748     abilityWindow_->OnPostAbilityForeground(sceneFlag_);
1749     TAG_LOGD(AAFwkTag::ABILITY, "end");
1750 }
1751 
GetCurrentWindowMode()1752 int Ability::GetCurrentWindowMode()
1753 {
1754     TAG_LOGD(AAFwkTag::ABILITY, "called");
1755     auto windowMode = static_cast<int>(Rosen::WindowMode::WINDOW_MODE_UNDEFINED);
1756     if (scene_ == nullptr) {
1757         return windowMode;
1758     }
1759     auto window = scene_->GetMainWindow();
1760     if (window != nullptr) {
1761         windowMode = static_cast<int>(window->GetMode());
1762     }
1763     return windowMode;
1764 }
1765 
SetMissionLabel(const std::string & label)1766 ErrCode Ability::SetMissionLabel(const std::string &label)
1767 {
1768     TAG_LOGD(AAFwkTag::ABILITY, "called");
1769     if (!abilityInfo_ || abilityInfo_->type != AppExecFwk::AbilityType::PAGE) {
1770         TAG_LOGE(AAFwkTag::ABILITY, "invalid ability info");
1771         return -1;
1772     }
1773 
1774     // stage mode
1775     if (abilityInfo_->isStageBasedModel) {
1776         if (scene_ == nullptr) {
1777             TAG_LOGE(AAFwkTag::ABILITY, "null scene_");
1778             return -1;
1779         }
1780         auto window = scene_->GetMainWindow();
1781         if (window == nullptr) {
1782             TAG_LOGE(AAFwkTag::ABILITY, "null window");
1783             return -1;
1784         }
1785 
1786         if (window->SetAPPWindowLabel(label) != OHOS::Rosen::WMError::WM_OK) {
1787             TAG_LOGE(AAFwkTag::ABILITY, "failed");
1788             return -1;
1789         }
1790         return ERR_OK;
1791     }
1792 
1793     // fa mode
1794     if (abilityWindow_ == nullptr) {
1795         TAG_LOGE(AAFwkTag::ABILITY, "null abilityWindow");
1796         return -1;
1797     }
1798     return abilityWindow_->SetMissionLabel(label);
1799 }
1800 
SetMissionIcon(const std::shared_ptr<OHOS::Media::PixelMap> & icon)1801 ErrCode Ability::SetMissionIcon(const std::shared_ptr<OHOS::Media::PixelMap> &icon)
1802 {
1803     TAG_LOGD(AAFwkTag::ABILITY, "called");
1804     if (!abilityInfo_ || abilityInfo_->type != AppExecFwk::AbilityType::PAGE) {
1805         TAG_LOGE(AAFwkTag::ABILITY, "invalid ability info");
1806         return -1;
1807     }
1808 
1809     // stage mode
1810     if (abilityInfo_->isStageBasedModel) {
1811         if (scene_ == nullptr) {
1812             TAG_LOGE(AAFwkTag::ABILITY, "null scene_");
1813             return -1;
1814         }
1815         auto window = scene_->GetMainWindow();
1816         if (window == nullptr) {
1817             TAG_LOGE(AAFwkTag::ABILITY, "null window");
1818             return -1;
1819         }
1820 
1821         if (window->SetAPPWindowIcon(icon) != OHOS::Rosen::WMError::WM_OK) {
1822             TAG_LOGE(AAFwkTag::ABILITY, "failed");
1823             return -1;
1824         }
1825         return ERR_OK;
1826     }
1827 
1828     // fa mode
1829     if (abilityWindow_ == nullptr) {
1830         TAG_LOGE(AAFwkTag::ABILITY, "null abilityWindow");
1831         return -1;
1832     }
1833     return abilityWindow_->SetMissionIcon(icon);
1834 }
1835 
GetWindowRect(int32_t & left,int32_t & top,int32_t & width,int32_t & height)1836 void Ability::GetWindowRect(int32_t &left, int32_t &top, int32_t &width, int32_t &height)
1837 {
1838     TAG_LOGD(AAFwkTag::ABILITY, "call");
1839     if (scene_ == nullptr) {
1840         TAG_LOGE(AAFwkTag::ABILITY, "null scene_");
1841         return;
1842     }
1843     auto window = scene_->GetMainWindow();
1844     if (window == nullptr) {
1845         TAG_LOGE(AAFwkTag::ABILITY, "null window");
1846         return;
1847     }
1848     left = window->GetRect().posX_;
1849     top = window->GetRect().posY_;
1850     width = static_cast<int32_t>(window->GetRect().width_);
1851     height = static_cast<int32_t>(window->GetRect().height_);
1852     TAG_LOGI(AAFwkTag::ABILITY, "left:%{public}d, top:%{public}d, width:%{public}d, height:%{public}d",
1853         left, top, width, height);
1854 }
1855 
GetUIContent()1856 Ace::UIContent* Ability::GetUIContent()
1857 {
1858     TAG_LOGD(AAFwkTag::ABILITY, "call");
1859     if (scene_ == nullptr) {
1860         TAG_LOGE(AAFwkTag::ABILITY, "null scene_");
1861         return nullptr;
1862     }
1863     auto window = scene_->GetMainWindow();
1864     if (window == nullptr) {
1865         TAG_LOGE(AAFwkTag::ABILITY, "null window");
1866         return nullptr;
1867     }
1868     return window->GetUIContent();
1869 }
1870 
OnCreate(Rosen::DisplayId displayId)1871 void Ability::OnCreate(Rosen::DisplayId displayId)
1872 {
1873     TAG_LOGD(AAFwkTag::ABILITY, "called");
1874 }
1875 
OnDestroy(Rosen::DisplayId displayId)1876 void Ability::OnDestroy(Rosen::DisplayId displayId)
1877 {
1878     TAG_LOGD(AAFwkTag::ABILITY, "called");
1879 }
1880 
OnChange(Rosen::DisplayId displayId)1881 void Ability::OnChange(Rosen::DisplayId displayId)
1882 {
1883     TAG_LOGD(AAFwkTag::ABILITY, "displayId:%{public}" PRIu64"", displayId);
1884 
1885     // Get display
1886     auto display = Rosen::DisplayManager::GetInstance().GetDisplayById(displayId);
1887     if (!display) {
1888         TAG_LOGE(AAFwkTag::ABILITY, "displayId %{public}" PRIu64" failed", displayId);
1889         return;
1890     }
1891 
1892     // Notify ResourceManager
1893     float density = display->GetVirtualPixelRatio();
1894     int32_t width = display->GetWidth();
1895     int32_t height = display->GetHeight();
1896     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
1897     if (resConfig != nullptr) {
1898         auto resourceManager = GetResourceManager();
1899         if (resourceManager != nullptr) {
1900             resourceManager->GetResConfig(*resConfig);
1901             resConfig->SetScreenDensity(density);
1902             resConfig->SetDirection(ConvertDirection(height, width));
1903             resourceManager->UpdateResConfig(*resConfig);
1904             TAG_LOGI(AAFwkTag::ABILITY, "notify ResourceManager, Density:%{public}f, Direction:%{public}d",
1905                 resConfig->GetScreenDensity(), resConfig->GetDirection());
1906         }
1907     }
1908 
1909     // Notify ability
1910     Configuration newConfig;
1911     newConfig.AddItem(displayId, ConfigurationInner::APPLICATION_DIRECTION, GetDirectionStr(height, width));
1912     newConfig.AddItem(displayId, ConfigurationInner::APPLICATION_DENSITYDPI, GetDensityStr(density));
1913 
1914     if (application_ == nullptr) {
1915         TAG_LOGE(AAFwkTag::ABILITY, "null application_");
1916         return;
1917     }
1918 
1919     auto configuration = application_->GetConfiguration();
1920     if (!configuration) {
1921         TAG_LOGE(AAFwkTag::ABILITY, "null configuration");
1922         return;
1923     }
1924 
1925     std::vector<std::string> changeKeyV;
1926     configuration->CompareDifferent(changeKeyV, newConfig);
1927     TAG_LOGD(AAFwkTag::ABILITY, "changeKeyV size:%{public}zu", changeKeyV.size());
1928     if (!changeKeyV.empty()) {
1929         configuration->Merge(changeKeyV, newConfig);
1930         auto task = [ability = shared_from_this(), configuration = *configuration]() {
1931             ability->OnConfigurationUpdated(configuration);
1932         };
1933         handler_->PostTask(task, "Ability:OnChange");
1934 
1935         auto diffConfiguration = std::make_shared<AppExecFwk::Configuration>(newConfig);
1936         TAG_LOGI(AAFwkTag::ABILITY, "update display config %{public}s for all windows",
1937             diffConfiguration->GetName().c_str());
1938         Rosen::Window::UpdateConfigurationForAll(diffConfiguration);
1939     }
1940 
1941     TAG_LOGD(AAFwkTag::ABILITY, "end");
1942 }
1943 
OnDisplayMove(Rosen::DisplayId from,Rosen::DisplayId to)1944 void Ability::OnDisplayMove(Rosen::DisplayId from, Rosen::DisplayId to)
1945 {
1946     TAG_LOGI(AAFwkTag::ABILITY, "displayId %{public}" PRIu64" to %{public}" PRIu64"", from, to);
1947 
1948     auto display = Rosen::DisplayManager::GetInstance().GetDisplayById(to);
1949     if (!display) {
1950         TAG_LOGE(AAFwkTag::ABILITY, "displayId %{public}" PRIu64" failed", to);
1951         return;
1952     }
1953 
1954     // Get new display config
1955     float density = display->GetVirtualPixelRatio();
1956     int32_t width = display->GetWidth();
1957     int32_t height = display->GetHeight();
1958     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
1959     if (resConfig != nullptr) {
1960         auto resourceManager = GetResourceManager();
1961         if (resourceManager != nullptr) {
1962             resourceManager->GetResConfig(*resConfig);
1963             resConfig->SetScreenDensity(density);
1964             resConfig->SetDirection(ConvertDirection(height, width));
1965             resourceManager->UpdateResConfig(*resConfig);
1966             TAG_LOGI(AAFwkTag::ABILITY, "notify ResourceManager, Density:%{public}f, Direction:%{public}d",
1967                 resConfig->GetScreenDensity(), resConfig->GetDirection());
1968         }
1969     }
1970 
1971     Configuration newConfig;
1972     newConfig.AddItem(ConfigurationInner::APPLICATION_DISPLAYID, std::to_string(to));
1973     newConfig.AddItem(to, ConfigurationInner::APPLICATION_DIRECTION, GetDirectionStr(height, width));
1974     newConfig.AddItem(to, ConfigurationInner::APPLICATION_DENSITYDPI, GetDensityStr(density));
1975 
1976     if (application_ == nullptr) {
1977         TAG_LOGE(AAFwkTag::ABILITY, "null application_");
1978         return;
1979     }
1980 
1981     std::vector<std::string> changeKeyV;
1982     auto configuration = application_->GetConfiguration();
1983     if (!configuration) {
1984         TAG_LOGE(AAFwkTag::ABILITY, "null configuration");
1985         return;
1986     }
1987 
1988     configuration->CompareDifferent(changeKeyV, newConfig);
1989     TAG_LOGD(AAFwkTag::ABILITY, "changeKeyV size :%{public}zu", changeKeyV.size());
1990     if (!changeKeyV.empty()) {
1991         configuration->Merge(changeKeyV, newConfig);
1992         auto task = [ability = shared_from_this(), configuration = *configuration]() {
1993             ability->OnConfigurationUpdated(configuration);
1994         };
1995         handler_->PostTask(task, "Ability:OnDisplayMove");
1996     }
1997 }
1998 
RequestFocus(const Want & want)1999 void Ability::RequestFocus(const Want &want)
2000 {
2001     TAG_LOGD(AAFwkTag::ABILITY, "called");
2002     if (abilityWindow_ == nullptr) {
2003         return;
2004     }
2005     auto window = abilityWindow_->GetWindow();
2006     if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) {
2007         auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE,
2008             AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED);
2009         window->SetWindowMode(static_cast<Rosen::WindowMode>(windowMode));
2010         TAG_LOGD(AAFwkTag::ABILITY, "set window mode = %{public}d", windowMode);
2011     }
2012     abilityWindow_->OnPostAbilityForeground(sceneFlag_);
2013 }
2014 
SetWakeUpScreen(bool wakeUp)2015 void Ability::SetWakeUpScreen(bool wakeUp)
2016 {
2017     TAG_LOGD(AAFwkTag::ABILITY, "wakeUp:%{public}d", wakeUp);
2018     if (abilityWindow_ == nullptr) {
2019         TAG_LOGE(AAFwkTag::ABILITY, "null abilityWindow_");
2020         return;
2021     }
2022     auto window = abilityWindow_->GetWindow();
2023     if (window == nullptr) {
2024         TAG_LOGE(AAFwkTag::ABILITY, "null window");
2025         return;
2026     }
2027     window->SetTurnScreenOn(wakeUp);
2028 }
2029 
SetDisplayOrientation(int orientation)2030 void Ability::SetDisplayOrientation(int orientation)
2031 {
2032     TAG_LOGD(AAFwkTag::ABILITY, "fa mode, orientation:%{public}d", orientation);
2033     if (abilityWindow_ == nullptr) {
2034         TAG_LOGE(AAFwkTag::ABILITY, "null Ability window");
2035         return;
2036     }
2037     auto window = abilityWindow_->GetWindow();
2038     if (window == nullptr) {
2039         TAG_LOGE(AAFwkTag::ABILITY, "null window");
2040         return;
2041     }
2042     if (orientation == static_cast<int>(DisplayOrientation::FOLLOWRECENT)) {
2043         int defaultOrientation = 0;
2044         if (setWant_) {
2045             orientation = setWant_->GetIntParam("ohos.aafwk.Orientation", defaultOrientation);
2046         } else {
2047             orientation = defaultOrientation;
2048         }
2049     }
2050     if (orientation == static_cast<int>(DisplayOrientation::LANDSCAPE)) {
2051         TAG_LOGD(AAFwkTag::ABILITY, "set LANDSCAPE");
2052         window->SetRequestedOrientation(Rosen::Orientation::HORIZONTAL);
2053     } else if (orientation == static_cast<int>(DisplayOrientation::PORTRAIT)) {
2054         TAG_LOGD(AAFwkTag::ABILITY, "set PORTRAIT");
2055         window->SetRequestedOrientation(Rosen::Orientation::VERTICAL);
2056     } else {
2057         TAG_LOGD(AAFwkTag::ABILITY, "set UNSPECIFIED");
2058         window->SetRequestedOrientation(Rosen::Orientation::UNSPECIFIED);
2059     }
2060 }
2061 
GetDisplayOrientation()2062 int Ability::GetDisplayOrientation()
2063 {
2064     TAG_LOGD(AAFwkTag::ABILITY, "called");
2065     if (abilityWindow_ == nullptr) {
2066         TAG_LOGE(AAFwkTag::ABILITY, "null abilityWindow_");
2067         return -1;
2068     }
2069     TAG_LOGD(AAFwkTag::ABILITY, "fa mode");
2070     auto window = abilityWindow_->GetWindow();
2071     if (window == nullptr) {
2072         TAG_LOGE(AAFwkTag::ABILITY, "null window");
2073         return -1;
2074     }
2075     auto orientation = window->GetRequestedOrientation();
2076     if (orientation == Rosen::Orientation::HORIZONTAL) {
2077         TAG_LOGD(AAFwkTag::ABILITY, "get window orientation: LANDSCAPE");
2078         return static_cast<int>(DisplayOrientation::LANDSCAPE);
2079     }
2080     if (orientation == Rosen::Orientation::VERTICAL) {
2081         TAG_LOGD(AAFwkTag::ABILITY, "get window orientation: PORTRAIT");
2082         return static_cast<int>(DisplayOrientation::PORTRAIT);
2083     }
2084     TAG_LOGD(AAFwkTag::ABILITY, "get window orientation: UNSPECIFIED");
2085     return 0;
2086 }
2087 
ContinuationRestore(const Want & want)2088 void Ability::ContinuationRestore(const Want &want)
2089 {
2090     TAG_LOGD(AAFwkTag::ABILITY, "called");
2091 }
2092 
CreateModalUIExtension(const Want & want)2093 int Ability::CreateModalUIExtension(const Want &want)
2094 {
2095     TAG_LOGD(AAFwkTag::ABILITY, "call");
2096     auto abilityContextImpl = GetAbilityContext();
2097     if (abilityContextImpl == nullptr) {
2098         TAG_LOGE(AAFwkTag::ABILITY, "null abilitycontext");
2099         return ERR_INVALID_VALUE;
2100     }
2101     return abilityContextImpl->CreateModalUIExtensionWithApp(want);
2102 }
2103 
SetSessionToken(sptr<IRemoteObject> sessionToken)2104 void Ability::SetSessionToken(sptr<IRemoteObject> sessionToken)
2105 {
2106     std::lock_guard lock(sessionTokenMutex_);
2107     sessionToken_ = sessionToken;
2108 }
2109 
UpdateSessionToken(sptr<IRemoteObject> sessionToken)2110 void Ability::UpdateSessionToken(sptr<IRemoteObject> sessionToken)
2111 {
2112     SetSessionToken(sessionToken);
2113     if (abilityWindow_ == nullptr) {
2114         TAG_LOGE(AAFwkTag::ABILITY, "null Ability window");
2115         return;
2116     }
2117     abilityWindow_->SetSessionToken(sessionToken);
2118 }
2119 
InitFAWindow(const Want & want,int32_t displayId)2120 void Ability::InitFAWindow(const Want &want, int32_t displayId)
2121 {
2122     if (!abilityInfo_->isStageBasedModel) {
2123         auto option = GetWindowOption(want);
2124         InitWindow(displayId, option);
2125     }
2126 
2127     if (abilityWindow_ != nullptr) {
2128         TAG_LOGD(AAFwkTag::ABILITY, "get window from abilityWindow");
2129         auto window = abilityWindow_->GetWindow();
2130         if (window) {
2131             TAG_LOGD(AAFwkTag::ABILITY, "call RegisterDisplayMoveListener, windowId:%{public}d",
2132                 window->GetWindowId());
2133             abilityDisplayMoveListener_ = new AbilityDisplayMoveListener(weak_from_this());
2134             window->RegisterDisplayMoveListener(abilityDisplayMoveListener_);
2135         }
2136     }
2137 }
2138 
UpdateResMgrAndConfiguration(int32_t displayId)2139 bool Ability::UpdateResMgrAndConfiguration(int32_t displayId)
2140 {
2141     auto display = Rosen::DisplayManager::GetInstance().GetDisplayById(displayId);
2142     if (!display) {
2143         TAG_LOGI(AAFwkTag::ABILITY, "invalid display");
2144         return true;
2145     }
2146     float density = display->GetVirtualPixelRatio();
2147     int32_t width = display->GetWidth();
2148     int32_t height = display->GetHeight();
2149     std::shared_ptr<Configuration> configuration = nullptr;
2150     if (application_) {
2151         configuration = application_->GetConfiguration();
2152     }
2153     if (configuration) {
2154         std::string direction = GetDirectionStr(height, width);
2155         configuration->AddItem(displayId, ConfigurationInner::APPLICATION_DIRECTION, direction);
2156         configuration->AddItem(displayId, ConfigurationInner::APPLICATION_DENSITYDPI, GetDensityStr(density));
2157         configuration->AddItem(ConfigurationInner::APPLICATION_DISPLAYID, std::to_string(displayId));
2158         UpdateContextConfiguration();
2159     }
2160 
2161     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
2162     if (resConfig == nullptr) {
2163         TAG_LOGE(AAFwkTag::ABILITY, "create resConfig failed");
2164         return false;
2165     }
2166     auto resourceManager = GetResourceManager();
2167     if (resourceManager != nullptr) {
2168         resourceManager->GetResConfig(*resConfig);
2169         resConfig->SetScreenDensity(density);
2170         resConfig->SetDirection(ConvertDirection(height, width));
2171         resourceManager->UpdateResConfig(*resConfig);
2172         TAG_LOGD(AAFwkTag::ABILITY, "notify ResourceManager, Density:%{public}f, Direction:%{public}d",
2173             resConfig->GetScreenDensity(), resConfig->GetDirection());
2174     }
2175     return true;
2176 }
2177 
EraseUIExtension(int32_t sessionId)2178 void Ability::EraseUIExtension(int32_t sessionId)
2179 {
2180     TAG_LOGD(AAFwkTag::ABILITY, "call");
2181     auto abilityContextImpl = GetAbilityContext();
2182     if (abilityContextImpl == nullptr) {
2183         TAG_LOGE(AAFwkTag::ABILITY, "null abilityContext");
2184         return;
2185     }
2186     abilityContextImpl->EraseUIExtension(sessionId);
2187 }
2188 #endif
2189 }  // namespace AppExecFwk
2190 }  // namespace OHOS
2191