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