1 /*
2  * Copyright (c) 2021-2024 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 "bundlemgr/bundle_mgr_proxy.h"
24 #include "configuration.h"
25 #include "if_system_ability_manager.h"
26 #include "ipc_skeleton.h"
27 #include "iservice_registry.h"
28 #include "js_runtime_utils.h"
29 #include "locale_config.h"
30 #include "native_reference.h"
31 #include "ohos/init_data.h"
32 #include "service_extension_context.h"
33 #include "system_ability_definition.h"
34 #include "wm_common.h"
35 
36 #include "base/log/log_wrapper.h"
37 #include "base/memory/referenced.h"
38 #include "base/utils/utils.h"
39 #include "core/components/common/layout/constants.h"
40 #include "core/components_ng/base/frame_node.h"
41 #include "core/components_ng/render/animation_utils.h"
42 
43 #if !defined(ACE_UNITTEST)
44 #include "core/components_ng/base/transparent_node_detector.h"
45 #endif
46 
47 #include "core/components_ng/property/safe_area_insets.h"
48 
49 #ifdef ENABLE_ROSEN_BACKEND
50 #include "render_service_client/core/transaction/rs_transaction.h"
51 #include "render_service_client/core/ui/rs_ui_director.h"
52 #endif
53 
54 #include "interfaces/inner_api/ui_session/ui_session_manager.h"
55 
56 #include "adapter/ohos/entrance/ace_application_info.h"
57 #include "adapter/ohos/entrance/ace_container.h"
58 #include "adapter/ohos/entrance/ace_new_pipe_judgement.h"
59 #include "adapter/ohos/entrance/ace_view_ohos.h"
60 #include "adapter/ohos/entrance/capability_registry.h"
61 #include "adapter/ohos/entrance/cj_utils/cj_utils.h"
62 #include "adapter/ohos/entrance/dialog_container.h"
63 #include "adapter/ohos/entrance/dynamic_component/uv_task_wrapper_impl.h"
64 #include "adapter/ohos/entrance/file_asset_provider_impl.h"
65 #include "adapter/ohos/entrance/form_utils_impl.h"
66 #include "adapter/ohos/entrance/aps_monitor_impl.h"
67 #include "adapter/ohos/entrance/hap_asset_provider_impl.h"
68 #include "adapter/ohos/entrance/plugin_utils_impl.h"
69 #include "adapter/ohos/entrance/ui_event_impl.h"
70 #include "adapter/ohos/entrance/utils.h"
71 #include "adapter/ohos/osal/navigation_route_ohos.h"
72 #include "adapter/ohos/osal/page_url_checker_ohos.h"
73 #include "adapter/ohos/osal/pixel_map_ohos.h"
74 #include "adapter/ohos/osal/thp_extra_manager_impl.h"
75 #include "adapter/ohos/osal/view_data_wrap_ohos.h"
76 #include "base/geometry/rect.h"
77 #include "base/i18n/localization.h"
78 #include "base/log/ace_checker.h"
79 #include "base/log/ace_performance_check.h"
80 #include "base/log/ace_trace.h"
81 #include "base/log/log.h"
82 #include "base/perfmonitor/perf_monitor.h"
83 #include "base/subwindow/subwindow_manager.h"
84 #include "base/utils/system_properties.h"
85 #include "bridge/card_frontend/form_frontend_declarative.h"
86 #include "core/common/ace_engine.h"
87 #include "core/common/asset_manager_impl.h"
88 #include "core/common/container.h"
89 #include "core/common/container_scope.h"
90 #include "core/common/modal_ui_extension.h"
91 #include "core/common/recorder/event_recorder.h"
92 #include "core/common/resource/resource_manager.h"
93 #include "core/common/xcollie/xcollieInterface.h"
94 #include "core/components/theme/shadow_theme.h"
95 #include "core/components_ng/base/inspector.h"
96 #include "core/components_ng/base/view_abstract.h"
97 #include "core/components_ng/pattern/text_field/text_field_manager.h"
98 #include "core/image/image_file_cache.h"
99 #include "core/pipeline_ng/pipeline_context.h"
100 #ifdef FORM_SUPPORTED
101 #include "core/common/form_manager.h"
102 #endif
103 #include "core/common/layout_inspector.h"
104 #ifdef PLUGIN_COMPONENT_SUPPORTED
105 #include "core/common/plugin_manager.h"
106 #endif
107 #ifdef NG_BUILD
108 #include "frameworks/bridge/declarative_frontend/ng/declarative_frontend_ng.h"
109 #endif
110 
111 #include "core/components_ng/render/adapter/rosen_render_context.h"
112 #include "screen_session_manager_client.h"
113 
114 namespace OHOS::Ace {
115 namespace {
116 
117 const std::string ABS_BUNDLE_CODE_PATH = "/data/app/el1/bundle/public/";
118 const std::string LOCAL_BUNDLE_CODE_PATH = "/data/storage/el1/bundle/";
119 const std::string FILE_SEPARATOR = "/";
120 const std::string START_PARAMS_KEY = "__startParams";
121 const std::string ACTION_VIEWDATA = "ohos.want.action.viewData";
122 constexpr char IS_PREFERRED_LANGUAGE[] = "1";
123 
124 #define UICONTENT_IMPL_HELPER(name) _##name = std::make_shared<UIContentImplHelper>(this)
125 #define UICONTENT_IMPL_PTR(name) _##name->uiContent_
126 #define UICONTENT_IMPL_HELPER_GUARD(name, ifInvalid...) \
127     std::lock_guard lg(*_##name->mutex_);               \
128     if (!*_##name->isValid_) {                          \
129         ifInvalid;                                      \
130     }
131 
132 struct UIContentImplHelper {
UIContentImplHelperOHOS::Ace::__anon1571::UIContentImplHelper133     explicit UIContentImplHelper(UIContentImpl* uiContent) : uiContent_(uiContent)
134     {
135         uiContent_->AddDestructCallback(this, [mutex = mutex_, isValid = isValid_] {
136             std::lock_guard lg(*mutex);
137             *isValid = false;
138         });
139     }
~UIContentImplHelperOHOS::Ace::__anon1571::UIContentImplHelper140     ~UIContentImplHelper()
141     {
142         std::lock_guard lg(*mutex_);
143         if (*isValid_) {
144             uiContent_->RemoveDestructCallback(this);
145         }
146     }
147     UIContentImpl* uiContent_;
148     std::shared_ptr<std::mutex> mutex_ = std::make_shared<std::mutex>();
149     std::shared_ptr<bool> isValid_ = std::make_shared<bool>(true);
150     UIContentImplHelper(const UIContentImplHelper& rhs) = delete;
151     UIContentImplHelper& operator=(const UIContentImplHelper& rhs) = delete;
152 };
153 
ConvertToRSRect(NG::RectF& rect)154 Rosen::Rect ConvertToRSRect(NG::RectF& rect)
155 {
156     Rosen::Rect rsRect;
157     rsRect.posX_ = floor(rect.GetX());
158     rsRect.posY_ = floor(rect.GetY());
159     rsRect.width_ = ceil(rect.Width());
160     rsRect.height_ = ceil(rect.Height());
161     return rsRect;
162 }
163 
IsNeedAvoidWindowMode(OHOS::Rosen::Window* rsWindow)164 bool IsNeedAvoidWindowMode(OHOS::Rosen::Window* rsWindow)
165 {
166     if (!SystemProperties::GetNeedAvoidWindow()) {
167         return false;
168     }
169 
170     auto mode = rsWindow->GetMode();
171     return mode == Rosen::WindowMode::WINDOW_MODE_FLOATING || mode == Rosen::WindowMode::WINDOW_MODE_SPLIT_PRIMARY ||
172             mode == Rosen::WindowMode::WINDOW_MODE_SPLIT_SECONDARY;
173 }
174 
AddResConfigInfo( const std::shared_ptr<OHOS::AbilityRuntime::Context>& context, ResourceConfiguration& aceResCfg)175 void AddResConfigInfo(
176     const std::shared_ptr<OHOS::AbilityRuntime::Context>& context, ResourceConfiguration& aceResCfg)
177 {
178     if (!context || !context->GetResourceManager()) {
179         return;
180     }
181     auto resourceManager = context->GetResourceManager();
182     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
183     resourceManager->GetResConfig(*resConfig);
184     aceResCfg.SetMcc(resConfig->GetMcc());
185     aceResCfg.SetMnc(resConfig->GetMnc());
186     aceResCfg.SetAppHasDarkRes(resConfig->GetAppDarkRes());
187     auto preferredLocaleInfo = resConfig->GetPreferredLocaleInfo();
188     if (preferredLocaleInfo != nullptr) {
189         std::string preferredLanguage = preferredLocaleInfo->getLanguage();
190         std::string script = preferredLocaleInfo->getScript();
191         std::string country = preferredLocaleInfo->getCountry();
192         if (!script.empty()) {
193             preferredLanguage += "-" + script;
194         }
195         if (!country.empty()) {
196             preferredLanguage += "-" + country;
197         }
198         aceResCfg.SetPreferredLanguage(preferredLanguage);
199     }
200 }
201 
AddSetAppColorModeToResConfig( const std::shared_ptr<OHOS::AbilityRuntime::Context>& context, ResourceConfiguration& aceResCfg)202 void AddSetAppColorModeToResConfig(
203     const std::shared_ptr<OHOS::AbilityRuntime::Context>& context, ResourceConfiguration& aceResCfg)
204 {
205     CHECK_NULL_VOID(context);
206     auto config = context->GetConfiguration();
207     CHECK_NULL_VOID(config);
208     auto colorModeIsSetByApp = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::COLORMODE_IS_SET_BY_APP);
209     if (!colorModeIsSetByApp.empty()) {
210         aceResCfg.SetColorModeIsSetByApp(true);
211     }
212 }
213 } // namespace
214 
215 const std::string SUBWINDOW_PREFIX = "ARK_APP_SUBWINDOW_";
216 const std::string SUBWINDOW_TOAST_DIALOG_PREFIX = "ARK_APP_SUBWINDOW_TOAST_DIALOG_";
217 const std::string SUBWINDOW_TOAST_PREFIX = "ARK_APP_SUBWINDOW_TOPMOST_TOAST";
218 const int32_t REQUEST_CODE = -1;
219 constexpr uint32_t TIMEOUT_LIMIT = 5;
220 constexpr int32_t COUNT_LIMIT = 3;
221 
222 using ContentFinishCallback = std::function<void()>;
223 using ContentStartAbilityCallback = std::function<void(const std::string& address)>;
224 class ContentEventCallback final : public Platform::PlatformEventCallback {
225 public:
ContentEventCallback(ContentFinishCallback onFinish)226     explicit ContentEventCallback(ContentFinishCallback onFinish) : onFinish_(onFinish) {}
ContentEventCallback(ContentFinishCallback onFinish, ContentStartAbilityCallback onStartAbility)227     ContentEventCallback(ContentFinishCallback onFinish, ContentStartAbilityCallback onStartAbility)
228         : onFinish_(onFinish), onStartAbility_(onStartAbility)
229     {}
230     ~ContentEventCallback() override = default;
231 
232     void OnFinish() const override
233     {
234         CHECK_NULL_VOID(onFinish_);
235         onFinish_();
236     }
237 
238     void OnStartAbility(const std::string& address) override
239     {
240         CHECK_NULL_VOID(onStartAbility_);
241         onStartAbility_(address);
242     }
243 
244     void OnStatusBarBgColorChanged(uint32_t color) override
245     {
246         LOGI("StatusBarBgColorChanged: %{public}u", color);
247     }
248 
249 private:
250     ContentFinishCallback onFinish_;
251     ContentStartAbilityCallback onStartAbility_;
252 };
253 
OHOS_ACE_CreateUIContent(void* context, void* runtime)254 extern "C" ACE_FORCE_EXPORT void* OHOS_ACE_CreateUIContent(void* context, void* runtime)
255 {
256     LOGI("CreateUIContent.");
257     Recorder::Init();
258     return new UIContentImpl(reinterpret_cast<OHOS::AbilityRuntime::Context*>(context), runtime);
259 }
260 
OHOS_ACE_CreateFormContent(void* context, void* runtime, bool isCard)261 extern "C" ACE_FORCE_EXPORT void* OHOS_ACE_CreateFormContent(void* context, void* runtime, bool isCard)
262 {
263     TAG_LOGI(AceLogTag::ACE_FORM, "CreateFormUIContent.");
264     Recorder::Init();
265     return new UIContentImpl(reinterpret_cast<OHOS::AbilityRuntime::Context*>(context), runtime, isCard);
266 }
267 
OHOS_ACE_CreateSubWindowUIContent(void* ability)268 extern "C" ACE_FORCE_EXPORT void* OHOS_ACE_CreateSubWindowUIContent(void* ability)
269 {
270     TAG_LOGI(AceLogTag::ACE_SUB_WINDOW, "Create SubWindowUIContent.");
271     Recorder::Init();
272     return new UIContentImpl(reinterpret_cast<OHOS::AppExecFwk::Ability*>(ability));
273 }
274 
OHOS_ACE_GetUIContent(int32_t instanceId)275 extern "C" ACE_FORCE_EXPORT void* OHOS_ACE_GetUIContent(int32_t instanceId)
276 {
277     LOGI("GetUIContent: %{public}d", instanceId);
278     auto uiWindow = Platform::AceContainer::GetUIWindow(instanceId);
279     CHECK_NULL_RETURN(uiWindow, nullptr);
280     return uiWindow->GetUIContent();
281 }
282 
OHOS_ACE_GetCurrentUIStackInfo()283 extern "C" ACE_FORCE_EXPORT char* OHOS_ACE_GetCurrentUIStackInfo()
284 {
285     auto container = Container::Current();
286     CHECK_NULL_RETURN(container, nullptr);
287     auto pipeline = container->GetPipelineContext();
288     CHECK_NULL_RETURN(pipeline, nullptr);
289     static auto tmp = pipeline->GetCurrentExtraInfo();
290     std::replace(tmp.begin(), tmp.end(), '\\', '/');
291     return tmp.data();
292 }
293 
AddAlarmLogFunc()294 void AddAlarmLogFunc()
295 {
296     std::function<void(uint64_t, int, int)> logFunc = [](uint64_t nodeId, int count, int num) {
297         auto rsNode = Rosen::RSNodeMap::Instance().GetNode<Rosen::RSNode>(nodeId);
298         if (rsNode == nullptr) {
299             LOGI("rsNodeId:%{public}" PRId64 "not found, sendCommands:%{public}d, totalNumber:%{public}d",
300                 nodeId, count, num);
301             return;
302         }
303         auto frameNodeId = rsNode->GetFrameNodeId();
304         auto frameNodeTag = rsNode->GetFrameNodeTag();
305         auto frameNode = NG::FrameNode::GetFrameNode(frameNodeTag, frameNodeId);
306         if (frameNode == nullptr) {
307             LOGI("frameNodeId:%{public}d not found, rsNodeId:%{public}" PRId64 " sendCommands:%{public}d, "
308                  "totalRsNodeNumber:%{public}d.",
309                 frameNodeId, nodeId, count, num);
310             return;
311         }
312         LOGI("frameNodeId:%{public}d found, rsNodeId:%{public}" PRId64 " sendCommands:%{public}d, "
313              "FrameNodeTag:%{public}s, totalRsNodeNumber:%{public}d",
314             frameNodeId, nodeId, count, frameNodeTag.c_str(), num);
315     };
316 
317     OHOS::Rosen::RSTransactionData::AddAlarmLog(logFunc);
318 }
319 
ParseAvoidAreasUpdate(const RefPtr<NG::PipelineContext>& context, const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas, const ViewportConfig& config)320 bool ParseAvoidAreasUpdate(const RefPtr<NG::PipelineContext>& context,
321     const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas,
322     const ViewportConfig& config)
323 {
324     CHECK_NULL_RETURN(context, false);
325     auto safeAreaManager = context->GetSafeAreaManager();
326     CHECK_NULL_RETURN(safeAreaManager, false);
327     bool safeAreaUpdated = false;
328     for (auto& avoidArea : avoidAreas) {
329         if (avoidArea.first == OHOS::Rosen::AvoidAreaType::TYPE_SYSTEM) {
330             safeAreaUpdated |= safeAreaManager->UpdateSystemSafeArea(ConvertAvoidArea(avoidArea.second));
331         } else if (avoidArea.first == OHOS::Rosen::AvoidAreaType::TYPE_NAVIGATION_INDICATOR) {
332             safeAreaUpdated |= safeAreaManager->UpdateNavArea(ConvertAvoidArea(avoidArea.second));
333         } else if (avoidArea.first == OHOS::Rosen::AvoidAreaType::TYPE_CUTOUT && context->GetUseCutout()) {
334             safeAreaUpdated |= safeAreaManager->UpdateCutoutSafeArea(ConvertAvoidArea(avoidArea.second),
335                 NG::OptionalSize<uint32_t>(config.Width(), config.Height()));
336         }
337     }
338     if (safeAreaUpdated) {
339         context->SyncSafeArea(SafeAreaSyncType::SYNC_TYPE_AVOID_AREA);
340         return true;
341     }
342     return false;
343 }
344 
AvoidAreasUpdateOnUIExtension(const RefPtr<NG::PipelineContext>& context, const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas)345 void AvoidAreasUpdateOnUIExtension(const RefPtr<NG::PipelineContext>& context,
346     const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas)
347 {
348     if (avoidAreas.empty()) {
349         return;
350     }
351     CHECK_NULL_VOID(context);
352     // for ui extension component
353     for (auto& avoidArea : avoidAreas) {
354         context->UpdateOriginAvoidArea(avoidArea.second, static_cast<uint32_t>(avoidArea.first));
355     }
356 }
357 
UpdateSafeArea(const RefPtr<PipelineBase>& pipelineContext, const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas, const ViewportConfig& config, const RefPtr<Platform::AceContainer>& container)358 void UpdateSafeArea(const RefPtr<PipelineBase>& pipelineContext,
359     const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas,
360     const ViewportConfig& config,
361     const RefPtr<Platform::AceContainer>& container)
362 {
363     CHECK_NULL_VOID(container);
364     CHECK_NULL_VOID(pipelineContext);
365     auto context = AceType::DynamicCast<NG::PipelineContext>(pipelineContext);
366     CHECK_NULL_VOID(context);
367     auto safeAreaManager = context->GetSafeAreaManager();
368     CHECK_NULL_VOID(safeAreaManager);
369     uint32_t keyboardHeight = safeAreaManager->GetKeyboardInset().Length();
370     safeAreaManager->UpdateKeyboardSafeArea(keyboardHeight, config.Height());
371     if (avoidAreas.find(OHOS::Rosen::AvoidAreaType::TYPE_CUTOUT) == avoidAreas.end()) {
372         safeAreaManager->UpdateCutoutSafeArea(container->GetViewSafeAreaByType(Rosen::AvoidAreaType::TYPE_CUTOUT),
373             NG::OptionalSize<uint32_t>(config.Width(), config.Height()));
374     }
375     ParseAvoidAreasUpdate(context, avoidAreas, config);
376     AvoidAreasUpdateOnUIExtension(context, avoidAreas);
377 }
378 
379 class OccupiedAreaChangeListener : public OHOS::Rosen::IOccupiedAreaChangeListener {
380 public:
OccupiedAreaChangeListener(int32_t instanceId)381     explicit OccupiedAreaChangeListener(int32_t instanceId) : instanceId_(instanceId) {}
382     ~OccupiedAreaChangeListener() = default;
383 
OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info, const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction)384     void OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info,
385         const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction)
386     {
387         auto rect = info->rect_;
388         double positionY = info->textFieldPositionY_;
389         double height = info->textFieldHeight_;
390         Rect keyboardRect = Rect(rect.posX_, rect.posY_, rect.width_, rect.height_);
391         LOGI("OccupiedAreaChange rect:%{public}s type: %{public}d, positionY:%{public}f, height:%{public}f, "
392              "instanceId_ %{public}d",
393             keyboardRect.ToString().c_str(), info->type_, positionY, height, instanceId_);
394         CHECK_NULL_VOID(info->type_ == OHOS::Rosen::OccupiedAreaType::TYPE_INPUT);
395         auto container = Platform::AceContainer::GetContainer(instanceId_);
396         CHECK_NULL_VOID(container);
397         auto taskExecutor = container->GetTaskExecutor();
398         CHECK_NULL_VOID(taskExecutor);
399         auto context = container->GetPipelineContext();
400         CHECK_NULL_VOID(context);
401         auto pipeline = AceType::DynamicCast<NG::PipelineContext>(context);
402         if (pipeline) {
403             ContainerScope scope(instanceId_);
404             auto uiExtMgr = pipeline->GetUIExtensionManager();
405             if (uiExtMgr) {
406                 SetUIExtensionImeShow(keyboardRect);
407             }
408             if (uiExtMgr && uiExtMgr->NotifyOccupiedAreaChangeInfo(info)) {
409                 TAG_LOGI(AceLogTag::ACE_KEYBOARD, "uiExtension consumed");
410                 taskExecutor->PostTask([id = instanceId_] {
411                         ContainerScope scope(id);
412                         auto container = Platform::AceContainer::GetContainer(id);
413                         CHECK_NULL_VOID(container);
414                         auto context = container->GetPipelineContext();
415                         CHECK_NULL_VOID(context);
416                         context->OnVirtualKeyboardAreaChange(Rect());
417                     }, TaskExecutor::TaskType::UI, "ArkUIVirtualKeyboardAreaChange");
418                 return;
419             }
420         }
421         auto curWindow = context->GetCurrentWindowRect();
422         positionY -= curWindow.Top();
423         ContainerScope scope(instanceId_);
424         if (LaterAvoid(keyboardRect, positionY, height)) {
425             return;
426         }
427         taskExecutor->PostSyncTask([context, keyboardRect, rsTransaction, positionY, height] {
428                 CHECK_NULL_VOID(context);
429                 context->OnVirtualKeyboardAreaChange(keyboardRect, positionY, height, rsTransaction);
430             }, TaskExecutor::TaskType::UI, "ArkUIVirtualKeyboardAreaChange");
431     }
432 
433 private:
LaterAvoid(const Rect& keyboardRect, double positionY, double height)434     bool LaterAvoid(const Rect& keyboardRect, double positionY, double height)
435     {
436         auto container = Platform::AceContainer::GetContainer(instanceId_);
437         CHECK_NULL_RETURN(container, false);
438         auto taskExecutor = container->GetTaskExecutor();
439         CHECK_NULL_RETURN(taskExecutor, false);
440         auto context = container->GetPipelineContext();
441         CHECK_NULL_RETURN(context, false);
442         auto pipeline = AceType::DynamicCast<NG::PipelineContext>(context);
443         CHECK_NULL_RETURN(pipeline, false);
444         bool isRotate = false;
445         auto displayInfo = container->GetDisplayInfo();
446         uint32_t lastKeyboardHeight = pipeline->GetSafeAreaManager() ?
447             pipeline->GetSafeAreaManager()->GetKeyboardInset().Length() : 0;
448         if (displayInfo) {
449             auto dmRotation = static_cast<int32_t>(displayInfo->GetRotation());
450             isRotate = lastRotation != -1 && lastRotation != dmRotation;
451             lastRotation = dmRotation;
452         } else {
453             lastRotation = -1;
454         }
455         auto textFieldManager = AceType::DynamicCast<NG::TextFieldManagerNG>(pipeline->GetTextFieldManager());
456         CHECK_NULL_RETURN(textFieldManager, false);
457         if (textFieldManager->GetLaterAvoid()) {
458             auto laterRect = textFieldManager->GetLaterAvoidKeyboardRect();
459             if (NearEqual(laterRect.Height(), keyboardRect.Height())) {
460                 TAG_LOGI(AceLogTag::ACE_KEYBOARD, "will trigger avoid later, ignore this notify");
461                 return true;
462             }
463         }
464         // do not avoid immediately when device is in rotation, trigger it after context trigger root rect update
465         if (isRotate && !NearZero(lastKeyboardHeight) && !NearZero(keyboardRect.Height())) {
466             TAG_LOGI(AceLogTag::ACE_KEYBOARD, "rotation change to %{public}d,"
467                 "later avoid %{public}s %{public}f %{public}f",
468                 lastRotation, keyboardRect.ToString().c_str(), positionY, height);
469             textFieldManager->SetLaterAvoidArgs(keyboardRect, positionY, height);
470             return true;
471         }
472         return false;
473     }
474 
SetUIExtensionImeShow(const Rect& keyboardRect)475     void SetUIExtensionImeShow(const Rect& keyboardRect)
476     {
477         auto container = Platform::AceContainer::GetContainer(instanceId_);
478         CHECK_NULL_VOID(container);
479         auto taskExecutor = container->GetTaskExecutor();
480         if (GreatNotEqual(keyboardRect.Height(), 0.0f)) {
481             taskExecutor->PostTask(
482                 [id = instanceId_] {
483                     ContainerScope scope(id);
484                     auto pipeline = NG::PipelineContext::GetCurrentContext();
485                     CHECK_NULL_VOID(pipeline);
486                     pipeline->SetUIExtensionImeShow(true);
487                 }, TaskExecutor::TaskType::UI, "ArkUISetUIExtensionImeShow");
488         } else {
489             taskExecutor->PostTask(
490                 [id = instanceId_] {
491                     ContainerScope scope(id);
492                     auto pipeline = NG::PipelineContext::GetCurrentContext();
493                     CHECK_NULL_VOID(pipeline);
494                     pipeline->SetUIExtensionImeShow(false);
495                 }, TaskExecutor::TaskType::UI, "ArkUISetUIExtensionImeHide");
496         }
497     }
498     int32_t instanceId_ = -1;
499     int32_t lastRotation = -1;
500 };
501 
502 class AvoidAreaChangedListener : public OHOS::Rosen::IAvoidAreaChangedListener {
503 public:
AvoidAreaChangedListener(int32_t instanceId)504     explicit AvoidAreaChangedListener(int32_t instanceId) : instanceId_(instanceId) {}
505     ~AvoidAreaChangedListener() = default;
506 
507     void OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea avoidArea, OHOS::Rosen::AvoidAreaType type) override
508     {
509         ACE_SCOPED_TRACE("OnAvoidAreaChanged: incoming avoidArea: %s, instanceId %d, type %d",
510             avoidArea.ToString().c_str(), instanceId_, type);
511         TAG_LOGI(ACE_LAYOUT, "Avoid area changed, type:%{public}d, value:%{public}s; instanceId %{public}d", type,
512             avoidArea.ToString().c_str(), instanceId_);
513         auto container = Platform::AceContainer::GetContainer(instanceId_);
514         CHECK_NULL_VOID(container);
515         auto pipeline = container->GetPipelineContext();
516         CHECK_NULL_VOID(pipeline);
517         auto taskExecutor = container->GetTaskExecutor();
518         CHECK_NULL_VOID(taskExecutor);
519         if (type == Rosen::AvoidAreaType::TYPE_SYSTEM) {
520             systemSafeArea_ = ConvertAvoidArea(avoidArea);
521         } else if (type == Rosen::AvoidAreaType::TYPE_NAVIGATION_INDICATOR) {
522             navigationBar_ = ConvertAvoidArea(avoidArea);
523         } else if (type == Rosen::AvoidAreaType::TYPE_CUTOUT) {
524             cutoutSafeArea_ = ConvertAvoidArea(avoidArea);
525         }
526         auto safeArea = systemSafeArea_;
527         auto navSafeArea = navigationBar_;
528         auto cutoutSafeArea = cutoutSafeArea_;
529         ContainerScope scope(instanceId_);
530         taskExecutor->PostTask(
531             [pipeline, safeArea, navSafeArea, cutoutSafeArea, type, avoidArea] {
532                 if (type == Rosen::AvoidAreaType::TYPE_SYSTEM) {
533                     pipeline->UpdateSystemSafeArea(safeArea);
534                 } else if (type == Rosen::AvoidAreaType::TYPE_NAVIGATION_INDICATOR) {
535                     pipeline->UpdateNavSafeArea(navSafeArea);
536                 } else if (type == Rosen::AvoidAreaType::TYPE_CUTOUT && pipeline->GetUseCutout()) {
537                     pipeline->UpdateCutoutSafeArea(cutoutSafeArea);
538                 }
539                 // for ui extension component
540                 pipeline->UpdateOriginAvoidArea(avoidArea, static_cast<uint32_t>(type));
541             },
542             TaskExecutor::TaskType::UI, "ArkUIUpdateOriginAvoidArea");
543     }
544 
545 private:
546     NG::SafeAreaInsets systemSafeArea_;
547     NG::SafeAreaInsets navigationBar_;
548     NG::SafeAreaInsets cutoutSafeArea_;
549     int32_t instanceId_ = -1;
550 };
551 
552 class PretendChangedListener : public OHOS::Rosen::IAvoidAreaChangedListener {
553 public:
PretendChangedListener(int32_t instanceId)554     explicit PretendChangedListener(int32_t instanceId) {}
555     ~PretendChangedListener() = default;
556 
557     void OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea avoidArea, OHOS::Rosen::AvoidAreaType type) override {}
558 };
559 
560 class AvailableAreaChangedListener : public OHOS::Rosen::DisplayManager::IAvailableAreaListener {
561 public:
AvailableAreaChangedListener(int32_t instanceId)562     explicit AvailableAreaChangedListener(int32_t instanceId) : instanceId_(instanceId) {}
563     ~AvailableAreaChangedListener() = default;
564 
565     void OnAvailableAreaChanged(const Rosen::DMRect availableArea) override
566     {
567         auto container = Platform::AceContainer::GetContainer(instanceId_);
568         CHECK_NULL_VOID(container);
569         auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
570         CHECK_NULL_VOID(pipeline);
571         auto taskExecutor = container->GetTaskExecutor();
572         CHECK_NULL_VOID(taskExecutor);
573         auto displayAvailableRect = ConvertDMRect2Rect(availableArea);
574         ContainerScope scope(instanceId_);
575         taskExecutor->PostTask(
576             [pipeline, displayAvailableRect] {
577                 pipeline->UpdateDisplayAvailableRect(displayAvailableRect);
578                 TAG_LOGI(AceLogTag::ACE_WINDOW, "UpdateDisplayAvailableRect : %{public}s",
579                     displayAvailableRect.ToString().c_str());
580             },
581             TaskExecutor::TaskType::UI, "ArkUIUpdateDisplayAvailableRect");
582     }
583 
584 private:
585     int32_t instanceId_ = -1;
586 };
587 
588 class DragWindowListener : public OHOS::Rosen::IWindowDragListener {
589 public:
DragWindowListener(int32_t instanceId)590     explicit DragWindowListener(int32_t instanceId) : instanceId_(instanceId) {}
591     ~DragWindowListener() = default;
OnDrag(int32_t x, int32_t y, OHOS::Rosen::DragEvent event)592     void OnDrag(int32_t x, int32_t y, OHOS::Rosen::DragEvent event)
593     {
594         auto container = Platform::AceContainer::GetContainer(instanceId_);
595         CHECK_NULL_VOID(container);
596         int32_t instanceId = instanceId_;
597         if (container->IsSubContainer()) {
598             instanceId = container->GetParentId();
599         }
600         auto aceView =
601             AceType::DynamicCast<Platform::AceViewOhos>(Platform::AceContainer::GetContainer(instanceId)->GetAceView());
602         CHECK_NULL_VOID(aceView);
603         DragEventAction action;
604         switch (event) {
605             case OHOS::Rosen::DragEvent::DRAG_EVENT_END:
606                 action = DragEventAction::DRAG_EVENT_END;
607                 break;
608             case OHOS::Rosen::DragEvent::DRAG_EVENT_OUT:
609                 action = DragEventAction::DRAG_EVENT_OUT;
610                 break;
611             case OHOS::Rosen::DragEvent::DRAG_EVENT_MOVE:
612                 action = DragEventAction::DRAG_EVENT_MOVE;
613                 break;
614             case OHOS::Rosen::DragEvent::DRAG_EVENT_IN:
615             default:
616                 action = DragEventAction::DRAG_EVENT_START;
617                 break;
618         }
619         CHECK_NULL_VOID(static_cast<int>(action));
620     }
621 
622 private:
623     int32_t instanceId_ = -1;
624 };
625 
626 class FoldScreenListener : public OHOS::Rosen::DisplayManager::IFoldStatusListener {
627 public:
FoldScreenListener(int32_t instanceId)628     explicit FoldScreenListener(int32_t instanceId) : instanceId_(instanceId) {}
629     ~FoldScreenListener() = default;
630     void OnFoldStatusChanged(OHOS::Rosen::FoldStatus foldStatus) override
631     {
632         auto container = Platform::AceContainer::GetContainer(instanceId_);
633         CHECK_NULL_VOID(container);
634         auto taskExecutor = container->GetTaskExecutor();
635         CHECK_NULL_VOID(taskExecutor);
636         ContainerScope scope(instanceId_);
637         taskExecutor->PostTask(
638             [container, foldStatus] {
639                 auto context = container->GetPipelineContext();
640                 CHECK_NULL_VOID(context);
641                 auto aceFoldStatus = static_cast<FoldStatus>(static_cast<uint32_t>(foldStatus));
642                 context->OnFoldStatusChanged(aceFoldStatus);
643             },
644             TaskExecutor::TaskType::UI, "ArkUIFoldStatusChanged");
645     }
646 
647 private:
648     int32_t instanceId_ = -1;
649 };
650 
651 class FoldDisplayModeListener : public OHOS::Rosen::DisplayManager::IDisplayModeListener {
652 public:
FoldDisplayModeListener(int32_t instanceId, bool isDialog = false)653     explicit FoldDisplayModeListener(int32_t instanceId, bool isDialog = false)
654         : instanceId_(instanceId), isDialog_(isDialog)
655     {}
656     ~FoldDisplayModeListener() = default;
657     void OnDisplayModeChanged(OHOS::Rosen::FoldDisplayMode displayMode) override
658     {
659         if (!isDialog_) {
660             auto container = Platform::AceContainer::GetContainer(instanceId_);
661             CHECK_NULL_VOID(container);
662             auto taskExecutor = container->GetTaskExecutor();
663             CHECK_NULL_VOID(taskExecutor);
664             ContainerScope scope(instanceId_);
665             taskExecutor->PostTask(
666                 [container, displayMode] {
667                     auto context = container->GetPipelineContext();
668                     CHECK_NULL_VOID(context);
669                     auto aceDisplayMode = static_cast<FoldDisplayMode>(static_cast<uint32_t>(displayMode));
670                     context->OnFoldDisplayModeChanged(aceDisplayMode);
671                 },
672                 TaskExecutor::TaskType::UI, "ArkUIFoldDisplayModeChanged");
673             return;
674         }
675         auto container = Platform::DialogContainer::GetContainer(instanceId_);
676         CHECK_NULL_VOID(container);
677         auto taskExecutor = container->GetTaskExecutor();
678         CHECK_NULL_VOID(taskExecutor);
679         ContainerScope scope(instanceId_);
680         taskExecutor->PostTask(
681             [container, displayMode] {
682                 auto context = container->GetPipelineContext();
683                 CHECK_NULL_VOID(context);
684                 auto aceDisplayMode = static_cast<FoldDisplayMode>(static_cast<uint32_t>(displayMode));
685                 context->OnFoldDisplayModeChanged(aceDisplayMode);
686             },
687             TaskExecutor::TaskType::UI, "ArkUIDialogFoldDisplayModeChanged");
688     }
689 
690 private:
691     int32_t instanceId_ = -1;
692     bool isDialog_ = false;
693 };
694 
695 class TouchOutsideListener : public OHOS::Rosen::ITouchOutsideListener {
696 public:
TouchOutsideListener(int32_t instanceId)697     explicit TouchOutsideListener(int32_t instanceId) : instanceId_(instanceId) {}
698     ~TouchOutsideListener() = default;
699 
OnTouchOutside() const700     void OnTouchOutside() const
701     {
702         TAG_LOGI(AceLogTag::ACE_MENU, "window is touching outside. instance id is %{public}d", instanceId_);
703         auto container = Platform::AceContainer::GetContainer(instanceId_);
704         CHECK_NULL_VOID(container);
705         auto taskExecutor = container->GetTaskExecutor();
706         CHECK_NULL_VOID(taskExecutor);
707         ContainerScope scope(instanceId_);
708         taskExecutor->PostTask(
709             [instanceId = instanceId_, targetId = targetId_] {
710                 SubwindowManager::GetInstance()->ClearMenu();
711                 SubwindowManager::GetInstance()->ClearMenuNG(instanceId, targetId, true, true);
712                 SubwindowManager::GetInstance()->ClearPopupInSubwindow(instanceId);
713             },
714             TaskExecutor::TaskType::UI, "ArkUITouchOutsideSubwindowClear");
715     }
716 
717 private:
718     int32_t instanceId_ = -1;
719     int32_t targetId_ = -1;
720 };
721 
UIContentImpl(OHOS::AbilityRuntime::Context* context, void* runtime)722 UIContentImpl::UIContentImpl(OHOS::AbilityRuntime::Context* context, void* runtime) : runtime_(runtime)
723 {
724     CHECK_NULL_VOID(context);
725     context_ = context->weak_from_this();
726     bundleName_ = context->GetBundleName();
727     auto hapModuleInfo = context->GetHapModuleInfo();
728     CHECK_NULL_VOID(hapModuleInfo);
729     moduleName_ = hapModuleInfo->name;
730     StoreConfiguration(context->GetConfiguration());
731 }
732 
UIContentImpl(OHOS::AbilityRuntime::Context* context, void* runtime, bool isCard)733 UIContentImpl::UIContentImpl(OHOS::AbilityRuntime::Context* context, void* runtime, bool isCard)
734     : runtime_(runtime), isFormRender_(isCard)
735 {
736     CHECK_NULL_VOID(context);
737     bundleName_ = context->GetBundleName();
738     if (CJUtils::IsCJFrontendContext(context)) {
739         LOGD("UIContentImpl cj");
740         context_ = context->weak_from_this();
741     } else {
742         auto hapModuleInfo = context->GetHapModuleInfo();
743         CHECK_NULL_VOID(hapModuleInfo);
744         moduleName_ = hapModuleInfo->name;
745         hapPath_ = hapModuleInfo->hapPath;
746         isBundle_ = (hapModuleInfo->compileMode == AppExecFwk::CompileMode::JS_BUNDLE);
747         SetConfiguration(context->GetConfiguration());
748         context_ = context->weak_from_this();
749     }
750 }
751 
UIContentImpl(OHOS::AppExecFwk::Ability* ability)752 UIContentImpl::UIContentImpl(OHOS::AppExecFwk::Ability* ability)
753 {
754     CHECK_NULL_VOID(ability);
755     context_ = ability->GetAbilityContext();
756     auto context = context_.lock();
757     CHECK_NULL_VOID(context);
758     StoreConfiguration(context->GetConfiguration());
759 }
760 
DestroyUIDirector()761 void UIContentImpl::DestroyUIDirector()
762 {
763 #ifndef NG_BUILD
764     auto container = Platform::AceContainer::GetContainer(instanceId_);
765     CHECK_NULL_VOID(container);
766     auto pipelineContext = AceType::DynamicCast<PipelineContext>(container->GetPipelineContext());
767     CHECK_NULL_VOID(pipelineContext);
768 #ifdef ENABLE_ROSEN_BACKEND
769     auto rsUIDirector = pipelineContext->GetRSUIDirector();
770     CHECK_NULL_VOID(rsUIDirector);
771     LOGI("[%{public}s][%{public}s][%{public}d]: Destroying old rsUIDirectory", bundleName_.c_str(), moduleName_.c_str(),
772         instanceId_);
773     rsUIDirector->Destroy();
774 #endif
775 #endif
776 }
777 
DestroyCallback() const778 void UIContentImpl::DestroyCallback() const
779 {
780     auto container = Platform::AceContainer::GetContainer(instanceId_);
781     CHECK_NULL_VOID(container);
782     auto pipelineContext = container->GetPipelineContext();
783     CHECK_NULL_VOID(pipelineContext);
784     pipelineContext->SetNextFrameLayoutCallback(nullptr);
785 }
786 
InitializeInner( OHOS::Rosen::Window* window, const std::string& contentInfo, napi_value storage, bool isNamedRouter)787 UIContentErrorCode UIContentImpl::InitializeInner(
788     OHOS::Rosen::Window* window, const std::string& contentInfo, napi_value storage, bool isNamedRouter)
789 {
790     auto errorCode = UIContentErrorCode::NO_ERRORS;
791     if (window && StringUtils::StartWith(window->GetWindowName(), SUBWINDOW_TOAST_DIALOG_PREFIX)) {
792         return CommonInitialize(window, contentInfo, storage);
793     }
794     if (window) {
795         errorCode = CommonInitialize(window, contentInfo, storage);
796         CHECK_ERROR_CODE_RETURN(errorCode);
797     }
798 
799     // ArkTSCard need no window : 梳理所有需要window和不需要window的场景
800     if (isFormRender_ && !window) {
801         LOGI("[%{public}s][%{public}s][%{public}d]: CommonInitializeForm url: %{public}s", bundleName_.c_str(),
802             moduleName_.c_str(), instanceId_, contentInfo.c_str());
803         errorCode = CommonInitializeForm(window, contentInfo, storage);
804         CHECK_ERROR_CODE_RETURN(errorCode);
805     }
806     LOGI("[%{public}s][%{public}s][%{public}d]: Initialize: %{public}s", bundleName_.c_str(),
807         moduleName_.c_str(), instanceId_, startUrl_.c_str());
808     // run page.
809     errorCode = Platform::AceContainer::RunPage(instanceId_, startUrl_, "", isNamedRouter);
810     CHECK_ERROR_CODE_RETURN(errorCode);
811     auto distributedUI = std::make_shared<NG::DistributedUI>();
812     uiManager_ = std::make_unique<DistributedUIManager>(instanceId_, distributedUI);
813     Platform::AceContainer::GetContainer(instanceId_)->SetDistributedUI(distributedUI);
814     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionSubWindow(isUIExtensionSubWindow_);
815     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionAbilityProcess(isUIExtensionAbilityProcess_);
816     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionAbilityHost(isUIExtensionAbilityHost_);
817 #if !defined(ACE_UNITTEST)
818     auto pipelineContext = NG::PipelineContext::GetCurrentContext();
819     CHECK_NULL_RETURN(pipelineContext, errorCode);
820     auto rootNode = pipelineContext->GetRootElement();
821     NG::TransparentNodeDetector::GetInstance().PostCheckNodeTransparentTask(rootNode, startUrl_);
822 #endif
823     return errorCode;
824 }
825 
PreInitializeForm(OHOS::Rosen::Window* window, const std::string& url, napi_value storage)826 void UIContentImpl::PreInitializeForm(OHOS::Rosen::Window* window, const std::string& url, napi_value storage)
827 {
828     // ArkTSCard need no window
829     if (isFormRender_ && !window) {
830         LOGI("[%{public}s][%{public}s][%{public}d]: InitializeForm: %{public}s", bundleName_.c_str(),
831             moduleName_.c_str(), instanceId_, url.c_str());
832         CommonInitializeForm(window, url, storage);
833         AddWatchSystemParameter();
834     }
835 }
836 
RunFormPage()837 void UIContentImpl::RunFormPage()
838 {
839     LOGI("[%{public}s][%{public}s][%{public}d]: Initialize startUrl: %{public}s",
840         bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str());
841     // run page.
842     Platform::AceContainer::RunPage(instanceId_, startUrl_, formData_, false);
843     auto distributedUI = std::make_shared<NG::DistributedUI>();
844     uiManager_ = std::make_unique<DistributedUIManager>(instanceId_, distributedUI);
845     auto container = Platform::AceContainer::GetContainer(instanceId_);
846     CHECK_NULL_VOID(container);
847     container->SetDistributedUI(distributedUI);
848 }
849 
Initialize(OHOS::Rosen::Window* window, const std::string& url, napi_value storage)850 UIContentErrorCode UIContentImpl::Initialize(OHOS::Rosen::Window* window, const std::string& url, napi_value storage)
851 {
852     auto errorCode = InitializeInner(window, url, storage, false);
853     AddWatchSystemParameter();
854     return errorCode;
855 }
856 
Initialize( OHOS::Rosen::Window* window, const std::shared_ptr<std::vector<uint8_t>>& content, napi_value storage)857 UIContentErrorCode UIContentImpl::Initialize(
858     OHOS::Rosen::Window* window, const std::shared_ptr<std::vector<uint8_t>>& content, napi_value storage)
859 {
860     auto errorCode = UIContentErrorCode::NO_ERRORS;
861     errorCode = CommonInitialize(window, "", storage);
862     CHECK_ERROR_CODE_RETURN(errorCode);
863     AddWatchSystemParameter();
864     if (content) {
865         LOGI("Initialize by buffer, size:%{public}zu", content->size());
866         // run page.
867         errorCode = Platform::AceContainer::RunPage(instanceId_, content, "");
868         CHECK_ERROR_CODE_RETURN(errorCode);
869     } else {
870         LOGE("Initialize failed, buffer is null");
871     }
872     auto distributedUI = std::make_shared<NG::DistributedUI>();
873     uiManager_ = std::make_unique<DistributedUIManager>(instanceId_, distributedUI);
874     Platform::AceContainer::GetContainer(instanceId_)->SetDistributedUI(distributedUI);
875     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionSubWindow(isUIExtensionSubWindow_);
876     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionAbilityProcess(isUIExtensionAbilityProcess_);
877     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionAbilityHost(isUIExtensionAbilityHost_);
878     return errorCode;
879 }
880 
InitializeByName( OHOS::Rosen::Window* window, const std::string& name, napi_value storage)881 UIContentErrorCode UIContentImpl::InitializeByName(
882     OHOS::Rosen::Window* window, const std::string& name, napi_value storage)
883 {
884     auto errorCode = InitializeInner(window, name, storage, true);
885     AddWatchSystemParameter();
886     return errorCode;
887 }
888 
InitializeDynamic(int32_t hostInstanceId, const std::string& hapPath, const std::string& abcPath, const std::string& entryPoint, const std::vector<std::string>& registerComponents)889 void UIContentImpl::InitializeDynamic(int32_t hostInstanceId, const std::string& hapPath, const std::string& abcPath,
890     const std::string& entryPoint, const std::vector<std::string>& registerComponents)
891 {
892     isDynamicRender_ = true;
893     hapPath_ = hapPath;
894     hostInstanceId_ = hostInstanceId;
895     registerComponents_ = registerComponents;
896     auto env = reinterpret_cast<napi_env>(runtime_);
897     CHECK_NULL_VOID(env);
898     taskWrapper_ = std::make_shared<NG::UVTaskWrapperImpl>(env);
899 
900     CommonInitializeForm(nullptr, abcPath, nullptr);
901     AddWatchSystemParameter();
902 
903     LOGI("[%{public}s][%{public}s][%{public}d]: InitializeDynamic, startUrl"
904          ": %{public}s, entryPoint: %{public}s",
905         bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str(), entryPoint.c_str());
906     Platform::AceContainer::RunDynamicPage(instanceId_, startUrl_, "", entryPoint);
907     auto distributedUI = std::make_shared<NG::DistributedUI>();
908     uiManager_ = std::make_unique<DistributedUIManager>(instanceId_, distributedUI);
909     Platform::AceContainer::GetContainer(instanceId_)->SetDistributedUI(distributedUI);
910 }
911 
Initialize( OHOS::Rosen::Window* window, const std::string& url, napi_value storage, uint32_t focusWindowId)912 void UIContentImpl::Initialize(
913     OHOS::Rosen::Window* window, const std::string& url, napi_value storage, uint32_t focusWindowId)
914 {
915     if (window == nullptr) {
916         LOGE("UIExtensionAbility [%{public}s][%{public}s][%{public}d][%{public}s] initialize ui instance failed, the"
917              "window is invalid",
918             bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str());
919         return;
920     }
921     auto errorCode = CommonInitialize(window, url, storage, focusWindowId);
922     if (errorCode != UIContentErrorCode::NO_ERRORS) {
923         return;
924     }
925     AddWatchSystemParameter();
926 
927     TAG_LOGI(AceLogTag::ACE_UIEXTENSIONCOMPONENT, "[%{public}s][%{public}s][%{public}d]: StartUIExtension: %{public}s",
928         bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str());
929     // run page.
930     Platform::AceContainer::RunPage(instanceId_, startUrl_, "");
931     auto distributedUI = std::make_shared<NG::DistributedUI>();
932     uiManager_ = std::make_unique<DistributedUIManager>(instanceId_, distributedUI);
933     Platform::AceContainer::GetContainer(instanceId_)->SetDistributedUI(distributedUI);
934 #if !defined(ACE_UNITTEST)
935     auto pipelineContext = NG::PipelineContext::GetCurrentContext();
936     CHECK_NULL_VOID(pipelineContext);
937     auto rootNode = pipelineContext->GetRootElement();
938     NG::TransparentNodeDetector::GetInstance().PostCheckNodeTransparentTask(rootNode, startUrl_);
939 #endif
940 }
941 
GetUINapiContext()942 napi_value UIContentImpl::GetUINapiContext()
943 {
944     auto container = Platform::AceContainer::GetContainer(instanceId_);
945     ContainerScope scope(instanceId_);
946     napi_value result = nullptr;
947     auto frontend = container->GetFrontend();
948     CHECK_NULL_RETURN(frontend, result);
949     if (frontend->GetType() == FrontendType::DECLARATIVE_JS) {
950 #ifdef NG_BUILD
951         auto declarativeFrontend = AceType::DynamicCast<DeclarativeFrontendNG>(frontend);
952 #else
953         auto declarativeFrontend = AceType::DynamicCast<DeclarativeFrontend>(frontend);
954 #endif
955         CHECK_NULL_RETURN(declarativeFrontend, result);
956         return declarativeFrontend->GetContextValue();
957     }
958 
959     return result;
960 }
961 
Restore( OHOS::Rosen::Window* window, const std::string& contentInfo, napi_value storage, ContentInfoType type)962 UIContentErrorCode UIContentImpl::Restore(
963     OHOS::Rosen::Window* window, const std::string& contentInfo, napi_value storage, ContentInfoType type)
964 {
965     LOGI("Restore with contentInfo size: %{public}d, ContentInfotype: %{public}d",
966         static_cast<int32_t>(contentInfo.size()), static_cast<int32_t>(type));
967     auto errorCode = UIContentErrorCode::NO_ERRORS;
968     errorCode = CommonInitialize(window, contentInfo, storage);
969     CHECK_ERROR_CODE_RETURN(errorCode);
970     RouterRecoverRecord record;
971     std::tie(record, errorCode) = Platform::AceContainer::RestoreRouterStack(instanceId_, contentInfo, type);
972     startUrl_ = record.url;
973     CHECK_ERROR_CODE_RETURN(errorCode);
974     if (startUrl_.empty()) {
975         LOGW("Restore start url is empty");
976     }
977     LOGI("[%{public}s][%{public}s][%{public}d]: Restore startUrl: %{public}s, isNamedRouter: %{public}s",
978         bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str(),
979         (record.isNamedRouter ? "yes" : "no"));
980     return Platform::AceContainer::RunPage(instanceId_, startUrl_, record.params, record.isNamedRouter);
981 }
982 
GetContentInfo(ContentInfoType type) const983 std::string UIContentImpl::GetContentInfo(ContentInfoType type) const
984 {
985     LOGI("[%{public}s][%{public}s][%{public}d]: GetContentInfoType: %{public}d",
986         bundleName_.c_str(), moduleName_.c_str(), instanceId_, type);
987     return Platform::AceContainer::GetContentInfo(instanceId_, type);
988 }
989 
990 // ArkTSCard start
CommonInitializeForm( OHOS::Rosen::Window* window, const std::string& contentInfo, napi_value storage)991 UIContentErrorCode UIContentImpl::CommonInitializeForm(
992     OHOS::Rosen::Window* window, const std::string& contentInfo, napi_value storage)
993 {
994     ACE_FUNCTION_TRACE();
995     window_ = window;
996     startUrl_ = contentInfo;
997     auto errorCode = UIContentErrorCode::NO_ERRORS;
998 
999     if (window_) {
1000         if (StringUtils::StartWith(window->GetWindowName(), SUBWINDOW_TOAST_DIALOG_PREFIX)) {
1001             InitializeSubWindow(window_, true);
1002             return errorCode;
1003         }
1004         if (StringUtils::StartWith(window->GetWindowName(), SUBWINDOW_PREFIX)) {
1005             InitializeSubWindow(window_);
1006             return errorCode;
1007         }
1008     }
1009 
1010     auto context = context_.lock();
1011     static std::once_flag onceFlag;
1012     if (!isFormRender_) {
1013         std::call_once(onceFlag, [&context]() {
1014             SetHwIcuDirectory();
1015             Container::UpdateCurrent(INSTANCE_ID_PLATFORM);
1016             AceApplicationInfo::GetInstance().SetProcessName(context->GetBundleName());
1017             AceApplicationInfo::GetInstance().SetPackageName(context->GetBundleName());
1018             AceApplicationInfo::GetInstance().SetDataFileDirPath(context->GetFilesDir());
1019             AceApplicationInfo::GetInstance().SetUid(IPCSkeleton::GetCallingUid());
1020             AceApplicationInfo::GetInstance().SetPid(IPCSkeleton::GetCallingRealPid());
1021             CapabilityRegistry::Register();
1022             ImageFileCache::GetInstance().SetImageCacheFilePath(context->GetCacheDir());
1023             ImageFileCache::GetInstance().SetCacheFileInfo();
1024         });
1025     }
1026 
1027     bool useNewPipe = true;
1028     int32_t deviceWidth = 0;
1029     int32_t deviceHeight = 0;
1030     float density = 1.0f;
1031     auto defaultDisplay = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
1032     if (defaultDisplay) {
1033         auto displayInfo = defaultDisplay->GetDisplayInfo();
1034         if (displayInfo) {
1035             density = displayInfo->GetDensityInCurResolution();
1036         }
1037         deviceWidth = defaultDisplay->GetWidth();
1038         deviceHeight = defaultDisplay->GetHeight();
1039         TAG_LOGI(AceLogTag::ACE_FORM,
1040             "[%{public}s][%{public}s][%{public}d]: CommonInitializeForm virtualPixelRatio: %{public}f, deviceWidth: "
1041             "%{public}d, deviceHeight: %{public}d",
1042             bundleName_.c_str(), moduleName_.c_str(), instanceId_, density, deviceWidth, deviceHeight);
1043     }
1044 
1045     SystemProperties::InitDeviceInfo(deviceWidth, deviceHeight, deviceHeight >= deviceWidth ? 0 : 1, density, false);
1046     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
1047     if (context) {
1048         auto resourceManager = context->GetResourceManager();
1049         if (resourceManager != nullptr) {
1050             resourceManager->GetResConfig(*resConfig);
1051             auto localeInfo = resConfig->GetLocaleInfo();
1052             Platform::AceApplicationInfoImpl::GetInstance().SetResourceManager(resourceManager);
1053             if (localeInfo != nullptr) {
1054                 auto language = localeInfo->getLanguage();
1055                 auto region = localeInfo->getCountry();
1056                 auto script = localeInfo->getScript();
1057                 AceApplicationInfo::GetInstance().SetLocale((language == nullptr) ? "" : language,
1058                     (region == nullptr) ? "" : region, (script == nullptr) ? "" : script, "");
1059             }
1060             if (resConfig->GetColorMode() == OHOS::Global::Resource::ColorMode::DARK) {
1061                 SystemProperties::SetColorMode(ColorMode::DARK);
1062                 LOGI("Set dark mode");
1063             } else {
1064                 SystemProperties::SetColorMode(ColorMode::LIGHT);
1065                 LOGI("Set light mode");
1066             }
1067             SystemProperties::SetDeviceAccess(
1068                 resConfig->GetInputDevice() == Global::Resource::InputDevice::INPUTDEVICE_POINTINGDEVICE);
1069         }
1070     }
1071 
1072     auto abilityContext = OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(context);
1073     std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> info;
1074     if (abilityContext) {
1075         info = abilityContext->GetAbilityInfo();
1076     } else {
1077         auto extensionContext =
1078             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::ExtensionContext>(context);
1079         if (extensionContext) {
1080             info = extensionContext->GetAbilityInfo();
1081         }
1082     }
1083     if (info) {
1084         AceApplicationInfo::GetInstance().SetAbilityName(info->name);
1085     }
1086 
1087     RefPtr<AssetManagerImpl> assetManagerImpl = Referenced::MakeRefPtr<AssetManagerImpl>();
1088     bool isModelJson = info != nullptr ? info->isModuleJson : false;
1089     std::string moduleName = info != nullptr ? info->moduleName : "";
1090     auto appInfo = context != nullptr ? context->GetApplicationInfo() : nullptr;
1091     auto hapModuleInfo = context != nullptr ? context->GetHapModuleInfo() : nullptr;
1092     auto bundleName = info != nullptr ? info->bundleName : "";
1093     std::string moduleHapPath = info != nullptr ? info->hapPath : "";
1094     std::string resPath;
1095     std::string pageProfile;
1096     if (isFormRender_) {
1097         std::vector<std::string> basePaths;
1098         basePaths.emplace_back("assets/js/" + moduleName_ + "/");
1099         basePaths.emplace_back("assets/js/share/");
1100         basePaths.emplace_back("");
1101         basePaths.emplace_back("js/");
1102         basePaths.emplace_back("ets/");
1103         auto assetProvider = CreateAssetProviderImpl(hapPath_, basePaths, false);
1104         if (assetProvider) {
1105             assetManagerImpl->PushBack(std::move(assetProvider));
1106         }
1107     } else {
1108         if (isModelJson) {
1109             std::string hapPath = info != nullptr ? info->hapPath : "";
1110             // first use hap provider
1111             if (assetManagerImpl && !hapPath.empty()) {
1112                 auto hapAssetProviderImpl = AceType::MakeRefPtr<HapAssetProviderImpl>();
1113                 if (hapAssetProviderImpl->Initialize(hapPath, { "", "ets/", "resources/base/profile/" })) {
1114                     assetManagerImpl->PushBack(std::move(hapAssetProviderImpl));
1115                 }
1116             }
1117 
1118             if (appInfo) {
1119                 std::vector<OHOS::AppExecFwk::ModuleInfo> moduleList = appInfo->moduleInfos;
1120                 for (const auto& module : moduleList) {
1121                     if (module.moduleName == moduleName) {
1122                         std::regex pattern(ABS_BUNDLE_CODE_PATH + bundleName + FILE_SEPARATOR);
1123                         auto moduleSourceDir =
1124                             std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
1125                         resPath = moduleSourceDir + "/";
1126                         break;
1127                     }
1128                 }
1129             }
1130 
1131             // second use file provider, will remove later
1132             auto assetBasePathStr = { std::string("ets/"), std::string("resources/base/profile/") };
1133             if (assetManagerImpl && !resPath.empty()) {
1134                 auto assetProvider = AceType::MakeRefPtr<FileAssetProviderImpl>();
1135                 if (assetProvider->Initialize(resPath, assetBasePathStr)) {
1136                     assetManagerImpl->PushBack(std::move(assetProvider));
1137                 }
1138             }
1139 
1140             if (hapModuleInfo) {
1141                 pageProfile = hapModuleInfo->pages;
1142                 const std::string profilePrefix = "$profile:";
1143                 if (pageProfile.compare(0, profilePrefix.size(), profilePrefix) == 0) {
1144                     pageProfile = pageProfile.substr(profilePrefix.length()).append(".json");
1145                 }
1146             }
1147         } else {
1148             auto packagePathStr = context->GetBundleCodeDir();
1149             if (hapModuleInfo != nullptr) {
1150                 packagePathStr += "/" + hapModuleInfo->package + "/";
1151             }
1152             std::string srcPath = "";
1153             if (info != nullptr && !info->srcPath.empty()) {
1154                 srcPath = info->srcPath;
1155             }
1156 
1157             auto assetBasePathStr = { "assets/js/" + (srcPath.empty() ? "default" : srcPath) + "/",
1158                 std::string("assets/js/share/") };
1159             if (assetManagerImpl && !packagePathStr.empty()) {
1160                 auto fileAssetProvider = AceType::MakeRefPtr<FileAssetProviderImpl>();
1161                 if (fileAssetProvider->Initialize(packagePathStr, assetBasePathStr)) {
1162                     assetManagerImpl->PushBack(std::move(fileAssetProvider));
1163                 }
1164             }
1165             if (appInfo) {
1166                 std::vector<OHOS::AppExecFwk::ModuleInfo> moduleList = appInfo->moduleInfos;
1167                 for (const auto& module : moduleList) {
1168                     if (module.moduleName == moduleName) {
1169                         std::regex pattern(ABS_BUNDLE_CODE_PATH + bundleName + FILE_SEPARATOR);
1170                         auto moduleSourceDir =
1171                             std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
1172                         resPath = moduleSourceDir + "/assets/" + module.moduleName + "/";
1173                         break;
1174                     }
1175                 }
1176             }
1177         }
1178     }
1179 
1180     std::string hapPath; // hap path in sandbox
1181     if (!moduleHapPath.empty()) {
1182         if (moduleHapPath.find(ABS_BUNDLE_CODE_PATH) == std::string::npos) {
1183             hapPath = moduleHapPath;
1184         } else {
1185             auto pos = moduleHapPath.find_last_of('/');
1186             if (pos != std::string::npos) {
1187                 hapPath = LOCAL_BUNDLE_CODE_PATH + moduleHapPath.substr(pos + 1);
1188             }
1189         }
1190     }
1191 
1192 #ifdef PLUGIN_COMPONENT_SUPPORTED
1193     auto pluginUtils = std::make_shared<PluginUtilsImpl>();
1194     PluginManager::GetInstance().SetAceAbility(nullptr, pluginUtils);
1195 #endif
1196     // create container
1197     if (runtime_) {
1198         instanceId_ = Container::GenerateId<STAGE_CONTAINER>();
1199     } else {
1200         instanceId_ = Container::GenerateId<FA_SUBWINDOW_CONTAINER>();
1201     }
1202 #ifdef FORM_SUPPORTED
1203     auto formUtils = std::make_shared<FormUtilsImpl>();
1204     FormManager::GetInstance().SetFormUtils(formUtils);
1205 #endif
1206     auto container =
1207         AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, FrontendType::DECLARATIVE_JS, context_, info,
1208             std::make_unique<ContentEventCallback>(
1209                 [window = window_] {
1210                     CHECK_NULL_VOID(window);
1211                     window->PerformBack();
1212                 },
1213                 [context = context_](const std::string& address) {
1214                     auto sharedContext = context.lock();
1215                     CHECK_NULL_VOID(sharedContext);
1216                     auto abilityContext =
1217                         OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
1218                     CHECK_NULL_VOID(abilityContext);
1219                     LOGI("Start ability: %{private}s", address.c_str());
1220                     AAFwk::Want want;
1221                     want.AddEntity(Want::ENTITY_BROWSER);
1222                     want.SetUri(address);
1223                     want.SetAction(ACTION_VIEWDATA);
1224                     abilityContext->StartAbility(want, REQUEST_CODE);
1225                 }),
1226             taskWrapper_, false, false, useNewPipe);
1227 
1228     CHECK_NULL_RETURN(container, UIContentErrorCode::NULL_POINTER);
1229     container->SetIsFormRender(isFormRender_);
1230     container->SetIsDynamicRender(isDynamicRender_);
1231     container->SetRegisterComponents(registerComponents_);
1232     container->SetIsFRSCardContainer(isFormRender_);
1233     if (window_) {
1234         container->SetWindowName(window_->GetWindowName());
1235         container->SetWindowId(window_->GetWindowId());
1236     }
1237 
1238     if (context) {
1239         auto token = context->GetToken();
1240         container->SetToken(token);
1241     }
1242 
1243     if (appInfo) {
1244         container->SetApiTargetVersion(appInfo->apiTargetVersion);
1245     }
1246 
1247     // Mark the relationship between windowId and containerId, it is 1:1
1248     if (window) {
1249         SubwindowManager::GetInstance()->AddContainerId(window->GetWindowId(), instanceId_);
1250     }
1251     AceEngine::Get().AddContainer(instanceId_, container);
1252     if (runtime_) {
1253         container->GetSettings().SetUsingSharedRuntime(true);
1254         container->SetSharedRuntime(runtime_);
1255     } else {
1256         container->GetSettings().SetUsingSharedRuntime(false);
1257     }
1258     container->SetPageProfile(pageProfile);
1259     container->Initialize();
1260     ContainerScope scope(instanceId_);
1261     auto front = container->GetFrontend();
1262     if (front) {
1263         front->UpdateState(Frontend::State::ON_CREATE);
1264         front->SetJsMessageDispatcher(container);
1265     }
1266     auto aceResCfg = container->GetResourceConfiguration();
1267     aceResCfg.SetOrientation(SystemProperties::GetDeviceOrientation());
1268     aceResCfg.SetDensity(SystemProperties::GetResolution());
1269     aceResCfg.SetDeviceType(SystemProperties::GetDeviceType());
1270     aceResCfg.SetColorMode(SystemProperties::GetColorMode());
1271     aceResCfg.SetDeviceAccess(SystemProperties::GetDeviceAccess());
1272     AddResConfigInfo(context, aceResCfg);
1273     if (isDynamicRender_) {
1274         auto runtimeContext = Platform::AceContainer::GetRuntimeContext(hostInstanceId_);
1275         if (runtimeContext) {
1276             AddSetAppColorModeToResConfig(runtimeContext->shared_from_this(), aceResCfg);
1277         }
1278     } else {
1279         AddSetAppColorModeToResConfig(context, aceResCfg);
1280     }
1281     if (isDynamicRender_) {
1282         if (std::regex_match(hapPath_, std::regex(".*\\.hap"))) {
1283             hapPath = hapPath_;
1284         } else {
1285             resPath = hapPath_;
1286         }
1287     } else if (isFormRender_) {
1288         resPath = "/data/bundles/" + bundleName_ + "/" + moduleName_ + "/";
1289         hapPath = hapPath_;
1290     }
1291     TAG_LOGI(AceLogTag::ACE_FORM,
1292         "[%{public}s][%{public}s][%{public}d]: CommonInitializeForm resPath = %{public}s hapPath = %{public}s",
1293         bundleName_.c_str(), moduleName_.c_str(), instanceId_, resPath.c_str(), hapPath.c_str());
1294     container->SetResourceConfiguration(aceResCfg);
1295     container->SetPackagePathStr(resPath);
1296     container->SetHapPath(hapPath);
1297     container->SetAssetManager(assetManagerImpl);
1298 
1299     if (!isFormRender_) {
1300         container->SetBundlePath(context->GetBundleCodeDir());
1301         container->SetFilesDataPath(context->GetFilesDir());
1302     }
1303 
1304     if (window_) {
1305         if (window_->IsDecorEnable()) {
1306             container->SetWindowModal(WindowModal::CONTAINER_MODAL);
1307         }
1308 
1309         dragWindowListener_ = new DragWindowListener(instanceId_);
1310         window_->RegisterDragListener(dragWindowListener_);
1311         occupiedAreaChangeListener_ = new OccupiedAreaChangeListener(instanceId_);
1312         window_->RegisterOccupiedAreaChangeListener(occupiedAreaChangeListener_);
1313     }
1314 
1315     // create ace_view
1316     RefPtr<Platform::AceViewOhos> aceView = nullptr;
1317     if (isFormRender_ && !isDynamicRender_) {
1318         aceView = Platform::AceViewOhos::CreateView(instanceId_, true, container->GetSettings().usePlatformAsUIThread);
1319         Platform::AceViewOhos::SurfaceCreated(aceView, window_);
1320     } else {
1321         aceView = Platform::AceViewOhos::CreateView(instanceId_, false, container->GetSettings().usePlatformAsUIThread);
1322         Platform::AceViewOhos::SurfaceCreated(aceView, window_);
1323     }
1324 
1325     if (isFormRender_) {
1326         errorCode = Platform::AceContainer::SetViewNew(aceView, density, round(formWidth_),
1327             round(formHeight_), window_);
1328         CHECK_ERROR_CODE_RETURN(errorCode);
1329         auto frontend = AceType::DynamicCast<FormFrontendDeclarative>(container->GetFrontend());
1330         CHECK_NULL_RETURN(frontend, UIContentErrorCode::NULL_POINTER);
1331         frontend->SetBundleName(bundleName_);
1332         frontend->SetModuleName(moduleName_);
1333         // arkTSCard only support "esModule" compile mode
1334         frontend->SetIsBundle(false);
1335         container->SetBundleName(bundleName_);
1336     } else {
1337         errorCode = Platform::AceContainer::SetViewNew(aceView, density, 0, 0, window_);
1338         CHECK_ERROR_CODE_RETURN(errorCode);
1339     }
1340 
1341     // after frontend initialize
1342     if (window_ && window_->IsFocused()) {
1343         Focus();
1344     }
1345 
1346     if (isFormRender_ && !isFormRenderInit_) {
1347         container->UpdateFormSharedImage(formImageDataMap_);
1348         container->UpdateFormData(formData_);
1349         isFormRenderInit_ = true;
1350     }
1351 
1352     if (isFormRender_) {
1353         Platform::AceViewOhos::SurfaceChanged(aceView, round(formWidth_), round(formHeight_),
1354             deviceHeight >= deviceWidth ? 0 : 1);
1355         container->CheckAndSetFontFamily();
1356         SetFontScaleAndWeightScale(container, instanceId_);
1357         // Set sdk version in module json mode for form
1358         auto pipeline = container->GetPipelineContext();
1359         if (pipeline && appInfo) {
1360             pipeline->SetMinPlatformVersion(appInfo->apiCompatibleVersion);
1361         }
1362     } else {
1363         Platform::AceViewOhos::SurfaceChanged(aceView, 0, 0, deviceHeight >= deviceWidth ? 0 : 1);
1364     }
1365     // Set sdk version in module json mode
1366     if (isModelJson) {
1367         auto pipeline = container->GetPipelineContext();
1368         if (pipeline && appInfo) {
1369             pipeline->SetMinPlatformVersion(appInfo->apiCompatibleVersion);
1370         }
1371     }
1372     if (runtime_ && !isFormRender_) { // ArkTSCard not support inherit local strorage from context
1373         auto nativeEngine = reinterpret_cast<NativeEngine*>(runtime_);
1374         if (!storage) {
1375             container->SetLocalStorage(nullptr, context);
1376         } else {
1377             auto env = reinterpret_cast<napi_env>(nativeEngine);
1378             napi_ref ref = nullptr;
1379             napi_create_reference(env, storage, 1, &ref);
1380             container->SetLocalStorage(
1381                 reinterpret_cast<NativeReference*>(ref), context);
1382         }
1383     }
1384     if (context) {
1385         UpdateFontScale(context->GetConfiguration());
1386     }
1387     return UIContentErrorCode::NO_ERRORS;
1388 }
1389 
UpdateFontScale(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)1390 void UIContentImpl::UpdateFontScale(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)
1391 {
1392     CHECK_NULL_VOID(config);
1393     auto maxAppFontScale = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::APP_FONT_MAX_SCALE);
1394     auto followSystem = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::APP_FONT_SIZE_SCALE);
1395     auto context = NG::PipelineContext::GetContextByContainerId(instanceId_);
1396     CHECK_NULL_VOID(context);
1397     auto isFollowSystem = followSystem == "followSystem";
1398     if (!followSystem.empty()) {
1399         context->SetFollowSystem(isFollowSystem);
1400     }
1401     if (!maxAppFontScale.empty()) {
1402         context->SetMaxAppFontScale(StringUtils::StringToFloat(maxAppFontScale));
1403     }
1404     if (!isFollowSystem) {
1405         context->SetFontScale(1.0f);
1406     }
1407 
1408     auto fontScale = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_FONT_SIZE_SCALE);
1409     if (!fontScale.empty()) {
1410         context->SetFontScale(StringUtils::StringToFloat(fontScale));
1411     }
1412 }
1413 
SetConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)1414 void UIContentImpl::SetConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)
1415 {
1416     if (config == nullptr) {
1417         UErrorCode status = U_ZERO_ERROR;
1418         icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status);
1419         AceApplicationInfo::GetInstance().SetLocale(locale.getLanguage(), locale.getCountry(), locale.getScript(), "");
1420         SystemProperties::SetColorMode(ColorMode::LIGHT);
1421         return;
1422     }
1423 
1424     auto deviceAccess = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE);
1425     auto languageTag = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE);
1426 
1427     if (!deviceAccess.empty()) {
1428         // Event of accessing mouse or keyboard
1429         SystemProperties::SetDeviceAccess(deviceAccess == "true");
1430     }
1431 
1432     if (!languageTag.empty()) {
1433         std::string language;
1434         std::string script;
1435         std::string region;
1436         Localization::ParseLocaleTag(languageTag, language, script, region, false);
1437         if (!language.empty() || !script.empty() || !region.empty()) {
1438             AceApplicationInfo::GetInstance().SetLocale(language, region, script, "");
1439         }
1440     }
1441     StoreConfiguration(config);
1442 }
1443 
StoreConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)1444 void UIContentImpl::StoreConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)
1445 {
1446     if (!config) {
1447         return;
1448     }
1449     TAG_LOGD(AceLogTag::ACE_WINDOW, "StoreConfiguration %{public}s", config->GetName().c_str());
1450     auto colorMode = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
1451     if (!colorMode.empty()) {
1452         if (colorMode == "dark") {
1453             SystemProperties::SetColorMode(ColorMode::DARK);
1454         } else {
1455             SystemProperties::SetColorMode(ColorMode::LIGHT);
1456         }
1457     }
1458 
1459     auto string2float = [](const std::string& str) {
1460         return std::stof(str);
1461     };
1462     auto fontScale = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_FONT_SIZE_SCALE);
1463     if (!fontScale.empty()) {
1464         SystemProperties::SetFontScale(string2float(fontScale));
1465     }
1466     auto fontWeightScale = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_FONT_WEIGHT_SCALE);
1467     if (!fontWeightScale.empty()) {
1468         SystemProperties::SetFontWeightScale(string2float(fontWeightScale));
1469     }
1470 }
1471 
GetFormRootNode()1472 std::shared_ptr<Rosen::RSSurfaceNode> UIContentImpl::GetFormRootNode()
1473 {
1474     return Platform::AceContainer::GetFormSurfaceNode(instanceId_);
1475 }
1476 // ArkTSCard end
1477 
SetFontScaleAndWeightScale(const RefPtr<Platform::AceContainer>& container, int32_t instanceId)1478 void UIContentImpl::SetFontScaleAndWeightScale(const RefPtr<Platform::AceContainer>& container, int32_t instanceId)
1479 {
1480     float fontScale = SystemProperties::GetFontScale();
1481     if (isFormRender_ && !fontScaleFollowSystem_) {
1482         TAG_LOGW(AceLogTag::ACE_FORM, "setFontScale form default size");
1483         fontScale = 1.0f;
1484     }
1485     float fontWeightScale = SystemProperties::GetFontWeightScale();
1486     container->SetFontScale(instanceId, fontScale);
1487     container->SetFontWeightScale(instanceId, fontWeightScale);
1488 }
1489 
CommonInitialize( OHOS::Rosen::Window* window, const std::string& contentInfo, napi_value storage, uint32_t focusWindowId)1490 UIContentErrorCode UIContentImpl::CommonInitialize(
1491     OHOS::Rosen::Window* window, const std::string& contentInfo, napi_value storage, uint32_t focusWindowId)
1492 {
1493     auto errorCode = UIContentErrorCode::NO_ERRORS;
1494     window_ = window;
1495     CHECK_NULL_RETURN(window_, UIContentErrorCode::NULL_WINDOW);
1496     auto windowName = window->GetWindowName();
1497     ACE_SCOPED_TRACE_COMMERCIAL("UI Initialize:%s", windowName.c_str());
1498     startUrl_ = contentInfo;
1499     if (StringUtils::StartWith(windowName, SUBWINDOW_TOAST_DIALOG_PREFIX)) {
1500         InitializeSubWindow(window_, true);
1501         return errorCode;
1502     }
1503     if (StringUtils::StartWith(windowName, SUBWINDOW_PREFIX)) {
1504         InitializeSubWindow(window_);
1505         return errorCode;
1506     }
1507     auto context = context_.lock();
1508     CHECK_NULL_RETURN(context, UIContentErrorCode::NULL_POINTER);
1509     static std::once_flag onceFlag;
1510     std::call_once(onceFlag, [&context]() {
1511         SetHwIcuDirectory();
1512         Container::UpdateCurrent(INSTANCE_ID_PLATFORM);
1513         auto abilityContext = OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(context);
1514         if (abilityContext) {
1515             int32_t missionId = -1;
1516             abilityContext->GetMissionId(missionId);
1517             AceApplicationInfo::GetInstance().SetMissionId(missionId);
1518         }
1519         AceApplicationInfo::GetInstance().SetProcessName(context->GetBundleName());
1520         AceApplicationInfo::GetInstance().SetPackageName(context->GetBundleName());
1521         AceApplicationInfo::GetInstance().SetDataFileDirPath(context->GetFilesDir());
1522         AceApplicationInfo::GetInstance().SetApiTargetVersion(context->GetApplicationInfo()->apiTargetVersion);
1523         AceApplicationInfo::GetInstance().SetAppVersionName(context->GetApplicationInfo()->versionName);
1524         AceApplicationInfo::GetInstance().SetAppVersionCode(context->GetApplicationInfo()->versionCode);
1525         AceApplicationInfo::GetInstance().SetUid(IPCSkeleton::GetCallingUid());
1526         AceApplicationInfo::GetInstance().SetPid(IPCSkeleton::GetCallingRealPid());
1527         CapabilityRegistry::Register();
1528         ImageFileCache::GetInstance().SetImageCacheFilePath(context->GetCacheDir());
1529         ImageFileCache::GetInstance().SetCacheFileInfo();
1530         XcollieInterface::GetInstance().SetTimerCount("HIT_EMPTY_WARNING", TIMEOUT_LIMIT, COUNT_LIMIT);
1531     });
1532     AceNewPipeJudgement::InitAceNewPipeConfig();
1533     auto apiCompatibleVersion = context->GetApplicationInfo()->apiCompatibleVersion;
1534     auto apiReleaseType = context->GetApplicationInfo()->apiReleaseType;
1535     auto apiTargetVersion = context->GetApplicationInfo()->apiTargetVersion;
1536     const auto& hapModuleInfo = context->GetHapModuleInfo();
1537     std::vector<OHOS::AppExecFwk::Metadata> metaData;
1538     if (hapModuleInfo) {
1539         metaData = hapModuleInfo->metadata;
1540     }
1541     bool closeArkTSPartialUpdate = std::any_of(metaData.begin(), metaData.end(), [](const auto& metaDataItem) {
1542         return metaDataItem.name == "ArkTSPartialUpdate" && metaDataItem.value == "false";
1543     });
1544 
1545     auto useNewPipe =
1546         AceNewPipeJudgement::QueryAceNewPipeEnabledStage(AceApplicationInfo::GetInstance().GetPackageName(),
1547             apiCompatibleVersion, apiTargetVersion, apiReleaseType, closeArkTSPartialUpdate);
1548     AceApplicationInfo::GetInstance().SetIsUseNewPipeline(useNewPipe);
1549     LOGI("[%{public}s][%{public}s][%{public}d]: UIContent: apiCompatibleVersion: %{public}d, apiTargetVersion: "
1550          "%{public}d, and apiReleaseType: %{public}s, "
1551          "useNewPipe: %{public}d",
1552         bundleName_.c_str(), moduleName_.c_str(), instanceId_, apiCompatibleVersion, apiTargetVersion,
1553         apiReleaseType.c_str(), useNewPipe);
1554 #ifndef NG_BUILD
1555 #ifdef ENABLE_ROSEN_BACKEND
1556     std::shared_ptr<OHOS::Rosen::RSUIDirector> rsUiDirector;
1557     if (SystemProperties::GetRosenBackendEnabled() && !useNewPipe) {
1558         rsUiDirector = OHOS::Rosen::RSUIDirector::Create();
1559         if (rsUiDirector) {
1560             rsUiDirector->SetRSSurfaceNode(window->GetSurfaceNode());
1561             rsUiDirector->SetCacheDir(context->GetCacheDir());
1562             rsUiDirector->Init();
1563         }
1564     }
1565 #endif
1566 #endif
1567     int32_t deviceWidth = 0;
1568     int32_t deviceHeight = 0;
1569     float density = 1.0f;
1570     float defaultDensity = 1.0f;
1571     int32_t devicePhysicalWidth = 0;
1572     int32_t devicePhysicalHeight = 0;
1573 
1574     bool isSceneBoardWindow = window_->GetType() == Rosen::WindowType::WINDOW_TYPE_SCENE_BOARD;
1575     if (isSceneBoardWindow) {
1576         auto screenProperties = Rosen::ScreenSessionManagerClient::GetInstance().GetAllScreensProperties();
1577         if (!screenProperties.empty()) {
1578             auto iter = screenProperties.begin();
1579             defaultDensity = iter->second.GetDefaultDensity();
1580         }
1581     }
1582 
1583     auto defaultDisplay = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
1584     if (defaultDisplay) {
1585         density = defaultDisplay->GetVirtualPixelRatio();
1586         if (isSceneBoardWindow && !NearEqual(defaultDensity, 1.0f)) {
1587             density = defaultDensity;
1588         }
1589         deviceWidth = defaultDisplay->GetWidth();
1590         deviceHeight = defaultDisplay->GetHeight();
1591         devicePhysicalWidth = defaultDisplay->GetPhysicalWidth();
1592         devicePhysicalHeight = defaultDisplay->GetPhysicalHeight();
1593     }
1594     SystemProperties::InitDeviceInfo(deviceWidth, deviceHeight, deviceHeight >= deviceWidth ? 0 : 1, density, false);
1595     SystemProperties::SetDevicePhysicalWidth(devicePhysicalWidth);
1596     SystemProperties::SetDevicePhysicalHeight(devicePhysicalHeight);
1597     // Initialize performance check parameters
1598     AceChecker::InitPerformanceParameters();
1599     AcePerformanceCheck::Start();
1600     SystemProperties::SetColorMode(ColorMode::LIGHT);
1601 
1602     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
1603     auto resourceManager = context->GetResourceManager();
1604     if (resourceManager != nullptr) {
1605         resourceManager->GetResConfig(*resConfig);
1606         auto localeInfo = resConfig->GetLocaleInfo();
1607         Platform::AceApplicationInfoImpl::GetInstance().SetResourceManager(resourceManager);
1608         if (localeInfo != nullptr) {
1609             auto language = localeInfo->getLanguage();
1610             auto region = localeInfo->getCountry();
1611             auto script = localeInfo->getScript();
1612             AceApplicationInfo::GetInstance().SetLocale((language == nullptr) ? "" : language,
1613                 (region == nullptr) ? "" : region, (script == nullptr) ? "" : script, "");
1614         }
1615         if (resConfig->GetColorMode() == OHOS::Global::Resource::ColorMode::DARK) {
1616             SystemProperties::SetColorMode(ColorMode::DARK);
1617         } else {
1618             SystemProperties::SetColorMode(ColorMode::LIGHT);
1619         }
1620         SystemProperties::SetDeviceAccess(
1621             resConfig->GetInputDevice() == Global::Resource::InputDevice::INPUTDEVICE_POINTINGDEVICE);
1622         LOGI("[%{public}s][%{public}s][%{public}d]: SetLanguage: %{public}s, colorMode: %{public}s, "
1623              "deviceAccess: %{public}d",
1624             bundleName_.c_str(), moduleName_.c_str(), instanceId_,
1625             AceApplicationInfo::GetInstance().GetLanguage().c_str(),
1626             SystemProperties::GetColorMode() == ColorMode::DARK ? "dark" : "light",
1627             SystemProperties::GetDeviceAccess());
1628     }
1629 
1630     auto abilityContext = OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(context);
1631     std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> info;
1632     if (abilityContext) {
1633         info = abilityContext->GetAbilityInfo();
1634     } else {
1635         auto extensionContext =
1636             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::ExtensionContext>(context);
1637         if (!extensionContext) {
1638             return UIContentErrorCode::NULL_POINTER;
1639         }
1640         info = extensionContext->GetAbilityInfo();
1641     }
1642     if (info) {
1643         AceApplicationInfo::GetInstance().SetAbilityName(info->name);
1644     }
1645     RefPtr<AssetManagerImpl> assetManagerImpl = Referenced::MakeRefPtr<AssetManagerImpl>();
1646     bool isModelJson = info != nullptr ? info->isModuleJson : false;
1647     std::string moduleName = info != nullptr ? info->moduleName : "";
1648     auto appInfo = context->GetApplicationInfo();
1649     auto bundleName = info != nullptr ? info->bundleName : "";
1650     auto abilityName = info != nullptr ? info->name : "";
1651     std::string moduleHapPath = info != nullptr ? info->hapPath : "";
1652     std::string resPath;
1653     std::string pageProfile;
1654     LOGI("[%{public}s][%{public}s][%{public}d]: Initialize UIContent isModelJson:%{public}s", bundleName_.c_str(),
1655         moduleName_.c_str(), instanceId_, isModelJson ? "true" : "false");
1656     if (isModelJson) {
1657         std::string hapPath = info != nullptr ? info->hapPath : "";
1658         // first use hap provider
1659         if (assetManagerImpl && !hapPath.empty()) {
1660             auto hapAssetProvider = AceType::MakeRefPtr<HapAssetProviderImpl>();
1661             if (hapAssetProvider->Initialize(hapPath, { "", "ets/", "resources/base/profile/" })) {
1662                 assetManagerImpl->PushBack(std::move(hapAssetProvider));
1663             }
1664         }
1665 
1666         if (appInfo) {
1667             std::vector<OHOS::AppExecFwk::ModuleInfo> moduleList = appInfo->moduleInfos;
1668             for (const auto& module : moduleList) {
1669                 if (module.moduleName == moduleName) {
1670                     std::regex pattern(ABS_BUNDLE_CODE_PATH + bundleName + FILE_SEPARATOR);
1671                     auto moduleSourceDir = std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
1672                     resPath = moduleSourceDir + "/";
1673                     break;
1674                 }
1675             }
1676         }
1677 
1678         // second use file provider, will remove later
1679         auto assetBasePathStr = { std::string("ets/"), std::string("resources/base/profile/") };
1680         if (assetManagerImpl && !resPath.empty()) {
1681             auto fileAssetProvider = AceType::MakeRefPtr<FileAssetProviderImpl>();
1682             if (fileAssetProvider->Initialize(resPath, assetBasePathStr)) {
1683                 assetManagerImpl->PushBack(std::move(fileAssetProvider));
1684             }
1685         }
1686 
1687         if (hapModuleInfo) {
1688             pageProfile = hapModuleInfo->pages;
1689             const std::string profilePrefix = "$profile:";
1690             if (pageProfile.compare(0, profilePrefix.size(), profilePrefix) == 0) {
1691                 pageProfile = pageProfile.substr(profilePrefix.length()).append(".json");
1692             }
1693         }
1694     } else {
1695         auto packagePathStr = context->GetBundleCodeDir();
1696         if (hapModuleInfo != nullptr) {
1697             packagePathStr += "/" + hapModuleInfo->package + "/";
1698         }
1699         std::string srcPath = "";
1700         if (info != nullptr && !info->srcPath.empty()) {
1701             srcPath = info->srcPath;
1702         }
1703 
1704         auto assetBasePathStr = { "assets/js/" + (srcPath.empty() ? "default" : srcPath) + "/",
1705             std::string("assets/js/share/") };
1706 
1707         if (assetManagerImpl && !packagePathStr.empty()) {
1708             auto fileAssetProvider = AceType::MakeRefPtr<FileAssetProviderImpl>();
1709             if (fileAssetProvider->Initialize(packagePathStr, assetBasePathStr)) {
1710                 assetManagerImpl->PushBack(std::move(fileAssetProvider));
1711             }
1712         }
1713         if (appInfo) {
1714             std::vector<OHOS::AppExecFwk::ModuleInfo> moduleList = appInfo->moduleInfos;
1715             for (const auto& module : moduleList) {
1716                 if (module.moduleName == moduleName) {
1717                     std::regex pattern(ABS_BUNDLE_CODE_PATH + bundleName + FILE_SEPARATOR);
1718                     auto moduleSourceDir = std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
1719                     resPath = moduleSourceDir + "/assets/" + module.moduleName + "/";
1720                     break;
1721                 }
1722             }
1723         }
1724     }
1725 
1726     std::string hapPath; // hap path in sandbox
1727     if (!moduleHapPath.empty()) {
1728         if (moduleHapPath.find(ABS_BUNDLE_CODE_PATH) == std::string::npos) {
1729             hapPath = moduleHapPath;
1730         } else {
1731             auto pos = moduleHapPath.find_last_of('/');
1732             if (pos != std::string::npos) {
1733                 hapPath = LOCAL_BUNDLE_CODE_PATH + moduleHapPath.substr(pos + 1);
1734             }
1735         }
1736     }
1737 
1738 #ifdef PLUGIN_COMPONENT_SUPPORTED
1739     auto pluginUtils = std::make_shared<PluginUtilsImpl>();
1740     PluginManager::GetInstance().SetAceAbility(nullptr, pluginUtils);
1741 #endif
1742     // create container
1743     auto isCJFrontend = CJUtils::IsCJFrontendContext(context.get());
1744     if (runtime_ || isCJFrontend) {
1745         instanceId_ = Container::GenerateId<STAGE_CONTAINER>();
1746     } else {
1747         instanceId_ = Container::GenerateId<FA_SUBWINDOW_CONTAINER>();
1748     }
1749 #ifdef FORM_SUPPORTED
1750     auto formUtils = std::make_shared<FormUtilsImpl>();
1751     FormManager::GetInstance().SetFormUtils(formUtils);
1752 #endif
1753 #ifdef APS_ENABLE
1754     auto apsMonitor = std::make_shared<ApsMonitorImpl>();
1755     PerfMonitor::GetPerfMonitor()->SetApsMonitor(apsMonitor);
1756 #endif
1757     auto frontendType =  isCJFrontend? FrontendType::DECLARATIVE_CJ : FrontendType::DECLARATIVE_JS;
1758     auto container =
1759         AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, frontendType, context_, info,
1760             std::make_unique<ContentEventCallback>(
1761                 [window = window_] {
1762                     CHECK_NULL_VOID(window);
1763                     TAG_LOGI(AceLogTag::ACE_ROUTER, "router back to window");
1764                     window->PerformBack();
1765                 },
1766                 [context = context_](const std::string& address) {
1767                     auto sharedContext = context.lock();
1768                     CHECK_NULL_VOID(sharedContext);
1769                     auto abilityContext =
1770                         OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
1771                     CHECK_NULL_VOID(abilityContext);
1772                     LOGI("startAbility: %{private}s", address.c_str());
1773                     AAFwk::Want want;
1774                     want.AddEntity(Want::ENTITY_BROWSER);
1775                     want.SetUri(address);
1776                     want.SetAction(ACTION_VIEWDATA);
1777                     abilityContext->StartAbility(want, REQUEST_CODE);
1778                 }),
1779             false, false, useNewPipe);
1780     CHECK_NULL_RETURN(container, UIContentErrorCode::NULL_POINTER);
1781     container->SetUIContentType(uIContentType_);
1782     container->SetWindowName(window_->GetWindowName());
1783     container->SetWindowId(window_->GetWindowId());
1784     auto token = context->GetToken();
1785     container->SetToken(token);
1786     container->SetParentToken(parentToken_);
1787     if (!isCJFrontend) {
1788         container->SetPageUrlChecker(AceType::MakeRefPtr<PageUrlCheckerOhos>(context, info));
1789     }
1790     container->SetNavigationRoute(AceType::MakeRefPtr<NavigationRouteOhos>(context->GetBundleName()));
1791     // Mark the relationship between windowId and containerId, it is 1:1
1792     SubwindowManager::GetInstance()->AddContainerId(window->GetWindowId(), instanceId_);
1793     AceEngine::Get().AddContainer(instanceId_, container);
1794     ContainerScope::Add(instanceId_);
1795     if (runtime_) {
1796         container->GetSettings().SetUsingSharedRuntime(true);
1797         container->SetSharedRuntime(runtime_);
1798     } else if (isCJFrontend) {
1799         container->GetSettings().SetUsingSharedRuntime(true);
1800     } else {
1801         container->GetSettings().SetUsingSharedRuntime(false);
1802     }
1803     container->SetPageProfile(pageProfile);
1804     container->Initialize();
1805     ContainerScope scope(instanceId_);
1806     auto front = container->GetFrontend();
1807     if (front) {
1808         front->UpdateState(Frontend::State::ON_CREATE);
1809         front->SetJsMessageDispatcher(container);
1810     }
1811     auto aceResCfg = container->GetResourceConfiguration();
1812     aceResCfg.SetOrientation(SystemProperties::GetDeviceOrientation());
1813     aceResCfg.SetDensity(SystemProperties::GetResolution());
1814     aceResCfg.SetDeviceType(SystemProperties::GetDeviceType());
1815     aceResCfg.SetColorMode(SystemProperties::GetColorMode());
1816     aceResCfg.SetDeviceAccess(SystemProperties::GetDeviceAccess());
1817     AddResConfigInfo(context, aceResCfg);
1818     AddSetAppColorModeToResConfig(context, aceResCfg);
1819     container->SetResourceConfiguration(aceResCfg);
1820     container->SetPackagePathStr(resPath);
1821     container->SetHapPath(hapPath);
1822     container->SetAssetManager(assetManagerImpl);
1823 
1824     container->SetBundlePath(context->GetBundleCodeDir());
1825     container->SetFilesDataPath(context->GetFilesDir());
1826     container->SetBundleName(hapModuleInfo->bundleName);
1827     container->SetModuleName(hapModuleInfo->moduleName);
1828     container->SetIsModule(hapModuleInfo->compileMode == AppExecFwk::CompileMode::ES_MODULE);
1829     container->SetApiTargetVersion(apiTargetVersion);
1830 
1831     // for atomic service
1832     container->SetInstallationFree(hapModuleInfo && hapModuleInfo->installationFree);
1833     if (hapModuleInfo->installationFree) {
1834         container->SetSharePanelCallback(
1835             [context = context_](const std::string& bundleName, const std::string& abilityName) {
1836                 auto sharedContext = context.lock();
1837                 CHECK_NULL_VOID(sharedContext);
1838                 auto abilityContext =
1839                     OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
1840                 CHECK_NULL_VOID(abilityContext);
1841                 auto abilityInfo = abilityContext->GetAbilityInfo();
1842                 AAFwk::Want want;
1843                 want.SetParam("abilityName", abilityInfo->name);
1844                 want.SetParam("bundleName", abilityInfo->bundleName);
1845                 want.SetParam("moduleName", abilityInfo->moduleName);
1846                 want.SetParam("hostPkgName", abilityInfo->bundleName);
1847                 want.SetElementName(bundleName, abilityName);
1848                 abilityContext->StartAbility(want, REQUEST_CODE);
1849             });
1850     }
1851 
1852     if (window_->IsDecorEnable()) {
1853         container->SetWindowModal(WindowModal::CONTAINER_MODAL);
1854     }
1855     dragWindowListener_ = new DragWindowListener(instanceId_);
1856     window_->RegisterDragListener(dragWindowListener_);
1857     occupiedAreaChangeListener_ = new OccupiedAreaChangeListener(instanceId_);
1858     window_->RegisterOccupiedAreaChangeListener(occupiedAreaChangeListener_);
1859     foldStatusListener_ = new FoldScreenListener(instanceId_);
1860     OHOS::Rosen::DisplayManager::GetInstance().RegisterFoldStatusListener(foldStatusListener_);
1861     foldDisplayModeListener_ = new FoldDisplayModeListener(instanceId_);
1862     OHOS::Rosen::DisplayManager::GetInstance().RegisterDisplayModeListener(foldDisplayModeListener_);
1863 
1864     // create ace_view
1865     auto aceView =
1866         Platform::AceViewOhos::CreateView(instanceId_, false, container->GetSettings().usePlatformAsUIThread);
1867     Platform::AceViewOhos::SurfaceCreated(aceView, window_);
1868 #ifndef NG_BUILD
1869     if (!useNewPipe) {
1870         Ace::Platform::UIEnvCallback callback = nullptr;
1871 #ifdef ENABLE_ROSEN_BACKEND
1872         callback = [id = instanceId_, container, rsUiDirector](
1873                        const OHOS::Ace::RefPtr<OHOS::Ace::PipelineContext>& context) {
1874             if (rsUiDirector) {
1875                 ACE_SCOPED_TRACE("OHOS::Rosen::RSUIDirector::Create()");
1876                 rsUiDirector->SetUITaskRunner(
1877                     [taskExecutor = container->GetTaskExecutor(), id](
1878                         const std::function<void()>& task, uint32_t delay) {
1879                         ContainerScope scope(id);
1880                         taskExecutor->PostDelayedTask(
1881                             task, TaskExecutor::TaskType::UI, delay, "ArkUIRenderServiceTask", PriorityType::HIGH);
1882                     }, id);
1883                 auto context = AceType::DynamicCast<PipelineContext>(container->GetPipelineContext());
1884                 if (context != nullptr) {
1885                     context->SetRSUIDirector(rsUiDirector);
1886                 }
1887             }
1888         };
1889 #endif
1890         // set view
1891         Platform::AceContainer::SetView(aceView, density, 0, 0, window_, callback);
1892     } else {
1893         errorCode = Platform::AceContainer::SetViewNew(aceView, density, 0, 0, window_);
1894         CHECK_ERROR_CODE_RETURN(errorCode);
1895     }
1896 #else
1897     errorCode = Platform::AceContainer::SetViewNew(aceView, density, 0, 0, window_);
1898     CHECK_ERROR_CODE_RETURN(errorCode);
1899 #endif
1900     // set focus window id for ui extension after pipeline context created.
1901     if (focusWindowId != 0) {
1902         container->SetFocusWindowId(focusWindowId);
1903     }
1904 
1905     auto realHostWindowId = window_->GetRealParentId();
1906     if (realHostWindowId != 0) {
1907         container->SetRealHostWindowId(static_cast<uint32_t>(realHostWindowId));
1908     }
1909     LOGI("focusWindowId: %{public}u, realHostWindowId: %{public}d",
1910         focusWindowId, realHostWindowId);
1911 
1912     // after frontend initialize
1913     if (window_->IsFocused()) {
1914         Focus();
1915     }
1916 
1917     Platform::AceViewOhos::SurfaceChanged(aceView, 0, 0, deviceHeight >= deviceWidth ? 0 : 1);
1918     auto pipeline = container->GetPipelineContext();
1919     // Use metadata to control the center-alignment of text at line height.
1920     bool halfLeading = std::any_of(metaData.begin(), metaData.end(),
1921         [](const auto& metaDataItem) { return metaDataItem.name == "half_leading" && metaDataItem.value == "true"; });
1922     pipeline->SetHalfLeading(halfLeading);
1923     bool hasPreviewTextOption = std::any_of(metaData.begin(), metaData.end(),
1924         [pipelineWeak = AceType::WeakClaim(AceType::RawPtr(pipeline))](const auto& metaDataItem) {
1925                 if (metaDataItem.name == "can_preview_text") {
1926                     auto pipeline = pipelineWeak.Upgrade();
1927                     CHECK_NULL_RETURN(pipeline, false);
1928                     pipeline->SetSupportPreviewText(metaDataItem.value == "false");
1929                     return true;
1930                 }
1931                 return false;
1932             });
1933     pipeline->SetHasPreviewTextOption(hasPreviewTextOption);
1934     // Use metadata to control whether the cutout safeArea takes effect.
1935     bool useCutout = std::any_of(metaData.begin(), metaData.end(),
1936         [](const auto& metaDataItem) { return metaDataItem.name == "avoid_cutout" && metaDataItem.value == "true"; });
1937     pipeline->SetUseCutout(useCutout);
1938     container->CheckAndSetFontFamily();
1939     SetFontScaleAndWeightScale(container, instanceId_);
1940     if (pipeline) {
1941         auto rsConfig = window_->GetKeyboardAnimationConfig();
1942         KeyboardAnimationCurve curveIn = {
1943             rsConfig.curveIn.curveType_, rsConfig.curveIn.curveParams_, rsConfig.curveIn.duration_};
1944         KeyboardAnimationCurve curveOut = {
1945             rsConfig.curveOut.curveType_, rsConfig.curveOut.curveParams_, rsConfig.curveOut.duration_};
1946         KeyboardAnimationConfig config = {curveIn, curveOut};
1947         pipeline->SetKeyboardAnimationConfig(config);
1948     }
1949     // Use metadata to control whether dirty mark is blocked.
1950     bool isOpenInvisibleFreeze = std::any_of(metaData.begin(), metaData.end(), [](const auto& metaDataItem) {
1951         return metaDataItem.name == "ArkUIInvisibleFreeze" && metaDataItem.value == "true";
1952     });
1953     LOGI("ArkUIInvisibleFreeze: %{public}d", isOpenInvisibleFreeze);
1954     pipeline->SetOpenInvisibleFreeze(isOpenInvisibleFreeze);
1955     // Set sdk version in module json mode
1956     if (isModelJson) {
1957         if (pipeline && appInfo) {
1958             LOGI("[%{public}s][%{public}s][%{public}d]: SetMinPlatformVersion is %{public}d", bundleName_.c_str(),
1959                 moduleName_.c_str(), instanceId_, appInfo->apiCompatibleVersion);
1960             pipeline->SetMinPlatformVersion(appInfo->apiCompatibleVersion);
1961         }
1962     }
1963     if (runtime_) {
1964         auto nativeEngine = reinterpret_cast<NativeEngine*>(runtime_);
1965         if (!storage) {
1966             container->SetLocalStorage(nullptr, context);
1967         } else {
1968             auto env = reinterpret_cast<napi_env>(nativeEngine);
1969             napi_ref ref = nullptr;
1970             napi_create_reference(env, storage, 1, &ref);
1971             container->SetLocalStorage(reinterpret_cast<NativeReference*>(ref), context);
1972         }
1973     }
1974 
1975     InitializeSafeArea(container);
1976     InitializeDisplayAvailableRect(container);
1977     InitDragSummaryMap(container);
1978 
1979     // set container temp dir
1980     if (abilityContext) {
1981         if (!abilityContext->GetTempDir().empty()) {
1982             container->SetTempDir(abilityContext->GetTempDir());
1983         }
1984     }
1985 
1986     LayoutInspector::SetCallback(instanceId_);
1987 
1988     // setLogFunc of current app
1989     AddAlarmLogFunc();
1990     // set get inspector tree function for ui session manager
1991     auto callback = [weakContext = WeakPtr(pipeline)]() {
1992         auto pipeline = AceType::DynamicCast<NG::PipelineContext>(weakContext.Upgrade());
1993         if (pipeline == nullptr) {
1994             pipeline = NG::PipelineContext::GetCurrentContextSafely();
1995         }
1996         CHECK_NULL_VOID(pipeline);
1997         auto taskExecutor = pipeline->GetTaskExecutor();
1998         CHECK_NULL_VOID(taskExecutor);
1999         taskExecutor->PostTask(
2000             [weakContext = WeakPtr(pipeline)]() {
2001                 auto pipeline = AceType::DynamicCast<NG::PipelineContext>(weakContext.Upgrade());
2002                 CHECK_NULL_VOID(pipeline);
2003                 ContainerScope scope(pipeline->GetInstanceId());
2004                 pipeline->GetInspectorTree();
2005                 UiSessionManager::GetInstance().WebTaskNumsChange(-1);
2006             },
2007             TaskExecutor::TaskType::UI, "UiSessionGetInspectorTree");
2008     };
2009     UiSessionManager::GetInstance().SaveInspectorTreeFunction(callback);
2010     auto webCallback = [weakContext = WeakPtr(pipeline)](bool isRegister) {
2011         auto pipeline = AceType::DynamicCast<NG::PipelineContext>(weakContext.Upgrade());
2012         CHECK_NULL_VOID(pipeline);
2013         auto taskExecutor = pipeline->GetTaskExecutor();
2014         CHECK_NULL_VOID(taskExecutor);
2015         taskExecutor->PostTask(
2016             [weakContext = WeakPtr(pipeline), isRegister]() {
2017                 auto pipeline = AceType::DynamicCast<NG::PipelineContext>(weakContext.Upgrade());
2018                 CHECK_NULL_VOID(pipeline);
2019                 pipeline->NotifyAllWebPattern(isRegister);
2020             },
2021             TaskExecutor::TaskType::UI, "UiSessionRegisterWebPattern");
2022     };
2023     UiSessionManager::GetInstance().SaveRegisterForWebFunction(webCallback);
2024     UiSessionManager::GetInstance().SaveBaseInfo(std::string("bundleName:")
2025                                                      .append(bundleName)
2026                                                      .append(",moduleName:")
2027                                                      .append(moduleName)
2028                                                      .append(",abilityName:")
2029                                                      .append(abilityName));
2030     UpdateFontScale(context->GetConfiguration());
2031     auto thpExtraManager = AceType::MakeRefPtr<NG::THPExtraManagerImpl>();
2032     if (thpExtraManager->Init()) {
2033         pipeline->SetTHPExtraManager(thpExtraManager);
2034     }
2035     return errorCode;
2036 }
2037 
InitializeSafeArea(const RefPtr<Platform::AceContainer>& container)2038 void UIContentImpl::InitializeSafeArea(const RefPtr<Platform::AceContainer>& container)
2039 {
2040     constexpr static int32_t PLATFORM_VERSION_TEN = 10;
2041     auto pipeline = container->GetPipelineContext();
2042     if (pipeline && pipeline->GetMinPlatformVersion() >= PLATFORM_VERSION_TEN &&
2043         (pipeline->GetIsAppWindow() || container->IsUIExtensionWindow())) {
2044         avoidAreaChangedListener_ = new PretendChangedListener(instanceId_);
2045         window_->RegisterAvoidAreaChangeListener(avoidAreaChangedListener_);
2046         pipeline->UpdateSystemSafeArea(container->GetViewSafeAreaByType(Rosen::AvoidAreaType::TYPE_SYSTEM));
2047         if (pipeline->GetUseCutout()) {
2048             pipeline->UpdateCutoutSafeArea(container->GetViewSafeAreaByType(Rosen::AvoidAreaType::TYPE_CUTOUT));
2049         }
2050         pipeline->UpdateNavSafeArea(container->GetViewSafeAreaByType(Rosen::AvoidAreaType::TYPE_NAVIGATION_INDICATOR));
2051     }
2052 }
2053 
InitializeDisplayAvailableRect(const RefPtr<Platform::AceContainer>& container)2054 void UIContentImpl::InitializeDisplayAvailableRect(const RefPtr<Platform::AceContainer>& container)
2055 {
2056     auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
2057     auto& DMManager = Rosen::DisplayManager::GetInstance();
2058     availableAreaChangedListener_ = new AvailableAreaChangedListener(instanceId_);
2059     DMManager.RegisterAvailableAreaListener(availableAreaChangedListener_);
2060     Rosen::DMRect availableArea;
2061     auto defaultDisplay = DMManager.GetDefaultDisplay();
2062     if (pipeline && defaultDisplay) {
2063         Rosen::DMError ret = defaultDisplay->GetAvailableArea(availableArea);
2064         if (ret == Rosen::DMError::DM_OK) {
2065             pipeline->UpdateDisplayAvailableRect(ConvertDMRect2Rect(availableArea));
2066             TAG_LOGI(AceLogTag::ACE_WINDOW,
2067                 "InitializeDisplayAvailableRect : %{public}d, %{public}d, %{public}d, %{public}d", availableArea.posX_,
2068                 availableArea.posY_, availableArea.width_, availableArea.height_);
2069         }
2070     }
2071 }
2072 
InitDragSummaryMap(const RefPtr<Platform::AceContainer>& container)2073 void UIContentImpl::InitDragSummaryMap(const RefPtr<Platform::AceContainer>& container)
2074 {
2075     auto pipeline = container->GetPipelineContext();
2076     if (pipeline && container->IsUIExtensionWindow()) {
2077         pipeline->RequireSummary();
2078     }
2079 }
2080 
Foreground()2081 void UIContentImpl::Foreground()
2082 {
2083     LOGI("[%{public}s][%{public}s][%{public}d]: window foreground", bundleName_.c_str(), moduleName_.c_str(),
2084         instanceId_);
2085     if (window_ != nullptr && window_->GetType() == Rosen::WindowType::WINDOW_TYPE_APP_MAIN_WINDOW) {
2086         PerfMonitor::GetPerfMonitor()->SetAppStartStatus();
2087     }
2088     ContainerScope::UpdateRecentForeground(instanceId_);
2089     Platform::AceContainer::OnShow(instanceId_);
2090     // set the flag isForegroundCalled to be true
2091     auto container = Platform::AceContainer::GetContainer(instanceId_);
2092     CHECK_NULL_VOID(container);
2093     auto pipelineContext = container->GetPipelineContext();
2094     CHECK_NULL_VOID(pipelineContext);
2095     pipelineContext->SetForegroundCalled(true);
2096 
2097     CHECK_NULL_VOID(window_);
2098     std::string windowName = window_->GetWindowName();
2099     Recorder::EventRecorder::Get().SetContainerInfo(windowName, instanceId_, true);
2100 }
2101 
Background()2102 void UIContentImpl::Background()
2103 {
2104     LOGI("[%{public}s][%{public}s][%{public}d]: window background", bundleName_.c_str(), moduleName_.c_str(),
2105         instanceId_);
2106     Platform::AceContainer::OnHide(instanceId_);
2107 
2108     CHECK_NULL_VOID(window_);
2109     std::string windowName = window_->GetWindowName();
2110     Recorder::EventRecorder::Get().SetContainerInfo(windowName, instanceId_, false);
2111 }
2112 
ReloadForm(const std::string& url)2113 void UIContentImpl::ReloadForm(const std::string& url)
2114 {
2115     startUrl_ = url;
2116     LOGI("[%{public}s][%{public}s][%{public}d]: ReloadForm startUrl = %{public}s", bundleName_.c_str(),
2117         moduleName_.c_str(), instanceId_, startUrl_.c_str());
2118     auto container = Platform::AceContainer::GetContainer(instanceId_);
2119     CHECK_NULL_VOID(container);
2120     auto assetManager = AceType::DynamicCast<AssetManagerImpl>(container->GetAssetManager());
2121     assetManager->ReloadProvider();
2122     container->UpdateResource();
2123     Platform::AceContainer::RunPage(instanceId_, startUrl_, "");
2124 }
2125 
GetFormSerializedGesture()2126 SerializedGesture UIContentImpl::GetFormSerializedGesture()
2127 {
2128     auto container = Platform::AceContainer::GetContainer(instanceId_);
2129     CHECK_NULL_RETURN(container, SerializedGesture {});
2130     auto pipelineContext = container->GetPipelineContext();
2131     CHECK_NULL_RETURN(pipelineContext, SerializedGesture {});
2132     return pipelineContext->GetSerializedGesture();
2133 }
2134 
Focus()2135 void UIContentImpl::Focus()
2136 {
2137     LOGI("[%{public}s][%{public}s][%{public}d]: window focus", bundleName_.c_str(), moduleName_.c_str(), instanceId_);
2138     ContainerScope::UpdateRecentActive(instanceId_);
2139     Platform::AceContainer::OnActive(instanceId_);
2140     CHECK_NULL_VOID(window_);
2141     std::string windowName = window_->GetWindowName();
2142     Recorder::EventRecorder::Get().SetFocusContainerInfo(windowName, instanceId_);
2143     auto container = AceEngine::Get().GetContainer(instanceId_);
2144     CHECK_NULL_VOID(container);
2145     auto pipelineContext = container->GetPipelineContext();
2146     CHECK_NULL_VOID(pipelineContext);
2147 }
2148 
UnFocus()2149 void UIContentImpl::UnFocus()
2150 {
2151     LOGI("[%{public}s][%{public}s][%{public}d]: window unfocus", bundleName_.c_str(), moduleName_.c_str(), instanceId_);
2152     Platform::AceContainer::OnInactive(instanceId_);
2153     auto container = AceEngine::Get().GetContainer(instanceId_);
2154     CHECK_NULL_VOID(container);
2155     auto pipelineContext = container->GetPipelineContext();
2156     CHECK_NULL_VOID(pipelineContext);
2157 }
2158 
Destroy()2159 void UIContentImpl::Destroy()
2160 {
2161     LOGI("[%{public}s][%{public}s][%{public}d]: window destroy", bundleName_.c_str(), moduleName_.c_str(), instanceId_);
2162     auto container = AceEngine::Get().GetContainer(instanceId_);
2163     CHECK_NULL_VOID(container);
2164     // stop performance check and output json file
2165     AcePerformanceCheck::Stop();
2166     if (AceType::InstanceOf<Platform::DialogContainer>(container)) {
2167         Platform::DialogContainer::DestroyContainer(instanceId_);
2168     } else {
2169         Platform::AceContainer::DestroyContainer(instanceId_);
2170     }
2171     ContainerScope::RemoveAndCheck(instanceId_);
2172 }
2173 
OnNewWant(const OHOS::AAFwk::Want& want)2174 void UIContentImpl::OnNewWant(const OHOS::AAFwk::Want& want)
2175 {
2176     LOGI("[%{public}s][%{public}s][%{public}d]: UIContent OnNewWant", bundleName_.c_str(), moduleName_.c_str(),
2177         instanceId_);
2178     std::string params = want.GetStringParam(START_PARAMS_KEY);
2179     Platform::AceContainer::OnNewRequest(instanceId_, params);
2180 }
2181 
GetBackgroundColor()2182 uint32_t UIContentImpl::GetBackgroundColor()
2183 {
2184     auto container = Platform::AceContainer::GetContainer(instanceId_);
2185     CHECK_NULL_RETURN(container, 0x000000);
2186     auto taskExecutor = container->GetTaskExecutor();
2187     CHECK_NULL_RETURN(taskExecutor, 0x000000);
2188     ContainerScope scope(instanceId_);
2189     uint32_t bgColor = 0x000000;
2190     taskExecutor->PostSyncTask(
2191         [&bgColor, container]() {
2192             CHECK_NULL_VOID(container);
2193             auto pipelineContext = container->GetPipelineContext();
2194             CHECK_NULL_VOID(pipelineContext);
2195             bgColor = pipelineContext->GetAppBgColor().GetValue();
2196         },
2197         TaskExecutor::TaskType::UI, "ArkUIGetAppBackgroundColor");
2198 
2199     LOGD("[%{public}s][%{public}s][%{public}d]: GetBackgroundColor:%{public}u",
2200         bundleName_.c_str(), moduleName_.c_str(), instanceId_, bgColor);
2201     return bgColor;
2202 }
2203 
SetBackgroundColor(uint32_t color)2204 void UIContentImpl::SetBackgroundColor(uint32_t color)
2205 {
2206     LOGI("[%{public}s][%{public}s][%{public}d]: SetBackgroundColor:%{public}u",
2207         bundleName_.c_str(), moduleName_.c_str(), instanceId_, color);
2208     auto container = AceEngine::Get().GetContainer(instanceId_);
2209     CHECK_NULL_VOID(container);
2210     auto aceContainer = AceType::DynamicCast<Platform::AceContainer>(container);
2211     if (aceContainer) {
2212         aceContainer->SetIsUseCustomBg(true);
2213     }
2214     ContainerScope scope(instanceId_);
2215     auto taskExecutor = container->GetTaskExecutor();
2216     CHECK_NULL_VOID(taskExecutor);
2217     taskExecutor->PostSyncTask(
2218         [container, bgColor = color]() {
2219             auto pipelineContext = container->GetPipelineContext();
2220             CHECK_NULL_VOID(pipelineContext);
2221             pipelineContext->SetAppBgColor(Color(bgColor));
2222             pipelineContext->ChangeDarkModeBrightness();
2223         },
2224         TaskExecutor::TaskType::UI, "ArkUISetAppBackgroundColor");
2225 }
2226 
SetWindowContainerColor(uint32_t activeColor, uint32_t inactiveColor)2227 void UIContentImpl::SetWindowContainerColor(uint32_t activeColor, uint32_t inactiveColor)
2228 {
2229     TAG_LOGI(AceLogTag::ACE_APPBAR, "[%{public}s][%{public}s][%{public}d]: SetWindowContainerColor:"
2230         "active color %{public}u, inactive color %{public}u",
2231         bundleName_.c_str(), moduleName_.c_str(), instanceId_, activeColor, inactiveColor);
2232     auto container = AceEngine::Get().GetContainer(instanceId_);
2233     CHECK_NULL_VOID(container);
2234     ContainerScope scope(instanceId_);
2235     auto taskExecutor = container->GetTaskExecutor();
2236     CHECK_NULL_VOID(taskExecutor);
2237     taskExecutor->PostSyncTask(
2238         [container, activeColor, inactiveColor]() {
2239             auto pipelineContext = container->GetPipelineContext();
2240             CHECK_NULL_VOID(pipelineContext);
2241             pipelineContext->SetWindowContainerColor(Color(activeColor), Color(inactiveColor));
2242         },
2243         TaskExecutor::TaskType::UI, "ArkUISetWindowContainerColor");
2244 }
2245 
GetAppPaintSize(OHOS::Rosen::Rect& paintRect)2246 void UIContentImpl::GetAppPaintSize(OHOS::Rosen::Rect& paintRect)
2247 {
2248     auto container = AceEngine::Get().GetContainer(instanceId_);
2249     CHECK_NULL_VOID(container);
2250     ContainerScope scope(instanceId_);
2251     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
2252     CHECK_NULL_VOID(pipelineContext);
2253     auto stageManager = pipelineContext->GetStageManager();
2254     CHECK_NULL_VOID(stageManager);
2255     auto stageNode = stageManager->GetStageNode();
2256     CHECK_NULL_VOID(stageNode);
2257     auto renderContext = stageNode->GetRenderContext();
2258     CHECK_NULL_VOID(renderContext);
2259     auto rect = renderContext->GetPaintRectWithoutTransform();
2260     auto offset = stageNode->GetPaintRectOffset(false);
2261     paintRect.posX_ = static_cast<int32_t>(offset.GetX());
2262     paintRect.posY_ = static_cast<int32_t>(offset.GetY());
2263     paintRect.width_ = static_cast<uint32_t>(rect.Width());
2264     paintRect.height_ = static_cast<uint32_t>(rect.Height());
2265 }
2266 
GetWindowPaintSize(OHOS::Rosen::Rect& paintRect)2267 void UIContentImpl::GetWindowPaintSize(OHOS::Rosen::Rect& paintRect)
2268 {
2269     auto container = AceEngine::Get().GetContainer(instanceId_);
2270     CHECK_NULL_VOID(container);
2271     ContainerScope scope(instanceId_);
2272     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
2273     CHECK_NULL_VOID(pipelineContext);
2274     CHECK_NULL_VOID(window_);
2275     auto windowRect = window_->GetRect();
2276     NG::RectInt rect;
2277     rect.SetRect(0, 0, windowRect.width_, windowRect.height_);
2278     pipelineContext->GetWindowPaintRectWithoutMeasureAndLayout(rect);
2279     paintRect.posX_ = static_cast<int32_t>(rect.GetX());
2280     paintRect.posY_ = static_cast<int32_t>(rect.GetY());
2281     paintRect.width_ = static_cast<uint32_t>(rect.Width());
2282     paintRect.height_ = static_cast<uint32_t>(rect.Height());
2283 }
2284 
ProcessBackPressed()2285 bool UIContentImpl::ProcessBackPressed()
2286 {
2287     LOGI("[%{public}s][%{public}s][%{public}d]: OnBackPressed called", bundleName_.c_str(), moduleName_.c_str(),
2288         instanceId_);
2289     auto container = AceEngine::Get().GetContainer(instanceId_);
2290     CHECK_NULL_RETURN(container, false);
2291     if (container->IsUIExtensionWindow() && !container->WindowIsShow()) {
2292         return false;
2293     }
2294     auto taskExecutor = container->GetTaskExecutor();
2295     CHECK_NULL_RETURN(taskExecutor, false);
2296     auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
2297     if (pipeline) {
2298         auto uiExtMgr = pipeline->GetUIExtensionManager();
2299         if (uiExtMgr && uiExtMgr->OnBackPressed()) {
2300             LOGI("UIExtension consumed backpressed event");
2301             return true;
2302         }
2303     }
2304     bool ret = false;
2305     taskExecutor->PostSyncTask(
2306         [container, this, &ret]() {
2307             if (AceType::InstanceOf<Platform::DialogContainer>(container)) {
2308                 if (Platform::DialogContainer::OnBackPressed(instanceId_)) {
2309                     ret = true;
2310                 }
2311             } else {
2312                 PerfMonitor::GetPerfMonitor()->RecordInputEvent(LAST_UP, UNKNOWN_SOURCE, 0);
2313                 if (Platform::AceContainer::OnBackPressed(instanceId_)) {
2314                     ret = true;
2315                 }
2316             }
2317         },
2318         TaskExecutor::TaskType::UI, "ArkUIProcessBackPressed");
2319     return ret;
2320 }
2321 
ProcessPointerEvent(const std::shared_ptr<OHOS::MMI::PointerEvent>& pointerEvent)2322 bool UIContentImpl::ProcessPointerEvent(const std::shared_ptr<OHOS::MMI::PointerEvent>& pointerEvent)
2323 {
2324     auto container = AceType::DynamicCast<Platform::AceContainer>(AceEngine::Get().GetContainer(instanceId_));
2325     CHECK_NULL_RETURN(container, false);
2326     if (pointerEvent->GetPointerAction() != MMI::PointerEvent::POINTER_ACTION_MOVE) {
2327         TAG_LOGD(AceLogTag::ACE_INPUTTRACKING,
2328             "PointerEvent Process to ui_content, eventInfo: id:%{public}d, "
2329             "WindowName = %{public}s, WindowId = %{public}d, ViewWidth = %{public}d, ViewHeight = %{public}d, "
2330             "ViewPosX = %{public}d, ViewPosY = %{public}d",
2331             pointerEvent->GetId(), container->GetWindowName().c_str(), container->GetWindowId(),
2332             container->GetViewWidth(), container->GetViewHeight(), container->GetViewPosX(), container->GetViewPosY());
2333     }
2334     auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
2335     Platform::AceViewOhos::DispatchTouchEvent(aceView, pointerEvent);
2336     return true;
2337 }
2338 
ProcessPointerEventWithCallback( const std::shared_ptr<OHOS::MMI::PointerEvent>& pointerEvent, const std::function<void()>& callback)2339 bool UIContentImpl::ProcessPointerEventWithCallback(
2340     const std::shared_ptr<OHOS::MMI::PointerEvent>& pointerEvent, const std::function<void()>& callback)
2341 {
2342     auto container = AceType::DynamicCast<Platform::AceContainer>(AceEngine::Get().GetContainer(instanceId_));
2343     CHECK_NULL_RETURN(container, false);
2344     if (pointerEvent->GetPointerAction() != MMI::PointerEvent::POINTER_ACTION_MOVE) {
2345         TAG_LOGD(AceLogTag::ACE_INPUTTRACKING,
2346             "PointerEvent Process to ui_content, eventInfo: id:%{public}d, "
2347             "WindowName = %{public}s, WindowId = %{public}d, ViewWidth = %{public}d, ViewHeight = %{public}d, "
2348             "ViewPosX = %{public}d, ViewPosY = %{public}d",
2349             pointerEvent->GetId(), container->GetWindowName().c_str(), container->GetWindowId(),
2350             container->GetViewWidth(), container->GetViewHeight(), container->GetViewPosX(), container->GetViewPosY());
2351     }
2352     auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
2353     Platform::AceViewOhos::DispatchTouchEvent(aceView, pointerEvent, nullptr, callback);
2354     return true;
2355 }
2356 
ProcessKeyEvent(const std::shared_ptr<OHOS::MMI::KeyEvent>& touchEvent, bool isPreIme)2357 bool UIContentImpl::ProcessKeyEvent(const std::shared_ptr<OHOS::MMI::KeyEvent>& touchEvent, bool isPreIme)
2358 {
2359     TAG_LOGD(AceLogTag::ACE_INPUTTRACKING,
2360         "KeyEvent Process to ui_content, eventInfo: id:%{public}d, "
2361         "keyEvent info: keyCode is %{private}d, "
2362         "keyAction is %{public}d, keyActionTime is %{public}" PRId64,
2363         touchEvent->GetId(), touchEvent->GetKeyCode(), touchEvent->GetKeyAction(), touchEvent->GetActionTime());
2364     auto container = AceEngine::Get().GetContainer(instanceId_);
2365     CHECK_NULL_RETURN(container, false);
2366     auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
2367     return Platform::AceViewOhos::DispatchKeyEvent(aceView, touchEvent, isPreIme);
2368 }
2369 
ProcessAxisEvent(const std::shared_ptr<OHOS::MMI::AxisEvent>& axisEvent)2370 bool UIContentImpl::ProcessAxisEvent(const std::shared_ptr<OHOS::MMI::AxisEvent>& axisEvent)
2371 {
2372     return false;
2373 }
2374 
ProcessVsyncEvent(uint64_t timeStampNanos)2375 bool UIContentImpl::ProcessVsyncEvent(uint64_t timeStampNanos)
2376 {
2377     return false;
2378 }
2379 
UpdateConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)2380 void UIContentImpl::UpdateConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)
2381 {
2382     CHECK_NULL_VOID(config);
2383 
2384     auto dialogContainer = Platform::DialogContainer::GetContainer(instanceId_);
2385     if (dialogContainer) {
2386         UpdateDialogContainerConfig(config);
2387         return;
2388     }
2389 
2390     StoreConfiguration(config);
2391     auto container = Platform::AceContainer::GetContainer(instanceId_);
2392     CHECK_NULL_VOID(container);
2393     auto taskExecutor = container->GetTaskExecutor();
2394     CHECK_NULL_VOID(taskExecutor);
2395     bool formFontUseDefault = isFormRender_ && !fontScaleFollowSystem_;
2396     taskExecutor->PostTask(
2397         [weakContainer = WeakPtr<Platform::AceContainer>(container), config, instanceId = instanceId_,
2398             bundleName = bundleName_, moduleName = moduleName_, formFontUseDefault]() {
2399             auto container = weakContainer.Upgrade();
2400             CHECK_NULL_VOID(container);
2401             Platform::ParsedConfig parsedConfig;
2402             parsedConfig.colorMode = config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
2403             parsedConfig.deviceAccess = config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE);
2404             parsedConfig.direction = config->GetItem(OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DIRECTION);
2405             parsedConfig.densitydpi = config->GetItem(OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DENSITYDPI);
2406             parsedConfig.fontFamily = config->GetItem(OHOS::AppExecFwk::ConfigurationInner::APPLICATION_FONT);
2407             parsedConfig.themeTag = config->GetItem("ohos.application.theme");
2408             parsedConfig.colorModeIsSetByApp =
2409                 config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::COLORMODE_IS_SET_BY_APP);
2410             parsedConfig.mcc = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_MCC);
2411             parsedConfig.mnc = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_MNC);
2412             // Process system language and preferred language
2413             auto isPreferredLanguage = config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::IS_PREFERRED_LANGUAGE);
2414             if (isPreferredLanguage == IS_PREFERRED_LANGUAGE) {
2415                 parsedConfig.preferredLanguage =
2416                     config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE);
2417             } else {
2418                 parsedConfig.languageTag = config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE);
2419             }
2420             // EtsCard Font followSytem disable
2421             if (formFontUseDefault) {
2422                 parsedConfig.fontScale = "1.0";
2423             } else {
2424                 parsedConfig.fontScale = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_FONT_SIZE_SCALE);
2425             }
2426             parsedConfig.fontWeightScale =
2427                         config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_FONT_WEIGHT_SCALE);
2428             container->UpdateConfiguration(parsedConfig, config->GetName());
2429             LOGI("[%{public}d][%{public}s][%{public}s] UpdateConfiguration, name:%{public}s",
2430                 instanceId, bundleName.c_str(), moduleName.c_str(), config->GetName().c_str());
2431         },
2432         TaskExecutor::TaskType::UI, "ArkUIUIContentUpdateConfiguration");
2433 }
2434 
UpdateViewportConfig(const ViewportConfig& config, OHOS::Rosen::WindowSizeChangeReason reason, const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction, const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas)2435 void UIContentImpl::UpdateViewportConfig(const ViewportConfig& config, OHOS::Rosen::WindowSizeChangeReason reason,
2436     const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction,
2437     const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas)
2438 {
2439     if (SystemProperties::GetWindowRectResizeEnabled()) {
2440         PerfMonitor::GetPerfMonitor()->RecordWindowRectResize(static_cast<OHOS::Ace::WindowSizeChangeReason>(reason),
2441             bundleName_);
2442     }
2443     UpdateViewportConfigWithAnimation(config, reason, {}, rsTransaction, avoidAreas);
2444 }
2445 
UpdateViewportConfigWithAnimation(const ViewportConfig& config, OHOS::Rosen::WindowSizeChangeReason reason, AnimationOption animationOpt, const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction, const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas)2446 void UIContentImpl::UpdateViewportConfigWithAnimation(const ViewportConfig& config,
2447     OHOS::Rosen::WindowSizeChangeReason reason, AnimationOption animationOpt,
2448     const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction,
2449     const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas)
2450 {
2451     LOGI("[%{public}s][%{public}s][%{public}d]: UpdateViewportConfig %{public}s, windowSizeChangeReason %d",
2452         bundleName_.c_str(), moduleName_.c_str(), instanceId_, config.ToString().c_str(),
2453         static_cast<uint32_t>(reason));
2454     bool isOrientationChanged = static_cast<int32_t>(SystemProperties::GetDeviceOrientation()) != config.Orientation();
2455     SystemProperties::SetDeviceOrientation(config.Orientation());
2456     TAG_LOGI(
2457         AceLogTag::ACE_WINDOW, "Update orientation to : %{public}d", static_cast<uint32_t>(config.Orientation()));
2458     ContainerScope scope(instanceId_);
2459     auto container = Platform::AceContainer::GetContainer(instanceId_);
2460     CHECK_NULL_VOID(container);
2461     if (container->IsSubContainer()) {
2462         auto rect = NG::RectF(config.Left(), config.Top(), config.Width(), config.Height());
2463         SubwindowManager::GetInstance()->SetRect(rect, instanceId_);
2464         TAG_LOGI(AceLogTag::ACE_WINDOW, "UpdateViewportConfig for subContainer: %{public}s",
2465             rect.ToString().c_str());
2466     }
2467     // The density of sub windows related to dialog needs to be consistent with the main window.
2468     auto modifyConfig = config;
2469     if (instanceId_ >= MIN_SUBCONTAINER_ID) {
2470         auto parentContainer = Platform::AceContainer::GetContainer(container->GetParentId());
2471         CHECK_NULL_VOID(parentContainer);
2472         auto parentPipeline = parentContainer->GetPipelineContext();
2473         CHECK_NULL_VOID(parentPipeline);
2474         modifyConfig.SetDensity(parentPipeline->GetDensity());
2475     }
2476     auto taskExecutor = container->GetTaskExecutor();
2477     CHECK_NULL_VOID(taskExecutor);
2478     auto updateDensityTask = [container, modifyConfig]() {
2479         auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
2480         CHECK_NULL_VOID(aceView);
2481         Platform::AceViewOhos::SetViewportMetrics(aceView, modifyConfig); // update density into pipeline
2482     };
2483     auto updateDeviceOrientationTask = [container, modifyConfig, reason]() {
2484         if (reason == OHOS::Rosen::WindowSizeChangeReason::ROTATION) {
2485             container->UpdateResourceOrientation(modifyConfig.Orientation());
2486         }
2487     };
2488     if (taskExecutor->WillRunOnCurrentThread(TaskExecutor::TaskType::UI)) {
2489         updateDensityTask(); // ensure density has been updated before load first page
2490         updateDeviceOrientationTask();
2491     } else {
2492         taskExecutor->PostTask(std::move(updateDensityTask), TaskExecutor::TaskType::UI, "ArkUIUpdateDensity");
2493         taskExecutor->PostTask(
2494             std::move(updateDeviceOrientationTask), TaskExecutor::TaskType::UI, "ArkUIDeviceOrientation");
2495     }
2496     RefPtr<NG::SafeAreaManager> safeAreaManager = nullptr;
2497     auto pipelineContext = container->GetPipelineContext();
2498     auto context = AceType::DynamicCast<NG::PipelineContext>(pipelineContext);
2499     std::map<OHOS::Rosen::AvoidAreaType, NG::SafeAreaInsets> updatingInsets;
2500     if (context) {
2501         safeAreaManager = context->GetSafeAreaManager();
2502         context->FireSizeChangeByRotateCallback(isOrientationChanged, rsTransaction);
2503     }
2504 
2505     if (viewportConfigMgr_->IsConfigsEqual(config) && (rsTransaction == nullptr)) {
2506         taskExecutor->PostTask(
2507             [context, config, avoidAreas] {
2508                 if (avoidAreas.empty()) {
2509                     return;
2510                 }
2511                 if (ParseAvoidAreasUpdate(context, avoidAreas, config)) {
2512                     context->AnimateOnSafeAreaUpdate();
2513                 }
2514                 AvoidAreasUpdateOnUIExtension(context, avoidAreas);
2515             },
2516             TaskExecutor::TaskType::UI, "ArkUIUpdateOriginAvoidArea");
2517         return;
2518     }
2519 
2520     auto task = [config = modifyConfig, container, reason, rsTransaction, rsWindow = window_,
2521                     isDynamicRender = isDynamicRender_, animationOpt, avoidAreas]() {
2522         container->SetWindowPos(config.Left(), config.Top());
2523         auto pipelineContext = container->GetPipelineContext();
2524         if (pipelineContext) {
2525             auto uiExtensionFlushFinishCallback = [rsWindow]() {
2526                 CHECK_NULL_VOID(rsWindow);
2527                 rsWindow->NotifyExtensionEventAsync(0);
2528             };
2529             if (container->IsUIExtensionWindow()) {
2530                 pipelineContext->EnWaitFlushFinish();
2531                 pipelineContext->SetUIExtensionFlushFinishCallback(uiExtensionFlushFinishCallback);
2532             }
2533             UpdateSafeArea(pipelineContext, avoidAreas, config, container);
2534             pipelineContext->SetDisplayWindowRectInfo(
2535                 Rect(Offset(config.Left(), config.Top()), Size(config.Width(), config.Height())));
2536             TAG_LOGI(AceLogTag::ACE_WINDOW, "Update displayAvailableRect in UpdateViewportConfig to : %{public}s",
2537                 pipelineContext->GetDisplayWindowRectInfo().ToString().c_str());
2538             if (rsWindow) {
2539                 pipelineContext->SetIsLayoutFullScreen(
2540                     rsWindow->GetMode() == Rosen::WindowMode::WINDOW_MODE_FULLSCREEN);
2541                 auto isNeedAvoidWindowMode = IsNeedAvoidWindowMode(rsWindow);
2542                 pipelineContext->SetIsNeedAvoidWindow(isNeedAvoidWindowMode);
2543             }
2544             if (reason == OHOS::Rosen::WindowSizeChangeReason::ROTATION) {
2545                 pipelineContext->FlushBuild();
2546                 pipelineContext->StartWindowAnimation();
2547                 container->NotifyDirectionUpdate();
2548             }
2549         }
2550         auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
2551         CHECK_NULL_VOID(aceView);
2552         Platform::AceViewOhos::TransformHintChanged(aceView, config.TransformHint());
2553         if (isDynamicRender && animationOpt.IsValid()) {
2554             AnimationUtils::Animate(animationOpt, [pipelineContext, aceView, config, reason, rsTransaction] {
2555                 ContainerScope scope(aceView->GetInstanceId());
2556                 Platform::AceViewOhos::SurfaceChanged(aceView, config.Width(), config.Height(), config.Orientation(),
2557                     static_cast<WindowSizeChangeReason>(reason), rsTransaction);
2558                 pipelineContext->OnSurfaceChanged(
2559                     config.Width(), config.Height(), static_cast<WindowSizeChangeReason>(reason), rsTransaction);
2560                 pipelineContext->FlushUITasks(true);
2561             });
2562         } else {
2563             Platform::AceViewOhos::SurfaceChanged(aceView, config.Width(), config.Height(), config.Orientation(),
2564                 static_cast<WindowSizeChangeReason>(reason), rsTransaction);
2565         }
2566         Platform::AceViewOhos::SurfacePositionChanged(aceView, config.Left(), config.Top());
2567         SubwindowManager::GetInstance()->OnWindowSizeChanged(container->GetInstanceId(),
2568             Rect(Offset(config.Left(), config.Top()), Size(config.Width(), config.Height())),
2569             static_cast<WindowSizeChangeReason>(reason));
2570     };
2571     auto changeBrightnessTask = [container]() {
2572         auto pipelineContext = container->GetPipelineContext();
2573         if (pipelineContext) {
2574             pipelineContext->ChangeDarkModeBrightness();
2575         }
2576     };
2577     taskExecutor->PostTask(std::move(changeBrightnessTask), TaskExecutor::TaskType::UI, "ArkUIUpdateBrightness");
2578     AceViewportConfig aceViewportConfig(modifyConfig, reason, rsTransaction);
2579     bool isReasonRotationOrDPI = (reason == OHOS::Rosen::WindowSizeChangeReason::ROTATION ||
2580         reason == OHOS::Rosen::WindowSizeChangeReason::UPDATE_DPI_SYNC);
2581     if (container->IsUseStageModel() && isReasonRotationOrDPI) {
2582         viewportConfigMgr_->UpdateConfigSync(aceViewportConfig, std::move(task));
2583     } else if (rsTransaction != nullptr || !avoidAreas.empty()) {
2584         // When rsTransaction is not nullptr, the task contains animation. It shouldn't be cancled.
2585         // When avoidAreas need updating, the task shouldn't be cancelled.
2586         viewportConfigMgr_->UpdatePromiseConfig(aceViewportConfig, std::move(task), container,
2587             "ArkUIPromiseViewportConfig");
2588     } else {
2589         viewportConfigMgr_->UpdateConfig(aceViewportConfig, std::move(task), container, "ArkUIUpdateViewportConfig");
2590     }
2591     viewportConfigMgr_->StoreConfig(aceViewportConfig);
2592     UIExtensionUpdateViewportConfig(config);
2593 }
2594 
UIExtensionUpdateViewportConfig(const ViewportConfig& config)2595 void UIContentImpl::UIExtensionUpdateViewportConfig(const ViewportConfig& config)
2596 {
2597     auto container = Platform::AceContainer::GetContainer(instanceId_);
2598     CHECK_NULL_VOID(container);
2599     auto taskExecutor = container->GetTaskExecutor();
2600     CHECK_NULL_VOID(taskExecutor);
2601     auto context = NG::PipelineContext::GetCurrentContext();
2602     CHECK_NULL_VOID(context);
2603     auto updateSessionViewportConfigTask = [id = instanceId_, config]() {
2604         ContainerScope scope(id);
2605         auto context = NG::PipelineContext::GetCurrentContext();
2606         CHECK_NULL_VOID(context);
2607         auto uiExtMgr = context->GetUIExtensionManager();
2608         if (uiExtMgr) {
2609             uiExtMgr->UpdateSessionViewportConfig(config);
2610         }
2611     };
2612     taskExecutor->PostTask(
2613         std::move(updateSessionViewportConfigTask), TaskExecutor::TaskType::UI, "ArkUIUpdateSessionViewportConfig");
2614 }
2615 
SetIgnoreViewSafeArea(bool ignoreViewSafeArea)2616 void UIContentImpl::SetIgnoreViewSafeArea(bool ignoreViewSafeArea)
2617 {
2618     TAG_LOGI(ACE_LAYOUT, "[%{public}s][%{public}s][%{public}d]: SetIgnoreViewSafeArea:%{public}u",
2619         bundleName_.c_str(), moduleName_.c_str(), instanceId_, ignoreViewSafeArea);
2620     auto container = AceEngine::Get().GetContainer(instanceId_);
2621     CHECK_NULL_VOID(container);
2622     ContainerScope scope(instanceId_);
2623     auto pipeline = container->GetPipelineContext();
2624     const static int32_t PLATFORM_VERSION_TEN = 10;
2625     CHECK_NULL_VOID(
2626         pipeline && pipeline->GetMinPlatformVersion() >= PLATFORM_VERSION_TEN && pipeline->GetIsAppWindow());
2627     auto taskExecutor = container->GetTaskExecutor();
2628     CHECK_NULL_VOID(taskExecutor);
2629     taskExecutor->PostSyncTask(
2630         [container, ignoreSafeArea = ignoreViewSafeArea]() {
2631             auto pipelineContext = container->GetPipelineContext();
2632             CHECK_NULL_VOID(pipelineContext);
2633             pipelineContext->SetIgnoreViewSafeArea(ignoreSafeArea);
2634         },
2635         TaskExecutor::TaskType::UI, "ArkUISetIgnoreViewSafeArea");
2636 }
2637 
UpdateWindowMode(OHOS::Rosen::WindowMode mode, bool hasDeco)2638 void UIContentImpl::UpdateWindowMode(OHOS::Rosen::WindowMode mode, bool hasDeco)
2639 {
2640     LOGI("[%{public}s][%{public}s][%{public}d]: UpdateWindowMode: %{public}d, hasDeco: %{public}d",
2641         bundleName_.c_str(), moduleName_.c_str(), instanceId_, mode, hasDeco);
2642     UpdateDecorVisible(mode == OHOS::Rosen::WindowMode::WINDOW_MODE_FLOATING, hasDeco);
2643 }
2644 
UpdateDecorVisible(bool visible, bool hasDeco)2645 void UIContentImpl::UpdateDecorVisible(bool visible, bool hasDeco)
2646 {
2647     LOGI("[%{public}s][%{public}s][%{public}d]: UpdateWindowVisible: %{public}d, hasDeco: %{public}d",
2648         bundleName_.c_str(), moduleName_.c_str(), instanceId_, visible, hasDeco);
2649     auto container = Platform::AceContainer::GetContainer(instanceId_);
2650     CHECK_NULL_VOID(container);
2651     ContainerScope scope(instanceId_);
2652     auto taskExecutor = Container::CurrentTaskExecutor();
2653     CHECK_NULL_VOID(taskExecutor);
2654     auto task = [container, visible, hasDeco]() {
2655         auto pipelineContext = container->GetPipelineContext();
2656         CHECK_NULL_VOID(pipelineContext);
2657         pipelineContext->ShowContainerTitle(visible, hasDeco);
2658         pipelineContext->ChangeDarkModeBrightness();
2659     };
2660 
2661     // Cancel the pending task
2662     updateDecorVisibleTask_.Cancel();
2663     auto uiTaskRunner = SingleTaskExecutor::Make(taskExecutor, TaskExecutor::TaskType::UI);
2664     if (uiTaskRunner.IsRunOnCurrentThread()) {
2665         task();
2666     } else {
2667         updateDecorVisibleTask_ = SingleTaskExecutor::CancelableTask(std::move(task));
2668         taskExecutor->PostTask(updateDecorVisibleTask_,
2669             TaskExecutor::TaskType::UI, "ArkUIUpdateDecorVisible");
2670     }
2671 }
2672 
SetUIContentType(UIContentType uIContentType)2673 void UIContentImpl::SetUIContentType(UIContentType uIContentType)
2674 {
2675     uIContentType_ = uIContentType;
2676     auto container = Platform::AceContainer::GetContainer(instanceId_);
2677     CHECK_NULL_VOID(container);
2678     container->SetUIContentType(uIContentType);
2679 }
2680 
UpdateMaximizeMode(OHOS::Rosen::MaximizeMode mode)2681 void UIContentImpl::UpdateMaximizeMode(OHOS::Rosen::MaximizeMode mode)
2682 {
2683     LOGI("[%{public}s][%{public}s][%{public}d]: UpdateMaximizeMode: %{public}d", bundleName_.c_str(),
2684         moduleName_.c_str(), instanceId_, mode);
2685     auto container = Platform::AceContainer::GetContainer(instanceId_);
2686     CHECK_NULL_VOID(container);
2687     ContainerScope scope(instanceId_);
2688     auto taskExecutor = container->GetTaskExecutor();
2689     CHECK_NULL_VOID(taskExecutor);
2690     auto task = [container, mode]() {
2691         auto pipelineContext = container->GetPipelineContext();
2692         CHECK_NULL_VOID(pipelineContext);
2693         auto windowManager = pipelineContext->GetWindowManager();
2694         CHECK_NULL_VOID(windowManager);
2695         windowManager->SetCurrentWindowMaximizeMode(static_cast<OHOS::Ace::MaximizeMode>(mode));
2696         pipelineContext->ShowContainerTitle(true, true, true);
2697     };
2698     auto uiTaskRunner = SingleTaskExecutor::Make(taskExecutor, TaskExecutor::TaskType::UI);
2699     if (uiTaskRunner.IsRunOnCurrentThread()) {
2700         task();
2701     } else {
2702         taskExecutor->PostTask(std::move(task), TaskExecutor::TaskType::UI, "ArkUIUpdateMaximizeMode");
2703     }
2704 }
2705 
NeedSoftKeyboard()2706 bool UIContentImpl::NeedSoftKeyboard()
2707 {
2708     auto container = AceEngine::Get().GetContainer(instanceId_);
2709     CHECK_NULL_RETURN(container, false);
2710     auto pipeline = container->GetPipelineContext();
2711     CHECK_NULL_RETURN(pipeline, false);
2712     return pipeline->NeedSoftKeyboard();
2713 }
2714 
SetOnWindowFocused(const std::function<void()>& callback)2715 void UIContentImpl::SetOnWindowFocused(const std::function<void()>& callback)
2716 {
2717     auto container = AceEngine::Get().GetContainer(instanceId_);
2718     CHECK_NULL_VOID(container);
2719     auto pipeline = container->GetPipelineContext();
2720     CHECK_NULL_VOID(pipeline);
2721     pipeline->SetOnWindowFocused(callback);
2722 }
2723 
HideWindowTitleButton(bool hideSplit, bool hideMaximize, bool hideMinimize, bool hideClose)2724 void UIContentImpl::HideWindowTitleButton(bool hideSplit, bool hideMaximize, bool hideMinimize, bool hideClose)
2725 {
2726     LOGI("[%{public}s][%{public}s][%{public}d]: HideWindowTitleButton hideSplit: %{public}d, hideMaximize: %{public}d, "
2727         "hideMinimize: %{public}d, hideClose: %{public}d",
2728         bundleName_.c_str(), moduleName_.c_str(), instanceId_, hideSplit, hideMaximize, hideMinimize, hideClose);
2729     auto container = Platform::AceContainer::GetContainer(instanceId_);
2730     CHECK_NULL_VOID(container);
2731     ContainerScope scope(instanceId_);
2732     auto taskExecutor = Container::CurrentTaskExecutor();
2733     CHECK_NULL_VOID(taskExecutor);
2734     taskExecutor->PostTask(
2735         [container, hideSplit, hideMaximize, hideMinimize, hideClose]() {
2736             auto pipelineContext = container->GetPipelineContext();
2737             CHECK_NULL_VOID(pipelineContext);
2738             pipelineContext->SetContainerButtonHide(hideSplit, hideMaximize, hideMinimize, hideClose);
2739         },
2740         TaskExecutor::TaskType::UI, "ArkUIHideWindowTitleButton");
2741 }
2742 
UpdateTitleInTargetPos(bool isShow, int32_t height)2743 void UIContentImpl::UpdateTitleInTargetPos(bool isShow, int32_t height)
2744 {
2745     LOGI("[%{public}s][%{public}s][%{public}d]: UpdateTitleInTargetPos, isShow: %{public}d, height: "
2746          "%{public}d",
2747         bundleName_.c_str(), moduleName_.c_str(), instanceId_, isShow, height);
2748     auto container = Platform::AceContainer::GetContainer(instanceId_);
2749     CHECK_NULL_VOID(container);
2750     ContainerScope scope(instanceId_);
2751     auto taskExecutor = Container::CurrentTaskExecutor();
2752     CHECK_NULL_VOID(taskExecutor);
2753     taskExecutor->PostTask(
2754         [container, isShow, height]() {
2755             auto pipelineContext = container->GetPipelineContext();
2756             CHECK_NULL_VOID(pipelineContext);
2757             pipelineContext->UpdateTitleInTargetPos(isShow, height);
2758         },
2759         TaskExecutor::TaskType::UI, "ArkUIUpdateTitleInTargetPos");
2760 }
2761 
NotifyRotationAnimationEnd()2762 void UIContentImpl::NotifyRotationAnimationEnd()
2763 {
2764     auto container = Platform::AceContainer::GetContainer(instanceId_);
2765     CHECK_NULL_VOID(container);
2766     ContainerScope scope(instanceId_);
2767     auto taskExecutor = Container::CurrentTaskExecutor();
2768     CHECK_NULL_VOID(taskExecutor);
2769     taskExecutor->PostTask(
2770         [container]() {
2771             auto pipelineContext = container->GetPipelineContext();
2772             if (pipelineContext) {
2773                 pipelineContext->StopWindowAnimation();
2774             }
2775         },
2776         TaskExecutor::TaskType::UI, "ArkUINotifyRotationAnimationEnd");
2777 }
2778 
DumpInfo(const std::vector<std::string>& params, std::vector<std::string>& info)2779 void UIContentImpl::DumpInfo(const std::vector<std::string>& params, std::vector<std::string>& info)
2780 {
2781     std::string currentPid = std::to_string(getpid());
2782     for (auto param : params) {
2783         if (param == currentPid) {
2784             LOGE("DumpInfo pid has appeared");
2785             return;
2786         }
2787     }
2788     auto container = Platform::AceContainer::GetContainer(instanceId_);
2789     CHECK_NULL_VOID(container);
2790     auto taskExecutor = container->GetTaskExecutor();
2791     CHECK_NULL_VOID(taskExecutor);
2792     auto ret = taskExecutor->PostSyncTaskTimeout(
2793         [&]() { container->Dump(params, info); }, TaskExecutor::TaskType::UI, 1500, "ArkUIDumpInfo"); // timeout 1.5s
2794     if (!ret) {
2795         LOGE("DumpInfo failed");
2796     }
2797 }
2798 
UpdateDialogResourceConfiguration(RefPtr<Container>& container, const std::shared_ptr<OHOS::AbilityRuntime::Context>& context)2799 void UIContentImpl::UpdateDialogResourceConfiguration(RefPtr<Container>& container,
2800     const std::shared_ptr<OHOS::AbilityRuntime::Context>& context)
2801 {
2802     auto dialogContainer = AceType::DynamicCast<Platform::DialogContainer>(container);
2803     if (dialogContainer) {
2804         std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
2805         CHECK_NULL_VOID(context);
2806         auto resourceManager = context->GetResourceManager();
2807         if (resourceManager != nullptr) {
2808             resourceManager->GetResConfig(*resConfig);
2809             if (resConfig->GetColorMode() == OHOS::Global::Resource::ColorMode::DARK) {
2810                 SystemProperties::SetColorMode(ColorMode::DARK);
2811             } else {
2812                 SystemProperties::SetColorMode(ColorMode::LIGHT);
2813             }
2814         }
2815         auto aceResCfg = dialogContainer->GetResourceConfiguration();
2816         aceResCfg.SetOrientation(SystemProperties::GetDeviceOrientation());
2817         aceResCfg.SetDensity(SystemProperties::GetResolution());
2818         aceResCfg.SetDeviceType(SystemProperties::GetDeviceType());
2819         aceResCfg.SetColorMode(SystemProperties::GetColorMode());
2820         aceResCfg.SetDeviceAccess(SystemProperties::GetDeviceAccess());
2821         aceResCfg.SetColorModeIsSetByApp(true);
2822         dialogContainer->SetResourceConfiguration(aceResCfg);
2823     }
2824 }
2825 
InitializeSubWindow(OHOS::Rosen::Window* window, bool isDialog)2826 void UIContentImpl::InitializeSubWindow(OHOS::Rosen::Window* window, bool isDialog)
2827 {
2828     window_ = window;
2829     LOGI("InitSubwindow: %{public}s", window->GetWindowName().c_str());
2830     CHECK_NULL_VOID(window_);
2831     RefPtr<Container> container;
2832     instanceId_ = Container::GenerateId<COMPONENT_SUBWINDOW_CONTAINER>();
2833     int32_t deviceWidth = 0;
2834     int32_t deviceHeight = 0;
2835     float density = 1.0f;
2836     auto defaultDisplay = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
2837     if (defaultDisplay) {
2838         auto displayInfo = defaultDisplay->GetDisplayInfo();
2839         if (displayInfo) {
2840             density = displayInfo->GetDensityInCurResolution();
2841         }
2842         deviceWidth = defaultDisplay->GetWidth();
2843         deviceHeight = defaultDisplay->GetHeight();
2844     }
2845     SystemProperties::InitDeviceInfo(deviceWidth, deviceHeight, deviceHeight >= deviceWidth ? 0 : 1, density, false);
2846     std::weak_ptr<OHOS::AppExecFwk::AbilityInfo> abilityInfo;
2847     auto context = context_.lock();
2848     bool isCJFrontend = CJUtils::IsCJFrontendContext(context.get());
2849     auto frontendType = isCJFrontend ? FrontendType::DECLARATIVE_CJ : FrontendType::DECLARATIVE_JS;
2850     if (isDialog) {
2851         UErrorCode status = U_ZERO_ERROR;
2852         icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status);
2853         AceApplicationInfo::GetInstance().SetLocale(locale.getLanguage(), locale.getCountry(), locale.getScript(), "");
2854         container = AceType::MakeRefPtr<Platform::DialogContainer>(instanceId_, FrontendType::DECLARATIVE_JS);
2855         UpdateDialogResourceConfiguration(container, context);
2856     } else {
2857 #ifdef NG_BUILD
2858         container = AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, frontendType,
2859             context, abilityInfo, std::make_unique<ContentEventCallback>([] {
2860                 // Sub-window ,just return.
2861             }), false, true, true);
2862 #else
2863         if (Container::IsCurrentUseNewPipeline()) {
2864             container = AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, frontendType,
2865                 context, abilityInfo, std::make_unique<ContentEventCallback>([] {
2866                     // Sub-window ,just return.
2867                 }), false, true, true);
2868         } else {
2869             container = AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, frontendType,
2870                 context, abilityInfo, std::make_unique<ContentEventCallback>([] {
2871                     // Sub-window ,just return.
2872                 }), false, true);
2873         }
2874 #endif
2875     }
2876     if (context) {
2877         if (context->GetApplicationInfo()) {
2878             auto appInfo = context->GetApplicationInfo();
2879             container->SetApiTargetVersion(appInfo->apiTargetVersion);
2880         }
2881 
2882         container->SetBundlePath(context->GetBundleCodeDir());
2883         container->SetFilesDataPath(context->GetFilesDir());
2884     } else {
2885         // if window don't have context,like service eject a toast,find target version in bundle.
2886         auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2887         CHECK_NULL_VOID(systemAbilityMgr);
2888         auto bundleObj = systemAbilityMgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
2889         CHECK_NULL_VOID(bundleObj);
2890         auto bundleMgrProxy = iface_cast<AppExecFwk::IBundleMgr>(bundleObj);
2891         CHECK_NULL_VOID(bundleMgrProxy);
2892         AppExecFwk::BundleInfo bundleInfo;
2893         bundleMgrProxy->GetBundleInfoForSelf(
2894             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE), bundleInfo);
2895         container->SetApiTargetVersion(bundleInfo.targetVersion % 1000);
2896     }
2897     SubwindowManager::GetInstance()->AddContainerId(window->GetWindowId(), instanceId_);
2898     AceEngine::Get().AddContainer(instanceId_, container);
2899     if (!StringUtils::StartWith(window_->GetWindowName(), SUBWINDOW_TOAST_PREFIX)) {
2900         touchOutsideListener_ = new TouchOutsideListener(instanceId_);
2901         window_->RegisterTouchOutsideListener(touchOutsideListener_);
2902     }
2903     dragWindowListener_ = new DragWindowListener(instanceId_);
2904     window_->RegisterDragListener(dragWindowListener_);
2905     occupiedAreaChangeListener_ = new OccupiedAreaChangeListener(instanceId_);
2906     window_->RegisterOccupiedAreaChangeListener(occupiedAreaChangeListener_);
2907     foldStatusListener_ = new FoldScreenListener(instanceId_);
2908     OHOS::Rosen::DisplayManager::GetInstance().RegisterFoldStatusListener(foldStatusListener_);
2909     foldDisplayModeListener_ = new FoldDisplayModeListener(instanceId_, isDialog);
2910     OHOS::Rosen::DisplayManager::GetInstance().RegisterDisplayModeListener(foldDisplayModeListener_);
2911 }
2912 
SetNextFrameLayoutCallback(std::function<void()>&& callback)2913 void UIContentImpl::SetNextFrameLayoutCallback(std::function<void()>&& callback)
2914 {
2915     CHECK_NULL_VOID(callback);
2916     auto container = Platform::AceContainer::GetContainer(instanceId_);
2917     CHECK_NULL_VOID(container);
2918     auto pipelineContext = container->GetPipelineContext();
2919     CHECK_NULL_VOID(pipelineContext);
2920     pipelineContext->SetNextFrameLayoutCallback(std::move(callback));
2921 }
2922 
SetFrameLayoutFinishCallback(std::function<void()>&& callback)2923 void UIContentImpl::SetFrameLayoutFinishCallback(std::function<void()>&& callback)
2924 {
2925     CHECK_NULL_VOID(callback);
2926     auto container = Platform::AceContainer::GetContainer(instanceId_);
2927     CHECK_NULL_VOID(container);
2928     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
2929     CHECK_NULL_VOID(pipelineContext);
2930     pipelineContext->AddPersistAfterLayoutTask(std::move(callback));
2931     LOGI("[%{public}s][%{public}s][%{public}d]: SetFrameLayoutFinishCallback", bundleName_.c_str(),
2932         moduleName_.c_str(), instanceId_);
2933 }
2934 
SetLastestFrameLayoutFinishCallback(std::function<void()>&& callback)2935 void UIContentImpl::SetLastestFrameLayoutFinishCallback(std::function<void()>&& callback)
2936 {
2937     CHECK_NULL_VOID(callback);
2938     auto container = Platform::AceContainer::GetContainer(instanceId_);
2939     CHECK_NULL_VOID(container);
2940     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
2941     CHECK_NULL_VOID(pipelineContext);
2942     pipelineContext->AddLastestFrameLayoutFinishTask(std::move(callback));
2943     LOGI("[%{public}s][%{public}s][%{public}d]: SetLastestFrameLayoutFinishCallback", bundleName_.c_str(),
2944         moduleName_.c_str(), instanceId_);
2945 }
2946 
NotifyMemoryLevel(int32_t level)2947 void UIContentImpl::NotifyMemoryLevel(int32_t level)
2948 {
2949     LOGI("[%{public}s][%{public}s][%{public}d]: NotifyMemoryLevel: %{public}d",
2950         bundleName_.c_str(), moduleName_.c_str(), instanceId_, level);
2951     auto container = Platform::AceContainer::GetContainer(instanceId_);
2952     CHECK_NULL_VOID(container);
2953     auto pipelineContext = container->GetPipelineContext();
2954     CHECK_NULL_VOID(pipelineContext);
2955     ContainerScope scope(instanceId_);
2956     pipelineContext->NotifyMemoryLevel(level);
2957 }
2958 
SetAppWindowTitle(const std::string& title)2959 void UIContentImpl::SetAppWindowTitle(const std::string& title)
2960 {
2961     auto container = Platform::AceContainer::GetContainer(instanceId_);
2962     CHECK_NULL_VOID(container);
2963     auto pipelineContext = container->GetPipelineContext();
2964     CHECK_NULL_VOID(pipelineContext);
2965     ContainerScope scope(instanceId_);
2966     LOGI("[%{public}s][%{public}s][%{public}d]: setAppTitle", bundleName_.c_str(), moduleName_.c_str(), instanceId_);
2967     pipelineContext->SetAppTitle(title);
2968 }
2969 
SetAppWindowIcon(const std::shared_ptr<Media::PixelMap>& pixelMap)2970 void UIContentImpl::SetAppWindowIcon(const std::shared_ptr<Media::PixelMap>& pixelMap)
2971 {
2972     auto container = Platform::AceContainer::GetContainer(instanceId_);
2973     CHECK_NULL_VOID(container);
2974     auto pipelineContext = container->GetPipelineContext();
2975     CHECK_NULL_VOID(pipelineContext);
2976     ContainerScope scope(instanceId_);
2977     LOGI("[%{public}s][%{public}s][%{public}d]: setAppIcon", bundleName_.c_str(), moduleName_.c_str(), instanceId_);
2978     pipelineContext->SetAppIcon(AceType::MakeRefPtr<PixelMapOhos>(pixelMap));
2979 }
2980 
UpdateFormData(const std::string& data)2981 void UIContentImpl::UpdateFormData(const std::string& data)
2982 {
2983     if (isFormRenderInit_) {
2984         auto container = Platform::AceContainer::GetContainer(instanceId_);
2985         CHECK_NULL_VOID(container);
2986         container->UpdateFormData(data);
2987     } else {
2988         formData_ = data;
2989     }
2990 }
2991 
UpdateFormSharedImage(const std::map<std::string, sptr<OHOS::AppExecFwk::FormAshmem>>& imageDataMap)2992 void UIContentImpl::UpdateFormSharedImage(const std::map<std::string, sptr<OHOS::AppExecFwk::FormAshmem>>& imageDataMap)
2993 {
2994     if (isFormRenderInit_) {
2995         auto container = Platform::AceContainer::GetContainer(instanceId_);
2996         CHECK_NULL_VOID(container);
2997         container->UpdateFormSharedImage(imageDataMap);
2998     } else {
2999         formImageDataMap_ = imageDataMap;
3000     }
3001 }
3002 
SetActionEventHandler(std::function<void(const std::string& action)>&& actionCallback)3003 void UIContentImpl::SetActionEventHandler(std::function<void(const std::string& action)>&& actionCallback)
3004 {
3005     CHECK_NULL_VOID(actionCallback);
3006     auto container = Platform::AceContainer::GetContainer(instanceId_);
3007     CHECK_NULL_VOID(container);
3008     auto pipelineContext = container->GetPipelineContext();
3009     CHECK_NULL_VOID(pipelineContext);
3010     pipelineContext->SetActionEventHandler(std::move(actionCallback));
3011 }
3012 
SetFormLinkInfoUpdateHandler(std::function<void(const std::vector<std::string>&)>&& callback)3013 void UIContentImpl::SetFormLinkInfoUpdateHandler(std::function<void(const std::vector<std::string>&)>&& callback)
3014 {
3015     CHECK_NULL_VOID(callback);
3016     auto container = Platform::AceContainer::GetContainer(instanceId_);
3017     CHECK_NULL_VOID(container);
3018     auto pipelineContext = container->GetPipelineContext();
3019     CHECK_NULL_VOID(pipelineContext);
3020     pipelineContext->SetFormLinkInfoUpdateHandler(std::move(callback));
3021 }
3022 
RegisterAccessibilityChildTree( uint32_t parentWindowId, int32_t parentTreeId, int64_t parentElementId)3023 void UIContentImpl::RegisterAccessibilityChildTree(
3024     uint32_t parentWindowId, int32_t parentTreeId, int64_t parentElementId)
3025 {
3026     auto container = Platform::AceContainer::GetContainer(instanceId_);
3027     CHECK_NULL_VOID(container);
3028     auto front = container->GetFrontend();
3029     CHECK_NULL_VOID(front);
3030     auto accessibilityManager = front->GetAccessibilityManager();
3031     CHECK_NULL_VOID(accessibilityManager);
3032     accessibilityManager->RegisterInteractionOperationAsChildTree(parentWindowId, parentTreeId, parentElementId);
3033 }
3034 
SetAccessibilityGetParentRectHandler(std::function<void(int32_t&, int32_t&)>&& callback)3035 void UIContentImpl::SetAccessibilityGetParentRectHandler(std::function<void(int32_t&, int32_t&)>&& callback)
3036 {
3037     auto container = Platform::AceContainer::GetContainer(instanceId_);
3038     CHECK_NULL_VOID(container);
3039     auto front = container->GetFrontend();
3040     CHECK_NULL_VOID(front);
3041     auto accessibilityManager = front->GetAccessibilityManager();
3042     CHECK_NULL_VOID(accessibilityManager);
3043     accessibilityManager->SetAccessibilityGetParentRectHandler(std::move(callback));
3044 }
3045 
SetAccessibilityGetParentRectHandler( std::function<void(AccessibilityParentRectInfo&)>&& callback)3046 void UIContentImpl::SetAccessibilityGetParentRectHandler(
3047     std::function<void(AccessibilityParentRectInfo&)>&& callback)
3048 {
3049     auto container = Platform::AceContainer::GetContainer(instanceId_);
3050     CHECK_NULL_VOID(container);
3051     auto front = container->GetFrontend();
3052     CHECK_NULL_VOID(front);
3053     auto accessibilityManager = front->GetAccessibilityManager();
3054     CHECK_NULL_VOID(accessibilityManager);
3055     accessibilityManager->SetAccessibilityGetParentRectHandler(std::move(callback));
3056 }
3057 
DeregisterAccessibilityChildTree()3058 void UIContentImpl::DeregisterAccessibilityChildTree()
3059 {
3060     auto container = Platform::AceContainer::GetContainer(instanceId_);
3061     CHECK_NULL_VOID(container);
3062     auto front = container->GetFrontend();
3063     CHECK_NULL_VOID(front);
3064     auto accessibilityManager = front->GetAccessibilityManager();
3065     CHECK_NULL_VOID(accessibilityManager);
3066     accessibilityManager->DeregisterInteractionOperationAsChildTree();
3067 }
3068 
AccessibilityDumpChildInfo(const std::vector<std::string>& params, std::vector<std::string>& info)3069 void UIContentImpl::AccessibilityDumpChildInfo(const std::vector<std::string>& params, std::vector<std::string>& info)
3070 {
3071     auto container = Platform::AceContainer::GetContainer(instanceId_);
3072     CHECK_NULL_VOID(container);
3073     container->Dump(params, info);
3074 }
3075 
SetErrorEventHandler(std::function<void(const std::string&, const std::string&)>&& errorCallback)3076 void UIContentImpl::SetErrorEventHandler(std::function<void(const std::string&, const std::string&)>&& errorCallback)
3077 {
3078     CHECK_NULL_VOID(errorCallback);
3079     auto container = Platform::AceContainer::GetContainer(instanceId_);
3080     CHECK_NULL_VOID(container);
3081     auto front = container->GetFrontend();
3082     CHECK_NULL_VOID(front);
3083     return front->SetErrorEventHandler(std::move(errorCallback));
3084 }
3085 
OnFormSurfaceChange(float width, float height, OHOS::Rosen::WindowSizeChangeReason type, const std::shared_ptr<Rosen::RSTransaction>& rsTransaction)3086 void UIContentImpl::OnFormSurfaceChange(float width, float height, OHOS::Rosen::WindowSizeChangeReason type,
3087     const std::shared_ptr<Rosen::RSTransaction>& rsTransaction)
3088 {
3089     auto container = Platform::AceContainer::GetContainer(instanceId_);
3090     CHECK_NULL_VOID(container);
3091     int32_t formWidth = round(width);
3092     int32_t formHeight = round(height);
3093     auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
3094     Platform::AceViewOhos::ChangeViewSize(aceView, formWidth, formHeight);
3095     auto pipelineContext = container->GetPipelineContext();
3096     CHECK_NULL_VOID(pipelineContext);
3097     ContainerScope scope(instanceId_);
3098     auto density = pipelineContext->GetDensity();
3099     pipelineContext->SetRootSize(density, formWidth, formHeight);
3100     pipelineContext->OnSurfaceChanged(formWidth, formHeight, static_cast<WindowSizeChangeReason>(type), rsTransaction);
3101 }
3102 
SetFormBackgroundColor(const std::string& color)3103 void UIContentImpl::SetFormBackgroundColor(const std::string& color)
3104 {
3105     LOGI("[%{public}s][%{public}s][%{public}d]: SetFormBackgroundColor: %{public}s",
3106         bundleName_.c_str(), moduleName_.c_str(), instanceId_, color.c_str());
3107     if (!Rosen::RSSystemProperties::GetUniRenderEnabled()) {
3108         // cannot set transparent background effects in not-uniform-render mode
3109         return;
3110     }
3111     Color bgColor;
3112     if (!Color::ParseColorString(color, bgColor)) {
3113         return;
3114     }
3115     auto container = AceEngine::Get().GetContainer(instanceId_);
3116     CHECK_NULL_VOID(container);
3117     auto aceContainer = AceType::DynamicCast<Platform::AceContainer>(container);
3118     if (aceContainer) {
3119         aceContainer->SetIsUseCustomBg(true);
3120     }
3121     ContainerScope scope(instanceId_);
3122     auto taskExecutor = container->GetTaskExecutor();
3123     CHECK_NULL_VOID(taskExecutor);
3124     taskExecutor->PostSyncTask(
3125         [container, bgColor]() {
3126             auto pipelineContext = container->GetPipelineContext();
3127             CHECK_NULL_VOID(pipelineContext);
3128             pipelineContext->SetAppBgColor(bgColor);
3129         },
3130         TaskExecutor::TaskType::UI, "ArkUISetFormBackgroundColor");
3131 }
3132 
SetFontScaleFollowSystem(const bool fontScaleFollowSystem)3133 void UIContentImpl::SetFontScaleFollowSystem(const bool fontScaleFollowSystem)
3134 {
3135     LOGI("SetFontScaleFollowSystem: %{public}d", fontScaleFollowSystem);
3136     fontScaleFollowSystem_ = fontScaleFollowSystem;
3137 }
3138 
SetFormRenderingMode(int8_t renderMode)3139 void UIContentImpl::SetFormRenderingMode(int8_t renderMode)
3140 {
3141     auto container = Platform::AceContainer::GetContainer(instanceId_);
3142     CHECK_NULL_VOID(container);
3143     auto pipelineContext = container->GetPipelineContext();
3144     CHECK_NULL_VOID(pipelineContext);
3145     pipelineContext->SetFormRenderingMode(renderMode);
3146 }
3147 
GetResourcePaths(std::vector<std::string>& resourcesPaths, std::string& assetRootPath, std::vector<std::string>& assetBasePaths, std::string& resFolderName)3148 void UIContentImpl::GetResourcePaths(std::vector<std::string>& resourcesPaths, std::string& assetRootPath,
3149     std::vector<std::string>& assetBasePaths, std::string& resFolderName)
3150 {
3151     auto container = Platform::AceContainer::GetContainer(instanceId_);
3152     CHECK_NULL_VOID(container);
3153     ContainerScope scope(instanceId_);
3154     auto taskExecutor = Container::CurrentTaskExecutor();
3155     CHECK_NULL_VOID(taskExecutor);
3156     taskExecutor->PostTask(
3157         [container]() {
3158             auto pipelineContext = container->GetPipelineContext();
3159             CHECK_NULL_VOID(pipelineContext);
3160         },
3161         TaskExecutor::TaskType::PLATFORM, "ArkUIGetResourcePaths");
3162 }
3163 
SetResourcePaths(const std::vector<std::string>& resourcesPaths, const std::string& assetRootPath, const std::vector<std::string>& assetBasePaths)3164 void UIContentImpl::SetResourcePaths(const std::vector<std::string>& resourcesPaths, const std::string& assetRootPath,
3165     const std::vector<std::string>& assetBasePaths)
3166 {
3167     auto container = Platform::AceContainer::GetContainer(instanceId_);
3168     CHECK_NULL_VOID(container);
3169     ContainerScope scope(instanceId_);
3170     auto taskExecutor = Container::CurrentTaskExecutor();
3171     CHECK_NULL_VOID(taskExecutor);
3172     taskExecutor->PostTask(
3173         [container, resourcesPaths, assetRootPath, assetBasePaths]() {
3174             auto pipelineContext = container->GetPipelineContext();
3175             CHECK_NULL_VOID(pipelineContext);
3176             auto assetManager = pipelineContext->GetAssetManager();
3177             CHECK_NULL_VOID(assetManager);
3178             auto themeManager = pipelineContext->GetThemeManager();
3179             CHECK_NULL_VOID(themeManager);
3180 
3181             if (resourcesPaths.empty() && assetRootPath.empty()) {
3182                 return;
3183             }
3184 
3185             if (!assetRootPath.empty()) {
3186                 auto fileAssetProviderImpl = AceType::MakeRefPtr<FileAssetProviderImpl>();
3187                 if (fileAssetProviderImpl->Initialize(assetRootPath, assetBasePaths)) {
3188                     assetManager->PushBack(std::move(fileAssetProviderImpl));
3189                 }
3190                 return;
3191             }
3192             for (auto iter = resourcesPaths.begin(); iter != resourcesPaths.end(); iter++) {
3193                 auto hapAssetProviderImpl = AceType::MakeRefPtr<HapAssetProviderImpl>();
3194                 if (hapAssetProviderImpl->Initialize(*iter, assetBasePaths)) {
3195                     assetManager->PushBack(std::move(hapAssetProviderImpl));
3196                 }
3197             }
3198         },
3199         TaskExecutor::TaskType::PLATFORM, "ArkUISetResourcePaths");
3200 }
3201 
SetIsFocusActive(bool isFocusActive)3202 void UIContentImpl::SetIsFocusActive(bool isFocusActive)
3203 {
3204     auto container = Platform::AceContainer::GetContainer(instanceId_);
3205     CHECK_NULL_VOID(container);
3206     ContainerScope scope(instanceId_);
3207     auto taskExecutor = Container::CurrentTaskExecutor();
3208     CHECK_NULL_VOID(taskExecutor);
3209     taskExecutor->PostTask(
3210         [container, isFocusActive]() {
3211             auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
3212             CHECK_NULL_VOID(pipelineContext);
3213             ContainerScope scope(container->GetInstanceId());
3214             pipelineContext->SetIsFocusActive(isFocusActive);
3215         },
3216         TaskExecutor::TaskType::UI, "ArkUISetIsFocusActive");
3217 }
3218 
UpdateResource()3219 void UIContentImpl::UpdateResource()
3220 {
3221     auto container = Platform::AceContainer::GetContainer(instanceId_);
3222     CHECK_NULL_VOID(container);
3223     auto taskExecutor = container->GetTaskExecutor();
3224     CHECK_NULL_VOID(taskExecutor);
3225     taskExecutor->PostTask([container]() { container->UpdateResource(); },
3226         TaskExecutor::TaskType::UI, "ArkUIUpdateResource");
3227 }
3228 
CreateModalUIExtension( const AAFwk::Want& want, const ModalUIExtensionCallbacks& callbacks, const ModalUIExtensionConfig& config)3229 int32_t UIContentImpl::CreateModalUIExtension(
3230     const AAFwk::Want& want, const ModalUIExtensionCallbacks& callbacks, const ModalUIExtensionConfig& config)
3231 {
3232     auto container = Platform::AceContainer::GetContainer(instanceId_);
3233     CHECK_NULL_RETURN(container, 0);
3234     ContainerScope scope(instanceId_);
3235     auto taskExecutor = Container::CurrentTaskExecutor();
3236     CHECK_NULL_RETURN(taskExecutor, 0);
3237     int32_t sessionId = 0;
3238     taskExecutor->PostSyncTask(
3239         [container, &sessionId, want, callbacks = callbacks, config = config]() {
3240             auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
3241             CHECK_NULL_VOID(pipeline);
3242             auto overlay = pipeline->GetOverlayManager();
3243             CHECK_NULL_VOID(overlay);
3244             sessionId = overlay->CreateModalUIExtension(want, callbacks, config);
3245         },
3246         TaskExecutor::TaskType::UI, "ArkUICreateModalUIExtension");
3247     TAG_LOGI(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
3248         "[%{public}s][%{public}s][%{public}d]: create modal page, "
3249         "sessionId=%{public}d, isProhibitBack=%{public}d, isAsyncModalBinding=%{public}d, "
3250         "isAllowedBeCovered=%{public}d, prohibitedRemoveByRouter=%{public}d, "
3251         "isAllowAddChildBelowModalUec=%{public}d",
3252         bundleName_.c_str(), moduleName_.c_str(), instanceId_, sessionId, config.isProhibitBack,
3253         config.isAsyncModalBinding, config.isAllowedBeCovered, config.prohibitedRemoveByRouter,
3254         config.isAllowAddChildBelowModalUec);
3255     return sessionId;
3256 }
3257 
CloseModalUIExtension(int32_t sessionId)3258 void UIContentImpl::CloseModalUIExtension(int32_t sessionId)
3259 {
3260     TAG_LOGI(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
3261         "[%{public}s][%{public}s][%{public}d]: close modal page, "
3262         "sessionId=%{public}d",
3263         bundleName_.c_str(), moduleName_.c_str(), instanceId_, sessionId);
3264     if (sessionId == 0) {
3265         LOGW("UIExtension refuse to close modal page");
3266         return;
3267     }
3268     auto container = Platform::AceContainer::GetContainer(instanceId_);
3269     CHECK_NULL_VOID(container);
3270     ContainerScope scope(instanceId_);
3271     auto taskExecutor = Container::CurrentTaskExecutor();
3272     CHECK_NULL_VOID(taskExecutor);
3273     taskExecutor->PostTask(
3274         [container, sessionId]() {
3275             auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
3276             CHECK_NULL_VOID(pipeline);
3277             auto overlay = pipeline->GetOverlayManager();
3278             CHECK_NULL_VOID(overlay);
3279             overlay->CloseModalUIExtension(sessionId);
3280         },
3281         TaskExecutor::TaskType::UI, "ArkUICloseModalUIExtension");
3282 }
3283 
SetParentToken(sptr<IRemoteObject> token)3284 void UIContentImpl::SetParentToken(sptr<IRemoteObject> token)
3285 {
3286     parentToken_ = token;
3287 }
3288 
GetParentToken()3289 sptr<IRemoteObject> UIContentImpl::GetParentToken()
3290 {
3291     return parentToken_;
3292 }
3293 
CheckNeedAutoSave()3294 bool UIContentImpl::CheckNeedAutoSave()
3295 {
3296     auto container = Platform::AceContainer::GetContainer(instanceId_);
3297     CHECK_NULL_RETURN(container, false);
3298     auto taskExecutor = container->GetTaskExecutor();
3299     CHECK_NULL_RETURN(taskExecutor, false);
3300     ContainerScope scope(instanceId_);
3301     bool needAutoSave = false;
3302     taskExecutor->PostSyncTask(
3303         [&needAutoSave, container]() {
3304             CHECK_NULL_VOID(container);
3305             auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
3306             CHECK_NULL_VOID(pipelineContext);
3307             needAutoSave = pipelineContext->CheckNeedAutoSave();
3308         },
3309         TaskExecutor::TaskType::UI, "ArkUICheckNeedAutoSave");
3310 
3311     TAG_LOGI(AceLogTag::ACE_AUTO_FILL, "UIContentImpl CheckNeedAutoSave, value is %{public}d", needAutoSave);
3312     return needAutoSave;
3313 }
3314 
DumpViewData(AbilityBase::ViewData& viewData, AbilityBase::AutoFillType& type)3315 bool UIContentImpl::DumpViewData(AbilityBase::ViewData& viewData, AbilityBase::AutoFillType& type)
3316 {
3317     auto container = Platform::AceContainer::GetContainer(instanceId_);
3318     CHECK_NULL_RETURN(container, false);
3319     auto taskExecutor = container->GetTaskExecutor();
3320     CHECK_NULL_RETURN(taskExecutor, false);
3321     ContainerScope scope(instanceId_);
3322     bool ret = false;
3323     taskExecutor->PostSyncTask(
3324         [this, &ret, &viewData]() {
3325             auto viewDataWrap = ViewDataWrap::CreateViewDataWrap();
3326             CHECK_NULL_VOID(viewDataWrap);
3327             ret = DumpViewData(nullptr, viewDataWrap);
3328             auto viewDataWrapOhos = AceType::DynamicCast<ViewDataWrapOhos>(viewDataWrap);
3329             CHECK_NULL_VOID(viewDataWrapOhos);
3330             viewData = viewDataWrapOhos->GetViewData();
3331         },
3332         TaskExecutor::TaskType::UI, "ArkUIDumpViewData");
3333     type = ViewDataWrap::ViewDataToType(viewData);
3334     TAG_LOGI(AceLogTag::ACE_AUTO_FILL, "UIContentImpl DumpViewData, ret is %{public}d", ret);
3335     return ret;
3336 }
3337 
DumpViewData(const RefPtr<NG::FrameNode>& node, RefPtr<ViewDataWrap> viewDataWrap, bool skipSubAutoFillContainer, bool needsRecordData)3338 bool UIContentImpl::DumpViewData(const RefPtr<NG::FrameNode>& node, RefPtr<ViewDataWrap> viewDataWrap,
3339     bool skipSubAutoFillContainer, bool needsRecordData)
3340 {
3341     CHECK_NULL_RETURN(viewDataWrap, false);
3342     auto context = context_.lock();
3343     auto abilityContext = OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(context);
3344     std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> info;
3345     if (abilityContext) {
3346         info = abilityContext->GetAbilityInfo();
3347     } else {
3348         auto extensionContext =
3349             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::ExtensionContext>(context);
3350         if (extensionContext) {
3351             info = extensionContext->GetAbilityInfo();
3352         } else {
3353             TAG_LOGE(AceLogTag::ACE_AUTO_FILL, "context is not AbilityContext or ExtensionContext.");
3354             return false;
3355         }
3356     }
3357     CHECK_NULL_RETURN(info, false);
3358     viewDataWrap->SetAbilityName(info->name);
3359     viewDataWrap->SetModuleName(info->moduleName);
3360     viewDataWrap->SetBundleName(info->bundleName);
3361     TAG_LOGI(AceLogTag::ACE_AUTO_FILL, "bundleName=[%{private}s], moduleName=[%{private}s], abilityName=[%{private}s]",
3362         info->bundleName.c_str(), info->moduleName.c_str(), info->name.c_str());
3363     auto container = Platform::AceContainer::GetContainer(instanceId_);
3364     CHECK_NULL_RETURN(container, false);
3365     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
3366     CHECK_NULL_RETURN(pipelineContext, false);
3367     return pipelineContext->DumpPageViewData(node, viewDataWrap, skipSubAutoFillContainer, needsRecordData);
3368 }
3369 
SearchElementInfoByAccessibilityId( int64_t elementId, int32_t mode, int64_t baseParent, std::list<Accessibility::AccessibilityElementInfo>& output)3370 void UIContentImpl::SearchElementInfoByAccessibilityId(
3371     int64_t elementId, int32_t mode, int64_t baseParent, std::list<Accessibility::AccessibilityElementInfo>& output)
3372 {
3373     auto container = Platform::AceContainer::GetContainer(instanceId_);
3374     CHECK_NULL_VOID(container);
3375     container->SearchElementInfoByAccessibilityIdNG(elementId, mode, baseParent, output);
3376 }
3377 
SearchElementInfosByText(int64_t elementId, const std::string& text, int64_t baseParent, std::list<Accessibility::AccessibilityElementInfo>& output)3378 void UIContentImpl::SearchElementInfosByText(int64_t elementId, const std::string& text, int64_t baseParent,
3379     std::list<Accessibility::AccessibilityElementInfo>& output)
3380 {
3381     auto container = Platform::AceContainer::GetContainer(instanceId_);
3382     CHECK_NULL_VOID(container);
3383     container->SearchElementInfosByTextNG(elementId, text, baseParent, output);
3384 }
3385 
FindFocusedElementInfo( int64_t elementId, int32_t focusType, int64_t baseParent, Accessibility::AccessibilityElementInfo& output)3386 void UIContentImpl::FindFocusedElementInfo(
3387     int64_t elementId, int32_t focusType, int64_t baseParent, Accessibility::AccessibilityElementInfo& output)
3388 {
3389     auto container = Platform::AceContainer::GetContainer(instanceId_);
3390     CHECK_NULL_VOID(container);
3391     container->FindFocusedElementInfoNG(elementId, focusType, baseParent, output);
3392 }
3393 
FocusMoveSearch( int64_t elementId, int32_t direction, int64_t baseParent, Accessibility::AccessibilityElementInfo& output)3394 void UIContentImpl::FocusMoveSearch(
3395     int64_t elementId, int32_t direction, int64_t baseParent, Accessibility::AccessibilityElementInfo& output)
3396 {
3397     auto container = Platform::AceContainer::GetContainer(instanceId_);
3398     CHECK_NULL_VOID(container);
3399     container->FocusMoveSearchNG(elementId, direction, baseParent, output);
3400 }
3401 
NotifyExecuteAction( int64_t elementId, const std::map<std::string, std::string>& actionArguments, int32_t action, int64_t offset)3402 bool UIContentImpl::NotifyExecuteAction(
3403     int64_t elementId, const std::map<std::string, std::string>& actionArguments, int32_t action, int64_t offset)
3404 {
3405     auto container = Platform::AceContainer::GetContainer(instanceId_);
3406     CHECK_NULL_RETURN(container, false);
3407     return container->NotifyExecuteAction(elementId, actionArguments, action, offset);
3408 }
3409 
HandleAccessibilityHoverEvent(float pointX, float pointY, int32_t sourceType, int32_t eventType, int64_t timeMs)3410 void UIContentImpl::HandleAccessibilityHoverEvent(float pointX, float pointY, int32_t sourceType,
3411     int32_t eventType, int64_t timeMs)
3412 {
3413     auto container = Platform::AceContainer::GetContainer(instanceId_);
3414     CHECK_NULL_VOID(container);
3415     TAG_LOGI(AceLogTag::ACE_ACCESSIBILITY, "HandleAccessibilityHoverEvent Point:[%{public}f, %{public}f] "
3416         "source:%{public}d type:%{public}d time:%{public}" PRId64,
3417         pointX, pointY, sourceType, eventType, timeMs);
3418     container->HandleAccessibilityHoverEvent(pointX, pointY, sourceType, eventType, timeMs);
3419 }
3420 
RecycleForm()3421 std::string UIContentImpl::RecycleForm()
3422 {
3423     auto container = Platform::AceContainer::GetContainer(instanceId_);
3424     std::string statusData;
3425     CHECK_NULL_RETURN(container, statusData);
3426     auto pipeline = container->GetPipelineContext();
3427     CHECK_NULL_RETURN(pipeline, statusData);
3428     return pipeline->OnFormRecycle();
3429 }
3430 
RecoverForm(const std::string& statusData)3431 void UIContentImpl::RecoverForm(const std::string& statusData)
3432 {
3433     auto container = Platform::AceContainer::GetContainer(instanceId_);
3434     CHECK_NULL_VOID(container);
3435     auto pipeline = container->GetPipelineContext();
3436     CHECK_NULL_VOID(pipeline);
3437     return pipeline->OnFormRecover(statusData);
3438 }
3439 
CreateCustomPopupParam(bool isShow, const CustomPopupUIExtensionConfig& config)3440 RefPtr<PopupParam> UIContentImpl::CreateCustomPopupParam(bool isShow, const CustomPopupUIExtensionConfig& config)
3441 {
3442     auto popupParam = AceType::MakeRefPtr<PopupParam>();
3443     popupParam->SetIsShow(isShow);
3444     popupParam->SetUseCustomComponent(true);
3445     popupParam->SetShowInSubWindow(config.isShowInSubWindow);
3446     popupParam->SetShadow(GetPopupShadow());
3447     if (config.isAutoCancel.has_value()) {
3448         popupParam->SetHasAction(!config.isAutoCancel.value());
3449     }
3450 
3451     if (config.isEnableArrow.has_value()) {
3452         popupParam->SetEnableArrow(config.isEnableArrow.value());
3453     }
3454 
3455     if (config.targetOffset.has_value()) {
3456         PopupOffset targetOffset = config.targetOffset.value();
3457         DimensionUnit unit = static_cast<DimensionUnit>(targetOffset.unit);
3458         if (unit != DimensionUnit::PERCENT) { // not support percent settings
3459             CalcDimension dx(targetOffset.deltaX, unit);
3460             CalcDimension dy(targetOffset.deltaY, unit);
3461             popupParam->SetTargetOffset(Offset(dx.ConvertToPx(), dy.ConvertToPx()));
3462         }
3463     }
3464 
3465     if (config.targetSpace.has_value()) {
3466         PopupLength targetSpace = config.targetSpace.value();
3467         DimensionUnit unit = static_cast<DimensionUnit>(targetSpace.unit);
3468         popupParam->SetTargetSpace(CalcDimension(targetSpace.length, unit));
3469     }
3470 
3471     if (config.arrowOffset.has_value()) {
3472         PopupLength arrowOffset = config.arrowOffset.value();
3473         DimensionUnit unit = static_cast<DimensionUnit>(arrowOffset.unit);
3474         popupParam->SetArrowOffset(CalcDimension(arrowOffset.length, unit));
3475     }
3476 
3477     if (config.placement.has_value()) {
3478         popupParam->SetPlacement(static_cast<Placement>(config.placement.value()));
3479     }
3480 
3481     if (config.backgroundColor.has_value()) {
3482         popupParam->SetBackgroundColor(Color(config.backgroundColor.value()));
3483     }
3484 
3485     if (config.maskColor.has_value()) {
3486         popupParam->SetMaskColor(Color(config.maskColor.value()));
3487     }
3488     return popupParam;
3489 }
3490 
GetPopupShadow()3491 Shadow UIContentImpl::GetPopupShadow()
3492 {
3493     Shadow shadow;
3494     auto colorMode = SystemProperties::GetColorMode();
3495     auto container = Container::Current();
3496     CHECK_NULL_RETURN(container, shadow);
3497     auto pipelineContext = container->GetPipelineContext();
3498     CHECK_NULL_RETURN(pipelineContext, shadow);
3499     auto shadowTheme = pipelineContext->GetTheme<ShadowTheme>();
3500     CHECK_NULL_RETURN(shadowTheme, shadow);
3501     return shadowTheme->GetShadow(ShadowStyle::OuterDefaultMD, colorMode);
3502 }
3503 
OnPopupStateChange( const std::string& event, const CustomPopupUIExtensionConfig& config, int32_t nodeId)3504 void UIContentImpl::OnPopupStateChange(
3505     const std::string& event, const CustomPopupUIExtensionConfig& config, int32_t nodeId)
3506 {
3507     if (config.onStateChange) {
3508         config.onStateChange(event);
3509     }
3510 
3511     auto visible = JsonUtil::ParseJsonString(event);
3512     CHECK_NULL_VOID(visible);
3513     bool isVisible = visible->GetBool("isVisible");
3514     if (isVisible) {
3515         return;
3516     }
3517 
3518     LOGD("Created custom popup is invisible");
3519     ContainerScope scope(instanceId_);
3520     customPopupConfigMap_.erase(nodeId);
3521     popupUIExtensionRecords_.erase(nodeId);
3522 }
3523 
SetCustomPopupConfig(int32_t nodeId, const CustomPopupUIExtensionConfig& config, int32_t popupId)3524 void UIContentImpl::SetCustomPopupConfig(int32_t nodeId, const CustomPopupUIExtensionConfig& config, int32_t popupId)
3525 {
3526     customPopupConfigMap_[nodeId] = config;
3527     popupUIExtensionRecords_[nodeId] = popupId;
3528 }
3529 
GetTargetNode( int32_t& nodeIdLabel, RefPtr<NG::FrameNode>& targetNode, const CustomPopupUIExtensionConfig& config)3530 bool UIContentImpl::GetTargetNode(
3531     int32_t& nodeIdLabel, RefPtr<NG::FrameNode>& targetNode, const CustomPopupUIExtensionConfig& config)
3532 {
3533     if (config.nodeId > -1) {
3534         nodeIdLabel = config.nodeId;
3535         targetNode = ElementRegister::GetInstance()->GetSpecificItemById<NG::FrameNode>(nodeIdLabel);
3536         CHECK_NULL_RETURN(targetNode, false);
3537     } else if (!config.inspectorId.empty()) {
3538         targetNode = NG::Inspector::GetFrameNodeByKey(config.inspectorId);
3539         CHECK_NULL_RETURN(targetNode, false);
3540         nodeIdLabel = targetNode->GetId();
3541     } else {
3542         CHECK_NULL_RETURN(targetNode, false);
3543     }
3544     return true;
3545 }
3546 
CreateCustomPopupUIExtension( const AAFwk::Want& want, const ModalUIExtensionCallbacks& callbacks, const CustomPopupUIExtensionConfig& config)3547 int32_t UIContentImpl::CreateCustomPopupUIExtension(
3548     const AAFwk::Want& want, const ModalUIExtensionCallbacks& callbacks, const CustomPopupUIExtensionConfig& config)
3549 {
3550     ContainerScope scope(instanceId_);
3551     auto taskExecutor = Container::CurrentTaskExecutor();
3552     CHECK_NULL_RETURN(taskExecutor, 0);
3553     int32_t nodeId = 0;
3554     taskExecutor->PostSyncTask(
3555         [want, &nodeId, callbacks = callbacks, config = config, this]() {
3556             int32_t nodeIdLabel = -1;
3557             RefPtr<NG::FrameNode> targetNode = nullptr;
3558             if (!GetTargetNode(nodeIdLabel, targetNode, config)) {
3559                 return;
3560             }
3561             if (customPopupConfigMap_.find(nodeIdLabel) != customPopupConfigMap_.end()) {
3562                 LOGW("Nodeid=%{public}d has unclosed popup, cannot create new", nodeIdLabel);
3563                 return;
3564             }
3565             auto popupParam = CreateCustomPopupParam(true, config);
3566             popupParam->SetBlockEvent(false);
3567             auto uiExtNode = ModalUIExtension::Create(want, callbacks, false, false);
3568             auto focusHub = uiExtNode->GetFocusHub();
3569             if (focusHub) {
3570                 focusHub->SetFocusable(config.isFocusable);
3571             }
3572             if (config.targetSize.has_value()) {
3573                 auto layoutProperty = uiExtNode->GetLayoutProperty();
3574                 CHECK_NULL_VOID(layoutProperty);
3575                 PopupSize targetSize = config.targetSize.value();
3576                 DimensionUnit unit = static_cast<DimensionUnit>(targetSize.unit);
3577                 auto width = NG::CalcLength(targetSize.width, unit);
3578                 auto height = NG::CalcLength(targetSize.height, unit);
3579                 layoutProperty->UpdateUserDefinedIdealSize(NG::CalcSize(width, height));
3580             }
3581             uiExtNode->MarkModifyDone();
3582             nodeId = nodeIdLabel;
3583             popupParam->SetOnStateChange([config, nodeId, UICONTENT_IMPL_HELPER(content)](const std::string& event) {
3584                 UICONTENT_IMPL_HELPER_GUARD(content, return);
3585                 UICONTENT_IMPL_PTR(content)->OnPopupStateChange(event, config, nodeId);
3586             });
3587             NG::ViewAbstract::BindPopup(popupParam, targetNode, AceType::DynamicCast<NG::UINode>(uiExtNode));
3588             SetCustomPopupConfig(nodeId, config, uiExtNode->GetId());
3589         },
3590         TaskExecutor::TaskType::UI, "ArkUIUIExtensionCreateCustomPopup");
3591     TAG_LOGI(
3592         AceLogTag::ACE_UIEXTENSIONCOMPONENT, "Create custom popup with UIExtension end, nodeId=%{public}d", nodeId);
3593     return nodeId;
3594 }
3595 
DestroyCustomPopupUIExtension(int32_t nodeId)3596 void UIContentImpl::DestroyCustomPopupUIExtension(int32_t nodeId)
3597 {
3598     TAG_LOGI(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
3599         "[%{public}s][%{public}s][%{public}d]: Destroy custom popup start, nodeId=%{public}d", bundleName_.c_str(),
3600         moduleName_.c_str(), instanceId_, nodeId);
3601     auto container = Platform::AceContainer::GetContainer(instanceId_);
3602     CHECK_NULL_VOID(container);
3603     ContainerScope scope(instanceId_);
3604     auto taskExecutor = Container::CurrentTaskExecutor();
3605     CHECK_NULL_VOID(taskExecutor);
3606     auto popupConfig = customPopupConfigMap_.find(nodeId);
3607     if (popupConfig == customPopupConfigMap_.end()) {
3608         LOGW("Node doesn't hava popup or closed already");
3609         return;
3610     }
3611     auto config = popupConfig->second;
3612     taskExecutor->PostTask(
3613         [container, nodeId, config, UICONTENT_IMPL_HELPER(content)]() {
3614             UICONTENT_IMPL_HELPER_GUARD(content, return);
3615             auto targetNode =
3616                 AceType::DynamicCast<NG::FrameNode>(ElementRegister::GetInstance()->GetUINodeById(nodeId));
3617             CHECK_NULL_VOID(targetNode);
3618             auto popupParam = UICONTENT_IMPL_PTR(content)->CreateCustomPopupParam(false, config);
3619             NG::ViewAbstract::BindPopup(popupParam, targetNode, nullptr);
3620             UICONTENT_IMPL_PTR(content)->customPopupConfigMap_.erase(nodeId);
3621             UICONTENT_IMPL_PTR(content)->popupUIExtensionRecords_.erase(nodeId);
3622         },
3623         TaskExecutor::TaskType::UI, "ArkUIUIExtensionDestroyCustomPopup");
3624 }
3625 
UpdateCustomPopupUIExtension(const CustomPopupUIExtensionConfig& config)3626 void UIContentImpl::UpdateCustomPopupUIExtension(const CustomPopupUIExtensionConfig& config)
3627 {
3628     ContainerScope scope(instanceId_);
3629     auto taskExecutor = Container::CurrentTaskExecutor();
3630     CHECK_NULL_VOID(taskExecutor);
3631     taskExecutor->PostSyncTask(
3632         [config, this]() {
3633             int32_t targetId = config.nodeId;
3634             auto record = popupUIExtensionRecords_.find(targetId);
3635             int32_t uiExtNodeId = (record != popupUIExtensionRecords_.end()) ? record->second : 0;
3636             auto uiExtNode = NG::FrameNode::GetFrameNode(V2::UI_EXTENSION_COMPONENT_ETS_TAG, uiExtNodeId);
3637             CHECK_NULL_VOID(uiExtNode);
3638             if (config.targetSize.has_value()) {
3639                 auto layoutProperty = uiExtNode->GetLayoutProperty();
3640                 CHECK_NULL_VOID(layoutProperty);
3641                 PopupSize targetSize = config.targetSize.value();
3642                 DimensionUnit unit = static_cast<DimensionUnit>(targetSize.unit);
3643                 auto width = NG::CalcLength(targetSize.width, unit);
3644                 auto height = NG::CalcLength(targetSize.height, unit);
3645                 layoutProperty->UpdateUserDefinedIdealSize(NG::CalcSize(width, height));
3646             }
3647             auto popupParam = CreateCustomPopupParam(true, config);
3648             popupParam->SetIsCaretMode(false);
3649             popupParam->SetBlockEvent(false);
3650             auto popupConfig = customPopupConfigMap_.find(targetId);
3651             if (popupConfig != customPopupConfigMap_.end()) {
3652                 auto createConfig = popupConfig->second;
3653                 popupParam->SetShowInSubWindow(createConfig.isShowInSubWindow);
3654                 popupParam->SetOnStateChange(
3655                     [createConfig, targetId, UICONTENT_IMPL_HELPER(content)](const std::string& event) {
3656                         UICONTENT_IMPL_HELPER_GUARD(content, return);
3657                         UICONTENT_IMPL_PTR(content)->OnPopupStateChange(event, createConfig, targetId);
3658                     });
3659             }
3660             auto targetNode =
3661                 AceType::DynamicCast<NG::FrameNode>(ElementRegister::GetInstance()->GetUINodeById(targetId));
3662             CHECK_NULL_VOID(targetNode);
3663             NG::ViewAbstract::BindPopup(popupParam, targetNode, nullptr);
3664         },
3665         TaskExecutor::TaskType::UI, "ArkUIUIExtensionUpdateCustomPopup");
3666 }
3667 
SetContainerModalTitleVisible(bool customTitleSettedShow, bool floatingTitleSettedShow)3668 void UIContentImpl::SetContainerModalTitleVisible(bool customTitleSettedShow, bool floatingTitleSettedShow)
3669 {
3670     ContainerScope scope(instanceId_);
3671     auto taskExecutor = Container::CurrentTaskExecutor();
3672     CHECK_NULL_VOID(taskExecutor);
3673     auto task = [customTitleSettedShow, floatingTitleSettedShow]() {
3674         auto pipeline = NG::PipelineContext::GetCurrentContext();
3675         CHECK_NULL_VOID(pipeline);
3676         pipeline->SetContainerModalTitleVisible(customTitleSettedShow, floatingTitleSettedShow);
3677     };
3678     auto uiTaskRunner = SingleTaskExecutor::Make(taskExecutor, TaskExecutor::TaskType::UI);
3679     if (uiTaskRunner.IsRunOnCurrentThread()) {
3680         task();
3681     } else {
3682         taskExecutor->PostTask(std::move(task), TaskExecutor::TaskType::UI, "ArkUISetContainerModalTitleVisible");
3683     }
3684 }
3685 
SetContainerModalTitleHeight(int32_t height)3686 void UIContentImpl::SetContainerModalTitleHeight(int32_t height)
3687 {
3688     ContainerScope scope(instanceId_);
3689     auto taskExecutor = Container::CurrentTaskExecutor();
3690     CHECK_NULL_VOID(taskExecutor);
3691     auto task = [height]() {
3692         auto pipeline = NG::PipelineContext::GetCurrentContext();
3693         CHECK_NULL_VOID(pipeline);
3694         pipeline->SetContainerModalTitleHeight(height);
3695     };
3696     auto uiTaskRunner = SingleTaskExecutor::Make(taskExecutor, TaskExecutor::TaskType::UI);
3697     if (uiTaskRunner.IsRunOnCurrentThread()) {
3698         task();
3699     } else {
3700         taskExecutor->PostTask(std::move(task), TaskExecutor::TaskType::UI, "ArkUISetContainerModalTitleHeight");
3701     }
3702 }
3703 
GetContainerModalTitleHeight()3704 int32_t UIContentImpl::GetContainerModalTitleHeight()
3705 {
3706     ContainerScope scope(instanceId_);
3707     auto pipeline = NG::PipelineContext::GetCurrentContext();
3708     CHECK_NULL_RETURN(pipeline, -1);
3709     return pipeline->GetContainerModalTitleHeight();
3710 }
3711 
GetContainerModalButtonsRect(Rosen::Rect& containerModal, Rosen::Rect& buttons)3712 bool UIContentImpl::GetContainerModalButtonsRect(Rosen::Rect& containerModal, Rosen::Rect& buttons)
3713 {
3714     NG::RectF floatContainerModal;
3715     NG::RectF floatButtons;
3716     ContainerScope scope(instanceId_);
3717     auto pipeline = NG::PipelineContext::GetCurrentContext();
3718     CHECK_NULL_RETURN(pipeline, false);
3719     if (!pipeline->GetContainerModalButtonsRect(floatContainerModal, floatButtons)) {
3720         return false;
3721     }
3722     containerModal = ConvertToRSRect(floatContainerModal);
3723     buttons = ConvertToRSRect(floatButtons);
3724     return true;
3725 }
3726 
SubscribeContainerModalButtonsRectChange( std::function<void(Rosen::Rect& containerModal, Rosen::Rect& buttons)>&& callback)3727 void UIContentImpl::SubscribeContainerModalButtonsRectChange(
3728     std::function<void(Rosen::Rect& containerModal, Rosen::Rect& buttons)>&& callback)
3729 {
3730     ContainerScope scope(instanceId_);
3731     auto pipeline = NG::PipelineContext::GetCurrentContext();
3732     CHECK_NULL_VOID(pipeline);
3733 
3734     if (callback == nullptr) {
3735         pipeline->SubscribeContainerModalButtonsRectChange(nullptr);
3736         return;
3737     }
3738     std::function<void(NG::RectF&, NG::RectF&)> wrapFunc = [cb = std::move(callback)](NG::RectF& floatContainerModal,
3739                                                                NG::RectF& floatButtons) {
3740         Rosen::Rect containerModal = ConvertToRSRect(floatContainerModal);
3741         Rosen::Rect buttons = ConvertToRSRect(floatButtons);
3742         cb(containerModal, buttons);
3743     };
3744     pipeline->SubscribeContainerModalButtonsRectChange(std::move(wrapFunc));
3745 }
3746 
ChangeSensitiveNodes(bool isSensitive)3747 void UIContentImpl::ChangeSensitiveNodes(bool isSensitive)
3748 {
3749     auto container = Platform::AceContainer::GetContainer(instanceId_);
3750     CHECK_NULL_VOID(container);
3751     ContainerScope scope(instanceId_);
3752     auto pipeline = container->GetPipelineContext();
3753     CHECK_NULL_VOID(pipeline);
3754     auto taskExecutor = container->GetTaskExecutor();
3755     CHECK_NULL_VOID(taskExecutor);
3756     taskExecutor->PostTask(
3757         [pipeline, isSensitive]() { pipeline->ChangeSensitiveNodes(isSensitive); },
3758         TaskExecutor::TaskType::UI, "ArkUIChangeSensitiveNodes");
3759 }
3760 
UpdateTransform(const OHOS::Rosen::Transform& transform)3761 void UIContentImpl::UpdateTransform(const OHOS::Rosen::Transform& transform)
3762 {
3763     auto container = Platform::AceContainer::GetContainer(instanceId_);
3764     CHECK_NULL_VOID(container);
3765     ContainerScope scope(instanceId_);
3766     auto taskExecutor = Container::CurrentTaskExecutor();
3767     CHECK_NULL_VOID(taskExecutor);
3768     auto windowScale = transform.scaleX_;
3769     taskExecutor->PostTask(
3770         [container, windowScale]() { container->SetWindowScale(windowScale); },
3771         TaskExecutor::TaskType::UI, "ArkUISetWindowScale");
3772 }
3773 
AddWatchSystemParameter()3774 void UIContentImpl::AddWatchSystemParameter()
3775 {
3776     auto container = Platform::AceContainer::GetContainer(instanceId_);
3777     CHECK_NULL_VOID(container);
3778     container->AddWatchSystemParameter();
3779 }
3780 
GetOverlayNodePositions() const3781 std::vector<Ace::RectF> UIContentImpl::GetOverlayNodePositions() const
3782 {
3783     auto container = Platform::AceContainer::GetContainer(instanceId_);
3784     ContainerScope scope(instanceId_);
3785     CHECK_NULL_RETURN(container, {});
3786     return container->GetOverlayNodePositions();
3787 }
3788 
RegisterOverlayNodePositionsUpdateCallback( const std::function<void(std::vector<Ace::RectF>)>& callback) const3789 void UIContentImpl::RegisterOverlayNodePositionsUpdateCallback(
3790     const std::function<void(std::vector<Ace::RectF>)>& callback) const
3791 {
3792     auto container = Platform::AceContainer::GetContainer(instanceId_);
3793     ContainerScope scope(instanceId_);
3794     CHECK_NULL_VOID(container);
3795     container->RegisterOverlayNodePositionsUpdateCallback(std::move(callback));
3796 }
3797 
SetContentNodeGrayScale(float grayscale)3798 void UIContentImpl::SetContentNodeGrayScale(float grayscale)
3799 {
3800     if (LessNotEqual(grayscale, 0.001f)) {
3801         grayscale = 0.0f;
3802     }
3803     if (GreatNotEqual(grayscale, 1.0)) {
3804         grayscale = 1.0f;
3805     }
3806     auto container = Platform::AceContainer::GetContainer(instanceId_);
3807     CHECK_NULL_VOID(container);
3808     ContainerScope scope(instanceId_);
3809     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
3810     CHECK_NULL_VOID(pipelineContext);
3811     auto rootElement = pipelineContext->GetRootElement();
3812     CHECK_NULL_VOID(rootElement);
3813     auto renderContext = rootElement->GetRenderContext();
3814     CHECK_NULL_VOID(renderContext);
3815     renderContext->UpdateFrontGrayScale(Dimension(grayscale));
3816     pipelineContext->SetDragNodeGrayscale(grayscale);
3817 }
3818 
PreLayout()3819 void UIContentImpl::PreLayout()
3820 {
3821     TAG_LOGI(AceLogTag::ACE_WINDOW, "PreLayoutBegin");
3822     auto container = Platform::AceContainer::GetContainer(instanceId_);
3823     CHECK_NULL_VOID(container);
3824     ContainerScope scope(instanceId_);
3825     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
3826     CHECK_NULL_VOID(pipelineContext);
3827 
3828     auto stageManager = pipelineContext->GetStageManager();
3829     CHECK_NULL_VOID(stageManager);
3830     auto stageNode = stageManager->GetStageNode();
3831     CHECK_NULL_VOID(stageNode);
3832     auto renderContext = stageNode->GetRenderContext();
3833     CHECK_NULL_VOID(renderContext);
3834     auto paintRectf = renderContext->GetPaintRectWithoutTransform();
3835     if (LessOrEqual(static_cast<uint32_t>(paintRectf.Width()), 0) ||
3836         LessOrEqual(static_cast<uint32_t>(paintRectf.Height()), 0)) {
3837         TAG_LOGW(AceLogTag::ACE_WINDOW, "width:%{public}f, height:%{public}f", paintRectf.Width(),
3838             paintRectf.Height());
3839         return ;
3840     }
3841 
3842     auto taskExecutor = container->GetTaskExecutor();
3843     CHECK_NULL_VOID(taskExecutor);
3844     taskExecutor->PostSyncTask(
3845         [pipelineContext] {
3846             pipelineContext->PreLayout(pipelineContext->GetTimeFromExternalTimer(), 0);
3847         },
3848         TaskExecutor::TaskType::UI, "ArkUIPreLayout");
3849     TAG_LOGI(AceLogTag::ACE_WINDOW, "ArkUIPreLayoutEnd");
3850 }
3851 
SetStatusBarItemColor(uint32_t color)3852 void UIContentImpl::SetStatusBarItemColor(uint32_t color)
3853 {
3854     ContainerScope scope(instanceId_);
3855     auto container = Platform::AceContainer::GetContainer(instanceId_);
3856     CHECK_NULL_VOID(container);
3857     auto appBar = container->GetAppBar();
3858     CHECK_NULL_VOID(appBar);
3859     appBar->SetStatusBarItemColor(IsDarkColor(color));
3860 }
3861 
SetForceSplitEnable(bool isForceSplit, const std::string& homePage)3862 void UIContentImpl::SetForceSplitEnable(bool isForceSplit, const std::string& homePage)
3863 {
3864     ContainerScope scope(instanceId_);
3865     auto container = Platform::AceContainer::GetContainer(instanceId_);
3866     CHECK_NULL_VOID(container);
3867     auto context = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
3868     CHECK_NULL_VOID(context);
3869     context->SetForceSplitEnable(isForceSplit, homePage);
3870 }
3871 
UpdateDialogContainerConfig(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)3872 void UIContentImpl::UpdateDialogContainerConfig(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)
3873 {
3874     CHECK_NULL_VOID(config);
3875     auto container = Platform::DialogContainer::GetContainer(instanceId_);
3876     CHECK_NULL_VOID(container);
3877     auto taskExecutor = container->GetTaskExecutor();
3878     CHECK_NULL_VOID(taskExecutor);
3879     taskExecutor->PostTask(
3880         [weakContainer = WeakPtr<Platform::DialogContainer>(container), config, instanceId = instanceId_,
3881             bundleName = bundleName_, moduleName = moduleName_]() {
3882             auto container = weakContainer.Upgrade();
3883             CHECK_NULL_VOID(container);
3884             Platform::ParsedConfig parsedConfig;
3885             parsedConfig.colorMode = config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
3886             container->UpdateConfiguration(parsedConfig);
3887             TAG_LOGI(AceLogTag::ACE_DIALOG,
3888                 "[%{public}d][%{public}s][%{public}s] UIContentImpl: UpdateDialogContainerConfig called End, "
3889                 "name:%{public}s",
3890                 instanceId, bundleName.c_str(), moduleName.c_str(), config->GetName().c_str());
3891         },
3892         TaskExecutor::TaskType::UI, "ArkUIUIContentUpdateConfiguration");
3893 }
3894 
ProcessDestructCallbacks()3895 void UIContentImpl::ProcessDestructCallbacks()
3896 {
3897     for (auto& [_, callback] : destructCallbacks_) {
3898         callback();
3899     }
3900 }
3901 } // namespace OHOS::Ace
3902