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/preview/entrance/ace_ability.h"
17 #include "adapter/preview/entrance/ace_view_preview.h"
18
19 #ifdef INIT_ICU_DATA_PATH
20 #include "unicode/putil.h"
21 #endif
22
23 #include <ui/rs_surface_node.h>
24 #include <ui/rs_ui_director.h>
25
26 #include "include/core/SkFontMgr.h"
27 #include "previewer/include/window.h"
28
29 #include "adapter/ohos/entrance/ace_new_pipe_judgement.h"
30 #include "adapter/preview/entrance/ace_application_info.h"
31 #include "adapter/preview/entrance/ace_container.h"
32 #include "adapter/preview/entrance/event_dispatcher.h"
33 #include "adapter/preview/entrance/rs_dir_asset_provider.h"
34 #include "adapter/preview/external/ability/stage/stage_context.h"
35 #include "adapter/preview/inspector/inspector_client.h"
36 #include "core/common/resource/resource_configuration.h"
37 #include "frameworks/base/utils/utils.h"
38 #include "frameworks/bridge/common/utils/utils.h"
39 #include "frameworks/bridge/js_frontend/js_frontend.h"
40 #include "frameworks/core/common/ace_engine.h"
41 #ifdef COMPONENT_TEST_ENABLED
42 #include "frameworks/component_test/test_config.h"
43 #endif // COMPONENT_TEST_ENABLED
44
45 namespace OHOS::Ace::Platform {
46 namespace {
47
48 constexpr char ASSET_PATH_SHARE[] = "share";
49 #ifdef WINDOWS_PLATFORM
50 constexpr char DELIMITER[] = "\\";
51 constexpr char ASSET_PATH_SHARE_STAGE[] = "resources\\base\\profile";
52 #else
53 constexpr char DELIMITER[] = "/";
54 constexpr char ASSET_PATH_SHARE_STAGE[] = "resources/base/profile";
55 #endif
56
SetFontMgrConfig(const std::string & containerSdkPath)57 void SetFontMgrConfig(const std::string& containerSdkPath)
58 {
59 // To check if use ohos or container fonts.
60 std::string runtimeOS = "OHOS_Container";
61 std::string containerFontBasePath = containerSdkPath + DELIMITER + "resources" + DELIMITER + "fonts" + DELIMITER;
62 RSDirAssetProvider dirAsset(containerFontBasePath);
63 std::vector<std::string> fileList;
64 dirAsset.GetAssetList("", fileList);
65 if (containerSdkPath.empty() || fileList.empty()) {
66 runtimeOS = "OHOS";
67 containerFontBasePath = "";
68 }
69 SkFontMgr::SetFontMgrConfig(runtimeOS, containerFontBasePath);
70 }
71
GetCustomAssetPath(std::string assetPath)72 std::string GetCustomAssetPath(std::string assetPath)
73 {
74 if (assetPath.empty()) {
75 LOGW("AssetPath is null.");
76 return std::string();
77 }
78 std::string customAssetPath;
79 if (OHOS::Ace::Framework::EndWith(assetPath, DELIMITER)) {
80 assetPath = assetPath.substr(0, assetPath.size() - 1);
81 }
82 customAssetPath = assetPath.substr(0, assetPath.find_last_of(DELIMITER) + 1);
83 return customAssetPath;
84 }
85
DumpAceRunArgs(const AceRunArgs & runArgs)86 inline void DumpAceRunArgs(const AceRunArgs& runArgs)
87 {
88 #ifdef ACE_DEBUG
89 LOGI("runArgs.pageProfile: %{private}s", runArgs.pageProfile.c_str());
90 LOGI("runArgs.asset: %{private}s", runArgs.assetPath.c_str());
91 LOGI("runArgs.systemResources: %{private}s", runArgs.systemResourcesPath.c_str());
92 LOGI("runArgs.appResources: %{private}s", runArgs.appResourcesPath.c_str());
93 LOGI("runArgs.themeId: %{private}u", runArgs.themeId);
94 LOGI("runArgs.deviceConfig.orientation: %{private}d", static_cast<int>(runArgs.deviceConfig.orientation));
95 LOGI("runArgs.deviceConfig.density: %{private}lf", runArgs.deviceConfig.density);
96 LOGI("runArgs.deviceConfig.deviceType: %{private}d", static_cast<int>(runArgs.deviceConfig.deviceType));
97 LOGI("runArgs.deviceConfig.fontRatio: %{private}lf", runArgs.deviceConfig.fontRatio);
98 LOGI("runArgs.deviceConfig.colorMode: %{private}d", static_cast<int>(runArgs.deviceConfig.colorMode));
99 LOGI("runArgs.url: %{private}s", runArgs.url.c_str());
100 LOGI("runArgs.windowTitle: %{private}s", runArgs.windowTitle.c_str());
101 LOGI("runArgs.isRound: %{private}s", runArgs.isRound ? "true" : "false");
102 LOGI("runArgs.viewWidth: %{private}d", runArgs.viewWidth);
103 LOGI("runArgs.viewHeight: %{private}d", runArgs.viewHeight);
104 LOGI("runArgs.deviceWidth: %{private}d", runArgs.deviceWidth);
105 LOGI("runArgs.deviceHeight: %{private}d", runArgs.deviceHeight);
106 #endif
107 }
108
109 } // namespace
110
ConvertAvoidArea(const OHOS::Rosen::AvoidArea & avoidArea)111 NG::SafeAreaInsets ConvertAvoidArea(const OHOS::Rosen::AvoidArea& avoidArea)
112 {
113 return NG::SafeAreaInsets({ avoidArea.leftRect_.posX_, avoidArea.leftRect_.posX_ + avoidArea.leftRect_.width_ },
114 { avoidArea.topRect_.posY_, avoidArea.topRect_.posY_ + avoidArea.topRect_.height_ },
115 { avoidArea.rightRect_.posX_, avoidArea.rightRect_.posX_ + avoidArea.rightRect_.width_ },
116 { avoidArea.bottomRect_.posY_, avoidArea.bottomRect_.posY_ + avoidArea.bottomRect_.height_ });
117 }
118
GetViewSafeAreaByType(OHOS::Rosen::AvoidAreaType type,sptr<OHOS::Rosen::Window> rsWindow)119 NG::SafeAreaInsets GetViewSafeAreaByType(OHOS::Rosen::AvoidAreaType type, sptr<OHOS::Rosen::Window> rsWindow)
120 {
121 CHECK_NULL_RETURN(rsWindow, {});
122 Rosen::AvoidArea avoidArea;
123 Rosen::WMError ret = rsWindow->GetAvoidAreaByType(type, avoidArea);
124 if (ret == Rosen::WMError::WM_OK) {
125 auto safeAreaInsets = ConvertAvoidArea(avoidArea);
126 LOGI("SafeArea get success, area type is:%{public}d insets area is:%{public}s", static_cast<int32_t>(type),
127 safeAreaInsets.ToString().c_str());
128 return safeAreaInsets;
129 }
130 return {};
131 }
132
133 class IIgnoreViewSafeAreaListenerPreview : public OHOS::Rosen::IIgnoreViewSafeAreaListener {
134 public:
IIgnoreViewSafeAreaListenerPreview(int32_t instanceId)135 explicit IIgnoreViewSafeAreaListenerPreview(int32_t instanceId) : instanceId_(instanceId) {}
136 ~IIgnoreViewSafeAreaListenerPreview() = default;
137
SetIgnoreViewSafeArea(bool ignoreViewSafeArea)138 void SetIgnoreViewSafeArea(bool ignoreViewSafeArea)
139 {
140 LOGD("[instanceId_:%{public}d]: SetIgnoreViewSafeArea:%{public}u", instanceId_, ignoreViewSafeArea);
141 auto container = AceEngine::Get().GetContainer(instanceId_);
142 CHECK_NULL_VOID(container);
143 auto pipelineContext = container->GetPipelineContext();
144 auto taskExecutor = container->GetTaskExecutor();
145 CHECK_NULL_VOID(taskExecutor);
146 taskExecutor->PostSyncTask(
147 [&pipelineContext, container, ignoreSafeArea = ignoreViewSafeArea]() {
148 pipelineContext->SetIgnoreViewSafeArea(ignoreSafeArea);
149 },
150 TaskExecutor::TaskType::UI, "ArkUISetIgnoreViewSafeArea");
151 }
152
153 private:
154 int32_t instanceId_ = -1;
155 };
156
157 class AvoidAreaChangedListenerPreview : public OHOS::Rosen::IAvoidAreaChangedListener {
158 public:
AvoidAreaChangedListenerPreview(int32_t instanceId)159 explicit AvoidAreaChangedListenerPreview(int32_t instanceId) : instanceId_(instanceId) {}
160 ~AvoidAreaChangedListenerPreview() = default;
161
OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea avoidArea,OHOS::Rosen::AvoidAreaType type)162 void OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea avoidArea, OHOS::Rosen::AvoidAreaType type)
163 {
164 LOGD("Avoid area changed, type:%{public}d, topRect: avoidArea:x:%{public}d, y:%{public}d, "
165 "width:%{public}d, height:%{public}d; bottomRect: avoidArea:x:%{public}d, y:%{public}d, "
166 "width:%{public}d, height:%{public}d",
167 type, avoidArea.topRect_.posX_, avoidArea.topRect_.posY_, (int32_t)avoidArea.topRect_.width_,
168 (int32_t)avoidArea.topRect_.height_, avoidArea.bottomRect_.posX_, avoidArea.bottomRect_.posY_,
169 (int32_t)avoidArea.bottomRect_.width_, (int32_t)avoidArea.bottomRect_.height_);
170 auto container = Platform::AceContainer::GetContainerInstance(instanceId_);
171 CHECK_NULL_VOID(container);
172 auto pipeline = container->GetPipelineContext();
173 CHECK_NULL_VOID(pipeline);
174 auto taskExecutor = container->GetTaskExecutor();
175 CHECK_NULL_VOID(taskExecutor);
176 if (type == Rosen::AvoidAreaType::TYPE_SYSTEM) {
177 systemSafeArea_ = ConvertAvoidArea(avoidArea);
178 } else if (type == Rosen::AvoidAreaType::TYPE_NAVIGATION_INDICATOR) {
179 navigationBar_ = ConvertAvoidArea(avoidArea);
180 } else if (type == Rosen::AvoidAreaType::TYPE_CUTOUT) {
181 cutoutSafeArea_ = ConvertAvoidArea(avoidArea);
182 }
183 auto safeArea = systemSafeArea_;
184 auto navSafeArea = navigationBar_;
185 auto cutoutSafeArea = cutoutSafeArea_;
186 taskExecutor->PostTask(
187 [pipeline, safeArea, navSafeArea, cutoutSafeArea, type, avoidArea] {
188 if (type == Rosen::AvoidAreaType::TYPE_SYSTEM) {
189 pipeline->UpdateSystemSafeArea(safeArea);
190 } else if (type == Rosen::AvoidAreaType::TYPE_NAVIGATION_INDICATOR) {
191 pipeline->UpdateNavSafeArea(navSafeArea);
192 } else if (type == Rosen::AvoidAreaType::TYPE_CUTOUT) {
193 pipeline->UpdateCutoutSafeArea(cutoutSafeArea);
194 }
195 // for ui extension component
196 pipeline->UpdateOriginAvoidArea(avoidArea, static_cast<uint32_t>(type));
197 },
198 TaskExecutor::TaskType::UI, "ArkUIUpdateOriginAvoidArea");
199 }
200
201 private:
202 NG::SafeAreaInsets systemSafeArea_;
203 NG::SafeAreaInsets navigationBar_;
204 NG::SafeAreaInsets cutoutSafeArea_;
205 int32_t instanceId_ = -1;
206 };
207
AceAbility(const AceRunArgs & runArgs)208 AceAbility::AceAbility(const AceRunArgs& runArgs) : runArgs_(runArgs)
209 {
210 static std::once_flag onceFlag;
211 std::call_once(onceFlag, []() {
212 Container::UpdateCurrent(ACE_INSTANCE_ID);
213 });
214 SystemProperties::SetExtSurfaceEnabled(!runArgs.containerSdkPath.empty());
215 SystemProperties::InitDeviceInfo(runArgs.deviceWidth, runArgs.deviceHeight,
216 runArgs.deviceConfig.orientation == DeviceOrientation::PORTRAIT ? 0 : 1, runArgs.deviceConfig.density,
217 runArgs.isRound);
218 SystemProperties::InitDeviceType(runArgs.deviceConfig.deviceType);
219 InitializeAppInfo();
220 if (runArgs_.aceVersion == AceVersion::ACE_1_0) {
221 if (runArgs_.formsEnabled) {
222 LOGI("CreateContainer with JS_CARD frontend");
223 AceContainer::CreateContainer(ACE_INSTANCE_ID, FrontendType::JS_CARD, false);
224 } else {
225 LOGI("CreateContainer with JS frontend");
226 AceContainer::CreateContainer(ACE_INSTANCE_ID, FrontendType::JS, false);
227 }
228 } else if (runArgs_.aceVersion == AceVersion::ACE_2_0) {
229 if (runArgs_.formsEnabled) {
230 LOGI("CreateContainer with ETS_CARD frontend");
231 AceContainer::CreateContainer(ACE_INSTANCE_ID, FrontendType::ETS_CARD, useNewPipeline_);
232 } else {
233 LOGI("CreateContainer with JSDECLARATIVE frontend");
234 AceContainer::CreateContainer(ACE_INSTANCE_ID, FrontendType::DECLARATIVE_JS, useNewPipeline_);
235 }
236 } else {
237 LOGW("UnKnown frontend type");
238 }
239 AceContainer::SetComponentModeFlag(runArgs.isComponentMode);
240 SetConfigChanges(runArgs.configChanges);
241 auto container = AceContainer::GetContainerInstance(ACE_INSTANCE_ID);
242 CHECK_NULL_VOID(container);
243 container->SetColorMode(runArgs.deviceConfig.colorMode);
244 container->SetContainerSdkPath(runArgs.containerSdkPath);
245 container->SetInstallationFree(installationFree_);
246 container->SetLabelId(labelId_);
247 auto config = container->GetResourceConfiguration();
248 config.SetDeviceType(SystemProperties::GetDeviceType());
249 config.SetOrientation(SystemProperties::GetDeviceOrientation());
250 config.SetDensity(SystemProperties::GetResolution());
251 config.SetColorMode(container->GetColorMode());
252 config.SetFontRatio(runArgs.deviceConfig.fontRatio);
253 container->SetResourceConfiguration(config);
254 container->SetBundleName(bundleName_);
255 container->SetModuleName(moduleName_);
256 container->SetApiTargetVersion(AceApplicationInfo::GetInstance().GetApiTargetVersion());
257 InitializeClipboard();
258 }
259
~AceAbility()260 AceAbility::~AceAbility()
261 {
262 AceContainer::DestroyContainer(ACE_INSTANCE_ID);
263 }
264
SetMockModuleList(const std::map<std::string,std::string> & mockJsonInfo)265 void AceAbility::SetMockModuleList(const std::map<std::string, std::string>& mockJsonInfo)
266 {
267 // only support the stage model
268 if (runArgs_.projectModel == ProjectModel::STAGE) {
269 auto container = AceContainer::GetContainerInstance(ACE_INSTANCE_ID);
270 CHECK_NULL_VOID(container);
271 container->SetMockModuleList(mockJsonInfo);
272 }
273 }
274
CreateInstance(AceRunArgs & runArgs)275 std::unique_ptr<AceAbility> AceAbility::CreateInstance(AceRunArgs& runArgs)
276 {
277 DumpAceRunArgs(runArgs);
278 LOGI("Start create AceAbility instance");
279 #ifdef INIT_ICU_DATA_PATH
280 std::string icuPath = ".";
281 u_setDataDirectory(icuPath.c_str());
282 #endif
283 AceApplicationInfo::GetInstance().SetLocale(runArgs.language, runArgs.region, runArgs.script, "");
284 SetFontMgrConfig(runArgs.containerSdkPath);
285 EventDispatcher::GetInstance().Initialize();
286 auto aceAbility = std::make_unique<AceAbility>(runArgs);
287 return aceAbility;
288 }
289
InitEnv()290 void AceAbility::InitEnv()
291 {
292 std::vector<std::string> paths;
293 paths.push_back(runArgs_.assetPath);
294 std::string appResourcesPath(runArgs_.appResourcesPath);
295 if (!OHOS::Ace::Framework::EndWith(appResourcesPath, DELIMITER)) {
296 appResourcesPath.append(DELIMITER);
297 }
298 if (runArgs_.projectModel == ProjectModel::STAGE) {
299 // eTS Card
300 if (runArgs_.aceVersion == AceVersion::ACE_2_0 && runArgs_.formsEnabled) {
301 paths.push_back(runArgs_.assetPath + DELIMITER + "ets");
302 }
303 paths.push_back(appResourcesPath);
304 paths.push_back(appResourcesPath + ASSET_PATH_SHARE_STAGE);
305 } else {
306 paths.push_back(GetCustomAssetPath(runArgs_.assetPath) + ASSET_PATH_SHARE);
307 }
308 if (!runArgs_.containerSdkPath.empty()) {
309 paths.push_back(runArgs_.containerSdkPath);
310 }
311 AceContainer::AddAssetPath(ACE_INSTANCE_ID, "", paths);
312 auto container = AceContainer::GetContainerInstance(ACE_INSTANCE_ID);
313 CHECK_NULL_VOID(container);
314 if (runArgs_.projectModel == ProjectModel::STAGE) {
315 auto pkgcontextinfo = Referenced::MakeRefPtr<StagePkgContextInfo>();
316 pkgcontextinfo->SetPkgNameList(runArgs_.packageNameList);
317 pkgcontextinfo->SetPkgContextInfoAndAliasMap(runArgs_.pkgContextInfoJsonStringMap);
318 container->SetPkgContextInfo(pkgcontextinfo);
319 if (runArgs_.formsEnabled) {
320 container->SetStageCardConfig(runArgs_.pageProfile, runArgs_.url);
321 } else {
322 container->SetPageProfile((runArgs_.pageProfile.empty() ? "" : runArgs_.pageProfile + ".json"));
323 }
324 }
325 AceContainer::SetResourcesPathAndThemeStyle(ACE_INSTANCE_ID, runArgs_.systemResourcesPath,
326 runArgs_.containerSdkPath, runArgs_.appResourcesPath, runArgs_.themeId, runArgs_.deviceConfig.colorMode);
327
328 auto view = AceViewPreview::CreateView(ACE_INSTANCE_ID);
329 auto window = GetWindow();
330 avoidAreaChangedListener_ = new AvoidAreaChangedListenerPreview(ACE_INSTANCE_ID);
331 window->RegisterAvoidAreaChangeListener(avoidAreaChangedListener_);
332 ignoreViewSafeAreaListener_ = new IIgnoreViewSafeAreaListenerPreview(ACE_INSTANCE_ID);
333 window->RegisterIgnoreViewSafeAreaListener(ignoreViewSafeAreaListener_);
334 UIEnvCallback callback = [window, id = ACE_INSTANCE_ID](const OHOS::Ace::RefPtr<PipelineContext>& context) mutable {
335 CHECK_NULL_VOID(context);
336 CHECK_NULL_VOID(window);
337 auto director = OHOS::Rosen::RSUIDirector::Create();
338 CHECK_NULL_VOID(director);
339 director->SetRSSurfaceNode(window->GetSurfaceNode());
340 auto container = AceContainer::GetContainerInstance(id);
341 CHECK_NULL_VOID(container);
342 auto func = [taskExecutor = container->GetTaskExecutor(), id](
343 const std::function<void()>& task, uint32_t delay) {
344 CHECK_NULL_VOID(taskExecutor);
345 ContainerScope scope(id);
346 taskExecutor->PostDelayedTask(
347 task, TaskExecutor::TaskType::UI, delay, "ArkUIRenderServiceTask", PriorityType::HIGH);
348 };
349 director->SetUITaskRunner(func, id);
350 director->Init();
351 context->SetRSUIDirector(director);
352 };
353
354 if (runArgs_.aceVersion == AceVersion::ACE_2_0) {
355 AceContainer::SetView(
356 view, window, runArgs_.deviceConfig.density, runArgs_.deviceWidth, runArgs_.deviceHeight, callback);
357 AceContainer::RunPage(ACE_INSTANCE_ID, runArgs_.url, "");
358 } else {
359 AceContainer::RunPage(ACE_INSTANCE_ID, runArgs_.url, "");
360 AceContainer::SetView(
361 view, window, runArgs_.deviceConfig.density, runArgs_.deviceWidth, runArgs_.deviceHeight, callback);
362 }
363 // Drive the native engine with the platform thread.
364 container->RunNativeEngineLoop();
365 auto pipelineContext = container->GetPipelineContext();
366 if (pipelineContext) {
367 LOGI("Set MinPlatformVersion to %{public}d", compatibleVersion_);
368 pipelineContext->SetMinPlatformVersion(compatibleVersion_);
369 pipelineContext->SetDisplayWindowRectInfo(
370 Rect(Offset(0.0f, 0.0f), Size(runArgs_.deviceWidth, runArgs_.deviceHeight)));
371 }
372 container->InitializeAppConfig(runArgs_.assetPath, bundleName_, moduleName_, compileMode_);
373 pipelineContext->UpdateSystemSafeArea(GetViewSafeAreaByType(Rosen::AvoidAreaType::TYPE_SYSTEM, window));
374 pipelineContext->UpdateCutoutSafeArea(GetViewSafeAreaByType(Rosen::AvoidAreaType::TYPE_CUTOUT, window));
375 pipelineContext->UpdateNavSafeArea(GetViewSafeAreaByType(Rosen::AvoidAreaType::TYPE_NAVIGATION_INDICATOR, window));
376 AceContainer::AddRouterChangeCallback(ACE_INSTANCE_ID, runArgs_.onRouterChange);
377 OHOS::Ace::Framework::InspectorClient::GetInstance().RegisterFastPreviewErrorCallback(runArgs_.onError);
378 // Should make it possible to update surface changes by using viewWidth and viewHeight.
379 view->NotifySurfaceChanged(runArgs_.deviceWidth, runArgs_.deviceHeight);
380 view->NotifyDensityChanged(runArgs_.deviceConfig.density);
381 }
382
InitializeClipboard() const383 void AceAbility::InitializeClipboard() const
384 {
385 ClipboardProxy::GetInstance()->SetDelegate(std::make_unique<Platform::ClipboardProxyImpl>());
386 }
387
OnBackPressed() const388 void AceAbility::OnBackPressed() const
389 {
390 LOGI("Process Back Pressed Event");
391 EventDispatcher::GetInstance().DispatchBackPressedEvent();
392 }
393
OnInputEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent) const394 bool AceAbility::OnInputEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent) const
395 {
396 return EventDispatcher::GetInstance().DispatchTouchEvent(pointerEvent);
397 }
398
OnInputEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent) const399 bool AceAbility::OnInputEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent) const
400 {
401 return EventDispatcher::GetInstance().DispatchKeyEvent(keyEvent);
402 }
403
OnInputEvent(const std::shared_ptr<MMI::AxisEvent> & axisEvent) const404 bool AceAbility::OnInputEvent(const std::shared_ptr<MMI::AxisEvent>& axisEvent) const
405 {
406 return false;
407 }
408
OnInputMethodEvent(const unsigned int codePoint) const409 bool AceAbility::OnInputMethodEvent(const unsigned int codePoint) const
410 {
411 return EventDispatcher::GetInstance().DispatchInputMethodEvent(codePoint);
412 }
413
InitializeAppInfo()414 void AceAbility::InitializeAppInfo()
415 {
416 RefPtr<Context> context =
417 Context::CreateContext(runArgs_.projectModel == ProjectModel::STAGE, runArgs_.appResourcesPath);
418 if (runArgs_.projectModel == ProjectModel::STAGE) {
419 auto stageContext = AceType::DynamicCast<StageContext>(context);
420 CHECK_NULL_VOID(stageContext);
421 auto appInfo = stageContext->GetAppInfo();
422 CHECK_NULL_VOID(appInfo);
423 auto hapModuleInfo = stageContext->GetHapModuleInfo();
424 CHECK_NULL_VOID(hapModuleInfo);
425 bundleName_ = appInfo->GetBundleName();
426 moduleName_ = hapModuleInfo->GetModuleName();
427 compileMode_ = hapModuleInfo->GetCompileMode();
428 compatibleVersion_ = appInfo->GetMinAPIVersion();
429 auto targetVersion = appInfo->GetTargetAPIVersion();
430 AceApplicationInfo::GetInstance().SetApiTargetVersion(static_cast<int32_t>(targetVersion));
431 auto releaseType = appInfo->GetApiReleaseType();
432 bool enablePartialUpdate = hapModuleInfo->GetPartialUpdateFlag();
433 // only app should have menubar, card don't need
434 if (!runArgs_.formsEnabled) {
435 installationFree_ = appInfo->IsInstallationFree();
436 labelId_ = hapModuleInfo->GetLabelId();
437 }
438 useNewPipeline_ = AceNewPipeJudgement::QueryAceNewPipeEnabledStage(
439 "", compatibleVersion_, targetVersion, releaseType, !enablePartialUpdate);
440 } else {
441 auto faContext = AceType::DynamicCast<FaContext>(context);
442 CHECK_NULL_VOID(faContext);
443 auto appInfo = faContext->GetAppInfo();
444 CHECK_NULL_VOID(appInfo);
445 auto hapModuleInfo = faContext->GetHapModuleInfo();
446 CHECK_NULL_VOID(hapModuleInfo);
447 bundleName_ = appInfo->GetBundleName();
448 compatibleVersion_ = appInfo->GetMinAPIVersion();
449 auto targetVersion = appInfo->GetTargetAPIVersion();
450 auto releaseType = appInfo->GetApiReleaseType();
451 useNewPipeline_ =
452 AceNewPipeJudgement::QueryAceNewPipeEnabledFA("", compatibleVersion_, targetVersion, releaseType);
453 }
454 #ifdef COMPONENT_TEST_ENABLED
455 if (runArgs_.isComponentTestMode && runArgs_.componentTestConfig != "") {
456 ComponentTest::ParseComponentTestConfig(runArgs_.componentTestConfig);
457 }
458 #endif // COMPONENT_TEST_ENABLED
459 }
460
SetConfigChanges(const std::string & configChanges)461 void AceAbility::SetConfigChanges(const std::string& configChanges)
462 {
463 if (configChanges == "") {
464 return;
465 }
466 std::vector<std::string> configChangesSplitter;
467 OHOS::Ace::StringUtils::StringSplitter(configChanges, ',', configChangesSplitter);
468 for (const auto& singleConfig : configChangesSplitter) {
469 if (singleConfig == "locale") {
470 configChanges_.watchLocale = true;
471 continue;
472 } else if (singleConfig == "layout") {
473 configChanges_.watchLayout = true;
474 continue;
475 } else if (singleConfig == "fontSize") {
476 configChanges_.watchFontSize = true;
477 continue;
478 } else if (singleConfig == "orientation") {
479 configChanges_.watchOrientation = true;
480 continue;
481 } else if (singleConfig == "density") {
482 configChanges_.watchDensity = true;
483 continue;
484 } else {
485 LOGW("unsupported config %{public}s", singleConfig.c_str());
486 }
487 }
488 }
489
OnConfigurationChanged(const DeviceConfig & newConfig)490 void AceAbility::OnConfigurationChanged(const DeviceConfig& newConfig)
491 {
492 if (newConfig.colorMode == runArgs_.deviceConfig.colorMode) {
493 return;
494 }
495 int32_t width = runArgs_.deviceWidth;
496 int32_t height = runArgs_.deviceHeight;
497 SurfaceChanged(runArgs_.deviceConfig.orientation, runArgs_.deviceConfig.density, width, height);
498 auto container = AceContainer::GetContainerInstance(ACE_INSTANCE_ID);
499 if (!container) {
500 LOGW("container is null, change configuration failed.");
501 return;
502 }
503 container->UpdateDeviceConfig(newConfig);
504 runArgs_.deviceConfig.colorMode = newConfig.colorMode;
505 if (container->GetType() == FrontendType::DECLARATIVE_JS) {
506 container->NativeOnConfigurationUpdated(ACE_INSTANCE_ID);
507 }
508 }
509
SurfaceChanged(const DeviceOrientation & orientation,const double & resolution,int32_t & width,int32_t & height,WindowSizeChangeReason type)510 void AceAbility::SurfaceChanged(
511 const DeviceOrientation& orientation, const double& resolution, int32_t& width, int32_t& height,
512 WindowSizeChangeReason type)
513 {
514 auto container = AceContainer::GetContainerInstance(ACE_INSTANCE_ID);
515 CHECK_NULL_VOID(container);
516 auto viewPtr = AceType::DynamicCast<AceViewPreview>(container->GetAceView());
517 CHECK_NULL_VOID(viewPtr);
518 // Need to change the window resolution and then change the rendering resolution. Otherwise, the image may not adapt
519 // to the new window after the window is modified.
520 auto context = container->GetPipelineContext();
521 CHECK_NULL_VOID(context);
522 context->SetDisplayWindowRectInfo(Rect(Offset(0, 0), Size(width, height)));
523 SystemProperties::InitDeviceInfo(
524 width, height, orientation == DeviceOrientation::PORTRAIT ? 0 : 1, resolution, runArgs_.isRound);
525 DeviceConfig deviceConfig = runArgs_.deviceConfig;
526 deviceConfig.orientation = orientation;
527 deviceConfig.density = resolution;
528 container->UpdateDeviceConfig(deviceConfig);
529 viewPtr->NotifyDensityChanged(resolution);
530 viewPtr->NotifySurfaceChanged(width, height, type);
531 if ((orientation != runArgs_.deviceConfig.orientation && configChanges_.watchOrientation) ||
532 (resolution != runArgs_.deviceConfig.density && configChanges_.watchDensity) ||
533 ((width != runArgs_.deviceWidth || height != runArgs_.deviceHeight) && configChanges_.watchLayout)) {
534 container->NativeOnConfigurationUpdated(ACE_INSTANCE_ID);
535 }
536 if (orientation != runArgs_.deviceConfig.orientation || resolution != runArgs_.deviceConfig.density) {
537 container->NotifyConfigurationChange(false, ConfigurationChange({ false, false, true }));
538 }
539 runArgs_.deviceConfig.orientation = orientation;
540 runArgs_.deviceConfig.density = resolution;
541 runArgs_.deviceWidth = width;
542 runArgs_.deviceHeight = height;
543 }
544
ReplacePage(const std::string & url,const std::string & params)545 void AceAbility::ReplacePage(const std::string& url, const std::string& params)
546 {
547 auto container = AceContainer::GetContainerInstance(ACE_INSTANCE_ID);
548 CHECK_NULL_VOID(container);
549 container->GetFrontend()->ReplacePage(url, params);
550 }
551
LoadDocument(const std::string & url,const std::string & componentName,SystemParams & systemParams)552 void AceAbility::LoadDocument(const std::string& url, const std::string& componentName, SystemParams& systemParams)
553 {
554 LOGI("Component Preview start:%{public}s, ", componentName.c_str());
555 AceApplicationInfo::GetInstance().ChangeLocale(systemParams.language, systemParams.region);
556 runArgs_.isRound = systemParams.isRound;
557 SurfaceChanged(systemParams.orientation, systemParams.density, systemParams.deviceWidth, systemParams.deviceHeight);
558 DeviceConfig deviceConfig = {
559 .orientation = systemParams.orientation,
560 .density = systemParams.density,
561 .deviceType = systemParams.deviceType,
562 .colorMode = systemParams.colorMode,
563 };
564 OnConfigurationChanged(deviceConfig);
565 auto container = AceContainer::GetContainerInstance(ACE_INSTANCE_ID);
566 CHECK_NULL_VOID(container);
567 container->LoadDocument(url, componentName);
568 LOGI("Component Preview end");
569 }
570
GetJSONTree()571 std::string AceAbility::GetJSONTree()
572 {
573 LOGI("Inspector start");
574 std::string jsonTreeStr;
575 auto container = AceContainer::GetContainerInstance(ACE_INSTANCE_ID);
576 CHECK_NULL_RETURN(container, "");
577 auto taskExecutor = container->GetTaskExecutor();
578 CHECK_NULL_RETURN(taskExecutor, "");
579 taskExecutor->PostSyncTask(
580 [&jsonTreeStr] { OHOS::Ace::Framework::InspectorClient::GetInstance().AssembleJSONTreeStr(jsonTreeStr); },
581 TaskExecutor::TaskType::UI, "ArkUIGetJsonTreeStr");
582 LOGI("Inspector end");
583 return jsonTreeStr;
584 }
585
GetDefaultJSONTree()586 std::string AceAbility::GetDefaultJSONTree()
587 {
588 std::string defaultJsonTreeStr;
589 auto container = AceContainer::GetContainerInstance(ACE_INSTANCE_ID);
590 CHECK_NULL_RETURN(container, "");
591 auto taskExecutor = container->GetTaskExecutor();
592 CHECK_NULL_RETURN(taskExecutor, "");
593 taskExecutor->PostSyncTask(
594 [&defaultJsonTreeStr] {
595 OHOS::Ace::Framework::InspectorClient::GetInstance().AssembleDefaultJSONTreeStr(defaultJsonTreeStr);
596 },
597 TaskExecutor::TaskType::UI, "ArkUIGetDefaultJsonTreeStr");
598 return defaultJsonTreeStr;
599 }
600
OperateComponent(const std::string & attrsJson)601 bool AceAbility::OperateComponent(const std::string& attrsJson)
602 {
603 LOGI("Fast Preview start");
604 auto root = JsonUtil::ParseJsonString(attrsJson);
605 if (!root || !root->IsValid()) {
606 LOGE("Fast Preview failed: the attrsJson is illegal json format");
607 return false;
608 }
609
610 auto container = AceContainer::GetContainerInstance(ACE_INSTANCE_ID);
611 if (!container) {
612 LOGE("Fast Preview failed: container is null");
613 return false;
614 }
615 auto taskExecutor = container->GetTaskExecutor();
616 if (!taskExecutor) {
617 LOGE("Fast Preview failed: taskExecutor is null");
618 return false;
619 }
620 taskExecutor->PostTask(
621 [attrsJson, instanceId = ACE_INSTANCE_ID] {
622 ContainerScope scope(instanceId);
623 bool result = OHOS::Ace::Framework::InspectorClient::GetInstance().OperateComponent(attrsJson);
624 if (!result) {
625 OHOS::Ace::Framework::InspectorClient::GetInstance().CallFastPreviewErrorCallback(attrsJson);
626 }
627 },
628 TaskExecutor::TaskType::UI, "ArkUIOperateComponent");
629 LOGI("Fast Preview end");
630 return true;
631 }
632
SetWindow(sptr<OHOS::Rosen::Window> rsWindow)633 void AceAbility::SetWindow(sptr<OHOS::Rosen::Window> rsWindow)
634 {
635 rsWindow_ = rsWindow;
636 }
637
GetWindow()638 sptr<OHOS::Rosen::Window> AceAbility::GetWindow()
639 {
640 return rsWindow_;
641 }
642
643 } // namespace OHOS::Ace::Platform
644