• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "adapter/ohos/entrance/ui_content_impl.h"
17 
18 #include <atomic>
19 #include <cinttypes>
20 
21 #include "ability_context.h"
22 #include "ability_info.h"
23 #include "configuration.h"
24 #include "dm/display_manager.h"
25 #include "init_data.h"
26 #include "ipc_skeleton.h"
27 #include "js_runtime_utils.h"
28 #include "native_reference.h"
29 #include "service_extension_context.h"
30 
31 #include "adapter/ohos/osal/pixel_map_ohos.h"
32 
33 #ifdef ENABLE_ROSEN_BACKEND
34 #include "render_service_client/core/ui/rs_ui_director.h"
35 #endif
36 
37 #include "adapter/ohos/entrance/ace_application_info.h"
38 #include "adapter/ohos/entrance/ace_container.h"
39 #include "adapter/ohos/entrance/ace_new_pipe_judgement.h"
40 #include "adapter/ohos/entrance/capability_registry.h"
41 #include "adapter/ohos/entrance/dialog_container.h"
42 #include "adapter/ohos/entrance/file_asset_provider.h"
43 #include "adapter/ohos/entrance/flutter_ace_view.h"
44 #include "adapter/ohos/entrance/form_utils_impl.h"
45 #include "adapter/ohos/entrance/hap_asset_provider.h"
46 #include "adapter/ohos/entrance/plugin_utils_impl.h"
47 #include "adapter/ohos/entrance/utils.h"
48 #include "adapter/ohos/osal/page_url_checker_ohos.h"
49 #include "base/geometry/rect.h"
50 #include "base/i18n/localization.h"
51 #include "base/log/ace_trace.h"
52 #include "base/log/log.h"
53 #include "base/subwindow/subwindow_manager.h"
54 #include "base/utils/system_properties.h"
55 #include "bridge/card_frontend/form_frontend_declarative.h"
56 #include "core/common/ace_engine.h"
57 #include "core/common/container.h"
58 #include "core/common/container_scope.h"
59 #include "core/common/flutter/flutter_asset_manager.h"
60 #include "core/common/form_manager.h"
61 #include "core/common/layout_inspector.h"
62 #include "core/common/plugin_manager.h"
63 #include "locale_config.h"
64 
65 namespace OHOS::Ace {
66 namespace {
67 
68 const std::string ABS_BUNDLE_CODE_PATH = "/data/app/el1/bundle/public/";
69 const std::string LOCAL_BUNDLE_CODE_PATH = "/data/storage/el1/bundle/";
70 const std::string FILE_SEPARATOR = "/";
71 const std::string START_PARAMS_KEY = "__startParams";
72 const std::string ACTION_VIEWDATA = "ohos.want.action.viewData";
73 
74 } // namespace
75 
76 static std::atomic<int32_t> gInstanceId = 0;
77 static std::atomic<int32_t> gSubWindowInstanceId = 100000;
78 static std::atomic<int32_t> gSubInstanceId = 1000000;
79 const std::string SUBWINDOW_PREFIX = "ARK_APP_SUBWINDOW_";
80 const std::string SUBWINDOW_TOAST_DIALOG_PREFIX = "ARK_APP_SUBWINDOW_TOAST_DIALOG_";
81 const int32_t REQUEST_CODE = -1;
82 
83 using ContentFinishCallback = std::function<void()>;
84 using ContentStartAbilityCallback = std::function<void(const std::string& address)>;
85 class ContentEventCallback final : public Platform::PlatformEventCallback {
86 public:
ContentEventCallback(ContentFinishCallback onFinish)87     explicit ContentEventCallback(ContentFinishCallback onFinish) : onFinish_(onFinish) {}
ContentEventCallback(ContentFinishCallback onFinish,ContentStartAbilityCallback onStartAbility)88     ContentEventCallback(ContentFinishCallback onFinish, ContentStartAbilityCallback onStartAbility)
89         : onFinish_(onFinish), onStartAbility_(onStartAbility)
90     {}
91     ~ContentEventCallback() override = default;
92 
OnFinish() const93     void OnFinish() const override
94     {
95         LOGI("UIContent OnFinish");
96         CHECK_NULL_VOID_NOLOG(onFinish_);
97         onFinish_();
98     }
99 
OnStartAbility(const std::string & address)100     void OnStartAbility(const std::string& address) override
101     {
102         LOGI("UIContent OnStartAbility");
103         CHECK_NULL_VOID_NOLOG(onStartAbility_);
104         onStartAbility_(address);
105     }
106 
OnStatusBarBgColorChanged(uint32_t color)107     void OnStatusBarBgColorChanged(uint32_t color) override
108     {
109         LOGI("UIContent OnStatusBarBgColorChanged");
110     }
111 
112 private:
113     ContentFinishCallback onFinish_;
114     ContentStartAbilityCallback onStartAbility_;
115 };
116 
OHOS_ACE_CreateUIContent(void * context,void * runtime)117 extern "C" ACE_FORCE_EXPORT void* OHOS_ACE_CreateUIContent(void* context, void* runtime)
118 {
119     LOGI("Ace lib loaded, CreateUIContent.");
120     return new UIContentImpl(reinterpret_cast<OHOS::AbilityRuntime::Context*>(context), runtime);
121 }
122 
OHOS_ACE_CreateFormContent(void * context,void * runtime,bool isCard)123 extern "C" ACE_FORCE_EXPORT void* OHOS_ACE_CreateFormContent(void* context, void* runtime, bool isCard)
124 {
125     LOGI("Ace lib loaded, CreateFormUIContent.");
126     return new UIContentImpl(reinterpret_cast<OHOS::AbilityRuntime::Context*>(context), runtime, isCard);
127 }
128 
OHOS_ACE_CreateSubWindowUIContent(void * ability)129 extern "C" ACE_FORCE_EXPORT void* OHOS_ACE_CreateSubWindowUIContent(void* ability)
130 {
131     LOGI("Ace lib loaded, Create SubWindowUIContent.");
132     return new UIContentImpl(reinterpret_cast<OHOS::AppExecFwk::Ability*>(ability));
133 }
134 
135 class OccupiedAreaChangeListener : public OHOS::Rosen::IOccupiedAreaChangeListener {
136 public:
OccupiedAreaChangeListener(int32_t instanceId)137     explicit OccupiedAreaChangeListener(int32_t instanceId) : instanceId_(instanceId) {}
138     ~OccupiedAreaChangeListener() = default;
139 
OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo> & info)140     void OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info)
141     {
142         auto rect = info->rect_;
143         auto type = info->type_;
144         Rect keyboardRect = Rect(rect.posX_, rect.posY_, rect.width_, rect.height_);
145         LOGI("UIContent::OccupiedAreaChange rect:%{public}s type: %{public}d", keyboardRect.ToString().c_str(), type);
146         if (type == OHOS::Rosen::OccupiedAreaType::TYPE_INPUT) {
147             auto container = Platform::AceContainer::GetContainer(instanceId_);
148             CHECK_NULL_VOID(container);
149             auto taskExecutor = container->GetTaskExecutor();
150             CHECK_NULL_VOID(taskExecutor);
151             ContainerScope scope(instanceId_);
152             taskExecutor->PostTask(
153                 [container, keyboardRect] {
154                     auto context = container->GetPipelineContext();
155                     CHECK_NULL_VOID_NOLOG(context);
156                     context->OnVirtualKeyboardAreaChange(keyboardRect);
157                 },
158                 TaskExecutor::TaskType::UI);
159         }
160     }
161 
162 private:
163     int32_t instanceId_ = -1;
164 };
165 
166 class DragWindowListener : public OHOS::Rosen::IWindowDragListener {
167 public:
DragWindowListener(int32_t instanceId)168     explicit DragWindowListener(int32_t instanceId) : instanceId_(instanceId) {}
169     ~DragWindowListener() = default;
OnDrag(int32_t x,int32_t y,OHOS::Rosen::DragEvent event)170     void OnDrag(int32_t x, int32_t y, OHOS::Rosen::DragEvent event)
171     {
172         LOGI("DragWindowListener::OnDrag called.");
173         auto container = Platform::AceContainer::GetContainer(instanceId_);
174         CHECK_NULL_VOID_NOLOG(container);
175         int32_t instanceId = instanceId_;
176         if (container->IsSubContainer()) {
177             instanceId = container->GetParentId();
178         }
179         auto flutterAceView =
180             static_cast<Platform::FlutterAceView*>(Platform::AceContainer::GetContainer(instanceId)->GetView());
181         CHECK_NULL_VOID(flutterAceView);
182         DragEventAction action;
183         switch (event) {
184             case OHOS::Rosen::DragEvent::DRAG_EVENT_END:
185                 action = DragEventAction::DRAG_EVENT_END;
186                 break;
187             case OHOS::Rosen::DragEvent::DRAG_EVENT_OUT:
188                 action = DragEventAction::DRAG_EVENT_OUT;
189                 break;
190             case OHOS::Rosen::DragEvent::DRAG_EVENT_MOVE:
191                 action = DragEventAction::DRAG_EVENT_MOVE;
192                 break;
193             case OHOS::Rosen::DragEvent::DRAG_EVENT_IN:
194             default:
195                 action = DragEventAction::DRAG_EVENT_START;
196                 break;
197         }
198 
199         flutterAceView->ProcessDragEvent(x, y, action);
200     }
201 
202 private:
203     int32_t instanceId_ = -1;
204 };
205 
206 class TouchOutsideListener : public OHOS::Rosen::ITouchOutsideListener {
207 public:
TouchOutsideListener(int32_t instanceId)208     explicit TouchOutsideListener(int32_t instanceId) : instanceId_(instanceId) {}
209     ~TouchOutsideListener() = default;
210 
OnTouchOutside() const211     void OnTouchOutside() const
212     {
213         LOGI("window is touching outside. instance id is %{public}d", instanceId_);
214         auto container = Platform::AceContainer::GetContainer(instanceId_);
215         CHECK_NULL_VOID(container);
216         auto taskExecutor = container->GetTaskExecutor();
217         CHECK_NULL_VOID(taskExecutor);
218         ContainerScope scope(instanceId_);
219         taskExecutor->PostTask(
220             [] {
221                 SubwindowManager::GetInstance()->ClearMenu();
222                 SubwindowManager::GetInstance()->ClearMenuNG();
223                 SubwindowManager::GetInstance()->HidePopupNG();
224             },
225             TaskExecutor::TaskType::UI);
226     }
227 
228 private:
229     int32_t instanceId_ = -1;
230 };
231 
UIContentImpl(OHOS::AbilityRuntime::Context * context,void * runtime)232 UIContentImpl::UIContentImpl(OHOS::AbilityRuntime::Context* context, void* runtime) : runtime_(runtime)
233 {
234     CHECK_NULL_VOID(context);
235     const auto& obj = context->GetBindingObject();
236     auto ref = obj->Get<NativeReference>();
237     auto object = AbilityRuntime::ConvertNativeValueTo<NativeObject>(ref->Get());
238     auto weak = static_cast<std::weak_ptr<AbilityRuntime::Context>*>(object->GetNativePointer());
239     context_ = *weak;
240     LOGI("Create UIContentImpl successfully.");
241 }
242 
UIContentImpl(OHOS::AbilityRuntime::Context * context,void * runtime,bool isCard)243 UIContentImpl::UIContentImpl(OHOS::AbilityRuntime::Context* context,
244                              void* runtime, bool isCard) : runtime_(runtime), isFormRender_(isCard)
245 {
246     CHECK_NULL_VOID(context);
247     bundleName_ = context->GetBundleName();
248     auto hapModuleInfo = context->GetHapModuleInfo();
249     CHECK_NULL_VOID(hapModuleInfo);
250     moduleName_ = hapModuleInfo->name;
251     auto applicationInfo = context->GetApplicationInfo();
252     CHECK_NULL_VOID(applicationInfo);
253     minCompatibleVersionCode_ = applicationInfo->minCompatibleVersionCode;
254     isBundle_ = (hapModuleInfo->compileMode == AppExecFwk::CompileMode::JS_BUNDLE);
255     SetConfiguration(context->GetConfiguration());
256     const auto& obj = context->GetBindingObject();
257     CHECK_NULL_VOID(obj);
258     auto ref = obj->Get<NativeReference>();
259     CHECK_NULL_VOID(ref);
260     auto object = AbilityRuntime::ConvertNativeValueTo<NativeObject>(ref->Get());
261     CHECK_NULL_VOID(object);
262     auto weak = static_cast<std::weak_ptr<AbilityRuntime::Context>*>(object->GetNativePointer());
263     CHECK_NULL_VOID(weak);
264     context_ = *weak;
265     LOGI("Create form UIContentImpl successfully.");
266 }
267 
UIContentImpl(OHOS::AppExecFwk::Ability * ability)268 UIContentImpl::UIContentImpl(OHOS::AppExecFwk::Ability* ability)
269 {
270     CHECK_NULL_VOID(ability);
271     auto weak = static_cast<std::weak_ptr<AbilityRuntime::Context>>(ability->GetAbilityContext());
272     context_ = weak;
273     LOGI("Create UIContentImpl successfully.");
274 }
275 
DestroyUIDirector()276 void UIContentImpl::DestroyUIDirector()
277 {
278     auto container = Platform::AceContainer::GetContainer(instanceId_);
279     CHECK_NULL_VOID_NOLOG(container);
280     auto pipelineContext = AceType::DynamicCast<PipelineContext>(container->GetPipelineContext());
281     CHECK_NULL_VOID_NOLOG(pipelineContext);
282     auto rsUIDirector = pipelineContext->GetRSUIDirector();
283     CHECK_NULL_VOID_NOLOG(rsUIDirector);
284     LOGI("Destroying old rsUIDirectory");
285     rsUIDirector->Destroy();
286 }
287 
DestroyCallback() const288 void UIContentImpl::DestroyCallback() const
289 {
290     auto container = Platform::AceContainer::GetContainer(instanceId_);
291     CHECK_NULL_VOID_NOLOG(container);
292     auto pipelineContext = container->GetPipelineContext();
293     CHECK_NULL_VOID_NOLOG(pipelineContext);
294     pipelineContext->SetNextFrameLayoutCallback(nullptr);
295 }
296 
Initialize(OHOS::Rosen::Window * window,const std::string & url,NativeValue * storage)297 void UIContentImpl::Initialize(OHOS::Rosen::Window* window, const std::string& url, NativeValue* storage)
298 {
299     if (window && StringUtils::StartWith(window->GetWindowName(), SUBWINDOW_TOAST_DIALOG_PREFIX)) {
300         CommonInitialize(window, url, storage);
301         return;
302     }
303     if (window) {
304         CommonInitialize(window, url, storage);
305     }
306 
307     // ArkTSCard need no window : 梳理所有需要window和不需要window的场景
308     if (isFormRender_ && !window) {
309         LOGI("CommonInitializeForm url = %{public}s", url.c_str());
310         CommonInitializeForm(window, url, storage);
311     }
312 
313     LOGI("Initialize startUrl = %{public}s", startUrl_.c_str());
314     // run page.
315     Platform::AceContainer::RunPage(
316         instanceId_, Platform::AceContainer::GetContainer(instanceId_)->GeneratePageId(), startUrl_, "");
317     LOGD("Initialize UIContentImpl done.");
318 }
319 
Restore(OHOS::Rosen::Window * window,const std::string & contentInfo,NativeValue * storage)320 void UIContentImpl::Restore(OHOS::Rosen::Window* window, const std::string& contentInfo, NativeValue* storage)
321 {
322     CommonInitialize(window, contentInfo, storage);
323     startUrl_ = Platform::AceContainer::RestoreRouterStack(instanceId_, contentInfo);
324     if (startUrl_.empty()) {
325         LOGW("UIContent Restore start url is empty");
326     }
327     LOGI("Restore startUrl = %{public}s", startUrl_.c_str());
328     Platform::AceContainer::RunPage(
329         instanceId_, Platform::AceContainer::GetContainer(instanceId_)->GeneratePageId(), startUrl_, "");
330     LOGI("Restore UIContentImpl done.");
331 }
332 
GetContentInfo() const333 std::string UIContentImpl::GetContentInfo() const
334 {
335     LOGI("UIContent GetContentInfo");
336     return Platform::AceContainer::GetContentInfo(instanceId_);
337 }
338 
339 // ArkTSCard start
CommonInitializeForm(OHOS::Rosen::Window * window,const std::string & contentInfo,NativeValue * storage)340 void UIContentImpl::CommonInitializeForm(OHOS::Rosen::Window* window,
341                                          const std::string& contentInfo, NativeValue* storage)
342 {
343     LOGI("Initialize CommonInitializeForm start.");
344     ACE_FUNCTION_TRACE();
345     window_ = window;
346     startUrl_ = contentInfo;
347 
348     if (window_) {
349         if (StringUtils::StartWith(window->GetWindowName(), SUBWINDOW_TOAST_DIALOG_PREFIX)) {
350             InitializeSubWindow(window_, true);
351             return;
352         }
353         if (StringUtils::StartWith(window->GetWindowName(), SUBWINDOW_PREFIX)) {
354             InitializeSubWindow(window_);
355             return;
356         }
357     }
358 
359     auto context = context_.lock();
360     static std::once_flag onceFlag;
361     if (!isFormRender_) {
362         std::call_once(onceFlag, [&context]() {
363             LOGI("Initialize for current process.");
364             SetHwIcuDirectory();
365             Container::UpdateCurrent(INSTANCE_ID_PLATFORM);
366             AceApplicationInfo::GetInstance().SetProcessName(context->GetBundleName());
367             AceApplicationInfo::GetInstance().SetPackageName(context->GetBundleName());
368             AceApplicationInfo::GetInstance().SetDataFileDirPath(context->GetFilesDir());
369             AceApplicationInfo::GetInstance().SetUid(IPCSkeleton::GetCallingUid());
370             AceApplicationInfo::GetInstance().SetPid(IPCSkeleton::GetCallingPid());
371             CapabilityRegistry::Register();
372             ImageCache::SetImageCacheFilePath(context->GetCacheDir());
373             ImageCache::SetCacheFileInfo();
374         });
375     }
376 
377     bool useNewPipe = true;
378 #ifdef ENABLE_ROSEN_BACKEND
379     if (isFormRender_ && !window && !useNewPipe) {
380         useNewPipe = true;
381     }
382 
383     std::shared_ptr<OHOS::Rosen::RSUIDirector> rsUiDirector;
384     if (SystemProperties::GetRosenBackendEnabled() && !useNewPipe && isFormRender_) {
385         rsUiDirector = OHOS::Rosen::RSUIDirector::Create();
386         if (rsUiDirector) {
387             rsUiDirector->SetRSSurfaceNode(window->GetSurfaceNode());
388             rsUiDirector->SetCacheDir(context->GetCacheDir());
389             rsUiDirector->Init();
390         }
391     }
392 #endif
393     int32_t deviceWidth = 0;
394     int32_t deviceHeight = 0;
395     float density = 1.0f;
396     auto defaultDisplay = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
397     if (defaultDisplay) {
398         density = defaultDisplay->GetVirtualPixelRatio();
399         deviceWidth = defaultDisplay->GetWidth();
400         deviceHeight = defaultDisplay->GetHeight();
401         LOGI("UIContent: deviceWidth: %{public}d, deviceHeight: %{public}d, default density: %{public}f", deviceWidth,
402             deviceHeight, density);
403     }
404 
405     SystemProperties::InitDeviceInfo(deviceWidth, deviceHeight, deviceHeight >= deviceWidth ? 0 : 1, density, false);
406     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
407     if (context) {
408         auto resourceManager = context->GetResourceManager();
409         if (resourceManager != nullptr) {
410             resourceManager->GetResConfig(*resConfig);
411             auto localeInfo = resConfig->GetLocaleInfo();
412             Platform::AceApplicationInfoImpl::GetInstance().SetResourceManager(resourceManager);
413             if (localeInfo != nullptr) {
414                 auto language = localeInfo->getLanguage();
415                 auto region = localeInfo->getCountry();
416                 auto script = localeInfo->getScript();
417                 AceApplicationInfo::GetInstance().SetLocale((language == nullptr) ? "" : language,
418                     (region == nullptr) ? "" : region, (script == nullptr) ? "" : script, "");
419             }
420             if (resConfig->GetColorMode() == OHOS::Global::Resource::ColorMode::DARK) {
421                 SystemProperties::SetColorMode(ColorMode::DARK);
422                 LOGI("UIContent set dark mode");
423             } else {
424                 SystemProperties::SetColorMode(ColorMode::LIGHT);
425                 LOGI("UIContent set light mode");
426             }
427             SystemProperties::SetDeviceAccess(
428                 resConfig->GetInputDevice() == Global::Resource::InputDevice::INPUTDEVICE_POINTINGDEVICE);
429         }
430     }
431 
432     auto abilityContext = OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(context);
433     std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> info;
434     if (abilityContext) {
435         info = abilityContext->GetAbilityInfo();
436     } else {
437         auto extensionContext =
438             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::ExtensionContext>(context);
439         if (extensionContext) {
440             info = extensionContext->GetAbilityInfo();
441         } else {
442             LOGE("context is not AbilityContext or ExtensionContext.");
443         }
444     }
445     if (info) {
446         AceApplicationInfo::GetInstance().SetAbilityName(info->name);
447     }
448 
449     RefPtr<FlutterAssetManager> flutterAssetManager = Referenced::MakeRefPtr<FlutterAssetManager>();
450     bool isModelJson = info != nullptr ? info->isModuleJson : false;
451     std::string moduleName = info != nullptr ? info->moduleName : "";
452     auto appInfo = context != nullptr ? context->GetApplicationInfo() : nullptr;
453     auto hapModuleInfo = context != nullptr ? context->GetHapModuleInfo() : nullptr;
454     auto bundleName = info != nullptr ? info->bundleName : "";
455     std::string moduleHapPath = info != nullptr ? info->hapPath : "";
456     std::string resPath;
457     std::string pageProfile;
458     LOGI("Initialize UIContent isModelJson:%{public}s", isModelJson ? "true" : "false");
459     if (isFormRender_) {
460         LOGI("Initialize UIContent form assetProvider");
461         std::vector<std::string> basePaths;
462         basePaths.emplace_back("assets/js/" + moduleName_ + "/");
463         basePaths.emplace_back("assets/js/share/");
464         basePaths.emplace_back("");
465         basePaths.emplace_back("js/");
466         basePaths.emplace_back("ets/");
467         auto assetProvider =
468             CreateAssetProvider("/data/bundles/" + bundleName_ + "/" + moduleName_ + ".hap", basePaths);
469         if (assetProvider) {
470             LOGE("push card asset provider to queue.");
471             flutterAssetManager->PushBack(std::move(assetProvider));
472         }
473     } else {
474         if (isModelJson) {
475             std::string hapPath = info != nullptr ? info->hapPath : "";
476             LOGI("hapPath:%{public}s", hapPath.c_str());
477             // first use hap provider
478             if (flutterAssetManager && !hapPath.empty()) {
479                 auto assetProvider = AceType::MakeRefPtr<HapAssetProvider>();
480                 if (assetProvider->Initialize(hapPath, { "", "ets/", "resources/base/profile/" })) {
481                     LOGD("Push HapAssetProvider to queue.");
482                     flutterAssetManager->PushBack(std::move(assetProvider));
483                 }
484             }
485 
486             if (appInfo) {
487                 std::vector<OHOS::AppExecFwk::ModuleInfo> moduleList = appInfo->moduleInfos;
488                 for (const auto& module : moduleList) {
489                     if (module.moduleName == moduleName) {
490                         std::regex pattern(ABS_BUNDLE_CODE_PATH + bundleName + FILE_SEPARATOR);
491                         auto moduleSourceDir =
492                             std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
493                         resPath = moduleSourceDir + "/";
494                         break;
495                     }
496                 }
497             }
498 
499             // second use file provider, will remove later
500             LOGI("In stage mode, resPath:%{private}s", resPath.c_str());
501             auto assetBasePathStr = { std::string("ets/"), std::string("resources/base/profile/") };
502             if (flutterAssetManager && !resPath.empty()) {
503                 auto assetProvider = AceType::MakeRefPtr<FileAssetProvider>();
504                 if (assetProvider->Initialize(resPath, assetBasePathStr)) {
505                     LOGD("Push AssetProvider to queue.");
506                     flutterAssetManager->PushBack(std::move(assetProvider));
507                 }
508             }
509 
510             if (hapModuleInfo) {
511                 pageProfile = hapModuleInfo->pages;
512                 const std::string profilePrefix = "$profile:";
513                 if (pageProfile.compare(0, profilePrefix.size(), profilePrefix) == 0) {
514                     pageProfile = pageProfile.substr(profilePrefix.length()).append(".json");
515                 }
516                 LOGI("In stage mode, pageProfile:%{public}s", pageProfile.c_str());
517             } else {
518                 LOGE("In stage mode, can't get hap info.");
519             }
520         } else {
521             auto packagePathStr = context->GetBundleCodeDir();
522             if (hapModuleInfo != nullptr) {
523                 packagePathStr += "/" + hapModuleInfo->package + "/";
524             }
525             std::string srcPath = "";
526             if (info != nullptr && !info->srcPath.empty()) {
527                 srcPath = info->srcPath;
528             }
529 
530             auto assetBasePathStr = { "assets/js/" + (srcPath.empty() ? "default" : srcPath) + "/",
531                 std::string("assets/js/share/") };
532 
533             if (flutterAssetManager && !packagePathStr.empty()) {
534                 auto assetProvider = AceType::MakeRefPtr<FileAssetProvider>();
535                 if (assetProvider->Initialize(packagePathStr, assetBasePathStr)) {
536                     LOGD("Push AssetProvider to queue.");
537                     flutterAssetManager->PushBack(std::move(assetProvider));
538                 }
539             }
540 
541             if (appInfo) {
542                 std::vector<OHOS::AppExecFwk::ModuleInfo> moduleList = appInfo->moduleInfos;
543                 for (const auto& module : moduleList) {
544                     if (module.moduleName == moduleName) {
545                         std::regex pattern(ABS_BUNDLE_CODE_PATH + bundleName + FILE_SEPARATOR);
546                         auto moduleSourceDir =
547                             std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
548                         resPath = moduleSourceDir + "/assets/" + module.moduleName + "/";
549                         break;
550                     }
551                 }
552             }
553         }
554     }
555 
556     if (appInfo && flutterAssetManager && hapModuleInfo) {
557         /* Note: DO NOT modify the sequence of adding libPath  */
558         std::string nativeLibraryPath = appInfo->nativeLibraryPath;
559         std::string quickFixLibraryPath = appInfo->appQuickFix.deployedAppqfInfo.nativeLibraryPath;
560         std::vector<std::string> libPaths;
561         if (!quickFixLibraryPath.empty()) {
562             std::string libPath = GenerateFullPath(context->GetBundleCodeDir(), quickFixLibraryPath);
563             libPaths.push_back(libPath);
564             LOGI("napi quick fix lib path = %{private}s", libPath.c_str());
565         }
566         if (!nativeLibraryPath.empty()) {
567             std::string libPath = GenerateFullPath(context->GetBundleCodeDir(), nativeLibraryPath);
568             libPaths.push_back(libPath);
569             LOGI("napi lib path = %{private}s", libPath.c_str());
570         }
571         auto isLibIsolated = hapModuleInfo->isLibIsolated;
572         if (!libPaths.empty()) {
573             if (!isLibIsolated) {
574                 flutterAssetManager->SetLibPath("default", libPaths);
575             } else {
576                 std::string appLibPathKey = hapModuleInfo->bundleName + "/" + hapModuleInfo->moduleName;
577                 flutterAssetManager->SetLibPath(appLibPathKey, libPaths);
578             }
579         }
580     }
581     std::string hapPath; // hap path in sandbox
582     if (!moduleHapPath.empty()) {
583         if (moduleHapPath.find(ABS_BUNDLE_CODE_PATH) == std::string::npos) {
584             hapPath = moduleHapPath;
585         } else {
586             auto pos = moduleHapPath.find_last_of('/');
587             if (pos != std::string::npos) {
588                 hapPath = LOCAL_BUNDLE_CODE_PATH + moduleHapPath.substr(pos + 1);
589                 LOGI("In Stage mode, hapPath:%{private}s", hapPath.c_str());
590             }
591         }
592     }
593 
594     auto pluginUtils = std::make_shared<PluginUtilsImpl>();
595     PluginManager::GetInstance().SetAceAbility(nullptr, pluginUtils);
596     // create container
597     if (runtime_) {
598         instanceId_ = gInstanceId.fetch_add(1, std::memory_order_relaxed);
599     } else {
600         instanceId_ = gSubWindowInstanceId.fetch_add(1, std::memory_order_relaxed);
601     }
602     auto formUtils = std::make_shared<FormUtilsImpl>();
603     FormManager::GetInstance().SetFormUtils(formUtils);
604     auto container =
605         AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, FrontendType::DECLARATIVE_JS, true, context_, info,
606             std::make_unique<ContentEventCallback>(
607                 [context = context_] {
608                     auto sharedContext = context.lock();
609                     CHECK_NULL_VOID_NOLOG(sharedContext);
610                     auto abilityContext =
611                         OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
612                     CHECK_NULL_VOID_NOLOG(abilityContext);
613                     abilityContext->CloseAbility();
614                 },
615                 [context = context_](const std::string& address) {
616                     auto sharedContext = context.lock();
617                     CHECK_NULL_VOID_NOLOG(sharedContext);
618                     auto abilityContext =
619                         OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
620                     CHECK_NULL_VOID_NOLOG(abilityContext);
621                     LOGI("start ability with url = %{private}s", address.c_str());
622                     AAFwk::Want want;
623                     want.AddEntity(Want::ENTITY_BROWSER);
624                     want.SetUri(address);
625                     want.SetAction(ACTION_VIEWDATA);
626                     abilityContext->StartAbility(want, REQUEST_CODE);
627                 }),
628             false, false, useNewPipe);
629 
630     CHECK_NULL_VOID(container);
631     container->SetIsFormRender(isFormRender_);
632     container->SetIsFRSCardContainer(isFormRender_);
633     if (window_) {
634         container->SetWindowName(window_->GetWindowName());
635         container->SetWindowId(window_->GetWindowId());
636     }
637 
638     if (context) {
639         auto token = context->GetToken();
640         container->SetToken(token);
641     }
642 
643     // Mark the relationship between windowId and containerId, it is 1:1
644     if (window) {
645         SubwindowManager::GetInstance()->AddContainerId(window->GetWindowId(), instanceId_);
646     }
647     AceEngine::Get().AddContainer(instanceId_, container);
648     if (runtime_) {
649         container->GetSettings().SetUsingSharedRuntime(true);
650         container->SetSharedRuntime(runtime_);
651     } else {
652         container->GetSettings().SetUsingSharedRuntime(false);
653     }
654     container->SetPageProfile(pageProfile);
655     container->Initialize();
656     ContainerScope scope(instanceId_);
657     auto front = container->GetFrontend();
658     if (front) {
659         front->UpdateState(Frontend::State::ON_CREATE);
660         front->SetJsMessageDispatcher(container);
661     }
662     auto aceResCfg = container->GetResourceConfiguration();
663     aceResCfg.SetOrientation(SystemProperties::GetDeviceOrientation());
664     aceResCfg.SetDensity(SystemProperties::GetResolution());
665     aceResCfg.SetDeviceType(SystemProperties::GetDeviceType());
666     aceResCfg.SetColorMode(SystemProperties::GetColorMode());
667     aceResCfg.SetDeviceAccess(SystemProperties::GetDeviceAccess());
668     if (isFormRender_) {
669         resPath = "/data/bundles/" + bundleName_ + "/" + moduleName_ + "/";
670         hapPath = "/data/bundles/" + bundleName_ + "/" + moduleName_ + ".hap";
671     }
672     LOGI("CommonInitializeForm resPath = %{public}s hapPath = %{public}s", resPath.c_str(), hapPath.c_str());
673     container->SetResourceConfiguration(aceResCfg);
674     container->SetPackagePathStr(resPath);
675     container->SetHapPath(hapPath);
676     container->SetAssetManager(flutterAssetManager);
677     if (!isFormRender_) {
678         container->SetBundlePath(context->GetBundleCodeDir());
679         container->SetFilesDataPath(context->GetFilesDir());
680     }
681 
682     if (window_) {
683         if (window_->IsDecorEnable()) {
684             LOGI("Container modal is enabled.");
685             container->SetWindowModal(WindowModal::CONTAINER_MODAL);
686         }
687 
688         dragWindowListener_ = new DragWindowListener(instanceId_);
689         window_->RegisterDragListener(dragWindowListener_);
690         occupiedAreaChangeListener_ = new OccupiedAreaChangeListener(instanceId_);
691         window_->RegisterOccupiedAreaChangeListener(occupiedAreaChangeListener_);
692     }
693 
694     // create ace_view
695     Platform::FlutterAceView* flutterAceView = nullptr;
696     if (isFormRender_) {
697         flutterAceView =
698             Platform::FlutterAceView::CreateView(instanceId_, true, container->GetSettings().usePlatformAsUIThread);
699         Platform::FlutterAceView::SurfaceCreated(flutterAceView, window_);
700     } else {
701         flutterAceView =
702             Platform::FlutterAceView::CreateView(instanceId_, false, container->GetSettings().usePlatformAsUIThread);
703         Platform::FlutterAceView::SurfaceCreated(flutterAceView, window_);
704     }
705 
706     if (!useNewPipe) {
707         Ace::Platform::UIEnvCallback callback = nullptr;
708 #ifdef ENABLE_ROSEN_BACKEND
709         callback = [window, id = instanceId_, container, flutterAceView, rsUiDirector](
710                        const OHOS::Ace::RefPtr<OHOS::Ace::PipelineContext>& context) {
711             if (rsUiDirector) {
712                 ACE_SCOPED_TRACE("OHOS::Rosen::RSUIDirector::Create()");
713                 rsUiDirector->SetUITaskRunner(
714                     [taskExecutor = container->GetTaskExecutor(), id](const std::function<void()>& task) {
715                         ContainerScope scope(id);
716                         taskExecutor->PostTask(task, TaskExecutor::TaskType::UI);
717                     });
718                 auto context = AceType::DynamicCast<PipelineContext>(container->GetPipelineContext());
719                 if (context != nullptr) {
720                     context->SetRSUIDirector(rsUiDirector);
721                 }
722                 flutterAceView->InitIOManager(container->GetTaskExecutor());
723                 LOGD("UIContent Init Rosen Backend");
724             }
725         };
726 #endif
727         // set view
728         Platform::AceContainer::SetView(flutterAceView, density, 0, 0, window_, callback);
729     } else {
730         if (isFormRender_) {
731             LOGI("Platform::AceContainer::SetViewNew is card formWidth=%{public}f, formHeight=%{public}f",
732                 formWidth_, formHeight_);
733             Platform::AceContainer::SetViewNew(flutterAceView, density, formWidth_, formHeight_, window_);
734             auto frontend = AceType::DynamicCast<FormFrontendDeclarative>(container->GetFrontend());
735             CHECK_NULL_VOID(frontend);
736             frontend->SetBundleName(bundleName_);
737             frontend->SetModuleName(moduleName_);
738             // arkTSCard only support "esModule" compile mode
739             frontend->SetIsBundle(false);
740         } else {
741             Platform::AceContainer::SetViewNew(flutterAceView, density, 0, 0, window_);
742         }
743     }
744 
745     // after frontend initialize
746     if (window_ && window_->IsFocused()) {
747         LOGI("UIContentImpl: focus again");
748         Focus();
749     }
750 
751     if (isFormRender_ && !isFormRenderInit_) {
752         container->UpdateFormSharedImage(formImageDataMap_);
753         container->UpdateFormData(formData_);
754         isFormRenderInit_ = true;
755     }
756 
757     if (isFormRender_) {
758         Platform::FlutterAceView::SurfaceChanged(
759             flutterAceView, formWidth_, formHeight_, deviceHeight >= deviceWidth ? 0 : 1);
760         // Set sdk version in module json mode for form
761         auto pipeline = container->GetPipelineContext();
762         if (pipeline) {
763             pipeline->SetMinPlatformVersion(minCompatibleVersionCode_);
764         }
765     } else {
766         Platform::FlutterAceView::SurfaceChanged(flutterAceView, 0, 0, deviceHeight >= deviceWidth ? 0 : 1);
767     }
768     // Set sdk version in module json mode
769     if (isModelJson) {
770         auto pipeline = container->GetPipelineContext();
771         if (pipeline && appInfo) {
772             LOGI("SetMinPlatformVersion code is %{public}d", appInfo->minCompatibleVersionCode);
773             pipeline->SetMinPlatformVersion(appInfo->minCompatibleVersionCode);
774         }
775     }
776     if (runtime_ && !isFormRender_) { // ArkTSCard not support inherit local strorage from context
777         auto nativeEngine = reinterpret_cast<NativeEngine*>(runtime_);
778         if (!storage) {
779             container->SetLocalStorage(nullptr, context->GetBindingObject()->Get<NativeReference>());
780         } else {
781             LOGI("SetLocalStorage %{public}d", storage->TypeOf());
782             container->SetLocalStorage(
783                 nativeEngine->CreateReference(storage, 1), context->GetBindingObject()->Get<NativeReference>());
784         }
785     }
786     LayoutInspector::SetCallback(instanceId_);
787 }
788 
SetConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration> & config)789 void UIContentImpl::SetConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)
790 {
791     if (config == nullptr) {
792         LOGI("config is nullptr, set localeInfo to default");
793         UErrorCode status = U_ZERO_ERROR;
794         icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status);
795         AceApplicationInfo::GetInstance().SetLocale(locale.getLanguage(), locale.getCountry(), locale.getScript(), "");
796         SystemProperties::SetColorMode(ColorMode::LIGHT);
797         return;
798     }
799 
800     LOGI("SetConfiguration");
801     auto colorMode = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
802     auto deviceAccess = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE);
803     auto languageTag = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE);
804     if (!colorMode.empty()) {
805         LOGI("SetConfiguration colorMode: %{public}s", colorMode.c_str());
806         if (colorMode == "dark") {
807             SystemProperties::SetColorMode(ColorMode::DARK);
808         } else {
809             SystemProperties::SetColorMode(ColorMode::LIGHT);
810         }
811     }
812 
813     if (!deviceAccess.empty()) {
814         // Event of accessing mouse or keyboard
815         LOGI("SetConfiguration deviceAccess: %{public}s", deviceAccess.c_str());
816         SystemProperties::SetDeviceAccess(deviceAccess == "true");
817     }
818 
819     if (!languageTag.empty()) {
820         LOGI("SetConfiguration languageTag: %{public}s", languageTag.c_str());
821         std::string language;
822         std::string script;
823         std::string region;
824         Localization::ParseLocaleTag(languageTag, language, script, region, false);
825         if (!language.empty() || !script.empty() || !region.empty()) {
826             AceApplicationInfo::GetInstance().SetLocale(language, region, script, "");
827         }
828     }
829 }
830 
GetFormRootNode()831 std::shared_ptr<Rosen::RSSurfaceNode> UIContentImpl::GetFormRootNode()
832 {
833     return Platform::AceContainer::GetFormSurfaceNode(instanceId_);
834 }
835 // ArkTSCard end
836 
CommonInitialize(OHOS::Rosen::Window * window,const std::string & contentInfo,NativeValue * storage)837 void UIContentImpl::CommonInitialize(OHOS::Rosen::Window* window, const std::string& contentInfo, NativeValue* storage)
838 {
839     ACE_FUNCTION_TRACE();
840     window_ = window;
841     startUrl_ = contentInfo;
842     CHECK_NULL_VOID(window_);
843     if (StringUtils::StartWith(window->GetWindowName(), SUBWINDOW_TOAST_DIALOG_PREFIX)) {
844         InitializeSubWindow(window_, true);
845         return;
846     }
847     if (StringUtils::StartWith(window->GetWindowName(), SUBWINDOW_PREFIX)) {
848         InitializeSubWindow(window_);
849         return;
850     }
851     auto context = context_.lock();
852     CHECK_NULL_VOID(context);
853     LOGI("Initialize UIContentImpl start.");
854     static std::once_flag onceFlag;
855     std::call_once(onceFlag, [&context]() {
856         LOGI("Initialize for current process.");
857         SetHwIcuDirectory();
858         Container::UpdateCurrent(INSTANCE_ID_PLATFORM);
859         AceApplicationInfo::GetInstance().SetProcessName(context->GetBundleName());
860         AceApplicationInfo::GetInstance().SetPackageName(context->GetBundleName());
861         AceApplicationInfo::GetInstance().SetDataFileDirPath(context->GetFilesDir());
862         AceApplicationInfo::GetInstance().SetUid(IPCSkeleton::GetCallingUid());
863         AceApplicationInfo::GetInstance().SetPid(IPCSkeleton::GetCallingPid());
864         CapabilityRegistry::Register();
865         ImageCache::SetImageCacheFilePath(context->GetCacheDir());
866         ImageCache::SetCacheFileInfo();
867     });
868     AceNewPipeJudgement::InitAceNewPipeConfig();
869     auto apiCompatibleVersion = context->GetApplicationInfo()->apiCompatibleVersion;
870     auto apiReleaseType = context->GetApplicationInfo()->apiReleaseType;
871     auto apiTargetVersion = context->GetApplicationInfo()->apiTargetVersion;
872     const auto& hapModuleInfo = context->GetHapModuleInfo();
873     std::vector<OHOS::AppExecFwk::Metadata> metaData;
874     if (hapModuleInfo) {
875         metaData = hapModuleInfo->metadata;
876     }
877     bool closeArkTSPartialUpdate = std::any_of(metaData.begin(), metaData.end(), [](const auto& metaDataItem) {
878         return metaDataItem.name == "ArkTSPartialUpdate" && metaDataItem.value == "false";
879     });
880     auto useNewPipe =
881         AceNewPipeJudgement::QueryAceNewPipeEnabledStage(AceApplicationInfo::GetInstance().GetPackageName(),
882             apiCompatibleVersion, apiTargetVersion, apiReleaseType, closeArkTSPartialUpdate);
883     LOGI("UIContent: apiCompatibleVersion: %{public}d, apiTargetVersion: %{public}d, and apiReleaseType: %{public}s, "
884          "useNewPipe: %{public}d",
885         apiCompatibleVersion, apiTargetVersion, apiReleaseType.c_str(), useNewPipe);
886     std::shared_ptr<OHOS::Rosen::RSUIDirector> rsUiDirector;
887     if (SystemProperties::GetRosenBackendEnabled() && !useNewPipe) {
888         rsUiDirector = OHOS::Rosen::RSUIDirector::Create();
889         if (rsUiDirector) {
890             rsUiDirector->SetRSSurfaceNode(window->GetSurfaceNode());
891             rsUiDirector->SetCacheDir(context->GetCacheDir());
892             rsUiDirector->Init();
893         }
894     }
895 
896     int32_t deviceWidth = 0;
897     int32_t deviceHeight = 0;
898     float density = 1.0f;
899     auto defaultDisplay = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
900     if (defaultDisplay) {
901         density = defaultDisplay->GetVirtualPixelRatio();
902         deviceWidth = defaultDisplay->GetWidth();
903         deviceHeight = defaultDisplay->GetHeight();
904         LOGI("UIContent: deviceWidth: %{public}d, deviceHeight: %{public}d, default density: %{public}f", deviceWidth,
905             deviceHeight, density);
906     }
907     SystemProperties::InitDeviceInfo(deviceWidth, deviceHeight, deviceHeight >= deviceWidth ? 0 : 1, density, false);
908     SystemProperties::SetColorMode(ColorMode::LIGHT);
909 
910     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
911     auto resourceManager = context->GetResourceManager();
912     if (resourceManager != nullptr) {
913         resourceManager->GetResConfig(*resConfig);
914         auto localeInfo = resConfig->GetLocaleInfo();
915         Platform::AceApplicationInfoImpl::GetInstance().SetResourceManager(resourceManager);
916         if (localeInfo != nullptr) {
917             auto language = localeInfo->getLanguage();
918             auto region = localeInfo->getCountry();
919             auto script = localeInfo->getScript();
920             AceApplicationInfo::GetInstance().SetLocale((language == nullptr) ? "" : language,
921                 (region == nullptr) ? "" : region, (script == nullptr) ? "" : script, "");
922         }
923         if (resConfig->GetColorMode() == OHOS::Global::Resource::ColorMode::DARK) {
924             SystemProperties::SetColorMode(ColorMode::DARK);
925             LOGI("UIContent set dark mode");
926         } else {
927             SystemProperties::SetColorMode(ColorMode::LIGHT);
928             LOGI("UIContent set light mode");
929         }
930         SystemProperties::SetDeviceAccess(
931             resConfig->GetInputDevice() == Global::Resource::InputDevice::INPUTDEVICE_POINTINGDEVICE);
932     }
933 
934     auto abilityContext = OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(context);
935     std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> info;
936     if (abilityContext) {
937         info = abilityContext->GetAbilityInfo();
938     } else {
939         auto extensionContext =
940             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::ExtensionContext>(context);
941         if (!extensionContext) {
942             LOGE("context is not AbilityContext or ExtensionContext.");
943             return;
944         }
945         info = extensionContext->GetAbilityInfo();
946     }
947     if (info) {
948         AceApplicationInfo::GetInstance().SetAbilityName(info->name);
949     }
950 
951     RefPtr<FlutterAssetManager> flutterAssetManager = Referenced::MakeRefPtr<FlutterAssetManager>();
952     bool isModelJson = info != nullptr ? info->isModuleJson : false;
953     std::string moduleName = info != nullptr ? info->moduleName : "";
954     auto appInfo = context->GetApplicationInfo();
955     auto bundleName = info != nullptr ? info->bundleName : "";
956     std::string moduleHapPath = info != nullptr ? info->hapPath : "";
957     std::string resPath;
958     std::string pageProfile;
959     LOGI("Initialize UIContent isModelJson:%{public}s", isModelJson ? "true" : "false");
960     if (isModelJson) {
961         std::string hapPath = info != nullptr ? info->hapPath : "";
962         LOGI("hapPath:%{public}s", hapPath.c_str());
963         // first use hap provider
964         if (flutterAssetManager && !hapPath.empty()) {
965             auto assetProvider = AceType::MakeRefPtr<HapAssetProvider>();
966             if (assetProvider->Initialize(hapPath, { "", "ets/", "resources/base/profile/" })) {
967                 LOGD("Push HapAssetProvider to queue.");
968                 flutterAssetManager->PushBack(std::move(assetProvider));
969             }
970         }
971 
972         if (appInfo) {
973             std::vector<OHOS::AppExecFwk::ModuleInfo> moduleList = appInfo->moduleInfos;
974             for (const auto& module : moduleList) {
975                 if (module.moduleName == moduleName) {
976                     std::regex pattern(ABS_BUNDLE_CODE_PATH + bundleName + FILE_SEPARATOR);
977                     auto moduleSourceDir = std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
978                     resPath = moduleSourceDir + "/";
979                     break;
980                 }
981             }
982         }
983 
984         // second use file provider, will remove later
985         LOGI("In stage mode, resPath:%{private}s", resPath.c_str());
986         auto assetBasePathStr = { std::string("ets/"), std::string("resources/base/profile/") };
987         if (flutterAssetManager && !resPath.empty()) {
988             auto assetProvider = AceType::MakeRefPtr<FileAssetProvider>();
989             if (assetProvider->Initialize(resPath, assetBasePathStr)) {
990                 LOGD("Push AssetProvider to queue.");
991                 flutterAssetManager->PushBack(std::move(assetProvider));
992             }
993         }
994 
995         if (hapModuleInfo) {
996             pageProfile = hapModuleInfo->pages;
997             const std::string profilePrefix = "$profile:";
998             if (pageProfile.compare(0, profilePrefix.size(), profilePrefix) == 0) {
999                 pageProfile = pageProfile.substr(profilePrefix.length()).append(".json");
1000             }
1001             LOGI("In stage mode, pageProfile:%{public}s", pageProfile.c_str());
1002         } else {
1003             LOGE("In stage mode, can't get hap info.");
1004         }
1005     } else {
1006         auto packagePathStr = context->GetBundleCodeDir();
1007         if (hapModuleInfo != nullptr) {
1008             packagePathStr += "/" + hapModuleInfo->package + "/";
1009         }
1010         std::string srcPath = "";
1011         if (info != nullptr && !info->srcPath.empty()) {
1012             srcPath = info->srcPath;
1013         }
1014 
1015         auto assetBasePathStr = { "assets/js/" + (srcPath.empty() ? "default" : srcPath) + "/",
1016             std::string("assets/js/share/") };
1017 
1018         if (flutterAssetManager && !packagePathStr.empty()) {
1019             auto assetProvider = AceType::MakeRefPtr<FileAssetProvider>();
1020             if (assetProvider->Initialize(packagePathStr, assetBasePathStr)) {
1021                 LOGD("Push AssetProvider to queue.");
1022                 flutterAssetManager->PushBack(std::move(assetProvider));
1023             }
1024         }
1025 
1026         if (appInfo) {
1027             std::vector<OHOS::AppExecFwk::ModuleInfo> moduleList = appInfo->moduleInfos;
1028             for (const auto& module : moduleList) {
1029                 if (module.moduleName == moduleName) {
1030                     std::regex pattern(ABS_BUNDLE_CODE_PATH + bundleName + FILE_SEPARATOR);
1031                     auto moduleSourceDir = std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
1032                     resPath = moduleSourceDir + "/assets/" + module.moduleName + "/";
1033                     break;
1034                 }
1035             }
1036         }
1037     }
1038 
1039     if (appInfo && flutterAssetManager && hapModuleInfo) {
1040         /* Note: DO NOT modify the sequence of adding libPath  */
1041         std::string nativeLibraryPath = appInfo->nativeLibraryPath;
1042         std::string quickFixLibraryPath = appInfo->appQuickFix.deployedAppqfInfo.nativeLibraryPath;
1043         std::vector<std::string> libPaths;
1044         if (!quickFixLibraryPath.empty()) {
1045             std::string libPath = GenerateFullPath(context->GetBundleCodeDir(), quickFixLibraryPath);
1046             libPaths.push_back(libPath);
1047             LOGI("napi quick fix lib path = %{private}s", libPath.c_str());
1048         }
1049         if (!nativeLibraryPath.empty()) {
1050             std::string libPath = GenerateFullPath(context->GetBundleCodeDir(), nativeLibraryPath);
1051             libPaths.push_back(libPath);
1052             LOGI("napi lib path = %{private}s", libPath.c_str());
1053         }
1054         auto isLibIsolated = hapModuleInfo->isLibIsolated;
1055         if (!libPaths.empty()) {
1056             if (!isLibIsolated) {
1057                 flutterAssetManager->SetLibPath("default", libPaths);
1058             } else {
1059                 std::string appLibPathKey = hapModuleInfo->bundleName + "/" + hapModuleInfo->moduleName;
1060                 flutterAssetManager->SetLibPath(appLibPathKey, libPaths);
1061             }
1062         }
1063     }
1064     std::string hapPath; // hap path in sandbox
1065     if (!moduleHapPath.empty()) {
1066         if (moduleHapPath.find(ABS_BUNDLE_CODE_PATH) == std::string::npos) {
1067             hapPath = moduleHapPath;
1068         } else {
1069             auto pos = moduleHapPath.find_last_of('/');
1070             if (pos != std::string::npos) {
1071                 hapPath = LOCAL_BUNDLE_CODE_PATH + moduleHapPath.substr(pos + 1);
1072                 LOGI("In Stage mode, hapPath:%{private}s", hapPath.c_str());
1073             }
1074         }
1075     }
1076 
1077     auto pluginUtils = std::make_shared<PluginUtilsImpl>();
1078     PluginManager::GetInstance().SetAceAbility(nullptr, pluginUtils);
1079     // create container
1080     if (runtime_) {
1081         instanceId_ = gInstanceId.fetch_add(1, std::memory_order_relaxed);
1082     } else {
1083         instanceId_ = gSubWindowInstanceId.fetch_add(1, std::memory_order_relaxed);
1084     }
1085     auto formUtils = std::make_shared<FormUtilsImpl>();
1086     FormManager::GetInstance().SetFormUtils(formUtils);
1087     auto container =
1088         AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, FrontendType::DECLARATIVE_JS, true, context_, info,
1089             std::make_unique<ContentEventCallback>(
1090                 [context = context_] {
1091                     auto sharedContext = context.lock();
1092                     CHECK_NULL_VOID_NOLOG(sharedContext);
1093                     auto abilityContext =
1094                         OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
1095                     CHECK_NULL_VOID_NOLOG(abilityContext);
1096                     abilityContext->CloseAbility();
1097                 },
1098                 [context = context_](const std::string& address) {
1099                     auto sharedContext = context.lock();
1100                     CHECK_NULL_VOID_NOLOG(sharedContext);
1101                     auto abilityContext =
1102                         OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
1103                     CHECK_NULL_VOID_NOLOG(abilityContext);
1104                     LOGI("start ability with url = %{private}s", address.c_str());
1105                     AAFwk::Want want;
1106                     want.AddEntity(Want::ENTITY_BROWSER);
1107                     want.SetUri(address);
1108                     want.SetAction(ACTION_VIEWDATA);
1109                     abilityContext->StartAbility(want, REQUEST_CODE);
1110                 }),
1111             false, false, useNewPipe);
1112     CHECK_NULL_VOID(container);
1113     container->SetWindowName(window_->GetWindowName());
1114     container->SetWindowId(window_->GetWindowId());
1115     auto token = context->GetToken();
1116     container->SetToken(token);
1117     container->SetPageUrlChecker(AceType::MakeRefPtr<PageUrlCheckerOhos>(context));
1118     // Mark the relationship between windowId and containerId, it is 1:1
1119     SubwindowManager::GetInstance()->AddContainerId(window->GetWindowId(), instanceId_);
1120     AceEngine::Get().AddContainer(instanceId_, container);
1121     if (runtime_) {
1122         container->GetSettings().SetUsingSharedRuntime(true);
1123         container->SetSharedRuntime(runtime_);
1124     } else {
1125         container->GetSettings().SetUsingSharedRuntime(false);
1126     }
1127     container->SetPageProfile(pageProfile);
1128     container->Initialize();
1129     ContainerScope scope(instanceId_);
1130     auto front = container->GetFrontend();
1131     if (front) {
1132         front->UpdateState(Frontend::State::ON_CREATE);
1133         front->SetJsMessageDispatcher(container);
1134     }
1135     auto aceResCfg = container->GetResourceConfiguration();
1136     aceResCfg.SetOrientation(SystemProperties::GetDeviceOrientation());
1137     aceResCfg.SetDensity(SystemProperties::GetResolution());
1138     aceResCfg.SetDeviceType(SystemProperties::GetDeviceType());
1139     aceResCfg.SetColorMode(SystemProperties::GetColorMode());
1140     aceResCfg.SetDeviceAccess(SystemProperties::GetDeviceAccess());
1141     container->SetResourceConfiguration(aceResCfg);
1142     container->SetPackagePathStr(resPath);
1143     container->SetHapPath(hapPath);
1144     container->SetAssetManager(flutterAssetManager);
1145     container->SetBundlePath(context->GetBundleCodeDir());
1146     container->SetFilesDataPath(context->GetFilesDir());
1147     container->SetModuleName(hapModuleInfo->moduleName);
1148     container->SetIsModule(hapModuleInfo->compileMode == AppExecFwk::CompileMode::ES_MODULE);
1149     // for atomic service
1150     container->SetInstallationFree(hapModuleInfo && hapModuleInfo->installationFree);
1151     if (hapModuleInfo->installationFree) {
1152         container->SetSharePanelCallback(
1153             [context = context_](const std::string& bundleName, const std::string& abilityName) {
1154                 auto sharedContext = context.lock();
1155                 CHECK_NULL_VOID_NOLOG(sharedContext);
1156                 auto abilityContext =
1157                     OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
1158                 CHECK_NULL_VOID_NOLOG(abilityContext);
1159                 auto abilityInfo = abilityContext->GetAbilityInfo();
1160                 AAFwk::Want want;
1161                 want.SetParam("abilityName", abilityInfo->name);
1162                 want.SetParam("bundleName", abilityInfo->bundleName);
1163                 want.SetParam("moduleName", abilityInfo->moduleName);
1164                 want.SetParam("hostPkgName", abilityInfo->bundleName);
1165                 want.SetElementName(bundleName, abilityName);
1166                 abilityContext->StartAbility(want, REQUEST_CODE);
1167             });
1168     }
1169 
1170     if (window_->IsDecorEnable()) {
1171         LOGI("Container modal is enabled.");
1172         container->SetWindowModal(WindowModal::CONTAINER_MODAL);
1173     }
1174 
1175     dragWindowListener_ = new DragWindowListener(instanceId_);
1176     window_->RegisterDragListener(dragWindowListener_);
1177     occupiedAreaChangeListener_ = new OccupiedAreaChangeListener(instanceId_);
1178     window_->RegisterOccupiedAreaChangeListener(occupiedAreaChangeListener_);
1179 
1180     // create ace_view
1181     auto flutterAceView =
1182         Platform::FlutterAceView::CreateView(instanceId_, false, container->GetSettings().usePlatformAsUIThread);
1183     Platform::FlutterAceView::SurfaceCreated(flutterAceView, window_);
1184     if (!useNewPipe) {
1185         Ace::Platform::UIEnvCallback callback = nullptr;
1186 #ifdef ENABLE_ROSEN_BACKEND
1187         callback = [window, id = instanceId_, container, flutterAceView, rsUiDirector](
1188                        const OHOS::Ace::RefPtr<OHOS::Ace::PipelineContext>& context) {
1189             if (rsUiDirector) {
1190                 ACE_SCOPED_TRACE("OHOS::Rosen::RSUIDirector::Create()");
1191                 rsUiDirector->SetUITaskRunner(
1192                     [taskExecutor = container->GetTaskExecutor(), id](const std::function<void()>& task) {
1193                         ContainerScope scope(id);
1194                         taskExecutor->PostTask(task, TaskExecutor::TaskType::UI);
1195                     });
1196                 auto context = AceType::DynamicCast<PipelineContext>(container->GetPipelineContext());
1197                 if (context != nullptr) {
1198                     context->SetRSUIDirector(rsUiDirector);
1199                 }
1200                 flutterAceView->InitIOManager(container->GetTaskExecutor());
1201                 LOGD("UIContent Init Rosen Backend");
1202             }
1203         };
1204 #endif
1205         // set view
1206         Platform::AceContainer::SetView(flutterAceView, density, 0, 0, window_, callback);
1207     } else {
1208         Platform::AceContainer::SetViewNew(flutterAceView, density, 0, 0, window_);
1209     }
1210 
1211     // after frontend initialize
1212     if (window_->IsFocused()) {
1213         LOGI("UIContentImpl: focus again");
1214         Focus();
1215     }
1216 
1217     Platform::FlutterAceView::SurfaceChanged(flutterAceView, 0, 0, deviceHeight >= deviceWidth ? 0 : 1);
1218     // Set sdk version in module json mode
1219     if (isModelJson) {
1220         auto pipeline = container->GetPipelineContext();
1221         if (pipeline && appInfo) {
1222             LOGI("SetMinPlatformVersion code is %{public}d", appInfo->minCompatibleVersionCode);
1223             pipeline->SetMinPlatformVersion(appInfo->minCompatibleVersionCode);
1224         }
1225     }
1226     if (runtime_) {
1227         auto nativeEngine = reinterpret_cast<NativeEngine*>(runtime_);
1228         if (!storage) {
1229             container->SetLocalStorage(nullptr, context->GetBindingObject()->Get<NativeReference>());
1230         } else {
1231             LOGI("SetLocalStorage %{public}d", storage->TypeOf());
1232             container->SetLocalStorage(
1233                 nativeEngine->CreateReference(storage, 1), context->GetBindingObject()->Get<NativeReference>());
1234         }
1235     }
1236     LayoutInspector::SetCallback(instanceId_);
1237 
1238     LOGI("Initialize UIContentImpl end.");
1239 }
1240 
Foreground()1241 void UIContentImpl::Foreground()
1242 {
1243     LOGI("UIContentImpl: window foreground");
1244     Platform::AceContainer::OnShow(instanceId_);
1245     // set the flag isForegroundCalled to be true
1246     auto container = Platform::AceContainer::GetContainer(instanceId_);
1247     CHECK_NULL_VOID(container);
1248     auto pipelineContext = container->GetPipelineContext();
1249     CHECK_NULL_VOID(pipelineContext);
1250     pipelineContext->SetForegroundCalled(true);
1251 }
1252 
Background()1253 void UIContentImpl::Background()
1254 {
1255     LOGI("UIContentImpl: window background");
1256     Platform::AceContainer::OnHide(instanceId_);
1257 }
1258 
ReloadForm()1259 void UIContentImpl::ReloadForm()
1260 {
1261     LOGI("ReloadForm startUrl = %{public}s", startUrl_.c_str());
1262     auto container = Platform::AceContainer::GetContainer(instanceId_);
1263     auto flutterAssetManager = AceType::DynamicCast<FlutterAssetManager>(container->GetAssetManager());
1264     flutterAssetManager->ReloadProvider();
1265     Platform::AceContainer::ClearEngineCache(instanceId_);
1266     Platform::AceContainer::RunPage(instanceId_, Platform::AceContainer::GetContainer(instanceId_)->GeneratePageId(),
1267         startUrl_, "");
1268 }
1269 
Focus()1270 void UIContentImpl::Focus()
1271 {
1272     LOGI("UIContentImpl: window focus");
1273     Platform::AceContainer::OnActive(instanceId_);
1274 }
1275 
UnFocus()1276 void UIContentImpl::UnFocus()
1277 {
1278     LOGI("UIContentImpl: window unFocus");
1279     Platform::AceContainer::OnInactive(instanceId_);
1280 }
1281 
Destroy()1282 void UIContentImpl::Destroy()
1283 {
1284     LOGI("UIContentImpl: window destroy");
1285     auto container = AceEngine::Get().GetContainer(instanceId_);
1286     CHECK_NULL_VOID_NOLOG(container);
1287     if (strcmp(AceType::TypeName(container), AceType::TypeName<Platform::DialogContainer>()) == 0) {
1288         Platform::DialogContainer::DestroyContainer(instanceId_);
1289     } else {
1290         Platform::AceContainer::DestroyContainer(instanceId_);
1291     }
1292 }
1293 
OnNewWant(const OHOS::AAFwk::Want & want)1294 void UIContentImpl::OnNewWant(const OHOS::AAFwk::Want& want)
1295 {
1296     LOGI("UIContent OnNewWant");
1297     Platform::AceContainer::OnShow(instanceId_);
1298     std::string params = want.GetStringParam(START_PARAMS_KEY);
1299     Platform::AceContainer::OnNewRequest(instanceId_, params);
1300 }
1301 
GetBackgroundColor()1302 uint32_t UIContentImpl::GetBackgroundColor()
1303 {
1304     auto container = Platform::AceContainer::GetContainer(instanceId_);
1305     CHECK_NULL_RETURN(container, 0x000000);
1306     auto taskExecutor = container->GetTaskExecutor();
1307     CHECK_NULL_RETURN(taskExecutor, 0x000000);
1308     ContainerScope scope(instanceId_);
1309     uint32_t bgColor = 0x000000;
1310     taskExecutor->PostSyncTask(
1311         [&bgColor, container]() {
1312             CHECK_NULL_VOID(container);
1313             auto pipelineContext = container->GetPipelineContext();
1314             CHECK_NULL_VOID(pipelineContext);
1315             bgColor = pipelineContext->GetAppBgColor().GetValue();
1316         },
1317         TaskExecutor::TaskType::UI);
1318 
1319     LOGI("UIContentImpl::GetBackgroundColor, value is %{public}u", bgColor);
1320     return bgColor;
1321 }
1322 
SetBackgroundColor(uint32_t color)1323 void UIContentImpl::SetBackgroundColor(uint32_t color)
1324 {
1325     LOGI("UIContentImpl: SetBackgroundColor color is %{public}u", color);
1326     auto container = AceEngine::Get().GetContainer(instanceId_);
1327     CHECK_NULL_VOID(container);
1328     ContainerScope scope(instanceId_);
1329     auto taskExecutor = container->GetTaskExecutor();
1330     CHECK_NULL_VOID(taskExecutor);
1331     taskExecutor->PostSyncTask(
1332         [container, bgColor = color]() {
1333             auto pipelineContext = container->GetPipelineContext();
1334             CHECK_NULL_VOID(pipelineContext);
1335             pipelineContext->SetAppBgColor(Color(bgColor));
1336         },
1337         TaskExecutor::TaskType::UI);
1338 }
1339 
ProcessBackPressed()1340 bool UIContentImpl::ProcessBackPressed()
1341 {
1342     LOGI("UIContentImpl: ProcessBackPressed: Platform::AceContainer::OnBackPressed called");
1343     auto container = AceEngine::Get().GetContainer(instanceId_);
1344     CHECK_NULL_RETURN_NOLOG(container, false);
1345     if (strcmp(AceType::TypeName(container), AceType::TypeName<Platform::DialogContainer>()) == 0) {
1346         if (Platform::DialogContainer::OnBackPressed(instanceId_)) {
1347             LOGI("UIContentImpl::ProcessBackPressed DialogContainer return true");
1348             return true;
1349         }
1350     } else {
1351         LOGI("UIContentImpl::ProcessBackPressed AceContainer");
1352         if (Platform::AceContainer::OnBackPressed(instanceId_)) {
1353             LOGI("UIContentImpl::ProcessBackPressed AceContainer return true");
1354             return true;
1355         }
1356     }
1357     LOGI("ProcessBackPressed: Platform::AceContainer::OnBackPressed return false");
1358     return false;
1359 }
1360 
ProcessPointerEvent(const std::shared_ptr<OHOS::MMI::PointerEvent> & pointerEvent)1361 bool UIContentImpl::ProcessPointerEvent(const std::shared_ptr<OHOS::MMI::PointerEvent>& pointerEvent)
1362 {
1363     LOGD("UIContentImpl::ProcessPointerEvent begin");
1364     auto container = AceEngine::Get().GetContainer(instanceId_);
1365     CHECK_NULL_RETURN(container, false);
1366     auto aceView = static_cast<Platform::FlutterAceView*>(container->GetView());
1367     Platform::FlutterAceView::DispatchTouchEvent(aceView, pointerEvent);
1368     LOGD("UIContentImpl::ProcessPointerEvent end");
1369     return true;
1370 }
1371 
ProcessKeyEvent(const std::shared_ptr<OHOS::MMI::KeyEvent> & touchEvent)1372 bool UIContentImpl::ProcessKeyEvent(const std::shared_ptr<OHOS::MMI::KeyEvent>& touchEvent)
1373 {
1374     LOGI("UIContentImpl: OnKeyUp called,touchEvent info: keyCode is %{private}d,"
1375          "keyAction is %{public}d, keyActionTime is %{public}" PRId64,
1376         touchEvent->GetKeyCode(), touchEvent->GetKeyAction(), touchEvent->GetActionTime());
1377     auto container = AceEngine::Get().GetContainer(instanceId_);
1378     CHECK_NULL_RETURN(container, false);
1379     auto aceView = static_cast<Platform::FlutterAceView*>(container->GetView());
1380     return Platform::FlutterAceView::DispatchKeyEvent(aceView, touchEvent);
1381 }
1382 
ProcessAxisEvent(const std::shared_ptr<OHOS::MMI::AxisEvent> & axisEvent)1383 bool UIContentImpl::ProcessAxisEvent(const std::shared_ptr<OHOS::MMI::AxisEvent>& axisEvent)
1384 {
1385     LOGI("UIContentImpl ProcessAxisEvent");
1386     return false;
1387 }
1388 
ProcessVsyncEvent(uint64_t timeStampNanos)1389 bool UIContentImpl::ProcessVsyncEvent(uint64_t timeStampNanos)
1390 {
1391     LOGI("UIContentImpl ProcessVsyncEvent");
1392     return false;
1393 }
1394 
UpdateConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration> & config)1395 void UIContentImpl::UpdateConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)
1396 {
1397     LOGI("UIContentImpl: UpdateConfiguration called");
1398     CHECK_NULL_VOID(config);
1399     Platform::AceContainer::OnConfigurationUpdated(instanceId_, (*config).GetName());
1400     auto container = Platform::AceContainer::GetContainer(instanceId_);
1401     CHECK_NULL_VOID(container);
1402     auto taskExecutor = container->GetTaskExecutor();
1403     CHECK_NULL_VOID(taskExecutor);
1404     taskExecutor->PostTask(
1405         [weakContainer = WeakPtr<Platform::AceContainer>(container), config]() {
1406             auto container = weakContainer.Upgrade();
1407             CHECK_NULL_VOID_NOLOG(container);
1408             auto colorMode = config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
1409             auto deviceAccess = config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE);
1410             auto languageTag = config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE);
1411             container->UpdateConfiguration(colorMode, deviceAccess, languageTag);
1412         },
1413         TaskExecutor::TaskType::UI);
1414     LOGI("UIContentImpl: UpdateConfiguration called End, name:%{public}s", config->GetName().c_str());
1415 }
1416 
UpdateViewportConfig(const ViewportConfig & config,OHOS::Rosen::WindowSizeChangeReason reason)1417 void UIContentImpl::UpdateViewportConfig(const ViewportConfig& config, OHOS::Rosen::WindowSizeChangeReason reason)
1418 {
1419     LOGI("UIContentImpl: UpdateViewportConfig %{public}s", config.ToString().c_str());
1420     SystemProperties::SetResolution(config.Density());
1421     SystemProperties::SetDeviceOrientation(config.Height() >= config.Width() ? 0 : 1);
1422     auto container = Platform::AceContainer::GetContainer(instanceId_);
1423     CHECK_NULL_VOID(container);
1424     auto taskExecutor = container->GetTaskExecutor();
1425     CHECK_NULL_VOID(taskExecutor);
1426     taskExecutor->PostTask(
1427         [config, container, reason]() {
1428             container->SetWindowPos(config.Left(), config.Top());
1429             auto pipelineContext = container->GetPipelineContext();
1430             if (pipelineContext) {
1431                 pipelineContext->SetDisplayWindowRectInfo(
1432                     Rect(Offset(config.Left(), config.Top()), Size(config.Width(), config.Height())));
1433             }
1434             auto aceView = static_cast<Platform::FlutterAceView*>(container->GetAceView());
1435             CHECK_NULL_VOID(aceView);
1436             flutter::ViewportMetrics metrics;
1437             metrics.physical_width = config.Width();
1438             metrics.physical_height = config.Height();
1439             metrics.device_pixel_ratio = config.Density();
1440             Platform::FlutterAceView::SetViewportMetrics(aceView, metrics);
1441             Platform::FlutterAceView::SurfaceChanged(aceView, config.Width(), config.Height(), config.Orientation(),
1442                 static_cast<WindowSizeChangeReason>(reason));
1443             Platform::FlutterAceView::SurfacePositionChanged(aceView, config.Left(), config.Top());
1444         },
1445         TaskExecutor::TaskType::PLATFORM);
1446 }
1447 
UpdateWindowMode(OHOS::Rosen::WindowMode mode)1448 void UIContentImpl::UpdateWindowMode(OHOS::Rosen::WindowMode mode)
1449 {
1450     LOGI("UIContentImpl: UpdateWindowMode, window mode is %{public}d", mode);
1451     auto container = Platform::AceContainer::GetContainer(instanceId_);
1452     CHECK_NULL_VOID(container);
1453     ContainerScope scope(instanceId_);
1454     auto taskExecutor = Container::CurrentTaskExecutor();
1455     CHECK_NULL_VOID(taskExecutor);
1456     taskExecutor->PostTask(
1457         [container, mode]() {
1458             auto pipelineContext = container->GetPipelineContext();
1459             CHECK_NULL_VOID(pipelineContext);
1460             pipelineContext->ShowContainerTitle(mode == OHOS::Rosen::WindowMode::WINDOW_MODE_FLOATING);
1461         },
1462         TaskExecutor::TaskType::UI);
1463 }
1464 
HideWindowTitleButton(bool hideSplit,bool hideMaximize,bool hideMinimize)1465 void UIContentImpl::HideWindowTitleButton(bool hideSplit, bool hideMaximize, bool hideMinimize)
1466 {
1467     LOGI("HideWindowTitleButton hideSplit: %{public}d, hideMaximize: %{public}d, hideMinimize: %{public}d", hideSplit,
1468         hideMaximize, hideMinimize);
1469     auto container = Platform::AceContainer::GetContainer(instanceId_);
1470     CHECK_NULL_VOID(container);
1471     ContainerScope scope(instanceId_);
1472     auto taskExecutor = Container::CurrentTaskExecutor();
1473     CHECK_NULL_VOID(taskExecutor);
1474     taskExecutor->PostTask(
1475         [container, hideSplit, hideMaximize, hideMinimize]() {
1476             auto pipelineContext = AceType::DynamicCast<PipelineContext>(container->GetPipelineContext());
1477             CHECK_NULL_VOID(pipelineContext);
1478             pipelineContext->SetContainerButtonHide(hideSplit, hideMaximize, hideMinimize);
1479         },
1480         TaskExecutor::TaskType::UI);
1481 }
1482 
DumpInfo(const std::vector<std::string> & params,std::vector<std::string> & info)1483 void UIContentImpl::DumpInfo(const std::vector<std::string>& params, std::vector<std::string>& info)
1484 {
1485     auto container = Platform::AceContainer::GetContainer(instanceId_);
1486     CHECK_NULL_VOID(container);
1487     auto pipelineContext = container->GetPipelineContext();
1488     CHECK_NULL_VOID(pipelineContext);
1489     auto taskExecutor = container->GetTaskExecutor();
1490     CHECK_NULL_VOID(taskExecutor);
1491     auto ret = taskExecutor->PostSyncTaskTimeout(
1492         [&]() {
1493             pipelineContext->DumpInfo(params, info);
1494         },
1495         TaskExecutor::TaskType::UI, 1500); // timeout 1.5s
1496     if (!ret) {
1497         LOGE("DumpInfo failed");
1498     }
1499 }
1500 
InitializeSubWindow(OHOS::Rosen::Window * window,bool isDialog)1501 void UIContentImpl::InitializeSubWindow(OHOS::Rosen::Window* window, bool isDialog)
1502 {
1503     window_ = window;
1504     LOGI("The window name is %{public}s", window->GetWindowName().c_str());
1505     CHECK_NULL_VOID(window_);
1506     RefPtr<Container> container;
1507     instanceId_ = gSubInstanceId.fetch_add(1, std::memory_order_relaxed);
1508 
1509     std::weak_ptr<OHOS::AppExecFwk::AbilityInfo> abilityInfo;
1510     std::weak_ptr<OHOS::AbilityRuntime::Context> runtimeContext;
1511     if (isDialog) {
1512         container = AceType::MakeRefPtr<Platform::DialogContainer>(instanceId_, FrontendType::DECLARATIVE_JS);
1513     } else {
1514         if (Container::IsCurrentUseNewPipeline()) {
1515             container = AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, FrontendType::DECLARATIVE_JS, true,
1516                 runtimeContext, abilityInfo, std::make_unique<ContentEventCallback>([] {
1517                     // Sub-window ,just return.
1518                     LOGI("Content event callback");
1519                 }),
1520                 false, true, true);
1521         } else {
1522             container = AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, FrontendType::DECLARATIVE_JS, true,
1523                 runtimeContext, abilityInfo, std::make_unique<ContentEventCallback>([] {
1524                     // Sub-window ,just return.
1525                     LOGI("Content event callback");
1526                 }),
1527                 false, true);
1528         }
1529     }
1530     SubwindowManager::GetInstance()->AddContainerId(window->GetWindowId(), instanceId_);
1531     AceEngine::Get().AddContainer(instanceId_, container);
1532     touchOutsideListener_ = new TouchOutsideListener(instanceId_);
1533     window_->RegisterTouchOutsideListener(touchOutsideListener_);
1534     dragWindowListener_ = new DragWindowListener(instanceId_);
1535     window_->RegisterDragListener(dragWindowListener_);
1536 }
1537 
SetNextFrameLayoutCallback(std::function<void ()> && callback)1538 void UIContentImpl::SetNextFrameLayoutCallback(std::function<void()>&& callback)
1539 {
1540     CHECK_NULL_VOID(callback);
1541     auto container = Platform::AceContainer::GetContainer(instanceId_);
1542     CHECK_NULL_VOID(container);
1543     auto pipelineContext = container->GetPipelineContext();
1544     CHECK_NULL_VOID(pipelineContext);
1545     pipelineContext->SetNextFrameLayoutCallback(std::move(callback));
1546 }
1547 
NotifyMemoryLevel(int32_t level)1548 void UIContentImpl::NotifyMemoryLevel(int32_t level)
1549 {
1550     LOGI("Receive Memory level notification, level: %{public}d", level);
1551     auto container = Platform::AceContainer::GetContainer(instanceId_);
1552     CHECK_NULL_VOID(container);
1553     auto pipelineContext = container->GetPipelineContext();
1554     CHECK_NULL_VOID(pipelineContext);
1555     ContainerScope scope(instanceId_);
1556     pipelineContext->NotifyMemoryLevel(level);
1557 }
1558 
SetAppWindowTitle(const std::string & title)1559 void UIContentImpl::SetAppWindowTitle(const std::string& title)
1560 {
1561     auto container = Platform::AceContainer::GetContainer(instanceId_);
1562     CHECK_NULL_VOID(container);
1563     auto pipelineContext = container->GetPipelineContext();
1564     CHECK_NULL_VOID(pipelineContext);
1565     LOGI("set app title");
1566     pipelineContext->SetAppTitle(title);
1567 }
1568 
SetAppWindowIcon(const std::shared_ptr<Media::PixelMap> & pixelMap)1569 void UIContentImpl::SetAppWindowIcon(const std::shared_ptr<Media::PixelMap>& pixelMap)
1570 {
1571     auto container = Platform::AceContainer::GetContainer(instanceId_);
1572     CHECK_NULL_VOID(container);
1573     auto pipelineContext = container->GetPipelineContext();
1574     CHECK_NULL_VOID(pipelineContext);
1575     LOGI("set app icon");
1576     pipelineContext->SetAppIcon(AceType::MakeRefPtr<PixelMapOhos>(pixelMap));
1577 }
1578 
UpdateFormData(const std::string & data)1579 void UIContentImpl::UpdateFormData(const std::string& data)
1580 {
1581     if (isFormRenderInit_) {
1582         auto container = Platform::AceContainer::GetContainer(instanceId_);
1583         CHECK_NULL_VOID(container);
1584         container->UpdateFormData(data);
1585     } else {
1586         formData_ = data;
1587     }
1588 }
1589 
UpdateFormSharedImage(const std::map<std::string,sptr<OHOS::AppExecFwk::FormAshmem>> & imageDataMap)1590 void UIContentImpl::UpdateFormSharedImage(const std::map<std::string, sptr<OHOS::AppExecFwk::FormAshmem>>& imageDataMap)
1591 {
1592     if (isFormRenderInit_) {
1593         auto container = Platform::AceContainer::GetContainer(instanceId_);
1594         CHECK_NULL_VOID(container);
1595         container->UpdateFormSharedImage(imageDataMap);
1596     } else {
1597         formImageDataMap_ = imageDataMap;
1598     }
1599 }
1600 
SetActionEventHandler(std::function<void (const std::string & action)> && actionCallback)1601 void UIContentImpl::SetActionEventHandler(
1602     std::function<void(const std::string& action)>&& actionCallback)
1603 {
1604     CHECK_NULL_VOID(actionCallback);
1605     auto container = Platform::AceContainer::GetContainer(instanceId_);
1606     CHECK_NULL_VOID(container);
1607     auto pipelineContext = container->GetPipelineContext();
1608     CHECK_NULL_VOID(pipelineContext);
1609     pipelineContext->SetActionEventHandler(std::move(actionCallback));
1610 }
1611 
SetErrorEventHandler(std::function<void (const std::string &,const std::string &)> && errorCallback)1612 void UIContentImpl::SetErrorEventHandler(
1613     std::function<void(const std::string&, const std::string&)>&& errorCallback)
1614 {
1615     CHECK_NULL_VOID(errorCallback);
1616     auto container = Platform::AceContainer::GetContainer(instanceId_);
1617     CHECK_NULL_VOID(container);
1618     auto front = container->GetFrontend();
1619     CHECK_NULL_VOID(front);
1620     return front->SetErrorEventHandler(std::move(errorCallback));
1621 }
1622 
OnFormSurfaceChange(float width,float height)1623 void UIContentImpl::OnFormSurfaceChange(float width, float height)
1624 {
1625     auto container = Platform::AceContainer::GetContainer(instanceId_);
1626     CHECK_NULL_VOID(container);
1627     auto pipelineContext = container->GetPipelineContext();
1628     CHECK_NULL_VOID(pipelineContext);
1629     ContainerScope scope(instanceId_);
1630     auto density = pipelineContext->GetDensity();
1631     pipelineContext->SetRootSize(density, width, height);
1632     pipelineContext->OnSurfaceChanged(width, height);
1633 }
1634 } // namespace OHOS::Ace
1635