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