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