1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "adapter/ohos/entrance/ace_ability.h"
17 
18 #include <ui/rs_surface_node.h>
19 
20 #include "ability_process.h"
21 #include "dm/display_manager.h"
22 #include "form_utils_impl.h"
23 #include "ohos/init_data.h"
24 #include "ipc_skeleton.h"
25 #include "res_config.h"
26 #include "resource_manager.h"
27 #include "session_info.h"
28 #include "string_wrapper.h"
29 
30 #ifdef ENABLE_ROSEN_BACKEND
31 #include "render_service_client/core/ui/rs_ui_director.h"
32 #endif
33 
34 #include "adapter/ohos/entrance/ace_application_info.h"
35 #include "adapter/ohos/entrance/ace_container.h"
36 #include "adapter/ohos/entrance/ace_new_pipe_judgement.h"
37 #include "adapter/ohos/entrance/ace_view_ohos.h"
38 #include "adapter/ohos/entrance/capability_registry.h"
39 #include "adapter/ohos/entrance/plugin_utils_impl.h"
40 #include "adapter/ohos/entrance/utils.h"
41 #include "base/geometry/rect.h"
42 #include "base/subwindow/subwindow_manager.h"
43 #include "base/utils/system_properties.h"
44 #include "base/utils/utils.h"
45 #include "core/common/ace_engine.h"
46 #include "core/common/container_scope.h"
47 #include "core/common/form_manager.h"
48 #include "core/common/frontend.h"
49 #include "core/common/layout_inspector.h"
50 #include "core/common/plugin_manager.h"
51 #include "core/common/plugin_utils.h"
52 #include "core/image/image_file_cache.h"
53 namespace OHOS {
54 namespace Ace {
55 namespace {
56 
57 const std::string ABS_BUNDLE_CODE_PATH = "/data/app/el1/bundle/public/";
58 const std::string LOCAL_BUNDLE_CODE_PATH = "/data/storage/el1/bundle/";
59 const std::string FILE_SEPARATOR = "/";
60 const std::string ACTION_VIEWDATA = "ohos.want.action.viewData";
61 constexpr int32_t PLATFORM_VERSION_TEN = 10;
62 
GetFrontendType(const std::string& frontendType)63 FrontendType GetFrontendType(const std::string& frontendType)
64 {
65     if (frontendType == "normal") {
66         return FrontendType::JS;
67     } else if (frontendType == "form") {
68         return FrontendType::JS_CARD;
69     } else if (frontendType == "declarative") {
70         return FrontendType::DECLARATIVE_JS;
71     } else {
72         return FrontendType::JS;
73     }
74 }
75 
GetFrontendTypeFromManifest(const std::string& packagePath, const std::string& srcPath, bool isHap)76 FrontendType GetFrontendTypeFromManifest(const std::string& packagePath, const std::string& srcPath, bool isHap)
77 {
78     std::string manifest = std::string("assets/js/default/manifest.json");
79     if (!srcPath.empty()) {
80         manifest = "assets/js/" + srcPath + "/manifest.json";
81     }
82     std::string jsonStr = isHap ? GetStringFromHap(packagePath, manifest) : GetStringFromFile(packagePath, manifest);
83     if (jsonStr.empty()) {
84         return FrontendType::JS;
85     }
86     auto rootJson = JsonUtil::ParseJsonString(jsonStr);
87     if (rootJson == nullptr) {
88         return FrontendType::JS;
89     }
90     auto mode = rootJson->GetObject("mode");
91     if (mode != nullptr) {
92         if (mode->GetString("syntax") == "ets" || mode->GetString("type") == "pageAbility") {
93             return FrontendType::DECLARATIVE_JS;
94         }
95     }
96     return GetFrontendType(rootJson->GetString("type"));
97 }
98 
99 } // namespace
100 
101 using namespace OHOS::AAFwk;
102 using namespace OHOS::AppExecFwk;
103 
104 using AcePlatformFinish = std::function<void()>;
105 using AcePlatformStartAbility = std::function<void(const std::string& address)>;
106 class AcePlatformEventCallback final : public Platform::PlatformEventCallback {
107 public:
AcePlatformEventCallback(AcePlatformFinish onFinish)108     explicit AcePlatformEventCallback(AcePlatformFinish onFinish) : onFinish_(onFinish) {}
AcePlatformEventCallback(AcePlatformFinish onFinish, AcePlatformStartAbility onStartAbility)109     AcePlatformEventCallback(AcePlatformFinish onFinish, AcePlatformStartAbility onStartAbility)
110         : onFinish_(onFinish), onStartAbility_(onStartAbility)
111     {}
112 
113     ~AcePlatformEventCallback() override = default;
114 
115     void OnFinish() const override
116     {
117         LOGI("AcePlatformEventCallback OnFinish");
118         CHECK_NULL_VOID(onFinish_);
119         onFinish_();
120     }
121 
122     void OnStartAbility(const std::string& address) override
123     {
124         LOGI("AcePlatformEventCallback OnStartAbility");
125         CHECK_NULL_VOID(onStartAbility_);
126         onStartAbility_(address);
127     }
128 
129     void OnStatusBarBgColorChanged(uint32_t color) override
130     {
131         LOGI("AcePlatformEventCallback OnStatusBarBgColorChanged");
132     }
133 
134 private:
135     AcePlatformFinish onFinish_;
136     AcePlatformStartAbility onStartAbility_;
137 };
138 
139 const std::string AceAbility::START_PARAMS_KEY = "__startParams";
140 const std::string AceAbility::PAGE_URI = "url";
141 const std::string AceAbility::CONTINUE_PARAMS_KEY = "__remoteData";
142 
143 REGISTER_AA(AceAbility)
OnDrag(int32_t x, int32_t y, OHOS::Rosen::DragEvent event)144 void AceWindowListener::OnDrag(int32_t x, int32_t y, OHOS::Rosen::DragEvent event)
145 {
146     CHECK_NULL_VOID(callbackOwner_);
147     callbackOwner_->OnDrag(x, y, event);
148 }
149 
OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info, const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction)150 void AceWindowListener::OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info,
151     const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction)
152 {
153     CHECK_NULL_VOID(callbackOwner_);
154     callbackOwner_->OnSizeChange(info, rsTransaction);
155 }
156 
SetBackgroundColor(uint32_t color)157 void AceWindowListener::SetBackgroundColor(uint32_t color)
158 {
159     CHECK_NULL_VOID(callbackOwner_);
160     callbackOwner_->SetBackgroundColor(color);
161 }
162 
GetBackgroundColor()163 uint32_t AceWindowListener::GetBackgroundColor()
164 {
165     CHECK_NULL_RETURN(callbackOwner_, 0);
166     return callbackOwner_->GetBackgroundColor();
167 }
168 
OnSizeChange(OHOS::Rosen::Rect rect, OHOS::Rosen::WindowSizeChangeReason reason, const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction)169 void AceWindowListener::OnSizeChange(OHOS::Rosen::Rect rect, OHOS::Rosen::WindowSizeChangeReason reason,
170     const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction)
171 {
172     CHECK_NULL_VOID(callbackOwner_);
173     callbackOwner_->OnSizeChange(rect, reason, rsTransaction);
174 }
175 
OnModeChange(OHOS::Rosen::WindowMode mode, bool hasDeco)176 void AceWindowListener::OnModeChange(OHOS::Rosen::WindowMode mode, bool hasDeco)
177 {
178     CHECK_NULL_VOID(callbackOwner_);
179     callbackOwner_->OnModeChange(mode, hasDeco);
180 }
181 
OnInputEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent) const182 bool AceWindowListener::OnInputEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent) const
183 {
184     CHECK_NULL_RETURN(callbackOwner_, false);
185     return callbackOwner_->OnInputEvent(keyEvent);
186 }
187 
OnInputEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent) const188 bool AceWindowListener::OnInputEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent) const
189 {
190     CHECK_NULL_RETURN(callbackOwner_, false);
191     return callbackOwner_->OnInputEvent(pointerEvent);
192 }
193 
OnInputEvent(const std::shared_ptr<MMI::AxisEvent>& axisEvent) const194 bool AceWindowListener::OnInputEvent(const std::shared_ptr<MMI::AxisEvent>& axisEvent) const
195 {
196     CHECK_NULL_RETURN(callbackOwner_, false);
197     return callbackOwner_->OnInputEvent(axisEvent);
198 }
199 
OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea avoidArea, OHOS::Rosen::AvoidAreaType type)200 void AceWindowListener::OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea avoidArea, OHOS::Rosen::AvoidAreaType type)
201 {
202     CHECK_NULL_VOID(callbackOwner_);
203     return callbackOwner_->OnAvoidAreaChanged(avoidArea, type);
204 }
205 
206 AceAbility::AceAbility() = default;
207 
OnStart(const Want& want, sptr<AAFwk::SessionInfo> sessionInfo)208 void AceAbility::OnStart(const Want& want, sptr<AAFwk::SessionInfo> sessionInfo)
209 {
210     Ability::OnStart(want, sessionInfo);
211     abilityId_ = Container::GenerateId<FA_CONTAINER>();
212     static std::once_flag onceFlag;
213     auto abilityContext = GetAbilityContext();
214     auto cacheDir = abilityContext->GetCacheDir();
215     std::call_once(onceFlag, [abilityContext, cacheDir]() {
216         SetHwIcuDirectory();
217         Container::UpdateCurrent(INSTANCE_ID_PLATFORM);
218         CapabilityRegistry::Register();
219         AceApplicationInfo::GetInstance().SetPackageName(abilityContext->GetBundleName());
220         AceApplicationInfo::GetInstance().SetDataFileDirPath(abilityContext->GetFilesDir());
221         auto applicationInfo = abilityContext->GetApplicationInfo();
222         if (applicationInfo) {
223             AceApplicationInfo::GetInstance().SetApiTargetVersion(applicationInfo->apiTargetVersion);
224             AceApplicationInfo::GetInstance().SetAppVersionName(applicationInfo->versionName);
225             AceApplicationInfo::GetInstance().SetAppVersionCode(applicationInfo->versionCode);
226         } else {
227             LOGE("ability start set application info failed,it may cause exception");
228             return;
229         }
230         AceApplicationInfo::GetInstance().SetUid(IPCSkeleton::GetCallingUid());
231         AceApplicationInfo::GetInstance().SetPid(IPCSkeleton::GetCallingRealPid());
232         ImageFileCache::GetInstance().SetImageCacheFilePath(cacheDir);
233         ImageFileCache::GetInstance().SetCacheFileInfo();
234         AceEngine::InitJsDumpHeadSignal();
235     });
236     AceNewPipeJudgement::InitAceNewPipeConfig();
237     // now choose pipeline using param set as package name, later enable for all.
238     auto apiCompatibleVersion = abilityContext->GetApplicationInfo()->apiCompatibleVersion;
239     auto apiReleaseType = abilityContext->GetApplicationInfo()->apiReleaseType;
240     auto apiTargetVersion = abilityContext->GetApplicationInfo()->apiTargetVersion;
241     auto useNewPipe = AceNewPipeJudgement::QueryAceNewPipeEnabledFA(
242         AceApplicationInfo::GetInstance().GetPackageName(), apiCompatibleVersion, apiTargetVersion, apiReleaseType);
243     LOGI("AceAbility OnStart called, apiCompatibleVersion: %{public}d, apiTargetVersion: %{public}d, "
244          "and apiReleaseType: %{public}s, useNewPipe: %{public}d",
245         apiCompatibleVersion, apiTargetVersion, apiReleaseType.c_str(), useNewPipe);
246     OHOS::sptr<OHOS::Rosen::Window> window = Ability::GetWindow();
247     std::shared_ptr<AceAbility> self = std::static_pointer_cast<AceAbility>(shared_from_this());
248     OHOS::sptr<AceWindowListener> aceWindowListener = new AceWindowListener(self);
249     // register surface change callback and window mode change callback
250     window->RegisterWindowChangeListener(aceWindowListener);
251     // register drag event callback
252     window->RegisterDragListener(aceWindowListener);
253     // register Occupied Area callback
254     window->RegisterOccupiedAreaChangeListener(aceWindowListener);
255     // register ace ability handler callback
256     window->SetAceAbilityHandler(aceWindowListener);
257     // register input consumer callback
258     std::shared_ptr<AceWindowListener> aceInputConsumer = std::make_shared<AceWindowListener>(self);
259     window->SetInputEventConsumer(aceInputConsumer);
260 
261     int32_t deviceWidth = 0;
262     int32_t deviceHeight = 0;
263     auto defaultDisplay = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
264     if (defaultDisplay) {
265         density_ = defaultDisplay->GetVirtualPixelRatio();
266         deviceWidth = defaultDisplay->GetWidth();
267         deviceHeight = defaultDisplay->GetHeight();
268         LOGI("deviceWidth: %{public}d, deviceHeight: %{public}d, default density: %{public}f", deviceWidth,
269             deviceHeight, density_);
270     }
271     SystemProperties::InitDeviceInfo(deviceWidth, deviceHeight, deviceHeight >= deviceWidth ? 0 : 1, density_, false);
272     SystemProperties::SetColorMode(ColorMode::LIGHT);
273 
274     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
275     auto resourceManager = GetResourceManager();
276     if (resourceManager != nullptr) {
277         resourceManager->GetResConfig(*resConfig);
278         auto localeInfo = resConfig->GetLocaleInfo();
279         Platform::AceApplicationInfoImpl::GetInstance().SetResourceManager(resourceManager);
280         if (localeInfo != nullptr) {
281             auto language = localeInfo->getLanguage();
282             auto region = localeInfo->getCountry();
283             auto script = localeInfo->getScript();
284             AceApplicationInfo::GetInstance().SetLocale((language == nullptr) ? "" : language,
285                 (region == nullptr) ? "" : region, (script == nullptr) ? "" : script, "");
286         } else {
287             LOGW("localeInfo is null.");
288             AceApplicationInfo::GetInstance().SetLocale("", "", "", "");
289         }
290         if (resConfig->GetColorMode() == OHOS::Global::Resource::ColorMode::DARK) {
291             SystemProperties::SetColorMode(ColorMode::DARK);
292             LOGI("UIContent set dark mode");
293         } else {
294             SystemProperties::SetColorMode(ColorMode::LIGHT);
295             LOGI("UIContent set light mode");
296         }
297         SystemProperties::SetDeviceAccess(
298             resConfig->GetInputDevice() == Global::Resource::InputDevice::INPUTDEVICE_POINTINGDEVICE);
299     } else {
300         LOGW("resourceManager is null.");
301         AceApplicationInfo::GetInstance().SetLocale("", "", "", "");
302     }
303 
304     auto packagePathStr = GetBundleCodePath();
305     auto moduleInfo = GetHapModuleInfo();
306     CHECK_NULL_VOID(moduleInfo);
307     packagePathStr += "/" + moduleInfo->package + "/";
308     std::shared_ptr<AbilityInfo> info = GetAbilityInfo();
309     std::string srcPath;
310     if (info != nullptr && !info->srcPath.empty()) {
311         srcPath = info->srcPath;
312     }
313     if (info != nullptr && !info->bundleName.empty()) {
314         AceApplicationInfo::GetInstance().SetPackageName(info->bundleName);
315     }
316 
317     bool isHap = moduleInfo ? !moduleInfo->hapPath.empty() : false;
318     std::string& packagePath = isHap ? moduleInfo->hapPath : packagePathStr;
319     FrontendType frontendType = GetFrontendTypeFromManifest(packagePath, srcPath, isHap);
320     useNewPipe = useNewPipe && (frontendType == FrontendType::ETS_CARD || frontendType == FrontendType::DECLARATIVE_JS);
321 #ifdef ENABLE_ROSEN_BACKEND
322     std::shared_ptr<OHOS::Rosen::RSUIDirector> rsUiDirector;
323 #ifndef NG_BUILD
324     if (SystemProperties::GetRosenBackendEnabled() && !useNewPipe) {
325         rsUiDirector = OHOS::Rosen::RSUIDirector::Create();
326         auto surfaceNode = window->GetSurfaceNode();
327         rsUiDirector->SetRSSurfaceNode(surfaceNode);
328         rsUiDirector->SetCacheDir(cacheDir);
329         rsUiDirector->Init();
330     }
331 #endif
332 #endif
333     AceApplicationInfo::GetInstance().SetAbilityName(info ? info->name : "");
334     std::string moduleName = info ? info->moduleName : "";
335     std::string moduleHapPath = info ? info->hapPath : "";
336 
337     std::shared_ptr<ApplicationInfo> appInfo = GetApplicationInfo();
338     std::vector<ModuleInfo> moduleList = appInfo->moduleInfos;
339 
340     std::string resPath;
341     for (const auto& module : moduleList) {
342         if (module.moduleName == moduleName && info != nullptr) {
343             std::regex pattern(ABS_BUNDLE_CODE_PATH + info->bundleName + FILE_SEPARATOR);
344             auto moduleSourceDir = std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
345             resPath = moduleSourceDir + "/assets/" + module.moduleName + FILE_SEPARATOR;
346             break;
347         }
348     }
349     std::string hapPath;
350     if (!moduleHapPath.empty()) {
351         if (moduleHapPath.find(ABS_BUNDLE_CODE_PATH) == std::string::npos) {
352             hapPath = moduleHapPath;
353         } else {
354             auto pos = moduleHapPath.find_last_of('/');
355             if (pos != std::string::npos) {
356                 hapPath = LOCAL_BUNDLE_CODE_PATH + moduleHapPath.substr(pos + 1);
357                 LOGI("In FA mode, hapPath:%{private}s", hapPath.c_str());
358             }
359         }
360     }
361 
362     AceApplicationInfo::GetInstance().SetDebug(appInfo->debug, want.GetBoolParam("debugApp", false));
363 
364 #ifdef PLUGIN_COMPONENT_SUPPORTED
365     auto pluginUtils = std::make_shared<PluginUtilsImpl>();
366     PluginManager::GetInstance().SetAceAbility(this, pluginUtils);
367 #endif
368 #ifdef FORM_SUPPORTED
369     auto formUtils = std::make_shared<FormUtilsImpl>();
370     FormManager::GetInstance().SetFormUtils(formUtils);
371 #endif
372     // create container
373     Platform::AceContainer::CreateContainer(abilityId_, frontendType, srcPath, shared_from_this(),
374         std::make_unique<AcePlatformEventCallback>([this]() { TerminateAbility(); },
375             [this](const std::string& address) {
376                 AAFwk::Want want;
377                 want.AddEntity(Want::ENTITY_BROWSER);
378                 want.SetUri(address);
379                 want.SetAction(ACTION_VIEWDATA);
380                 this->StartAbility(want);
381             }),
382         false, useNewPipe);
383     auto container = Platform::AceContainer::GetContainer(abilityId_);
384     CHECK_NULL_VOID(container);
385     container->SetToken(token_);
386     auto aceResCfg = container->GetResourceConfiguration();
387     aceResCfg.SetOrientation(SystemProperties::GetDeviceOrientation());
388     aceResCfg.SetDensity(SystemProperties::GetResolution());
389     aceResCfg.SetDeviceType(SystemProperties::GetDeviceType());
390     aceResCfg.SetColorMode(SystemProperties::GetColorMode());
391     aceResCfg.SetDeviceAccess(SystemProperties::GetDeviceAccess());
392     container->SetResourceConfiguration(aceResCfg);
393     container->SetPackagePathStr(resPath);
394     container->SetHapPath(hapPath);
395     container->SetBundlePath(abilityContext->GetBundleCodeDir());
396     container->SetFilesDataPath(abilityContext->GetFilesDir());
397     if (window->IsDecorEnable()) {
398         LOGI("Container modal is enabled.");
399         container->SetWindowModal(WindowModal::CONTAINER_MODAL);
400     }
401     container->SetWindowName(window->GetWindowName());
402     container->SetWindowId(window->GetWindowId());
403     SubwindowManager::GetInstance()->AddContainerId(window->GetWindowId(), abilityId_);
404     // create view.
405     auto aceView = Platform::AceViewOhos::CreateView(abilityId_);
406     Platform::AceViewOhos::SurfaceCreated(aceView, window);
407 
408     if (srcPath.empty()) {
409         auto assetBasePathStr = { std::string("assets/js/default/"), std::string("assets/js/share/") };
410         Platform::AceContainer::AddAssetPath(abilityId_, packagePathStr, moduleInfo->hapPath, assetBasePathStr);
411     } else {
412         auto assetBasePathStr = { "assets/js/" + srcPath + "/", std::string("assets/js/share/"),
413             std::string("assets/js/") };
414         Platform::AceContainer::AddAssetPath(abilityId_, packagePathStr, moduleInfo->hapPath, assetBasePathStr);
415     }
416 
417 #ifndef NG_BUILD
418     if (!useNewPipe) {
419         Ace::Platform::UIEnvCallback callback = nullptr;
420 #ifdef ENABLE_ROSEN_BACKEND
421         callback = [window, id = abilityId_, aceView, rsUiDirector](
422                        const OHOS::Ace::RefPtr<OHOS::Ace::PipelineContext>& context) mutable {
423             if (rsUiDirector) {
424                 rsUiDirector->SetUITaskRunner(
425                     [taskExecutor = Platform::AceContainer::GetContainer(id)->GetTaskExecutor(), id](
426                         const std::function<void()>& task, uint32_t delay) {
427                         ContainerScope scope(id);
428                         taskExecutor->PostDelayedTask(
429                             task, TaskExecutor::TaskType::UI, delay, "ArkUIRenderServiceTask", PriorityType::HIGH);
430                     }, id);
431                 if (context != nullptr) {
432                     context->SetRSUIDirector(rsUiDirector);
433                 }
434                 LOGI("Init Rosen Backend");
435             }
436         };
437 #endif
438         // set view
439         Platform::AceContainer::SetView(aceView, density_, 0, 0, window, callback);
440     } else {
441         Platform::AceContainer::SetViewNew(aceView, density_, 0, 0, window);
442     }
443 #else
444     Platform::AceContainer::SetViewNew(aceView, density_, 0, 0, window);
445 #endif
446 
447     Platform::AceViewOhos::SurfaceChanged(aceView, 0, 0, deviceHeight >= deviceWidth ? 0 : 1);
448 
449     // action event handler
450     auto&& actionEventHandler = [this](const std::string& action) {
451         auto eventAction = JsonUtil::ParseJsonString(action);
452         auto bundleName = eventAction->GetValue("bundleName");
453         auto abilityName = eventAction->GetValue("abilityName");
454         auto params = eventAction->GetValue("params");
455         auto bundle = bundleName->GetString();
456         auto ability = abilityName->GetString();
457         LOGI("on Action called to event handler, bundle:%{public}s ability:%{public}s, params:%{public}s",
458             bundle.c_str(), ability.c_str(), params->GetString().c_str());
459         if (bundle.empty() || ability.empty()) {
460             LOGE("action ability or bundle is empty");
461             return;
462         }
463 
464         AAFwk::Want want;
465         want.SetElementName(bundle, ability);
466         this->StartAbility(want);
467     };
468 
469     // set window id & action event handler
470     auto context = Platform::AceContainer::GetContainer(abilityId_)->GetPipelineContext();
471     if (context) {
472         context->SetActionEventHandler(actionEventHandler);
473         context->SetGetWindowRectImpl([window]() -> Rect {
474             Rect rect;
475             CHECK_NULL_RETURN(window, rect);
476             auto windowRect = window->GetRect();
477             rect.SetRect(windowRect.posX_, windowRect.posY_, windowRect.width_, windowRect.height_);
478             return rect;
479         });
480         auto rsConfig = window->GetKeyboardAnimationConfig();
481         KeyboardAnimationCurve curveIn = {
482             rsConfig.curveIn.curveType_, rsConfig.curveIn.curveParams_, rsConfig.curveIn.duration_};
483         KeyboardAnimationCurve curveOut = {
484             rsConfig.curveOut.curveType_, rsConfig.curveOut.curveParams_, rsConfig.curveOut.duration_};
485         KeyboardAnimationConfig config = {curveIn, curveOut};
486         context->SetKeyboardAnimationConfig(config);
487         context->SetMinPlatformVersion(apiCompatibleVersion);
488 
489         if (apiCompatibleVersion >= PLATFORM_VERSION_TEN && context->GetIsAppWindow()) {
490             context->UpdateSystemSafeArea(container->GetViewSafeAreaByType(Rosen::AvoidAreaType::TYPE_SYSTEM));
491             context->UpdateCutoutSafeArea(container->GetViewSafeAreaByType(Rosen::AvoidAreaType::TYPE_CUTOUT));
492         }
493     }
494 
495     // get url
496     std::string parsedPageUrl;
497     if (!remotePageUrl_.empty()) {
498         parsedPageUrl = remotePageUrl_;
499     } else if (!pageUrl_.empty()) {
500         parsedPageUrl = pageUrl_;
501     } else if (want.HasParameter(PAGE_URI)) {
502         parsedPageUrl = want.GetStringParam(PAGE_URI);
503     } else {
504         parsedPageUrl = "";
505     }
506 
507     auto windowRect = window->GetRect();
508     if (!windowRect.IsUninitializedRect()) {
509         LOGW("notify window rect explicitly");
510         OnSizeChange(windowRect, OHOS::Rosen::WindowSizeChangeReason::UNDEFINED);
511     }
512     // run page.
513     Platform::AceContainer::RunPage(abilityId_, parsedPageUrl, want.GetStringParam(START_PARAMS_KEY));
514 
515     if (!remoteData_.empty()) {
516         Platform::AceContainer::OnRestoreData(abilityId_, remoteData_);
517     }
518     LayoutInspector::SetCallback(abilityId_);
519 }
520 
OnStop()521 void AceAbility::OnStop()
522 {
523     LOGI("AceAbility OnStop called ");
524     Ability::OnStop();
525     Platform::AceContainer::DestroyContainer(abilityId_);
526     abilityId_ = -1;
527 }
528 
OnActive()529 void AceAbility::OnActive()
530 {
531     LOGI("AceAbility OnActive called ");
532     // AbilityManager will miss first OnForeground notification
533     if (isFirstActive_) {
534         Platform::AceContainer::OnShow(abilityId_);
535         isFirstActive_ = false;
536     }
537     Ability::OnActive();
538     Platform::AceContainer::OnActive(abilityId_);
539 }
540 
OnForeground(const Want& want)541 void AceAbility::OnForeground(const Want& want)
542 {
543     LOGI("AceAbility OnForeground called ");
544     Ability::OnForeground(want);
545     Platform::AceContainer::OnShow(abilityId_);
546 }
547 
OnBackground()548 void AceAbility::OnBackground()
549 {
550     LOGI("AceAbility OnBackground called ");
551     Ability::OnBackground();
552     Platform::AceContainer::OnHide(abilityId_);
553 }
554 
OnInactive()555 void AceAbility::OnInactive()
556 {
557     LOGI("AceAbility OnInactive called ");
558     Ability::OnInactive();
559     Platform::AceContainer::OnInactive(abilityId_);
560 }
561 
OnBackPressed()562 void AceAbility::OnBackPressed()
563 {
564     LOGI("AceAbility OnBackPressed called ");
565     if (!Platform::AceContainer::OnBackPressed(abilityId_)) {
566         Ability::OnBackPressed();
567     }
568 }
569 
OnNewWant(const Want& want)570 void AceAbility::OnNewWant(const Want& want)
571 {
572     LOGI("AceAbility OnNewWant called ");
573     Ability::OnNewWant(want);
574     std::string params = want.GetStringParam(START_PARAMS_KEY);
575     Platform::AceContainer::OnNewRequest(abilityId_, params);
576     std::string data = want.ToString();
577     Platform::AceContainer::OnNewWant(abilityId_, data);
578 }
579 
OnRestoreAbilityState(const PacMap& inState)580 void AceAbility::OnRestoreAbilityState(const PacMap& inState)
581 {
582     LOGI("AceAbility OnRestoreAbilityState called ");
583     Ability::OnRestoreAbilityState(inState);
584 }
585 
OnSaveAbilityState(PacMap& outState)586 void AceAbility::OnSaveAbilityState(PacMap& outState)
587 {
588     LOGI("AceAbility OnSaveAbilityState called ");
589     Ability::OnSaveAbilityState(outState);
590 }
591 
OnConfigurationUpdated(const Configuration& configuration)592 void AceAbility::OnConfigurationUpdated(const Configuration& configuration)
593 {
594     Ability::OnConfigurationUpdated(configuration);
595 
596     auto container = Platform::AceContainer::GetContainer(abilityId_);
597     CHECK_NULL_VOID(container);
598     auto taskExecutor = container->GetTaskExecutor();
599     CHECK_NULL_VOID(taskExecutor);
600     taskExecutor->PostTask(
601         [weakContainer = WeakPtr<Platform::AceContainer>(container), configuration]() {
602             auto container = weakContainer.Upgrade();
603             CHECK_NULL_VOID(container);
604             Platform::ParsedConfig parsedConfig;
605             parsedConfig.colorMode = configuration.GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
606             parsedConfig.deviceAccess =
607                 configuration.GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE);
608             parsedConfig.languageTag = configuration.GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE);
609             parsedConfig.direction = configuration.GetItem(OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DIRECTION);
610             parsedConfig.densitydpi =
611                 configuration.GetItem(OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DENSITYDPI);
612             container->UpdateConfiguration(parsedConfig, configuration.GetName());
613         },
614         TaskExecutor::TaskType::UI, "ArkUIAbilityUpdateConfiguration");
615     LOGI("AceAbility OnConfigurationUpdated called End, name:%{public}s", configuration.GetName().c_str());
616 }
617 
OnAbilityResult(int requestCode, int resultCode, const OHOS::AAFwk::Want& resultData)618 void AceAbility::OnAbilityResult(int requestCode, int resultCode, const OHOS::AAFwk::Want& resultData)
619 {
620     LOGI("AceAbility OnAbilityResult called ");
621     AbilityProcess::GetInstance()->OnAbilityResult(this, requestCode, resultCode, resultData);
622 }
623 
OnStartContinuation()624 bool AceAbility::OnStartContinuation()
625 {
626     LOGI("AceAbility OnStartContinuation called.");
627     bool ret = Platform::AceContainer::OnStartContinuation(abilityId_);
628     return ret;
629 }
630 
OnSaveData(OHOS::AAFwk::WantParams& saveData)631 bool AceAbility::OnSaveData(OHOS::AAFwk::WantParams& saveData)
632 {
633     LOGI("AceAbility OnSaveData called.");
634     std::string data = Platform::AceContainer::OnSaveData(abilityId_);
635     if (data == "false") {
636         return false;
637     }
638     auto json = JsonUtil::ParseJsonString(data);
639     if (!json) {
640         return false;
641     }
642     if (json->Contains(PAGE_URI)) {
643         saveData.SetParam(PAGE_URI, OHOS::AAFwk::String::Box(json->GetString(PAGE_URI)));
644     }
645     if (json->Contains(CONTINUE_PARAMS_KEY)) {
646         std::string params = json->GetObject(CONTINUE_PARAMS_KEY)->ToString();
647         saveData.SetParam(CONTINUE_PARAMS_KEY, OHOS::AAFwk::String::Box(params));
648     }
649     return true;
650 }
651 
OnRestoreData(OHOS::AAFwk::WantParams& restoreData)652 bool AceAbility::OnRestoreData(OHOS::AAFwk::WantParams& restoreData)
653 {
654     LOGI("AceAbility OnRestoreData called.");
655     if (restoreData.HasParam(PAGE_URI)) {
656         auto value = restoreData.GetParam(PAGE_URI);
657         OHOS::AAFwk::IString* ao = OHOS::AAFwk::IString::Query(value);
658         if (ao != nullptr) {
659             remotePageUrl_ = OHOS::AAFwk::String::Unbox(ao);
660         }
661     }
662     if (restoreData.HasParam(CONTINUE_PARAMS_KEY)) {
663         auto value = restoreData.GetParam(CONTINUE_PARAMS_KEY);
664         OHOS::AAFwk::IString* ao = OHOS::AAFwk::IString::Query(value);
665         if (ao != nullptr) {
666             remoteData_ = OHOS::AAFwk::String::Unbox(ao);
667         }
668     }
669     return true;
670 }
671 
OnCompleteContinuation(int result)672 void AceAbility::OnCompleteContinuation(int result)
673 {
674     Ability::OnCompleteContinuation(result);
675     LOGI("AceAbility OnCompleteContinuation called.");
676     Platform::AceContainer::OnCompleteContinuation(abilityId_, result);
677 }
678 
OnRemoteTerminated()679 void AceAbility::OnRemoteTerminated()
680 {
681     LOGI("AceAbility OnRemoteTerminated called.");
682     Platform::AceContainer::OnRemoteTerminated(abilityId_);
683 }
684 
OnSizeChange(const OHOS::Rosen::Rect& rect, OHOS::Rosen::WindowSizeChangeReason reason, const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction)685 void AceAbility::OnSizeChange(const OHOS::Rosen::Rect& rect, OHOS::Rosen::WindowSizeChangeReason reason,
686     const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction)
687 {
688     LOGI("width: %{public}u, height: %{public}u, left: %{public}d, top: %{public}d", rect.width_, rect.height_,
689         rect.posX_, rect.posY_);
690     SystemProperties::SetDeviceOrientation(rect.height_ >= rect.width_ ? 0 : 1);
691     auto container = Platform::AceContainer::GetContainer(abilityId_);
692     CHECK_NULL_VOID(container);
693     container->SetWindowPos(rect.posX_, rect.posY_);
694     auto pipelineContext = container->GetPipelineContext();
695     if (pipelineContext) {
696         pipelineContext->SetDisplayWindowRectInfo(
697             Rect(Offset(rect.posX_, rect.posY_), Size(rect.width_, rect.height_)));
698         pipelineContext->SetIsLayoutFullScreen(
699             Ability::GetWindow()->GetMode() == Rosen::WindowMode::WINDOW_MODE_FULLSCREEN);
700         auto isNeedAvoidWindowMode = SystemProperties::GetNeedAvoidWindow() &&
701             (Ability::GetWindow()->GetMode() == Rosen::WindowMode::WINDOW_MODE_FLOATING ||
702             Ability::GetWindow()->GetMode() == Rosen::WindowMode::WINDOW_MODE_SPLIT_PRIMARY ||
703             Ability::GetWindow()->GetMode() == Rosen::WindowMode::WINDOW_MODE_SPLIT_SECONDARY);
704         pipelineContext->SetIsNeedAvoidWindow(isNeedAvoidWindowMode);
705     }
706     auto taskExecutor = container->GetTaskExecutor();
707     CHECK_NULL_VOID(taskExecutor);
708     taskExecutor->PostTask(
709         [rect, density = density_, reason, container, rsTransaction]() {
710             auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
711             CHECK_NULL_VOID(aceView);
712             ViewportConfig config(rect.width_, rect.height_, density);
713             Platform::AceViewOhos::SetViewportMetrics(aceView, config);
714             Platform::AceViewOhos::SurfaceChanged(aceView, rect.width_, rect.height_,
715                 rect.height_ >= rect.width_ ? 0 : 1, static_cast<WindowSizeChangeReason>(reason), rsTransaction);
716         },
717         TaskExecutor::TaskType::PLATFORM, "ArkUIAbilitySurfaceChanged");
718 }
719 
OnModeChange(OHOS::Rosen::WindowMode mode, bool hasDeco)720 void AceAbility::OnModeChange(OHOS::Rosen::WindowMode mode, bool hasDeco)
721 {
722     LOGI("OnModeChange, window mode is %{public}d", mode);
723     auto container = Platform::AceContainer::GetContainer(abilityId_);
724     CHECK_NULL_VOID(container);
725     auto taskExecutor = container->GetTaskExecutor();
726     CHECK_NULL_VOID(taskExecutor);
727     ContainerScope scope(abilityId_);
728     taskExecutor->PostTask(
729         [container, mode, hasDeco]() {
730             auto pipelineContext = container->GetPipelineContext();
731             CHECK_NULL_VOID(pipelineContext);
732             pipelineContext->ShowContainerTitle(mode == OHOS::Rosen::WindowMode::WINDOW_MODE_FLOATING, hasDeco);
733         },
734         TaskExecutor::TaskType::UI, "ArkUIWindowModeChange");
735 }
736 
OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info, const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction)737 void AceAbility::OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info,
738     const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction)
739 {
740     auto rect = info->rect_;
741     auto type = info->type_;
742     Rect keyboardRect = Rect(rect.posX_, rect.posY_, rect.width_, rect.height_);
743     LOGI("AceAbility OccupiedAreaChange rect:%{public}s type: %{public}d", keyboardRect.ToString().c_str(), type);
744     if (type == OHOS::Rosen::OccupiedAreaType::TYPE_INPUT) {
745         auto container = Platform::AceContainer::GetContainer(abilityId_);
746         CHECK_NULL_VOID(container);
747         auto taskExecutor = container->GetTaskExecutor();
748         CHECK_NULL_VOID(taskExecutor);
749         ContainerScope scope(abilityId_);
750         taskExecutor->PostTask(
751             [container, keyboardRect, rsTransaction] {
752                 auto context = container->GetPipelineContext();
753                 CHECK_NULL_VOID(context);
754                 context->OnVirtualKeyboardAreaChange(keyboardRect, rsTransaction);
755             },
756             TaskExecutor::TaskType::UI, "ArkUIAbilityVirtualKeyboardAreaChange");
757     }
758 }
759 
Dump(const std::vector<std::string>& params, std::vector<std::string>& info)760 void AceAbility::Dump(const std::vector<std::string>& params, std::vector<std::string>& info)
761 {
762     auto container = Platform::AceContainer::GetContainer(abilityId_);
763     CHECK_NULL_VOID(container);
764     auto taskExecutor = container->GetTaskExecutor();
765     CHECK_NULL_VOID(taskExecutor);
766     ContainerScope scope(abilityId_);
767     taskExecutor->PostSyncTask(
768         [container, params, &info] { container->Dump(params, info); },
769         TaskExecutor::TaskType::UI, "ArkUIAbilityDump");
770 }
771 
OnDrag(int32_t x, int32_t y, OHOS::Rosen::DragEvent event)772 void AceAbility::OnDrag(int32_t x, int32_t y, OHOS::Rosen::DragEvent event)
773 {
774     LOGI("AceAbility OnDrag called ");
775     auto container = Platform::AceContainer::GetContainer(abilityId_);
776     CHECK_NULL_VOID(container);
777     auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
778     CHECK_NULL_VOID(aceView);
779     DragEventAction action;
780     switch (event) {
781         case OHOS::Rosen::DragEvent::DRAG_EVENT_END:
782             action = DragEventAction::DRAG_EVENT_END;
783             break;
784         case OHOS::Rosen::DragEvent::DRAG_EVENT_OUT:
785             action = DragEventAction::DRAG_EVENT_OUT;
786             break;
787         case OHOS::Rosen::DragEvent::DRAG_EVENT_MOVE:
788             action = DragEventAction::DRAG_EVENT_MOVE;
789             break;
790         case OHOS::Rosen::DragEvent::DRAG_EVENT_IN:
791         default:
792             action = DragEventAction::DRAG_EVENT_START;
793             break;
794     }
795 
796     aceView->ProcessDragEvent(x, y, action);
797 }
798 
OnInputEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent) const799 bool AceAbility::OnInputEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent) const
800 {
801     auto container = AceType::DynamicCast<Platform::AceContainer>(AceEngine::Get().GetContainer(abilityId_));
802     CHECK_NULL_RETURN(container, false);
803     container->SetCurPointerEvent(pointerEvent);
804     auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
805     CHECK_NULL_RETURN(aceView, false);
806     aceView->DispatchTouchEvent(aceView, pointerEvent);
807     return true;
808 }
809 
OnInputEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent) const810 bool AceAbility::OnInputEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent) const
811 {
812     auto container = Platform::AceContainer::GetContainer(abilityId_);
813     CHECK_NULL_RETURN(container, false);
814     auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
815     CHECK_NULL_RETURN(aceView, false);
816     int32_t keyCode = keyEvent->GetKeyCode();
817     int32_t keyAction = keyEvent->GetKeyAction();
818     if (keyCode == MMI::KeyEvent::KEYCODE_BACK && keyAction == MMI::KeyEvent::KEY_ACTION_UP) {
819         LOGI("OnInputEvent: Platform AceContainer OnBackPressed called");
820         if (Platform::AceContainer::OnBackPressed(abilityId_)) {
821             return true;
822         }
823         return false;
824     }
825     LOGI("OnInputEvent: dispatch key to arkui");
826     if (aceView->DispatchKeyEvent(aceView, keyEvent)) {
827         return true;
828     }
829     return false;
830 }
831 
OnInputEvent(const std::shared_ptr<MMI::AxisEvent>& axisEvent) const832 bool AceAbility::OnInputEvent(const std::shared_ptr<MMI::AxisEvent>& axisEvent) const
833 {
834     return false;
835 }
836 
SetBackgroundColor(uint32_t color)837 void AceAbility::SetBackgroundColor(uint32_t color)
838 {
839     LOGI("AceAbilityHandler SetBackgroundColor color is %{public}u", color);
840     auto container = Platform::AceContainer::GetContainer(abilityId_);
841     CHECK_NULL_VOID(container);
842     ContainerScope scope(abilityId_);
843     auto taskExecutor = container->GetTaskExecutor();
844     CHECK_NULL_VOID(taskExecutor);
845     taskExecutor->PostSyncTask(
846         [container, bgColor = color]() {
847             auto pipelineContext = container->GetPipelineContext();
848             CHECK_NULL_VOID(pipelineContext);
849             pipelineContext->SetAppBgColor(Color(bgColor));
850         },
851         TaskExecutor::TaskType::UI, "ArkUISetAppBackgroundColor");
852 }
853 
GetBackgroundColor()854 uint32_t AceAbility::GetBackgroundColor()
855 {
856     auto container = Platform::AceContainer::GetContainer(abilityId_);
857     CHECK_NULL_RETURN(container, 0x000000);
858     auto taskExecutor = container->GetTaskExecutor();
859     CHECK_NULL_RETURN(taskExecutor, 0x000000);
860     ContainerScope scope(abilityId_);
861     uint32_t bgColor = 0x000000;
862     taskExecutor->PostSyncTask(
863         [&bgColor, container]() {
864             CHECK_NULL_VOID(container);
865             auto pipelineContext = container->GetPipelineContext();
866             CHECK_NULL_VOID(pipelineContext);
867             bgColor = pipelineContext->GetAppBgColor().GetValue();
868         },
869         TaskExecutor::TaskType::UI, "ArkUIAbilityGetAppBackgroundColor");
870 
871     LOGI("AceAbilityHandler GetBackgroundColor, value is %{public}u", bgColor);
872     return bgColor;
873 }
874 
OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea& avoidArea, OHOS::Rosen::AvoidAreaType type)875 void AceAbility::OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea& avoidArea, OHOS::Rosen::AvoidAreaType type)
876 {
877     auto container = Platform::AceContainer::GetContainer((abilityId_));
878     CHECK_NULL_VOID(container);
879     auto pipeline = container->GetPipelineContext();
880     CHECK_NULL_VOID(
881         pipeline && pipeline->GetMinPlatformVersion() >= PLATFORM_VERSION_TEN && pipeline->GetIsAppWindow());
882     LOGI("AceAbility OnAvoidAreaChanged type:%{public}d, avoidArea:topRect:x:%{public}d, y:%{public}d, "
883          "width:%{public}d, height%{public}d",
884         type, avoidArea.topRect_.posX_, avoidArea.topRect_.posY_, (int32_t)avoidArea.topRect_.width_,
885         (int32_t)avoidArea.topRect_.height_);
886     auto taskExecutor = container->GetTaskExecutor();
887     CHECK_NULL_VOID(taskExecutor);
888     auto safeArea = ConvertAvoidArea(avoidArea);
889     ContainerScope scope(abilityId_);
890     taskExecutor->PostTask(
891         [pipeline, safeArea, type]() {
892             if (type == OHOS::Rosen::AvoidAreaType::TYPE_SYSTEM) {
893                 pipeline->UpdateSystemSafeArea(safeArea);
894             } else if (type == OHOS::Rosen::AvoidAreaType::TYPE_CUTOUT) {
895                 pipeline->UpdateCutoutSafeArea(safeArea);
896             }
897         },
898         TaskExecutor::TaskType::UI, "ArkUIAbilityAvoidAreaChanged");
899 }
900 
901 } // namespace Ace
902 } // namespace OHOS
903