• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 <regex>
19 #include <ui/rs_surface_node.h>
20 
21 #include "ability_process.h"
22 #include "display_type.h"
23 #include "dm/display_manager.h"
24 #include "form_utils_impl.h"
25 #include "init_data.h"
26 #include "ipc_skeleton.h"
27 #include "res_config.h"
28 #include "resource_manager.h"
29 #include "string_wrapper.h"
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/capability_registry.h"
38 #include "adapter/ohos/entrance/flutter_ace_view.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/log/log.h"
43 #include "base/subwindow/subwindow_manager.h"
44 #include "base/utils/system_properties.h"
45 #include "base/utils/utils.h"
46 #include "core/common/ace_engine.h"
47 #include "core/common/container_scope.h"
48 #include "core/common/frontend.h"
49 #include "core/common/plugin_manager.h"
50 #include "core/common/plugin_utils.h"
51 #include "core/common/form_manager.h"
52 #include "core/common/layout_inspector.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 static int32_t g_instanceId = 0;
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         LOGE("return default frontend: JS frontend.");
85         return FrontendType::JS;
86     }
87     auto rootJson = JsonUtil::ParseJsonString(jsonStr);
88     if (rootJson == nullptr) {
89         LOGE("return default frontend: JS frontend.");
90         return FrontendType::JS;
91     }
92     auto mode = rootJson->GetObject("mode");
93     if (mode != nullptr) {
94         if (mode->GetString("syntax") == "ets" || mode->GetString("type") == "pageAbility") {
95             return FrontendType::DECLARATIVE_JS;
96         }
97     }
98     return GetFrontendType(rootJson->GetString("type"));
99 }
100 
101 } // namespace
102 
103 using namespace OHOS::AAFwk;
104 using namespace OHOS::AppExecFwk;
105 
106 using AcePlatformFinish = std::function<void()>;
107 using AcePlatformStartAbility = std::function<void(const std::string& address)>;
108 class AcePlatformEventCallback final : public Platform::PlatformEventCallback {
109 public:
AcePlatformEventCallback(AcePlatformFinish onFinish)110     explicit AcePlatformEventCallback(AcePlatformFinish onFinish) : onFinish_(onFinish) {}
AcePlatformEventCallback(AcePlatformFinish onFinish,AcePlatformStartAbility onStartAbility)111     AcePlatformEventCallback(AcePlatformFinish onFinish, AcePlatformStartAbility onStartAbility)
112         : onFinish_(onFinish), onStartAbility_(onStartAbility)
113     {}
114 
115     ~AcePlatformEventCallback() override = default;
116 
OnFinish() const117     void OnFinish() const override
118     {
119         LOGI("AcePlatformEventCallback OnFinish");
120         CHECK_NULL_VOID_NOLOG(onFinish_);
121         onFinish_();
122     }
123 
OnStartAbility(const std::string & address)124     void OnStartAbility(const std::string& address) override
125     {
126         LOGI("AcePlatformEventCallback OnStartAbility");
127         CHECK_NULL_VOID_NOLOG(onStartAbility_);
128         onStartAbility_(address);
129     }
130 
OnStatusBarBgColorChanged(uint32_t color)131     void OnStatusBarBgColorChanged(uint32_t color) override
132     {
133         LOGI("AcePlatformEventCallback OnStatusBarBgColorChanged");
134     }
135 
136 private:
137     AcePlatformFinish onFinish_;
138     AcePlatformStartAbility onStartAbility_;
139 };
140 
141 const std::string AceAbility::START_PARAMS_KEY = "__startParams";
142 const std::string AceAbility::PAGE_URI = "url";
143 const std::string AceAbility::CONTINUE_PARAMS_KEY = "__remoteData";
144 
REGISTER_AA(AceAbility)145 REGISTER_AA(AceAbility)
146 void AceWindowListener::OnDrag(int32_t x, int32_t y, OHOS::Rosen::DragEvent event)
147 {
148     CHECK_NULL_VOID(callbackOwner_);
149     callbackOwner_->OnDrag(x, y, event);
150 }
151 
OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo> & info)152 void AceWindowListener::OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info)
153 {
154     CHECK_NULL_VOID(callbackOwner_);
155     callbackOwner_->OnSizeChange(info);
156 }
157 
SetBackgroundColor(uint32_t color)158 void AceWindowListener::SetBackgroundColor(uint32_t color)
159 {
160     CHECK_NULL_VOID(callbackOwner_);
161     callbackOwner_->SetBackgroundColor(color);
162 }
163 
GetBackgroundColor()164 uint32_t AceWindowListener::GetBackgroundColor()
165 {
166     CHECK_NULL_RETURN(callbackOwner_, 0);
167     return callbackOwner_->GetBackgroundColor();
168 }
169 
OnSizeChange(OHOS::Rosen::Rect rect,OHOS::Rosen::WindowSizeChangeReason reason)170 void AceWindowListener::OnSizeChange(OHOS::Rosen::Rect rect, OHOS::Rosen::WindowSizeChangeReason reason)
171 {
172     CHECK_NULL_VOID(callbackOwner_);
173     callbackOwner_->OnSizeChange(rect, reason);
174 }
175 
OnModeChange(OHOS::Rosen::WindowMode mode)176 void AceWindowListener::OnModeChange(OHOS::Rosen::WindowMode mode)
177 {
178     CHECK_NULL_VOID(callbackOwner_);
179     callbackOwner_->OnModeChange(mode);
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 
200 AceAbility::AceAbility() = default;
201 
OnStart(const Want & want)202 void AceAbility::OnStart(const Want& want)
203 {
204     Ability::OnStart(want);
205     LOGI("AceAbility::OnStart called");
206     abilityId_ = g_instanceId++;
207     static std::once_flag onceFlag;
208     auto abilityContext = GetAbilityContext();
209     std::call_once(onceFlag, [abilityContext]() {
210         LOGI("Initialize for current process.");
211         SetHwIcuDirectory();
212         Container::UpdateCurrent(INSTANCE_ID_PLATFORM);
213         CapabilityRegistry::Register();
214         AceApplicationInfo::GetInstance().SetPackageName(abilityContext->GetBundleName());
215         AceApplicationInfo::GetInstance().SetDataFileDirPath(abilityContext->GetFilesDir());
216         AceApplicationInfo::GetInstance().SetUid(IPCSkeleton::GetCallingUid());
217         AceApplicationInfo::GetInstance().SetPid(IPCSkeleton::GetCallingPid());
218         ImageCache::SetImageCacheFilePath(abilityContext->GetCacheDir());
219         ImageCache::SetCacheFileInfo();
220         AceEngine::InitJsDumpHeadSignal();
221     });
222     AceNewPipeJudgement::InitAceNewPipeConfig();
223     // TODO: now choose pipeline using param set as package name, later enable for all.
224     auto apiCompatibleVersion = abilityContext->GetApplicationInfo()->apiCompatibleVersion;
225     auto apiReleaseType = abilityContext->GetApplicationInfo()->apiReleaseType;
226     auto apiTargetVersion = abilityContext->GetApplicationInfo()->apiTargetVersion;
227     auto useNewPipe = AceNewPipeJudgement::QueryAceNewPipeEnabledFA(
228         AceApplicationInfo::GetInstance().GetPackageName(), apiCompatibleVersion, apiTargetVersion, apiReleaseType);
229     LOGI("AceAbility: apiCompatibleVersion: %{public}d, apiTargetVersion: %{public}d, and apiReleaseType: %{public}s, "
230          "useNewPipe: %{public}d",
231         apiCompatibleVersion, apiTargetVersion, apiReleaseType.c_str(), useNewPipe);
232     OHOS::sptr<OHOS::Rosen::Window> window = Ability::GetWindow();
233 
234     std::shared_ptr<AceAbility> self = std::static_pointer_cast<AceAbility>(shared_from_this());
235     OHOS::sptr<AceWindowListener> aceWindowListener = new AceWindowListener(self);
236     // register surface change callback and window mode change callback
237     window->RegisterWindowChangeListener(aceWindowListener);
238     // register drag event callback
239     window->RegisterDragListener(aceWindowListener);
240     // register Occupied Area callback
241     window->RegisterOccupiedAreaChangeListener(aceWindowListener);
242     // register ace ability handler callback
243     window->SetAceAbilityHandler(aceWindowListener);
244     // register input consumer callback
245     std::shared_ptr<AceWindowListener> aceInputConsumer = std::make_shared<AceWindowListener>(self);
246     window->SetInputEventConsumer(aceInputConsumer);
247 
248     int32_t deviceWidth = 0;
249     int32_t deviceHeight = 0;
250     auto defaultDisplay = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
251     if (defaultDisplay) {
252         density_ = defaultDisplay->GetVirtualPixelRatio();
253         deviceWidth = defaultDisplay->GetWidth();
254         deviceHeight = defaultDisplay->GetHeight();
255         LOGI("deviceWidth: %{public}d, deviceHeight: %{public}d, default density: %{public}f", deviceWidth,
256             deviceHeight, density_);
257     }
258     SystemProperties::InitDeviceInfo(deviceWidth, deviceHeight, deviceHeight >= deviceWidth ? 0 : 1, density_, false);
259     SystemProperties::SetColorMode(ColorMode::LIGHT);
260 
261     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
262     auto resourceManager = GetResourceManager();
263     if (resourceManager != nullptr) {
264         resourceManager->GetResConfig(*resConfig);
265         auto localeInfo = resConfig->GetLocaleInfo();
266         Platform::AceApplicationInfoImpl::GetInstance().SetResourceManager(resourceManager);
267         if (localeInfo != nullptr) {
268             auto language = localeInfo->getLanguage();
269             auto region = localeInfo->getCountry();
270             auto script = localeInfo->getScript();
271             AceApplicationInfo::GetInstance().SetLocale((language == nullptr) ? "" : language,
272                 (region == nullptr) ? "" : region, (script == nullptr) ? "" : script, "");
273         } else {
274             LOGW("localeInfo is null.");
275             AceApplicationInfo::GetInstance().SetLocale("", "", "", "");
276         }
277         if (resConfig->GetColorMode() == OHOS::Global::Resource::ColorMode::DARK) {
278             SystemProperties::SetColorMode(ColorMode::DARK);
279             LOGI("UIContent set dark mode");
280         } else {
281             SystemProperties::SetColorMode(ColorMode::LIGHT);
282             LOGI("UIContent set light mode");
283         }
284         SystemProperties::SetDeviceAccess(
285             resConfig->GetInputDevice() == Global::Resource::InputDevice::INPUTDEVICE_POINTINGDEVICE);
286     } else {
287         LOGW("resourceManager is null.");
288         AceApplicationInfo::GetInstance().SetLocale("", "", "", "");
289     }
290 
291     auto packagePathStr = GetBundleCodePath();
292     auto moduleInfo = GetHapModuleInfo();
293     CHECK_NULL_VOID_NOLOG(moduleInfo);
294     packagePathStr += "/" + moduleInfo->package + "/";
295     std::shared_ptr<AbilityInfo> info = GetAbilityInfo();
296     std::string srcPath;
297     if (info != nullptr && !info->srcPath.empty()) {
298         srcPath = info->srcPath;
299     }
300     if (info != nullptr && !info->bundleName.empty()) {
301         AceApplicationInfo::GetInstance().SetPackageName(info->bundleName);
302     }
303 
304     bool isHap = moduleInfo ? !moduleInfo->hapPath.empty() : false;
305     std::string& packagePath = isHap ? moduleInfo->hapPath : packagePathStr;
306     FrontendType frontendType = GetFrontendTypeFromManifest(packagePath, srcPath, isHap);
307     useNewPipe = useNewPipe && (frontendType == FrontendType::ETS_CARD || frontendType == FrontendType::DECLARATIVE_JS);
308     if (frontendType != FrontendType::ETS_CARD && frontendType != FrontendType::DECLARATIVE_JS) {
309         LOGI("AceAbility: JS project use old pipeline");
310     }
311     std::shared_ptr<OHOS::Rosen::RSUIDirector> rsUiDirector;
312     if (SystemProperties::GetRosenBackendEnabled() && !useNewPipe) {
313         rsUiDirector = OHOS::Rosen::RSUIDirector::Create();
314         if (rsUiDirector) {
315             rsUiDirector->SetRSSurfaceNode(window->GetSurfaceNode());
316             rsUiDirector->SetCacheDir(abilityContext->GetCacheDir());
317             rsUiDirector->Init();
318         }
319     }
320     bool isArkApp = GetIsArkFromConfig(packagePath, isHap);
321 
322     AceApplicationInfo::GetInstance().SetAbilityName(info ? info->name : "");
323     std::string moduleName = info ? info->moduleName : "";
324     std::string moduleHapPath = info ? info->hapPath : "";
325 
326     std::shared_ptr<ApplicationInfo> appInfo = GetApplicationInfo();
327     std::vector<ModuleInfo> moduleList = appInfo->moduleInfos;
328 
329     std::string resPath;
330     for (const auto& module : moduleList) {
331         if (module.moduleName == moduleName && info != nullptr) {
332             std::regex pattern(ABS_BUNDLE_CODE_PATH + info->bundleName + FILE_SEPARATOR);
333             auto moduleSourceDir = std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
334             resPath = moduleSourceDir + "/assets/" + module.moduleName + FILE_SEPARATOR;
335             break;
336         }
337     }
338     std::string hapPath;
339     if (!moduleHapPath.empty()) {
340         if (moduleHapPath.find(ABS_BUNDLE_CODE_PATH) == std::string::npos) {
341             hapPath = moduleHapPath;
342         } else {
343             auto pos = moduleHapPath.find_last_of('/');
344             if (pos != std::string::npos) {
345                 hapPath = LOCAL_BUNDLE_CODE_PATH + moduleHapPath.substr(pos + 1);
346                 LOGI("In FA mode, hapPath:%{private}s", hapPath.c_str());
347             }
348         }
349     }
350 
351     AceApplicationInfo::GetInstance().SetDebug(appInfo->debug, want.GetBoolParam("debugApp", false));
352 
353     auto pluginUtils = std::make_shared<PluginUtilsImpl>();
354     PluginManager::GetInstance().SetAceAbility(this, pluginUtils);
355     auto formUtils = std::make_shared<FormUtilsImpl>();
356     FormManager::GetInstance().SetFormUtils(formUtils);
357     // create container
358     Platform::AceContainer::CreateContainer(abilityId_, frontendType, isArkApp, srcPath, shared_from_this(),
359         std::make_unique<AcePlatformEventCallback>([this]() { TerminateAbility(); },
360             [this](const std::string& address) {
361                 AAFwk::Want want;
362                 want.AddEntity(Want::ENTITY_BROWSER);
363                 want.SetUri(address);
364                 want.SetAction(ACTION_VIEWDATA);
365                 this->StartAbility(want);
366             }),
367         false, useNewPipe);
368     auto container = Platform::AceContainer::GetContainer(abilityId_);
369     CHECK_NULL_VOID(container);
370     container->SetToken(token_);
371     auto aceResCfg = container->GetResourceConfiguration();
372     aceResCfg.SetOrientation(SystemProperties::GetDeviceOrientation());
373     aceResCfg.SetDensity(SystemProperties::GetResolution());
374     aceResCfg.SetDeviceType(SystemProperties::GetDeviceType());
375     aceResCfg.SetColorMode(SystemProperties::GetColorMode());
376     aceResCfg.SetDeviceAccess(SystemProperties::GetDeviceAccess());
377     container->SetResourceConfiguration(aceResCfg);
378     container->SetPackagePathStr(resPath);
379     container->SetHapPath(hapPath);
380     container->SetBundlePath(abilityContext->GetBundleCodeDir());
381     container->SetFilesDataPath(abilityContext->GetFilesDir());
382     if (window->IsDecorEnable()) {
383         LOGI("Container modal is enabled.");
384         container->SetWindowModal(WindowModal::CONTAINER_MODAL);
385     }
386     container->SetWindowName(window->GetWindowName());
387     container->SetWindowId(window->GetWindowId());
388     SubwindowManager::GetInstance()->AddContainerId(window->GetWindowId(), abilityId_);
389     // create view.
390     auto flutterAceView = Platform::FlutterAceView::CreateView(abilityId_);
391     Platform::FlutterAceView::SurfaceCreated(flutterAceView, window);
392 
393     if (srcPath.empty()) {
394         auto assetBasePathStr = { std::string("assets/js/default/"), std::string("assets/js/share/") };
395         Platform::AceContainer::AddAssetPath(abilityId_, packagePathStr, moduleInfo->hapPath, assetBasePathStr);
396     } else {
397         auto assetBasePathStr = { "assets/js/" + srcPath + "/", std::string("assets/js/share/") };
398         Platform::AceContainer::AddAssetPath(abilityId_, packagePathStr, moduleInfo->hapPath, assetBasePathStr);
399     }
400 
401     /* Note: DO NOT modify the sequence of adding libPath  */
402     std::string nativeLibraryPath = appInfo->nativeLibraryPath;
403     std::string quickFixLibraryPath = appInfo->appQuickFix.deployedAppqfInfo.nativeLibraryPath;
404     std::vector<std::string> libPaths;
405     if (!quickFixLibraryPath.empty()) {
406         std::string libPath = GenerateFullPath(GetBundleCodePath(), quickFixLibraryPath);
407         libPaths.push_back(libPath);
408         LOGI("napi quick fix lib path = %{private}s", libPath.c_str());
409     }
410     if (!nativeLibraryPath.empty()) {
411         std::string libPath = GenerateFullPath(GetBundleCodePath(), nativeLibraryPath);
412         libPaths.push_back(libPath);
413         LOGI("napi lib path = %{private}s", libPath.c_str());
414     }
415     if (!libPaths.empty()) {
416         Platform::AceContainer::AddLibPath(abilityId_, libPaths);
417     }
418 
419     if (!useNewPipe) {
420         Ace::Platform::UIEnvCallback callback = nullptr;
421 #ifdef ENABLE_ROSEN_BACKEND
422         callback = [window, id = abilityId_, flutterAceView, rsUiDirector](
423                        const OHOS::Ace::RefPtr<OHOS::Ace::PipelineContext>& context) mutable {
424             if (rsUiDirector) {
425                 rsUiDirector->SetUITaskRunner(
426                     [taskExecutor = Platform::AceContainer::GetContainer(id)->GetTaskExecutor(), id](
427                         const std::function<void()>& task) {
428                         ContainerScope scope(id);
429                         taskExecutor->PostTask(task, TaskExecutor::TaskType::UI);
430                     });
431                 if (context != nullptr) {
432                     context->SetRSUIDirector(rsUiDirector);
433                 }
434                 flutterAceView->InitIOManager(Platform::AceContainer::GetContainer(id)->GetTaskExecutor());
435                 LOGI("Init Rosen Backend");
436             } else {
437                 LOGI("not Init Rosen Backend");
438             }
439         };
440 #endif
441         // set view
442         Platform::AceContainer::SetView(flutterAceView, density_, 0, 0, window, callback);
443     } else {
444         Platform::AceContainer::SetViewNew(flutterAceView, density_, 0, 0, window);
445     }
446 
447     Platform::FlutterAceView::SurfaceChanged(flutterAceView, 0, 0, deviceHeight >= deviceWidth ? 0 : 1);
448 
449     // action event handler
450     auto&& actionEventHandler = [this](const std::string& action) {
451         LOGI("on Action called to event handler");
452 
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("bundle:%{public}s ability:%{public}s, params:%{public}s", bundle.c_str(), ability.c_str(),
460             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_NOLOG(window, rect);
478             auto windowRect = window->GetRect();
479             rect.SetRect(windowRect.posX_, windowRect.posY_, windowRect.width_, windowRect.height_);
480             return rect;
481         });
482     }
483 
484     // get url
485     std::string parsedPageUrl;
486     if (!remotePageUrl_.empty()) {
487         parsedPageUrl = remotePageUrl_;
488     } else if (!pageUrl_.empty()) {
489         parsedPageUrl = pageUrl_;
490     } else if (want.HasParameter(PAGE_URI)) {
491         parsedPageUrl = want.GetStringParam(PAGE_URI);
492     } else {
493         parsedPageUrl = "";
494     }
495 
496     auto windowRect = window->GetRect();
497     if (!windowRect.isUninitializedRect()) {
498         LOGI("notify window rect explicitly");
499         OnSizeChange(windowRect, OHOS::Rosen::WindowSizeChangeReason::UNDEFINED);
500     }
501     // run page.
502     Platform::AceContainer::RunPage(abilityId_, Platform::AceContainer::GetContainer(abilityId_)->GeneratePageId(),
503         parsedPageUrl, want.GetStringParam(START_PARAMS_KEY));
504 
505     if (!remoteData_.empty()) {
506         Platform::AceContainer::OnRestoreData(abilityId_, remoteData_);
507     }
508     LayoutInspector::SetCallback(abilityId_);
509     LOGI("AceAbility::OnStart called End");
510 }
511 
OnStop()512 void AceAbility::OnStop()
513 {
514     LOGI("AceAbility::OnStop called ");
515     Ability::OnStop();
516     Platform::AceContainer::DestroyContainer(abilityId_);
517     abilityId_ = -1;
518     LOGI("AceAbility::OnStop called End");
519 }
520 
OnActive()521 void AceAbility::OnActive()
522 {
523     LOGI("AceAbility::OnActive called ");
524     // AbilityManager will miss first OnForeground notification
525     if (isFirstActive_) {
526         Platform::AceContainer::OnShow(abilityId_);
527         isFirstActive_ = false;
528     }
529     Ability::OnActive();
530     Platform::AceContainer::OnActive(abilityId_);
531     LOGI("AceAbility::OnActive called End");
532 }
533 
OnForeground(const Want & want)534 void AceAbility::OnForeground(const Want& want)
535 {
536     LOGI("AceAbility::OnForeground called ");
537     Ability::OnForeground(want);
538     Platform::AceContainer::OnShow(abilityId_);
539     LOGI("AceAbility::OnForeground called End");
540 }
541 
OnBackground()542 void AceAbility::OnBackground()
543 {
544     LOGI("AceAbility::OnBackground called ");
545     Ability::OnBackground();
546     Platform::AceContainer::OnHide(abilityId_);
547     LOGI("AceAbility::OnBackground called End");
548 }
549 
OnInactive()550 void AceAbility::OnInactive()
551 {
552     LOGI("AceAbility::OnInactive called ");
553     Ability::OnInactive();
554     Platform::AceContainer::OnInactive(abilityId_);
555     LOGI("AceAbility::OnInactive called End");
556 }
557 
OnBackPressed()558 void AceAbility::OnBackPressed()
559 {
560     LOGI("AceAbility::OnBackPressed called ");
561     if (!Platform::AceContainer::OnBackPressed(abilityId_)) {
562         LOGI("AceAbility::OnBackPressed: passed to Ability to process");
563         Ability::OnBackPressed();
564     }
565     LOGI("AceAbility::OnBackPressed called End");
566 }
567 
OnNewWant(const Want & want)568 void AceAbility::OnNewWant(const Want& want)
569 {
570     LOGI("AceAbility::OnNewWant called ");
571     Ability::OnNewWant(want);
572     std::string params = want.GetStringParam(START_PARAMS_KEY);
573     Platform::AceContainer::OnNewRequest(abilityId_, params);
574     std::string data = want.ToString();
575     Platform::AceContainer::OnNewWant(abilityId_, data);
576     LOGI("AceAbility::OnNewWant called End");
577 }
578 
OnRestoreAbilityState(const PacMap & inState)579 void AceAbility::OnRestoreAbilityState(const PacMap& inState)
580 {
581     LOGI("AceAbility::OnRestoreAbilityState called ");
582     Ability::OnRestoreAbilityState(inState);
583     LOGI("AceAbility::OnRestoreAbilityState called End");
584 }
585 
OnSaveAbilityState(PacMap & outState)586 void AceAbility::OnSaveAbilityState(PacMap& outState)
587 {
588     LOGI("AceAbility::OnSaveAbilityState called ");
589     Ability::OnSaveAbilityState(outState);
590     LOGI("AceAbility::OnSaveAbilityState called End");
591 }
592 
OnConfigurationUpdated(const Configuration & configuration)593 void AceAbility::OnConfigurationUpdated(const Configuration& configuration)
594 {
595     LOGI("AceAbility::OnConfigurationUpdated called ");
596     Ability::OnConfigurationUpdated(configuration);
597     Platform::AceContainer::OnConfigurationUpdated(abilityId_, configuration.GetName());
598 
599     auto container = Platform::AceContainer::GetContainer(abilityId_);
600     CHECK_NULL_VOID(container);
601     auto taskExecutor = container->GetTaskExecutor();
602     CHECK_NULL_VOID(taskExecutor);
603     taskExecutor->PostTask(
604         [weakContainer = WeakPtr<Platform::AceContainer>(container), configuration]() {
605             auto container = weakContainer.Upgrade();
606             CHECK_NULL_VOID_NOLOG(container);
607             auto colorMode = configuration.GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
608             auto deviceAccess = configuration.GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE);
609             auto languageTag = configuration.GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE);
610             container->UpdateConfiguration(colorMode, deviceAccess, languageTag);
611         },
612         TaskExecutor::TaskType::UI);
613     LOGI("AceAbility::OnConfigurationUpdated called End, name:%{public}s", configuration.GetName().c_str());
614 }
615 
OnAbilityResult(int requestCode,int resultCode,const OHOS::AAFwk::Want & resultData)616 void AceAbility::OnAbilityResult(int requestCode, int resultCode, const OHOS::AAFwk::Want& resultData)
617 {
618     LOGI("AceAbility::OnAbilityResult called ");
619     AbilityProcess::GetInstance()->OnAbilityResult(this, requestCode, resultCode, resultData);
620     LOGI("AceAbility::OnAbilityResult called End");
621 }
622 
OnStartContinuation()623 bool AceAbility::OnStartContinuation()
624 {
625     LOGI("AceAbility::OnStartContinuation called.");
626     bool ret = Platform::AceContainer::OnStartContinuation(abilityId_);
627     LOGI("AceAbility::OnStartContinuation finish.");
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     LOGI("AceAbility::OnSaveData finish.");
650     return true;
651 }
652 
OnRestoreData(OHOS::AAFwk::WantParams & restoreData)653 bool AceAbility::OnRestoreData(OHOS::AAFwk::WantParams& restoreData)
654 {
655     LOGI("AceAbility::OnRestoreData called.");
656     if (restoreData.HasParam(PAGE_URI)) {
657         auto value = restoreData.GetParam(PAGE_URI);
658         OHOS::AAFwk::IString* ao = OHOS::AAFwk::IString::Query(value);
659         if (ao != nullptr) {
660             remotePageUrl_ = OHOS::AAFwk::String::Unbox(ao);
661         }
662     }
663     if (restoreData.HasParam(CONTINUE_PARAMS_KEY)) {
664         auto value = restoreData.GetParam(CONTINUE_PARAMS_KEY);
665         OHOS::AAFwk::IString* ao = OHOS::AAFwk::IString::Query(value);
666         if (ao != nullptr) {
667             remoteData_ = OHOS::AAFwk::String::Unbox(ao);
668         }
669     }
670     LOGI("AceAbility::OnRestoreData finish.");
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     LOGI("AceAbility::OnCompleteContinuation finish.");
680 }
681 
OnRemoteTerminated()682 void AceAbility::OnRemoteTerminated()
683 {
684     LOGI("AceAbility::OnRemoteTerminated called.");
685     Platform::AceContainer::OnRemoteTerminated(abilityId_);
686     LOGI("AceAbility::OnRemoteTerminated finish.");
687 }
688 
OnSizeChange(const OHOS::Rosen::Rect & rect,OHOS::Rosen::WindowSizeChangeReason reason)689 void AceAbility::OnSizeChange(const OHOS::Rosen::Rect& rect, OHOS::Rosen::WindowSizeChangeReason reason)
690 {
691     LOGI("width: %{public}u, height: %{public}u, left: %{public}d, top: %{public}d", rect.width_, rect.height_,
692         rect.posX_, rect.posY_);
693     SystemProperties::SetDeviceOrientation(rect.height_ >= rect.width_ ? 0 : 1);
694     auto container = Platform::AceContainer::GetContainer(abilityId_);
695     CHECK_NULL_VOID(container);
696     container->SetWindowPos(rect.posX_, rect.posY_);
697     auto pipelineContext = container->GetPipelineContext();
698     if (pipelineContext) {
699         pipelineContext->SetDisplayWindowRectInfo(
700             Rect(Offset(rect.posX_, rect.posY_), Size(rect.width_, rect.height_)));
701     }
702     auto taskExecutor = container->GetTaskExecutor();
703     CHECK_NULL_VOID(taskExecutor);
704     taskExecutor->PostTask(
705         [rect, density = density_, reason, container]() {
706             auto flutterAceView = static_cast<Platform::FlutterAceView*>(container->GetView());
707             CHECK_NULL_VOID(flutterAceView);
708             flutter::ViewportMetrics metrics;
709             metrics.physical_width = rect.width_;
710             metrics.physical_height = rect.height_;
711             metrics.device_pixel_ratio = density;
712             Platform::FlutterAceView::SetViewportMetrics(flutterAceView, metrics);
713             Platform::FlutterAceView::SurfaceChanged(flutterAceView, rect.width_, rect.height_,
714                 rect.height_ >= rect.width_ ? 0 : 1, static_cast<WindowSizeChangeReason>(reason));
715         },
716         TaskExecutor::TaskType::PLATFORM);
717 }
718 
OnModeChange(OHOS::Rosen::WindowMode mode)719 void AceAbility::OnModeChange(OHOS::Rosen::WindowMode mode)
720 {
721     LOGI("OnModeChange, window mode is %{public}d", mode);
722     auto container = Platform::AceContainer::GetContainer(abilityId_);
723     CHECK_NULL_VOID(container);
724     auto taskExecutor = container->GetTaskExecutor();
725     CHECK_NULL_VOID(taskExecutor);
726     ContainerScope scope(abilityId_);
727     taskExecutor->PostTask(
728         [container, mode]() {
729             auto pipelineContext = container->GetPipelineContext();
730             CHECK_NULL_VOID(pipelineContext);
731             pipelineContext->ShowContainerTitle(mode == OHOS::Rosen::WindowMode::WINDOW_MODE_FLOATING);
732         },
733         TaskExecutor::TaskType::UI);
734 }
735 
OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo> & info)736 void AceAbility::OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info)
737 {
738     auto rect = info->rect_;
739     auto type = info->type_;
740     Rect keyboardRect = Rect(rect.posX_, rect.posY_, rect.width_, rect.height_);
741     LOGI("AceAbility::OccupiedAreaChange rect:%{public}s type: %{public}d", keyboardRect.ToString().c_str(), type);
742     if (type == OHOS::Rosen::OccupiedAreaType::TYPE_INPUT) {
743         auto container = Platform::AceContainer::GetContainer(abilityId_);
744         CHECK_NULL_VOID(container);
745         auto taskExecutor = container->GetTaskExecutor();
746         CHECK_NULL_VOID(taskExecutor);
747         ContainerScope scope(abilityId_);
748         taskExecutor->PostTask(
749             [container, keyboardRect] {
750                 auto context = container->GetPipelineContext();
751                 CHECK_NULL_VOID_NOLOG(context);
752                 context->OnVirtualKeyboardAreaChange(keyboardRect);
753             },
754             TaskExecutor::TaskType::UI);
755     }
756 }
757 
Dump(const std::vector<std::string> & params,std::vector<std::string> & info)758 void AceAbility::Dump(const std::vector<std::string>& params, std::vector<std::string>& info)
759 {
760     auto container = Platform::AceContainer::GetContainer(abilityId_);
761     CHECK_NULL_VOID(container);
762     auto taskExecutor = container->GetTaskExecutor();
763     CHECK_NULL_VOID(taskExecutor);
764     ContainerScope scope(abilityId_);
765     taskExecutor->PostSyncTask(
766         [container, params, &info] {
767             auto context = container->GetPipelineContext();
768             CHECK_NULL_VOID_NOLOG(context);
769             context->DumpInfo(params, info);
770         },
771         TaskExecutor::TaskType::UI);
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 flutterAceView = static_cast<Platform::FlutterAceView*>(container->GetView());
780     CHECK_NULL_VOID(flutterAceView);
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     flutterAceView->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 = Platform::AceContainer::GetContainer(abilityId_);
804     CHECK_NULL_RETURN(container, false);
805     auto flutterAceView = static_cast<Platform::FlutterAceView*>(container->GetView());
806     CHECK_NULL_RETURN(flutterAceView, false);
807     flutterAceView->DispatchTouchEvent(flutterAceView, pointerEvent);
808     return true;
809 }
810 
OnInputEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent) const811 bool AceAbility::OnInputEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent) const
812 {
813     auto container = Platform::AceContainer::GetContainer(abilityId_);
814     CHECK_NULL_RETURN(container, false);
815     auto flutterAceView = static_cast<Platform::FlutterAceView*>(container->GetView());
816     CHECK_NULL_RETURN(flutterAceView, false);
817     int32_t keyCode = keyEvent->GetKeyCode();
818     int32_t keyAction = keyEvent->GetKeyAction();
819     if (keyCode == MMI::KeyEvent::KEYCODE_BACK && keyAction == MMI::KeyEvent::KEY_ACTION_UP) {
820         LOGI("OnInputEvent: Platform::AceContainer::OnBackPressed called");
821         if (Platform::AceContainer::OnBackPressed(abilityId_)) {
822             LOGI("OnInputEvent: Platform::AceContainer::OnBackPressed return true");
823             return true;
824         }
825         LOGI("OnInputEvent: Platform::AceContainer::OnBackPressed return false");
826         return false;
827     }
828     LOGI("OnInputEvent: dispatch key to arkui");
829     if (flutterAceView->DispatchKeyEvent(flutterAceView, keyEvent)) {
830         LOGI("OnInputEvent: arkui consumed this key event");
831         return true;
832     }
833     LOGI("OnInputEvent: arkui do not consumed this key event");
834     return false;
835 }
836 
OnInputEvent(const std::shared_ptr<MMI::AxisEvent> & axisEvent) const837 bool AceAbility::OnInputEvent(const std::shared_ptr<MMI::AxisEvent>& axisEvent) const
838 {
839     return false;
840 }
841 
SetBackgroundColor(uint32_t color)842 void AceAbility::SetBackgroundColor(uint32_t color)
843 {
844     LOGI("AceAbilityHandler::SetBackgroundColor color is %{public}u", color);
845     auto container = Platform::AceContainer::GetContainer(abilityId_);
846     CHECK_NULL_VOID(container);
847     ContainerScope scope(abilityId_);
848     auto taskExecutor = container->GetTaskExecutor();
849     CHECK_NULL_VOID(taskExecutor);
850     taskExecutor->PostSyncTask(
851         [container, bgColor = color]() {
852             auto pipelineContext = container->GetPipelineContext();
853             CHECK_NULL_VOID(pipelineContext);
854             pipelineContext->SetAppBgColor(Color(bgColor));
855         },
856         TaskExecutor::TaskType::UI);
857 }
858 
GetBackgroundColor()859 uint32_t AceAbility::GetBackgroundColor()
860 {
861     auto container = Platform::AceContainer::GetContainer(abilityId_);
862     CHECK_NULL_RETURN(container, 0x000000);
863     auto taskExecutor = container->GetTaskExecutor();
864     CHECK_NULL_RETURN(taskExecutor, 0x000000);
865     ContainerScope scope(abilityId_);
866     uint32_t bgColor = 0x000000;
867     taskExecutor->PostSyncTask(
868         [&bgColor, container]() {
869             CHECK_NULL_VOID(container);
870             auto pipelineContext = container->GetPipelineContext();
871             CHECK_NULL_VOID(pipelineContext);
872             bgColor = pipelineContext->GetAppBgColor().GetValue();
873         },
874         TaskExecutor::TaskType::UI);
875 
876     LOGI("AceAbilityHandler::GetBackgroundColor, value is %{public}u", bgColor);
877     return bgColor;
878 }
879 } // namespace Ace
880 } // namespace OHOS
881