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