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