• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2025 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 #include <ani.h>
21 #include <optional>
22 
23 #include "ability_context.h"
24 #include "ability_info.h"
25 #include "bundlemgr/bundle_mgr_proxy.h"
26 #include "configuration.h"
27 #include "event_pass_through_subscriber.h"
28 #include "file_path_utils.h"
29 #include "if_system_ability_manager.h"
30 #include "ipc_skeleton.h"
31 #include "iservice_registry.h"
32 #include "js_runtime_utils.h"
33 #include "locale_config.h"
34 #include "native_reference.h"
35 #include "ohos/init_data.h"
36 #ifdef RESOURCE_SCHEDULE_SERVICE_ENABLE
37 #include "res_sched_client.h"
38 #include "res_type.h"
39 #include "resource_manager.h"
40 #endif // RESOURCE_SCHEDULE_SERVICE_ENABLE
41 #include "service_extension_context.h"
42 #include "system_ability_definition.h"
43 #include "wm_common.h"
44 
45 #include "base/log/event_report.h"
46 #include "base/log/log_wrapper.h"
47 #include "base/memory/referenced.h"
48 #include "base/perfmonitor/perf_monitor.h"
49 #include "base/ressched/ressched_report.h"
50 #include "base/subwindow/subwindow_manager.h"
51 #include "base/thread/background_task_executor.h"
52 #include "base/utils/utils.h"
53 #include "core/common/force_split/force_split_utils.h"
54 #include "core/common/multi_thread_build_manager.h"
55 #include "core/components/common/layout/constants.h"
56 #include "core/components_ng/base/frame_node.h"
57 #include "core/components_ng/render/animation_utils.h"
58 #include "core/pipeline/container_window_manager.h"
59 
60 #if !defined(ACE_UNITTEST)
61 #include "core/components_ng/base/transparent_node_detector.h"
62 #endif
63 
64 #include "core/components_ng/property/safe_area_insets.h"
65 
66 #ifdef ENABLE_ROSEN_BACKEND
67 #include "adapter/ohos/entrance/rs_adapter.h"
68 #include "render_service_client/core/transaction/rs_transaction.h"
69 #include "render_service_client/core/transaction/rs_sync_transaction_controller.h"
70 #include "render_service_client/core/transaction/rs_sync_transaction_handler.h"
71 #include "render_service_client/core/ui/rs_ui_director.h"
72 #endif
73 
74 #include "interfaces/inner_api/ui_session/ui_session_manager.h"
75 
76 #include "adapter/ohos/capability/feature_config/feature_param_manager.h"
77 #include "adapter/ohos/entrance/ace_application_info.h"
78 #include "adapter/ohos/entrance/ace_container.h"
79 #include "adapter/ohos/entrance/ace_new_pipe_judgement.h"
80 #include "adapter/ohos/entrance/ace_view_ohos.h"
81 #include "adapter/ohos/entrance/capability_registry.h"
82 #include "adapter/ohos/entrance/cj_utils/cj_utils.h"
83 #include "adapter/ohos/entrance/dialog_container.h"
84 #include "adapter/ohos/entrance/dynamic_component/uv_task_wrapper_impl.h"
85 #include "adapter/ohos/entrance/file_asset_provider_impl.h"
86 #include "adapter/ohos/entrance/form_utils_impl.h"
87 #include "adapter/ohos/entrance/global_pipeline_context_manager.h"
88 #include "adapter/ohos/entrance/aps_monitor_impl.h"
89 #include "adapter/ohos/entrance/hap_asset_provider_impl.h"
90 #include "adapter/ohos/entrance/plugin_utils_impl.h"
91 #include "adapter/ohos/entrance/ui_event_impl.h"
92 #include "adapter/ohos/entrance/utils.h"
93 #include "adapter/ohos/osal/navigation_route_ohos.h"
94 #include "adapter/ohos/osal/page_url_checker_ohos.h"
95 #include "adapter/ohos/osal/pixel_map_ohos.h"
96 #include "adapter/ohos/osal/resource_adapter_impl_v2.h"
97 #include "adapter/ohos/osal/thp_extra_manager_impl.h"
98 #include "adapter/ohos/osal/view_data_wrap_ohos.h"
99 #include "base/geometry/rect.h"
100 #include "base/i18n/localization.h"
101 #include "base/log/ace_checker.h"
102 #include "base/log/ace_performance_check.h"
103 #include "base/log/ace_trace.h"
104 #include "base/log/log.h"
105 #include "base/perfmonitor/perf_monitor.h"
106 #include "base/subwindow/subwindow_manager.h"
107 #include "base/utils/system_properties.h"
108 #include "bridge/arkts_frontend/arkts_frontend.h"
109 #include "bridge/card_frontend/form_frontend_declarative.h"
110 #include "core/common/ace_engine.h"
111 #include "core/common/asset_manager_impl.h"
112 #include "core/common/container.h"
113 #include "core/common/container_scope.h"
114 #include "core/common/modal_ui_extension.h"
115 #include "core/common/recorder/event_definition.h"
116 #include "core/common/recorder/event_recorder.h"
117 #include "core/common/resource/resource_manager.h"
118 #include "core/common/xcollie/xcollieInterface.h"
119 #include "core/components/theme/shadow_theme.h"
120 #include "core/components/popup/popup_theme.h"
121 #include "core/components_ng/base/inspector.h"
122 #include "core/components_ng/base/view_abstract.h"
123 #include "core/components_ng/pattern/container_modal/container_modal_view.h"
124 #include "core/components_ng/pattern/container_modal/enhance/container_modal_view_enhance.h"
125 #include "core/components_ng/pattern/select_overlay/expanded_menu_plugin_loader.h"
126 #include "core/components_ng/pattern/text_field/text_field_manager.h"
127 #include "core/components_ng/pattern/ui_extension/ui_extension_component/ui_extension_pattern.h"
128 #include "core/components_ng/pattern/ui_extension/ui_extension_config.h"
129 #include "core/components_ng/pattern/ui_extension/ui_extension_container_handler.h"
130 #include "core/components_ng/render/adapter/rosen_render_context.h"
131 #include "core/image/image_file_cache.h"
132 #include "core/pipeline_ng/pipeline_context.h"
133 #ifdef FORM_SUPPORTED
134 #include "core/common/form_manager.h"
135 #endif
136 #include "core/common/layout_inspector.h"
137 #ifdef PLUGIN_COMPONENT_SUPPORTED
138 #include "core/common/plugin_manager.h"
139 #endif
140 #ifdef NG_BUILD
141 #include "frameworks/bridge/declarative_frontend/ng/declarative_frontend_ng.h"
142 #endif
143 
144 #include "core/components_ng/render/adapter/rosen_render_context.h"
145 #include "screen_session_manager_client.h"
146 #include "pointer_event.h"
147 
148 namespace OHOS::Ace {
149 namespace {
150 
151 const std::string ABS_BUNDLE_CODE_PATH = "/data/app/el1/bundle/public/";
152 const std::string LOCAL_BUNDLE_CODE_PATH = "/data/storage/el1/bundle/";
153 const std::string FILE_SEPARATOR = "/";
154 const std::string START_PARAMS_KEY = "__startParams";
155 const std::string PARAM_QUERY_KEY = "query";
156 const std::string ACTION_SEARCH = "ohos.want.action.search";
157 const std::string ACTION_VIEWDATA = "ohos.want.action.viewData";
158 const std::string ACTION_APPDETAIL = "ohos.want.action.appdetail";
159 const std::string USE_GLOBAL_UICONTENT = "ohos.uec.params.useGlobalUIContent";
160 const std::string ACRION_CALENDAR = "JUMP_TO_VIEW_BY_AGENDA_PREVIEW";
161 const std::string ABILITYNAME_CALENDAR = "MainAbility";
162 const std::string ACTION_PARAM = "action";
163 constexpr char IS_PREFERRED_LANGUAGE[] = "1";
164 constexpr uint64_t DISPLAY_ID_INVALID = -1ULL;
165 static std::atomic<bool> g_isDynamicVsync = false;
166 static bool g_isDragging = false;
167 
168 enum class WindowChangeType {
169     RECT_CHANGE,
170     FOLD_STATUS_CHANGE,
171     DISPLAY_ID_CHANGE
172 };
173 
174 #define UICONTENT_IMPL_HELPER(name) _##name = std::make_shared<UIContentImplHelper>(this)
175 #define UICONTENT_IMPL_PTR(name) _##name->uiContent_
176 #define UICONTENT_IMPL_HELPER_GUARD(name, ifInvalid...) \
177     std::lock_guard lg(*_##name->mutex_);               \
178     if (!*_##name->isValid_) {                          \
179         ifInvalid;                                      \
180     }
181 
182 struct UIContentImplHelper {
UIContentImplHelperOHOS::Ace::__anon6e83243a0111::UIContentImplHelper183     explicit UIContentImplHelper(UIContentImpl* uiContent) : uiContent_(uiContent)
184     {
185         uiContent_->AddDestructCallback(this, [mutex = mutex_, isValid = isValid_] {
186             std::lock_guard lg(*mutex);
187             *isValid = false;
188         });
189     }
~UIContentImplHelperOHOS::Ace::__anon6e83243a0111::UIContentImplHelper190     ~UIContentImplHelper()
191     {
192         std::lock_guard lg(*mutex_);
193         if (*isValid_) {
194             uiContent_->RemoveDestructCallback(this);
195         }
196     }
197     UIContentImpl* uiContent_;
198     std::shared_ptr<std::mutex> mutex_ = std::make_shared<std::mutex>();
199     std::shared_ptr<bool> isValid_ = std::make_shared<bool>(true);
200     UIContentImplHelper(const UIContentImplHelper& rhs) = delete;
201     UIContentImplHelper& operator=(const UIContentImplHelper& rhs) = delete;
202 };
203 
ConvertToRSRect(NG::RectF & rect)204 Rosen::Rect ConvertToRSRect(NG::RectF& rect)
205 {
206     Rosen::Rect rsRect;
207     rsRect.posX_ = floor(rect.GetX());
208     rsRect.posY_ = floor(rect.GetY());
209     rsRect.width_ = ceil(rect.Width());
210     rsRect.height_ = ceil(rect.Height());
211     return rsRect;
212 }
213 
IsNeedAvoidWindowMode(OHOS::Rosen::Window * rsWindow)214 bool IsNeedAvoidWindowMode(OHOS::Rosen::Window* rsWindow)
215 {
216     // compatibleModeInPc needAvoidWindow
217     bool compatibleModeInPc = rsWindow->GetCompatibleModeInPc();
218     if (!SystemProperties::GetNeedAvoidWindow() && !compatibleModeInPc) {
219         return false;
220     }
221 
222     auto mode = rsWindow->GetWindowMode();
223     return mode == Rosen::WindowMode::WINDOW_MODE_FLOATING || mode == Rosen::WindowMode::WINDOW_MODE_SPLIT_PRIMARY ||
224             mode == Rosen::WindowMode::WINDOW_MODE_SPLIT_SECONDARY;
225 }
226 
AddResConfigInfo(const std::shared_ptr<OHOS::AbilityRuntime::Context> & context,ResourceConfiguration & aceResCfg)227 void AddResConfigInfo(
228     const std::shared_ptr<OHOS::AbilityRuntime::Context>& context, ResourceConfiguration& aceResCfg)
229 {
230     if (!context || !context->GetResourceManager()) {
231         return;
232     }
233     auto resourceManager = context->GetResourceManager();
234     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
235     resourceManager->GetResConfig(*resConfig);
236     aceResCfg.SetMcc(resConfig->GetMcc());
237     aceResCfg.SetMnc(resConfig->GetMnc());
238     aceResCfg.SetAppHasDarkRes(resConfig->GetAppDarkRes());
239     auto preferredLocaleInfo = resConfig->GetPreferredLocaleInfo();
240     if (preferredLocaleInfo != nullptr) {
241         std::string preferredLanguage = preferredLocaleInfo->getLanguage();
242         std::string script = preferredLocaleInfo->getScript();
243         std::string country = preferredLocaleInfo->getCountry();
244         AceApplicationInfo::GetInstance().SetLocale(preferredLanguage.c_str(), country.c_str(), script.c_str(), "");
245 
246         std::string preferredLanguageTag = preferredLanguage;
247         if (!script.empty()) {
248             preferredLanguageTag += "-" + script;
249         }
250         if (!country.empty()) {
251             preferredLanguageTag += "-" + country;
252         }
253         aceResCfg.SetPreferredLanguage(preferredLanguageTag);
254     }
255 }
256 
AddSetAppColorModeToResConfig(const std::shared_ptr<OHOS::AbilityRuntime::Context> & context,ResourceConfiguration & aceResCfg)257 void AddSetAppColorModeToResConfig(
258     const std::shared_ptr<OHOS::AbilityRuntime::Context>& context, ResourceConfiguration& aceResCfg)
259 {
260     CHECK_NULL_VOID(context);
261     auto config = context->GetConfiguration();
262     CHECK_NULL_VOID(config);
263     auto colorModeIsSetByApp = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::COLORMODE_IS_SET_BY_APP);
264     if (!colorModeIsSetByApp.empty()) {
265         aceResCfg.SetColorModeIsSetByApp(true);
266     }
267 }
268 
StringifyAvoidAreas(const std::map<OHOS::Rosen::AvoidAreaType,OHOS::Rosen::AvoidArea> & avoidAreas)269 std::string StringifyAvoidAreas(const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas)
270 {
271     std::stringstream ss;
272     if (avoidAreas.empty()) {
273         return ss.str();
274     }
275     ss << "updateAvoidAreas size: " << avoidAreas.size() << "[";
276     std::for_each(avoidAreas.begin(), avoidAreas.end(), [&ss](const auto& avoidArea) {
277         ss << "(" << static_cast<int32_t>(avoidArea.first) << "," << avoidArea.second.ToString() << ")";
278     });
279     ss << "]";
280     return ss.str();
281 }
282 
CloseGlobalModalUIExtension(int32_t instanceId,int32_t sessionId,const std::string & name)283 bool CloseGlobalModalUIExtension(int32_t instanceId, int32_t sessionId, const std::string& name)
284 {
285     auto globalPipelineManager = GlobalPipelineContextManager::GetInstance();
286     auto uecName = name.empty() ? globalPipelineManager->GetUecNameBySessionId(sessionId) : name;
287     if (uecName.empty()) {
288         return false;
289     }
290 
291     auto globalPipeline = globalPipelineManager->RemoveGlobalPipelineContext(uecName);
292     auto modalPageNode = globalPipelineManager->RemoveModalPageNode(uecName);
293     globalPipelineManager->RemoveSessionId(uecName);
294     CHECK_NULL_RETURN(globalPipeline, false);
295     CHECK_NULL_RETURN(modalPageNode, false);
296     auto parentNode = modalPageNode->GetParent();
297     if (parentNode) {
298         parentNode->RemoveChild(modalPageNode);
299         parentNode->RebuildRenderContextTree();
300     }
301     modalPageNode->MountToParent(globalPipeline->GetRootElement());
302     auto globalOverlay = globalPipeline->GetOverlayManager();
303     CHECK_NULL_RETURN(globalOverlay, false);
304     globalOverlay->CloseModalUIExtension(sessionId);
305     globalPipeline->Destroy();
306     globalPipeline.Reset();
307     return true;
308 }
309 
UpdateModalUIExtensionCallback(std::string uecName,const ModalUIExtensionCallbacks & callbacks)310 bool UpdateModalUIExtensionCallback(std::string uecName, const ModalUIExtensionCallbacks& callbacks)
311 {
312     auto modalPageNode = GlobalPipelineContextManager::GetInstance()->GetModalPageNode(uecName);
313     CHECK_NULL_RETURN(modalPageNode, false);
314     auto uiExtNode = AceType::DynamicCast<NG::FrameNode>(modalPageNode->GetFirstChild());
315     if (!uiExtNode || uiExtNode->GetTag() != V2::UI_EXTENSION_COMPONENT_ETS_TAG) {
316         TAG_LOGE(AceLogTag::ACE_UIEXTENSIONCOMPONENT, "GlobalPipelineContext record error ModalUIExtension");
317         return false;
318     }
319     auto pattern = uiExtNode->GetPattern<NG::UIExtensionPattern>();
320     CHECK_NULL_RETURN(pattern, false);
321     pattern->SetOnReleaseCallback(std::move(callbacks.onRelease));
322     pattern->SetOnErrorCallback(std::move(callbacks.onError));
323     pattern->SetModalOnDestroy(std::move(callbacks.onDestroy));
324     return true;
325 }
326 
CreateGlobalModalUIExtension(const AAFwk::Want & want,int32_t & sessionId,const ModalUIExtensionCallbacks & callbacks,const ModalUIExtensionConfig & config,int32_t instanceId,OHOS::Rosen::Window * window)327 bool CreateGlobalModalUIExtension(const AAFwk::Want& want, int32_t &sessionId,
328     const ModalUIExtensionCallbacks& callbacks, const ModalUIExtensionConfig& config,
329     int32_t instanceId, OHOS::Rosen::Window* window)
330 {
331     const std::string uecName = want.GetElement().GetBundleName() + "." + want.GetElement().GetModuleName() +
332         "." + want.GetElement().GetAbilityName();
333     auto globalPipelineManager = GlobalPipelineContextManager::GetInstance();
334     auto globalPipelineContext =
335         globalPipelineManager->GetGlobalPipelineContext(uecName);
336     if (!globalPipelineContext) {
337         globalPipelineContext = globalPipelineManager->CreateGlobalPipelineContext(
338             uecName, window, FrontendType::DECLARATIVE_JS, instanceId);
339         globalPipelineContext->SetupRootElement();
340 
341         auto overlay = globalPipelineContext->GetOverlayManager();
342         CHECK_NULL_RETURN(overlay, false);
343         sessionId =
344             overlay->CreateModalUIExtension(want, callbacks, config); // ModalPage -> UIExtensionComponent
345         globalPipelineManager->RegisterSessionId(uecName, sessionId);
346         globalPipelineManager->ProcessModalPageNode(uecName, instanceId);
347     } else {
348         if (!UpdateModalUIExtensionCallback(uecName, callbacks)) {
349             CloseGlobalModalUIExtension(instanceId, 0, uecName);
350             TAG_LOGE(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
351                 "GlobalPipelineContext with the name %{public}s reuse error", uecName.c_str());
352             return false;
353         }
354         sessionId = globalPipelineManager->GetSessionId(uecName);
355         globalPipelineManager->ProcessModalPageNode(uecName, instanceId);
356     }
357     return true;
358 }
359 } // namespace
360 
361 const std::string SUBWINDOW_PREFIX = "ARK_APP_SUBWINDOW_";
362 const std::string SUBWINDOW_TOAST_DIALOG_PREFIX = "ARK_APP_SUBWINDOW_TOAST_DIALOG_";
363 const std::string SUBWINDOW_TOAST_PREFIX = "ARK_APP_SUBWINDOW_TOAST";
364 const int32_t REQUEST_CODE = -1;
365 constexpr uint32_t TIMEOUT_LIMIT = 5;
366 constexpr int32_t COUNT_LIMIT = 3;
367 
368 using ContentFinishCallback = std::function<void()>;
369 using ContentStartAbilityCallback = std::function<void(const std::string& address)>;
370 class ContentEventCallback final : public Platform::PlatformEventCallback {
371 public:
ContentEventCallback(ContentFinishCallback onFinish)372     explicit ContentEventCallback(ContentFinishCallback onFinish) : onFinish_(onFinish) {}
ContentEventCallback(ContentFinishCallback onFinish,ContentStartAbilityCallback onStartAbility)373     ContentEventCallback(ContentFinishCallback onFinish, ContentStartAbilityCallback onStartAbility)
374         : onFinish_(onFinish), onStartAbility_(onStartAbility)
375     {}
376     ~ContentEventCallback() override = default;
377 
OnFinish() const378     void OnFinish() const override
379     {
380         CHECK_NULL_VOID(onFinish_);
381         onFinish_();
382     }
383 
OnStartAbility(const std::string & address)384     void OnStartAbility(const std::string& address) override
385     {
386         CHECK_NULL_VOID(onStartAbility_);
387         onStartAbility_(address);
388     }
389 
OnStatusBarBgColorChanged(uint32_t color)390     void OnStatusBarBgColorChanged(uint32_t color) override
391     {
392         LOGI("StatusBarBgColorChanged: %{public}u", color);
393     }
394 
395 private:
396     ContentFinishCallback onFinish_;
397     ContentStartAbilityCallback onStartAbility_;
398 };
399 
OHOS_ACE_CreateUIContent(void * context,void * runtime,int32_t vmType)400 extern "C" ACE_FORCE_EXPORT void* OHOS_ACE_CreateUIContent(void* context, void* runtime, int32_t vmType)
401 {
402     LOGI("CreateUIContent.");
403     Recorder::Init();
404     return new UIContentImpl(
405         reinterpret_cast<OHOS::AbilityRuntime::Context*>(context), runtime, static_cast<VMType>(vmType));
406 }
407 
OHOS_ACE_CreateFormContent(void * context,void * runtime,bool isCard)408 extern "C" ACE_FORCE_EXPORT void* OHOS_ACE_CreateFormContent(void* context, void* runtime, bool isCard)
409 {
410     TAG_LOGI(AceLogTag::ACE_FORM, "CreateFormUIContent.");
411     Recorder::Init();
412     return new UIContentImpl(reinterpret_cast<OHOS::AbilityRuntime::Context*>(context), runtime, isCard);
413 }
414 
OHOS_ACE_CreateSubWindowUIContent(void * ability)415 extern "C" ACE_FORCE_EXPORT void* OHOS_ACE_CreateSubWindowUIContent(void* ability)
416 {
417     TAG_LOGI(AceLogTag::ACE_SUB_WINDOW, "Create SubWindowUIContent.");
418     Recorder::Init();
419     return new UIContentImpl(reinterpret_cast<OHOS::AppExecFwk::Ability*>(ability));
420 }
421 
OHOS_ACE_GetUIContent(int32_t instanceId)422 extern "C" ACE_FORCE_EXPORT void* OHOS_ACE_GetUIContent(int32_t instanceId)
423 {
424     LOGI("GetUIContent: %{public}d", instanceId);
425     auto uiWindow = Platform::AceContainer::GetUIWindow(instanceId);
426     CHECK_NULL_RETURN(uiWindow, nullptr);
427     return uiWindow->GetUIContent();
428 }
429 
OHOS_ACE_GetCurrentUIStackInfo()430 extern "C" ACE_FORCE_EXPORT char* OHOS_ACE_GetCurrentUIStackInfo()
431 {
432     auto container = Container::Current();
433     CHECK_NULL_RETURN(container, nullptr);
434     auto pipeline = container->GetPipelineContext();
435     CHECK_NULL_RETURN(pipeline, nullptr);
436     static auto tmp = pipeline->GetCurrentExtraInfo();
437     std::replace(tmp.begin(), tmp.end(), '\\', '/');
438     return tmp.data();
439 }
440 
AddAlarmLogFunc(const RefPtr<PipelineBase> & pipeline)441 void AddAlarmLogFunc(const RefPtr<PipelineBase>& pipeline)
442 {
443     std::function<void(uint64_t, int, int)> logFunc = [pipeline](uint64_t nodeId, int count, int num) {
444         auto rsUIContext = RsAdapter::GetRSUIContext(pipeline);
445         auto rsNode = rsUIContext ? rsUIContext->GetNodeMap().GetNode(nodeId)
446                         : Rosen::RSNodeMap::Instance().GetNode(nodeId);
447         if (rsNode == nullptr) {
448             LOGI("rsNodeId:%{public}" PRId64 "not found, sendCommands:%{public}d, totalNumber:%{public}d",
449                 nodeId, count, num);
450             return;
451         }
452         auto frameNodeId = rsNode->GetFrameNodeId();
453         auto frameNodeTag = rsNode->GetFrameNodeTag();
454         auto frameNode = NG::FrameNode::GetFrameNode(frameNodeTag, frameNodeId);
455         if (frameNode == nullptr) {
456             LOGI("frameNodeId:%{public}d not found, rsNodeId:%{public}" PRId64 " sendCommands:%{public}d, "
457                  "totalRsNodeNumber:%{public}d.",
458                 frameNodeId, nodeId, count, num);
459             return;
460         }
461         LOGI("frameNodeId:%{public}d found, rsNodeId:%{public}" PRId64 " sendCommands:%{public}d, "
462              "FrameNodeTag:%{public}s, totalRsNodeNumber:%{public}d",
463             frameNodeId, nodeId, count, frameNodeTag.c_str(), num);
464     };
465 
466     OHOS::Rosen::RSTransactionData::AddAlarmLog(logFunc);
467 }
468 
ParseAvoidAreasUpdate(const RefPtr<NG::PipelineContext> & context,const std::map<OHOS::Rosen::AvoidAreaType,OHOS::Rosen::AvoidArea> & avoidAreas,const ViewportConfig & config)469 bool ParseAvoidAreasUpdate(const RefPtr<NG::PipelineContext>& context,
470     const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas,
471     const ViewportConfig& config)
472 {
473     CHECK_NULL_RETURN(context, false);
474     auto safeAreaManager = context->GetSafeAreaManager();
475     CHECK_NULL_RETURN(safeAreaManager, false);
476     bool safeAreaUpdated = false;
477     for (auto& avoidArea : avoidAreas) {
478         if (avoidArea.first == OHOS::Rosen::AvoidAreaType::TYPE_SYSTEM) {
479             safeAreaUpdated |= safeAreaManager->UpdateSystemSafeArea(ConvertAvoidArea(avoidArea.second));
480         } else if (avoidArea.first == OHOS::Rosen::AvoidAreaType::TYPE_NAVIGATION_INDICATOR) {
481             safeAreaUpdated |= safeAreaManager->UpdateNavSafeArea(ConvertAvoidArea(avoidArea.second));
482         } else if (avoidArea.first == OHOS::Rosen::AvoidAreaType::TYPE_CUTOUT) {
483             safeAreaUpdated |= safeAreaManager->UpdateCutoutSafeArea(ConvertAvoidArea(avoidArea.second),
484                 NG::OptionalSize<uint32_t>(config.Width(), config.Height()));
485         }
486     }
487     if (safeAreaUpdated) {
488         context->SyncSafeArea(SafeAreaSyncType::SYNC_TYPE_AVOID_AREA);
489         return true;
490     }
491     return false;
492 }
493 
AvoidAreasUpdateOnUIExtension(const RefPtr<NG::PipelineContext> & context,const std::map<OHOS::Rosen::AvoidAreaType,OHOS::Rosen::AvoidArea> & avoidAreas)494 void AvoidAreasUpdateOnUIExtension(const RefPtr<NG::PipelineContext>& context,
495     const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas)
496 {
497     if (avoidAreas.empty()) {
498         return;
499     }
500     CHECK_NULL_VOID(context);
501     // for ui extension component
502     for (auto& avoidArea : avoidAreas) {
503         context->UpdateOriginAvoidArea(avoidArea.second, static_cast<uint32_t>(avoidArea.first));
504     }
505 }
506 
UpdateSafeArea(const RefPtr<PipelineBase> & pipelineContext,const std::map<OHOS::Rosen::AvoidAreaType,OHOS::Rosen::AvoidArea> & avoidAreas,const ViewportConfig & config,const RefPtr<Platform::AceContainer> & container)507 void UpdateSafeArea(const RefPtr<PipelineBase>& pipelineContext,
508     const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas,
509     const ViewportConfig& config,
510     const RefPtr<Platform::AceContainer>& container)
511 {
512     CHECK_NULL_VOID(container);
513     CHECK_NULL_VOID(pipelineContext);
514     auto context = AceType::DynamicCast<NG::PipelineContext>(pipelineContext);
515     CHECK_NULL_VOID(context);
516     auto safeAreaManager = context->GetSafeAreaManager();
517     CHECK_NULL_VOID(safeAreaManager);
518     uint32_t keyboardHeight = safeAreaManager->GetKeyboardInset().Length();
519     safeAreaManager->UpdateKeyboardSafeArea(keyboardHeight, config.Height());
520     ParseAvoidAreasUpdate(context, avoidAreas, config);
521     AvoidAreasUpdateOnUIExtension(context, avoidAreas);
522 }
523 
ClearAllMenuPopup(int32_t instanceId,WindowChangeType type)524 void ClearAllMenuPopup(int32_t instanceId, WindowChangeType type)
525 {
526     auto container = Platform::AceContainer::GetContainer(instanceId);
527     CHECK_NULL_VOID(container);
528     auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
529     CHECK_NULL_VOID(pipeline);
530     auto overlay = pipeline->GetOverlayManager();
531     CHECK_NULL_VOID(overlay);
532     // The non-subwindow menu and popup disappear when the window area changes, and do not follow the current logic.
533     if (type != WindowChangeType::RECT_CHANGE) {
534         overlay->HideAllMenusWithoutAnimation(false);
535         overlay->HideAllPopupsWithoutAnimation();
536     }
537     SubwindowManager::GetInstance()->ClearAllMenuPopup(instanceId);
538 }
539 
540 class OccupiedAreaChangeListener : public OHOS::Rosen::IOccupiedAreaChangeListener {
541 public:
OccupiedAreaChangeListener(int32_t instanceId)542     explicit OccupiedAreaChangeListener(int32_t instanceId) : instanceId_(instanceId) {}
543     ~OccupiedAreaChangeListener() = default;
544 
OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo> & info,const std::shared_ptr<OHOS::Rosen::RSTransaction> & rsTransaction)545     void OnSizeChange(const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info,
546         const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction)
547     {
548         auto rect = info->rect_;
549         double positionY = info->textFieldPositionY_;
550         double height = info->textFieldHeight_;
551         Rect keyboardRect = Rect(rect.posX_, rect.posY_, rect.width_, rect.height_);
552         LOGI("OccupiedAreaChange rect:%{public}s type: %{public}d, positionY:%{public}f, height:%{public}f, "
553              "instanceId_ %{public}d", keyboardRect.ToString().c_str(), info->type_, positionY, height, instanceId_);
554         CHECK_NULL_VOID(info->type_ == OHOS::Rosen::OccupiedAreaType::TYPE_INPUT);
555         auto container = Platform::AceContainer::GetContainer(instanceId_);
556         CHECK_NULL_VOID(container);
557         auto taskExecutor = container->GetTaskExecutor();
558         CHECK_NULL_VOID(taskExecutor);
559         auto context = container->GetPipelineContext();
560         CHECK_NULL_VOID(context);
561         auto pipeline = AceType::DynamicCast<NG::PipelineContext>(context);
562         if (pipeline) {
563             ContainerScope scope(instanceId_);
564             auto manager = pipeline->GetSafeAreaManager();
565             CHECK_NULL_VOID(manager);
566             manager->SetKeyboardInfo(keyboardRect.Height());
567             auto uiExtMgr = pipeline->GetUIExtensionManager();
568             if (uiExtMgr) {
569                 SetUIExtensionImeShow(keyboardRect);
570             }
571             if (uiExtMgr && uiExtMgr->NotifyOccupiedAreaChangeInfo(info)) {
572                 TAG_LOGI(AceLogTag::ACE_KEYBOARD, "uiExtension consumed");
573                 taskExecutor->PostTask([id = instanceId_] {
574                         ContainerScope scope(id);
575                         auto container = Platform::AceContainer::GetContainer(id);
576                         CHECK_NULL_VOID(container);
577                         auto context = container->GetPipelineContext();
578                         CHECK_NULL_VOID(context);
579                         context->OnVirtualKeyboardAreaChange(Rect(), 0, 0);
580                     }, TaskExecutor::TaskType::UI, "ArkUIVirtualKeyboardAreaChange");
581                 return;
582             }
583         }
584         if (container->IsSceneBoardWindow()) {
585             TAG_LOGD(AceLogTag::ACE_KEYBOARD, "SceneBoard window, no keyboard avoidance");
586             return;
587         }
588         auto curWindow = context->GetCurrentWindowRect();
589         positionY -= curWindow.Top();
590         ContainerScope scope(instanceId_);
591         if (LaterAvoid(keyboardRect, positionY, height)) {
592             return;
593         }
594         taskExecutor->PostSyncTask([context, keyboardRect, rsTransaction, positionY, height] {
595                 CHECK_NULL_VOID(context);
596                 context->OnVirtualKeyboardAreaChange(keyboardRect, positionY, height, rsTransaction);
597             }, TaskExecutor::TaskType::UI, "ArkUIVirtualKeyboardAreaChange");
598     }
599 
600 private:
LaterAvoid(const Rect & keyboardRect,double positionY,double height)601     bool LaterAvoid(const Rect& keyboardRect, double positionY, double height)
602     {
603         auto container = Platform::AceContainer::GetContainer(instanceId_);
604         CHECK_NULL_RETURN(container, false);
605         auto context = container->GetPipelineContext();
606         CHECK_NULL_RETURN(context, false);
607         auto pipeline = AceType::DynamicCast<NG::PipelineContext>(context);
608         CHECK_NULL_RETURN(pipeline, false);
609         auto textFieldManager = AceType::DynamicCast<NG::TextFieldManagerNG>(pipeline->GetTextFieldManager());
610         CHECK_NULL_RETURN(textFieldManager, false);
611         auto windowManager = pipeline->GetWindowManager();
612         CHECK_NULL_RETURN(windowManager, false);
613         auto windowMode = windowManager->GetWindowMode();
614         if (windowMode == WindowMode::WINDOW_MODE_FLOATING || windowMode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY) {
615             textFieldManager->SetLaterAvoid(false);
616             return false;
617         }
618         bool isRotate = false;
619         auto displayInfo = container->GetDisplayInfo();
620         if (displayInfo) {
621             auto dmRotation = static_cast<int32_t>(displayInfo->GetRotation());
622             isRotate = lastRotation != -1 && lastRotation != dmRotation;
623             lastRotation = dmRotation;
624         } else {
625             lastRotation = -1;
626         }
627         auto triggerAvoidTaskOrientation = textFieldManager->GetContextTriggerAvoidTaskOrientation();
628         textFieldManager->SetContextTriggerAvoidTaskOrientation(-1);
629         if ((isRotate && lastRotation == triggerAvoidTaskOrientation) ||
630             (textFieldManager->GetLaterAvoid() && NearEqual(0.0f, keyboardRect.Height()))) {
631             TAG_LOGI(AceLogTag::ACE_KEYBOARD, "no need to later avoid, trigger avoid now");
632             textFieldManager->SetLaterAvoid(false);
633             return false;
634         }
635         auto laterRect = textFieldManager->GetLaterAvoidKeyboardRect();
636         if (textFieldManager->GetLaterAvoid() && NearEqual(laterRect.Height(), keyboardRect.Height())) {
637             TAG_LOGI(AceLogTag::ACE_KEYBOARD, "will trigger avoid later, ignore this notify");
638             return true;
639         }
640         // do not avoid immediately when device is in rotation, trigger it after context trigger root rect update
641         if (textFieldManager->GetLaterAvoid() || isRotate) {
642             TAG_LOGI(AceLogTag::ACE_KEYBOARD, "rotation change to %{public}d, later avoid %{public}s %{public}f"
643                 "%{public}f", lastRotation, keyboardRect.ToString().c_str(), positionY, height);
644             NG::LaterAvoidInfo laterAvoidInfo = {true, keyboardRect, positionY, height, lastRotation };
645             textFieldManager->SetLaterAvoidArgs(laterAvoidInfo);
646             return true;
647         }
648         return false;
649     }
650 
SetUIExtensionImeShow(const Rect & keyboardRect)651     void SetUIExtensionImeShow(const Rect& keyboardRect)
652     {
653         auto container = Platform::AceContainer::GetContainer(instanceId_);
654         CHECK_NULL_VOID(container);
655         auto taskExecutor = container->GetTaskExecutor();
656         if (GreatNotEqual(keyboardRect.Height(), 0.0f)) {
657             taskExecutor->PostTask(
658                 [id = instanceId_] {
659                     ContainerScope scope(id);
660                     auto pipeline = NG::PipelineContext::GetCurrentContext();
661                     CHECK_NULL_VOID(pipeline);
662                     pipeline->SetUIExtensionImeShow(true);
663                 }, TaskExecutor::TaskType::UI, "ArkUISetUIExtensionImeShow");
664         } else {
665             taskExecutor->PostTask(
666                 [id = instanceId_] {
667                     ContainerScope scope(id);
668                     auto pipeline = NG::PipelineContext::GetCurrentContext();
669                     CHECK_NULL_VOID(pipeline);
670                     pipeline->SetUIExtensionImeShow(false);
671                 }, TaskExecutor::TaskType::UI, "ArkUISetUIExtensionImeHide");
672         }
673     }
674     int32_t instanceId_ = -1;
675     int32_t lastRotation = -1;
676 };
677 
678 class AvoidAreaChangedListener : public OHOS::Rosen::IAvoidAreaChangedListener {
679 public:
AvoidAreaChangedListener(int32_t instanceId)680     explicit AvoidAreaChangedListener(int32_t instanceId) : instanceId_(instanceId) {}
681     ~AvoidAreaChangedListener() = default;
682 
OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea avoidArea,OHOS::Rosen::AvoidAreaType type,const sptr<OHOS::Rosen::OccupiedAreaChangeInfo> & info)683     void OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea avoidArea, OHOS::Rosen::AvoidAreaType type,
684         const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info) override
685     {
686         Rect keyboardRect = Rect(0, 0, 0, 0);
687         double textFieldPositionY = 0.0f;
688         double textFieldHeight = 0.0f;
689 
690         if (info) {
691             auto rect = info->rect_;
692             keyboardRect = Rect(rect.posX_, rect.posY_, rect.width_, rect.height_);
693             textFieldPositionY = info->textFieldPositionY_;
694             textFieldHeight = info->textFieldHeight_;
695             ACE_SCOPED_TRACE("OnAvoidAreaChanged type: %d, value: %s; keyboardRect: %s, textFieldPositionY %f, "
696                 "textFieldHeight %f; instanceId: %d", type, avoidArea.ToString().c_str(),
697                 keyboardRect.ToString().c_str(), textFieldPositionY, textFieldHeight, instanceId_);
698             TAG_LOGI(ACE_LAYOUT, "OnAvoidAreaChanged type: %{public}d, value: %{public}s; keyboardRect: %{public}s, "
699                 "textFieldPositionY: %{public}f, textFieldHeight: %{public}f; instanceId: %{public}d",
700                 type, avoidArea.ToString().c_str(), keyboardRect.ToString().c_str(), textFieldPositionY,
701                 textFieldHeight, instanceId_);
702         } else {
703             ACE_SCOPED_TRACE("OnAvoidAreaChanged type: %d, value: %s, instanceId: %d, "
704             "keyboardInfo is null", type, avoidArea.ToString().c_str(), instanceId_);
705             TAG_LOGI(ACE_LAYOUT, "OnAvoidAreaChanged type: %{public}d, value: %{public}s; instanceId: %{public}d, "
706             "keyboardInfo is null", type, avoidArea.ToString().c_str(), instanceId_);
707         }
708         auto container = Platform::AceContainer::GetContainer(instanceId_);
709         CHECK_NULL_VOID(container);
710         auto pipeline = container->GetPipelineContext();
711         CHECK_NULL_VOID(pipeline);
712         auto taskExecutor = container->GetTaskExecutor();
713         CHECK_NULL_VOID(taskExecutor);
714         if (type == Rosen::AvoidAreaType::TYPE_SYSTEM) {
715             systemSafeArea_ = ConvertAvoidArea(avoidArea);
716         } else if (type == Rosen::AvoidAreaType::TYPE_NAVIGATION_INDICATOR) {
717             navigationBar_ = ConvertAvoidArea(avoidArea);
718         } else if (type == Rosen::AvoidAreaType::TYPE_CUTOUT) {
719             cutoutSafeArea_ = ConvertAvoidArea(avoidArea);
720         }
721         auto safeArea = systemSafeArea_;
722         auto navSafeArea = navigationBar_;
723         auto cutoutSafeArea = cutoutSafeArea_;
724         ContainerScope scope(instanceId_);
725         taskExecutor->PostTask(
726             [pipeline, safeArea, navSafeArea, cutoutSafeArea, type, avoidArea] {
727                 if (type == Rosen::AvoidAreaType::TYPE_SYSTEM) {
728                     pipeline->UpdateSystemSafeArea(safeArea, true);
729                 } else if (type == Rosen::AvoidAreaType::TYPE_NAVIGATION_INDICATOR) {
730                     pipeline->UpdateNavSafeArea(navSafeArea, true);
731                 } else if (type == Rosen::AvoidAreaType::TYPE_CUTOUT) {
732                     pipeline->UpdateCutoutSafeArea(cutoutSafeArea, true);
733                 }
734                 // for ui extension component
735                 pipeline->UpdateOriginAvoidArea(avoidArea, static_cast<uint32_t>(type));
736             },
737             TaskExecutor::TaskType::UI, "ArkUIUpdateOriginAvoidArea");
738 
739         CHECK_NULL_VOID(info);
740         CHECK_NULL_VOID(info->type_ == OHOS::Rosen::OccupiedAreaType::TYPE_INPUT);
741         auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(pipeline);
742         if (pipelineContext) {
743             ContainerScope scope(instanceId_);
744             auto manager = pipelineContext->GetSafeAreaManager();
745             CHECK_NULL_VOID(manager);
746             manager->SetKeyboardInfo(keyboardRect.Height());
747             auto uiExtensionManager = pipelineContext->GetUIExtensionManager();
748             CHECK_NULL_VOID(uiExtensionManager);
749             SetUIExtensionImeShow(keyboardRect);
750             if (uiExtensionManager->NotifyOccupiedAreaChangeInfo(info)) {
751                 TAG_LOGI(AceLogTag::ACE_KEYBOARD, "uiExtension consumed");
752                 taskExecutor->PostTask([id = instanceId_] {
753                         ContainerScope scope(id);
754                         auto container = Platform::AceContainer::GetContainer(id);
755                         CHECK_NULL_VOID(container);
756                         auto context = container->GetPipelineContext();
757                         CHECK_NULL_VOID(context);
758                         context->OnVirtualKeyboardAreaChange(Rect(), 0, 0);
759                     }, TaskExecutor::TaskType::UI, "ArkUIVirtualKeyboardAreaChange");
760                 return;
761             }
762         }
763     }
764 
765 private:
SetUIExtensionImeShow(const Rect & keyboardRect)766     void SetUIExtensionImeShow(const Rect& keyboardRect)
767     {
768         auto container = Platform::AceContainer::GetContainer(instanceId_);
769         CHECK_NULL_VOID(container);
770         auto taskExecutor = container->GetTaskExecutor();
771         if (GreatNotEqual(keyboardRect.Height(), 0.0f)) {
772             taskExecutor->PostTask(
773                 [id = instanceId_] {
774                     ContainerScope scope(id);
775                     auto pipeline = NG::PipelineContext::GetCurrentContext();
776                     CHECK_NULL_VOID(pipeline);
777                     pipeline->SetUIExtensionImeShow(true);
778                 }, TaskExecutor::TaskType::UI, "ArkUISetUIExtensionImeShow");
779         } else {
780             taskExecutor->PostTask(
781                 [id = instanceId_] {
782                     ContainerScope scope(id);
783                     auto pipeline = NG::PipelineContext::GetCurrentContext();
784                     CHECK_NULL_VOID(pipeline);
785                     pipeline->SetUIExtensionImeShow(false);
786                 }, TaskExecutor::TaskType::UI, "ArkUISetUIExtensionImeHide");
787         }
788     }
789     NG::SafeAreaInsets systemSafeArea_;
790     NG::SafeAreaInsets navigationBar_;
791     NG::SafeAreaInsets cutoutSafeArea_;
792     int32_t instanceId_ = -1;
793 };
794 
795 class PretendChangedListener : public OHOS::Rosen::IAvoidAreaChangedListener {
796 public:
PretendChangedListener(int32_t instanceId)797     explicit PretendChangedListener(int32_t instanceId) {}
798     ~PretendChangedListener() = default;
799 
OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea avoidArea,OHOS::Rosen::AvoidAreaType type,const sptr<OHOS::Rosen::OccupiedAreaChangeInfo> & info)800     void OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea avoidArea, OHOS::Rosen::AvoidAreaType type,
801         const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info) override {}
802 };
803 
804 class AvailableAreaChangedListener : public OHOS::Rosen::DisplayManager::IAvailableAreaListener {
805 public:
AvailableAreaChangedListener(int32_t instanceId)806     explicit AvailableAreaChangedListener(int32_t instanceId) : instanceId_(instanceId) {}
807     ~AvailableAreaChangedListener() = default;
808 
OnAvailableAreaChanged(const Rosen::DMRect availableArea)809     void OnAvailableAreaChanged(const Rosen::DMRect availableArea) override
810     {
811         auto container = Platform::AceContainer::GetContainer(instanceId_);
812         CHECK_NULL_VOID(container);
813         auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
814         CHECK_NULL_VOID(pipeline);
815         auto taskExecutor = container->GetTaskExecutor();
816         CHECK_NULL_VOID(taskExecutor);
817         auto displayAvailableRect = ConvertDMRect2Rect(availableArea);
818         ContainerScope scope(instanceId_);
819         taskExecutor->PostTask(
820             [pipeline, displayAvailableRect] {
821                 pipeline->UpdateDisplayAvailableRect(displayAvailableRect);
822                 TAG_LOGI(AceLogTag::ACE_WINDOW, "UpdateDisplayAvailableRect : %{public}s",
823                     displayAvailableRect.ToString().c_str());
824             },
825             TaskExecutor::TaskType::UI, "ArkUIUpdateDisplayAvailableRect");
826     }
827 
828 private:
829     int32_t instanceId_ = -1;
830 };
831 
832 class DragWindowListener : public OHOS::Rosen::IWindowDragListener {
833 public:
DragWindowListener(int32_t instanceId)834     explicit DragWindowListener(int32_t instanceId) : instanceId_(instanceId) {}
835     ~DragWindowListener() = default;
OnDrag(int32_t x,int32_t y,OHOS::Rosen::DragEvent event)836     void OnDrag(int32_t x, int32_t y, OHOS::Rosen::DragEvent event)
837     {
838         auto container = Platform::AceContainer::GetContainer(instanceId_);
839         CHECK_NULL_VOID(container);
840         int32_t instanceId = instanceId_;
841         if (container->IsSubContainer()) {
842             instanceId = container->GetParentId();
843         }
844         auto aceView =
845             AceType::DynamicCast<Platform::AceViewOhos>(Platform::AceContainer::GetContainer(instanceId)->GetAceView());
846         CHECK_NULL_VOID(aceView);
847         DragEventAction action;
848         switch (event) {
849             case OHOS::Rosen::DragEvent::DRAG_EVENT_END:
850                 action = DragEventAction::DRAG_EVENT_END;
851                 break;
852             case OHOS::Rosen::DragEvent::DRAG_EVENT_OUT:
853                 action = DragEventAction::DRAG_EVENT_OUT;
854                 break;
855             case OHOS::Rosen::DragEvent::DRAG_EVENT_MOVE:
856                 action = DragEventAction::DRAG_EVENT_MOVE;
857                 break;
858             case OHOS::Rosen::DragEvent::DRAG_EVENT_IN:
859             default:
860                 action = DragEventAction::DRAG_EVENT_START;
861                 break;
862         }
863         CHECK_NULL_VOID(static_cast<int>(action));
864     }
865 
866 private:
867     int32_t instanceId_ = -1;
868 };
869 
870 class WaterfallModeChangeListener : public OHOS::Rosen::IWaterfallModeChangeListener {
871 public:
WaterfallModeChangeListener(int32_t instanceId)872     explicit WaterfallModeChangeListener(int32_t instanceId) : instanceId_(instanceId) {}
873     ~WaterfallModeChangeListener() = default;
874 
OnWaterfallModeChange(bool enable)875     void OnWaterfallModeChange(bool enable) override
876     {
877         TAG_LOGI(AceLogTag::ACE_WINDOW, "waterfall mode is changed, waterfallMode: %{public}d", enable);
878         auto container = Platform::AceContainer::GetContainer(instanceId_);
879         CHECK_NULL_VOID(container);
880         auto taskExecutor = container->GetTaskExecutor();
881         CHECK_NULL_VOID(taskExecutor);
882         ContainerScope scope(instanceId_);
883         taskExecutor->PostTask(
884             [instanceId = instanceId_, enable] {
885                 SubwindowManager::GetInstance()->OnWaterfallModeChanged(instanceId, enable);
886             },
887             TaskExecutor::TaskType::UI, "ArkUIWaterfallModeChanged");
888     }
889 
890 private:
891     int32_t instanceId_ = -1;
892 };
893 
894 class FoldScreenListener : public OHOS::Rosen::DisplayManager::IFoldStatusListener {
895 public:
FoldScreenListener(int32_t instanceId)896     explicit FoldScreenListener(int32_t instanceId) : instanceId_(instanceId) {}
897     ~FoldScreenListener() = default;
OnFoldStatusChanged(OHOS::Rosen::FoldStatus foldStatus)898     void OnFoldStatusChanged(OHOS::Rosen::FoldStatus foldStatus) override
899     {
900         TAG_LOGI(AceLogTag::ACE_WINDOW, "fold status is changed, foldStatus: %{public}d", foldStatus);
901         auto container = Platform::AceContainer::GetContainer(instanceId_);
902         CHECK_NULL_VOID(container);
903         container->SetFoldStatusFromListener(static_cast<FoldStatus>(static_cast<uint32_t>(foldStatus)));
904         auto taskExecutor = container->GetTaskExecutor();
905         CHECK_NULL_VOID(taskExecutor);
906         ContainerScope scope(instanceId_);
907         taskExecutor->PostTask(
908             [instanceId = instanceId_, container, foldStatus] {
909                 auto context = container->GetPipelineContext();
910                 CHECK_NULL_VOID(context);
911                 auto aceFoldStatus = static_cast<FoldStatus>(static_cast<uint32_t>(foldStatus));
912                 context->OnFoldStatusChanged(aceFoldStatus);
913                 if (SystemProperties::IsSuperFoldDisplayDevice()) {
914                     ClearAllMenuPopup(instanceId, WindowChangeType::FOLD_STATUS_CHANGE);
915                 }
916             },
917             TaskExecutor::TaskType::UI, "ArkUIFoldStatusChanged");
918     }
919 
920 private:
921     int32_t instanceId_ = -1;
922 };
923 
924 class FoldDisplayModeListener : public OHOS::Rosen::DisplayManager::IDisplayModeListener {
925 public:
FoldDisplayModeListener(int32_t instanceId,bool isDialog=false)926     explicit FoldDisplayModeListener(int32_t instanceId, bool isDialog = false)
927         : instanceId_(instanceId), isDialog_(isDialog)
928     {}
929     ~FoldDisplayModeListener() = default;
OnDisplayModeChanged(OHOS::Rosen::FoldDisplayMode displayMode)930     void OnDisplayModeChanged(OHOS::Rosen::FoldDisplayMode displayMode) override
931     {
932         TAG_LOGI(AceLogTag::ACE_WINDOW, "display mode is changed, displayMode: %{public}d", displayMode);
933         if (!isDialog_) {
934             auto container = Platform::AceContainer::GetContainer(instanceId_);
935             CHECK_NULL_VOID(container);
936             auto taskExecutor = container->GetTaskExecutor();
937             CHECK_NULL_VOID(taskExecutor);
938             ContainerScope scope(instanceId_);
939             taskExecutor->PostTask(
940                 [container, displayMode] {
941                     auto context = container->GetPipelineContext();
942                     CHECK_NULL_VOID(context);
943                     auto aceDisplayMode = static_cast<FoldDisplayMode>(static_cast<uint32_t>(displayMode));
944                     context->OnFoldDisplayModeChanged(aceDisplayMode);
945                 },
946                 TaskExecutor::TaskType::UI, "ArkUIFoldDisplayModeChanged");
947             return;
948         }
949         auto container = Platform::DialogContainer::GetContainer(instanceId_);
950         CHECK_NULL_VOID(container);
951         auto taskExecutor = container->GetTaskExecutor();
952         CHECK_NULL_VOID(taskExecutor);
953         ContainerScope scope(instanceId_);
954         taskExecutor->PostTask(
955             [container, displayMode] {
956                 auto context = container->GetPipelineContext();
957                 CHECK_NULL_VOID(context);
958                 auto aceDisplayMode = static_cast<FoldDisplayMode>(static_cast<uint32_t>(displayMode));
959                 context->OnFoldDisplayModeChanged(aceDisplayMode);
960             },
961             TaskExecutor::TaskType::UI, "ArkUIDialogFoldDisplayModeChanged");
962     }
963 
964 private:
965     int32_t instanceId_ = -1;
966     bool isDialog_ = false;
967 };
968 
969 class TouchOutsideListener : public OHOS::Rosen::ITouchOutsideListener {
970 public:
TouchOutsideListener(int32_t instanceId)971     explicit TouchOutsideListener(int32_t instanceId) : instanceId_(instanceId) {}
972     ~TouchOutsideListener() = default;
973 
OnTouchOutside() const974     void OnTouchOutside() const
975     {
976         TAG_LOGI(AceLogTag::ACE_MENU, "window is touching outside. instance id is %{public}d", instanceId_);
977         auto container = Platform::AceContainer::GetContainer(instanceId_);
978         CHECK_NULL_VOID(container);
979         auto taskExecutor = container->GetTaskExecutor();
980         CHECK_NULL_VOID(taskExecutor);
981         ContainerScope scope(instanceId_);
982         taskExecutor->PostTask(
983             [instanceId = instanceId_, targetId = targetId_] {
984                 SubwindowManager::GetInstance()->ClearMenu();
985                 SubwindowManager::GetInstance()->ClearMenuNG(instanceId, targetId, true, true);
986                 SubwindowManager::GetInstance()->ClearPopupInSubwindow(instanceId, false);
987             },
988             TaskExecutor::TaskType::UI, "ArkUITouchOutsideSubwindowClear");
989     }
990 
991 private:
992     int32_t instanceId_ = -1;
993     int32_t targetId_ = -1;
994 };
995 
996 class WindowRectChangeListener : public OHOS::Rosen::IWindowRectChangeListener {
997 public:
WindowRectChangeListener(int32_t instanceId)998     explicit WindowRectChangeListener(int32_t instanceId) : instanceId_(instanceId) {}
999     ~WindowRectChangeListener() = default;
1000 
OnRectChange(OHOS::Rosen::Rect rect,OHOS::Rosen::WindowSizeChangeReason reason)1001     void OnRectChange(OHOS::Rosen::Rect rect, OHOS::Rosen::WindowSizeChangeReason reason)
1002     {
1003         TAG_LOGD(AceLogTag::ACE_WINDOW, "window size is changed. current rect width: %{public}u, "
1004             "height: %{public}u, left: %{public}d, top: %{public}d, instance id is %{public}d, reason: %{public}d",
1005             rect.width_, rect.height_, rect.posX_, rect.posY_, instanceId_, reason);
1006         auto container = Platform::AceContainer::GetContainer(instanceId_);
1007         CHECK_NULL_VOID(container);
1008         auto taskExecutor = container->GetTaskExecutor();
1009         CHECK_NULL_VOID(taskExecutor);
1010         bool isWindowSizeChanged = !isRectEquel(rect);
1011         lastRect_ = rect;
1012         taskExecutor->PostTask(
1013             [instanceId = instanceId_, isWindowSizeChanged] {
1014                 CHECK_EQUAL_VOID(isWindowSizeChanged, false);
1015                 ContainerScope scope(instanceId);
1016                 ClearAllMenuPopup(instanceId, WindowChangeType::RECT_CHANGE);
1017             },
1018             TaskExecutor::TaskType::UI, "ArkUIWindowRectChange");
1019     }
1020 
1021 private:
isRectEquel(OHOS::Rosen::Rect curRect) const1022     bool isRectEquel(OHOS::Rosen::Rect curRect) const
1023     {
1024         return curRect.width_ == lastRect_.width_ && curRect.height_ == lastRect_.height_ &&
1025             curRect.posX_ == lastRect_.posX_ && curRect.posY_ == lastRect_.posY_;
1026     }
1027     int32_t instanceId_ = -1;
1028     OHOS::Rosen::Rect lastRect_ = {0, 0, 0, 0};
1029 };
1030 
1031 class DisplayIdChangeListener : public OHOS::Rosen::IDisplayIdChangeListener {
1032 public:
DisplayIdChangeListener(int32_t instanceId)1033     explicit DisplayIdChangeListener(int32_t instanceId) : instanceId_(instanceId) {}
1034     ~DisplayIdChangeListener() = default;
1035 
OnDisplayIdChanged(OHOS::Rosen::DisplayId displayId)1036     void OnDisplayIdChanged(OHOS::Rosen::DisplayId displayId)
1037     {
1038         TAG_LOGD(AceLogTag::ACE_WINDOW, "DisplayId is changed, displayId id is %{public}d, instanceId: %{public}d",
1039             static_cast<int32_t>(displayId), instanceId_);
1040         auto container = Platform::AceContainer::GetContainer(instanceId_);
1041         CHECK_NULL_VOID(container);
1042         auto taskExecutor = container->GetTaskExecutor();
1043         CHECK_NULL_VOID(taskExecutor);
1044         taskExecutor->PostTask(
1045             [instanceId = instanceId_] {
1046                 ContainerScope scope(instanceId);
1047                 ClearAllMenuPopup(instanceId, WindowChangeType::DISPLAY_ID_CHANGE);
1048             },
1049             TaskExecutor::TaskType::UI, "ArkUIDisplayIdChange");
1050     }
1051 
1052 private:
1053     int32_t instanceId_ = -1;
1054 };
1055 
UIContentImpl(OHOS::AbilityRuntime::Context * context,void * runtime,VMType vmType)1056 UIContentImpl::UIContentImpl(OHOS::AbilityRuntime::Context* context, void* runtime, VMType vmType)
1057     : runtime_(runtime), vmType_(vmType)
1058 {
1059     MultiThreadBuildManager::InitOnUIThread();
1060     CHECK_NULL_VOID(context);
1061     context_ = context->weak_from_this();
1062     bundleName_ = context->GetBundleName();
1063     auto hapModuleInfo = context->GetHapModuleInfo();
1064     CHECK_NULL_VOID(hapModuleInfo);
1065     moduleName_ = hapModuleInfo->name;
1066     StoreConfiguration(context->GetConfiguration());
1067 }
1068 
UIContentImpl(OHOS::AbilityRuntime::Context * context,void * runtime,bool isCard)1069 UIContentImpl::UIContentImpl(OHOS::AbilityRuntime::Context* context, void* runtime, bool isCard)
1070     : runtime_(runtime), isFormRender_(isCard)
1071 {
1072     MultiThreadBuildManager::InitOnUIThread();
1073     CHECK_NULL_VOID(context);
1074     bundleName_ = context->GetBundleName();
1075     if (CJUtils::IsCJFrontendContext(context)) {
1076         LOGD("UIContentImpl cj");
1077         context_ = context->weak_from_this();
1078         SetConfiguration(context->GetConfiguration());
1079     } else {
1080         auto hapModuleInfo = context->GetHapModuleInfo();
1081         CHECK_NULL_VOID(hapModuleInfo);
1082         moduleName_ = hapModuleInfo->name;
1083         hapPath_ = hapModuleInfo->hapPath;
1084         isBundle_ = (hapModuleInfo->compileMode == AppExecFwk::CompileMode::JS_BUNDLE);
1085         SetConfiguration(context->GetConfiguration());
1086         context_ = context->weak_from_this();
1087     }
1088 }
1089 
UIContentImpl(OHOS::AppExecFwk::Ability * ability)1090 UIContentImpl::UIContentImpl(OHOS::AppExecFwk::Ability* ability)
1091 {
1092     MultiThreadBuildManager::InitOnUIThread();
1093     CHECK_NULL_VOID(ability);
1094     context_ = ability->GetAbilityContext();
1095     auto context = context_.lock();
1096     CHECK_NULL_VOID(context);
1097     StoreConfiguration(context->GetConfiguration());
1098 }
1099 
DestroyUIDirector()1100 void UIContentImpl::DestroyUIDirector()
1101 {
1102 #ifndef NG_BUILD
1103     auto container = Platform::AceContainer::GetContainer(instanceId_);
1104     CHECK_NULL_VOID(container);
1105     auto pipelineContext = AceType::DynamicCast<PipelineContext>(container->GetPipelineContext());
1106     CHECK_NULL_VOID(pipelineContext);
1107 #ifdef ENABLE_ROSEN_BACKEND
1108     auto rsUIDirector = pipelineContext->GetRSUIDirector();
1109     CHECK_NULL_VOID(rsUIDirector);
1110     LOGI("[%{public}s][%{public}s][%{public}d]: Destroying old rsUIDirectory", bundleName_.c_str(), moduleName_.c_str(),
1111         instanceId_);
1112     rsUIDirector->Destroy();
1113 #endif
1114 #endif
1115 }
1116 
DestroyCallback() const1117 void UIContentImpl::DestroyCallback() const
1118 {
1119     auto container = Platform::AceContainer::GetContainer(instanceId_);
1120     CHECK_NULL_VOID(container);
1121     auto pipelineContext = container->GetPipelineContext();
1122     CHECK_NULL_VOID(pipelineContext);
1123     pipelineContext->SetNextFrameLayoutCallback(nullptr);
1124 }
1125 
InitializeInner(OHOS::Rosen::Window * window,const std::string & contentInfo,StorageWrapper storage,bool isNamedRouter)1126 UIContentErrorCode UIContentImpl::InitializeInner(
1127     OHOS::Rosen::Window* window, const std::string& contentInfo, StorageWrapper storage, bool isNamedRouter)
1128 {
1129     auto errorCode = UIContentErrorCode::NO_ERRORS;
1130     if (window && StringUtils::StartWith(window->GetWindowName(), SUBWINDOW_TOAST_DIALOG_PREFIX)) {
1131         return CommonInitialize(window, contentInfo, storage);
1132     }
1133     if (window) {
1134         errorCode = CommonInitialize(window, contentInfo, storage);
1135         CHECK_ERROR_CODE_RETURN(errorCode);
1136         bool isSceneBoardWindow = window->GetType() == Rosen::WindowType::WINDOW_TYPE_SCENE_BOARD;
1137         if (isSceneBoardWindow) {
1138             avoidAreaChangedListener_ = new AvoidAreaChangedListener(instanceId_);
1139             window->RegisterAvoidAreaChangeListener(avoidAreaChangedListener_);
1140         }
1141     }
1142 
1143     // ArkTSCard need no window : 梳理所有需要window和不需要window的场景
1144     if (isFormRender_ && !window) {
1145         LOGI("[%{public}s][%{public}s][%{public}d]: CommonInitializeForm url: %{public}s", bundleName_.c_str(),
1146             moduleName_.c_str(), instanceId_, contentInfo.c_str());
1147         errorCode = CommonInitializeForm(window, contentInfo, storage);
1148         CHECK_ERROR_CODE_RETURN(errorCode);
1149     }
1150     RunIntentPageIfNeeded();
1151     if (!restoreNavDestinationInfo_.empty()) {
1152         RestoreNavDestinationInfoInner(std::move(restoreNavDestinationInfo_), true);
1153         restoreNavDestinationInfo_ = "";
1154     }
1155     LOGI("[%{public}s][%{public}s][%{public}d]: Initialize: %{public}s", bundleName_.c_str(), moduleName_.c_str(),
1156         instanceId_, startUrl_.c_str());
1157     // run page.
1158     errorCode = Platform::AceContainer::RunPage(instanceId_, startUrl_, "", isNamedRouter);
1159     CHECK_ERROR_CODE_RETURN(errorCode);
1160     auto distributedUI = std::make_shared<NG::DistributedUI>();
1161     uiManager_ = std::make_unique<DistributedUIManager>(instanceId_, distributedUI);
1162     Platform::AceContainer::GetContainer(instanceId_)->SetDistributedUI(distributedUI);
1163     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionSubWindow(isUIExtensionSubWindow_);
1164     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionAbilityProcess(isUIExtensionAbilityProcess_);
1165     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionAbilityHost(isUIExtensionAbilityHost_);
1166     SubscribeEventsPassThroughMode();
1167 #if !defined(ACE_UNITTEST)
1168     auto pipelineContext = NG::PipelineContext::GetCurrentContext();
1169     CHECK_NULL_RETURN(pipelineContext, errorCode);
1170     auto rootNode = pipelineContext->GetRootElement();
1171     NG::TransparentNodeDetector::GetInstance().PostCheckNodeTransparentTask(rootNode, startUrl_);
1172 #endif
1173     return errorCode;
1174 }
1175 
SubscribeEventsPassThroughMode()1176 void UIContentImpl::SubscribeEventsPassThroughMode()
1177 {
1178     auto container = Platform::AceContainer::GetContainer(instanceId_);
1179     CHECK_NULL_VOID(container);
1180     auto taskExecutor = container->GetTaskExecutor();
1181     CHECK_NULL_VOID(taskExecutor);
1182     taskExecutor->PostTask(
1183         [instanceId = instanceId_]() {
1184             EventPassThroughSubscribeProxy::GetInstance()->SubscribeEvent(instanceId);
1185         },
1186         TaskExecutor::TaskType::BACKGROUND, "ArkUIRegisterEventsPassThroughAsync");
1187 }
1188 
UnSubscribeEventsPassThroughMode()1189 void UIContentImpl::UnSubscribeEventsPassThroughMode()
1190 {
1191     auto container = Platform::AceContainer::GetContainer(instanceId_);
1192     CHECK_NULL_VOID(container);
1193     auto taskExecutor = container->GetTaskExecutor();
1194     CHECK_NULL_VOID(taskExecutor);
1195     taskExecutor->PostTask(
1196         [instanceId = instanceId_]() {
1197             EventPassThroughSubscribeProxy::GetInstance()->UnSubscribeEvent(instanceId);
1198         },
1199         TaskExecutor::TaskType::BACKGROUND, "ArkUIUnSubscribeEventsPassThroughAsync");
1200 }
1201 
PreInitializeForm(OHOS::Rosen::Window * window,const std::string & url,napi_value storage)1202 void UIContentImpl::PreInitializeForm(OHOS::Rosen::Window* window, const std::string& url, napi_value storage)
1203 {
1204     StorageWrapper storageWrapper { .napiStorage_ = storage };
1205     // ArkTSCard need no window
1206     if (isFormRender_ && !window) {
1207         LOGI("[%{public}s][%{public}s][%{public}d]: InitializeForm: %{public}s", bundleName_.c_str(),
1208             moduleName_.c_str(), instanceId_, url.c_str());
1209         CommonInitializeForm(window, url, storageWrapper);
1210         AddWatchSystemParameter();
1211     }
1212 }
1213 
PreInitializeFormAni(OHOS::Rosen::Window * window,const std::string & url,ani_object storage)1214 void UIContentImpl::PreInitializeFormAni(OHOS::Rosen::Window* window, const std::string& url, ani_object storage)
1215 {
1216     StorageWrapper storageWrapper { .aniStorage_ = storage };
1217     // ArkTSCard need no window
1218     if (isFormRender_ && !window) {
1219         LOGI("[%{public}s][%{public}s][%{public}d]: InitializeForm: %{public}s", bundleName_.c_str(),
1220             moduleName_.c_str(), instanceId_, url.c_str());
1221         CommonInitializeForm(window, url, storageWrapper);
1222         AddWatchSystemParameter();
1223     }
1224 }
1225 
RunFormPage()1226 void UIContentImpl::RunFormPage()
1227 {
1228     LOGI("[%{public}s][%{public}s][%{public}d]: Initialize startUrl: %{public}s, \
1229         formData_.size:%{public}zu",
1230         bundleName_.c_str(), moduleName_.c_str(),
1231         instanceId_, startUrl_.c_str(),
1232         formData_.size());
1233     // run page.
1234     Platform::AceContainer::RunPage(instanceId_, startUrl_, formData_, false);
1235     auto distributedUI = std::make_shared<NG::DistributedUI>();
1236     uiManager_ = std::make_unique<DistributedUIManager>(instanceId_, distributedUI);
1237     auto container = Platform::AceContainer::GetContainer(instanceId_);
1238     CHECK_NULL_VOID(container);
1239     container->SetDistributedUI(distributedUI);
1240 }
1241 
Initialize(OHOS::Rosen::Window * window,const std::string & url,napi_value storage)1242 UIContentErrorCode UIContentImpl::Initialize(OHOS::Rosen::Window* window, const std::string& url, napi_value storage)
1243 {
1244     StorageWrapper storageWrapper { .napiStorage_ = storage };
1245     auto errorCode = InitializeInner(window, url, storageWrapper, false);
1246     AddWatchSystemParameter();
1247     UpdateWindowBlur();
1248     return errorCode;
1249 }
1250 
Initialize(OHOS::Rosen::Window * window,const std::shared_ptr<std::vector<uint8_t>> & content,napi_value storage)1251 UIContentErrorCode UIContentImpl::Initialize(
1252     OHOS::Rosen::Window* window, const std::shared_ptr<std::vector<uint8_t>>& content, napi_value storage)
1253 {
1254     std::string contentName = "";
1255     return Initialize(window, content, storage, contentName);
1256 }
1257 
Initialize(OHOS::Rosen::Window * window,const std::shared_ptr<std::vector<uint8_t>> & content,napi_value storage,const std::string & contentName)1258 UIContentErrorCode UIContentImpl::Initialize(OHOS::Rosen::Window* window,
1259     const std::shared_ptr<std::vector<uint8_t>>& content, napi_value storage, const std::string& contentName)
1260 {
1261     auto errorCode = UIContentErrorCode::NO_ERRORS;
1262     StorageWrapper storageWrapper { .napiStorage_ = storage };
1263     errorCode = CommonInitialize(window, "", storageWrapper);
1264     CHECK_ERROR_CODE_RETURN(errorCode);
1265     AddWatchSystemParameter();
1266     if (content) {
1267         LOGI("Initialize by buffer, size:%{public}zu", content->size());
1268         // run page.
1269         errorCode = Platform::AceContainer::RunPage(instanceId_, content, contentName);
1270         CHECK_ERROR_CODE_RETURN(errorCode);
1271     } else {
1272         LOGE("Initialize failed, buffer is null");
1273     }
1274     auto distributedUI = std::make_shared<NG::DistributedUI>();
1275     uiManager_ = std::make_unique<DistributedUIManager>(instanceId_, distributedUI);
1276     Platform::AceContainer::GetContainer(instanceId_)->SetDistributedUI(distributedUI);
1277     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionSubWindow(isUIExtensionSubWindow_);
1278     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionAbilityProcess(isUIExtensionAbilityProcess_);
1279     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionAbilityHost(isUIExtensionAbilityHost_);
1280     return errorCode;
1281 }
1282 
InitializeByName(OHOS::Rosen::Window * window,const std::string & name,napi_value storage)1283 UIContentErrorCode UIContentImpl::InitializeByName(
1284     OHOS::Rosen::Window* window, const std::string& name, napi_value storage)
1285 {
1286     StorageWrapper storageWrapper { .napiStorage_ = storage };
1287     auto errorCode = InitializeInner(window, name, storageWrapper, true);
1288     AddWatchSystemParameter();
1289     UpdateWindowBlur();
1290     return errorCode;
1291 }
1292 
InitializeDynamic(const DynamicInitialConfig & config)1293 void UIContentImpl::InitializeDynamic(const DynamicInitialConfig& config)
1294 {
1295     isDynamicRender_ = true;
1296     hapPath_ = config.hapPath;
1297     hostInstanceId_ = config.hostInstanceId;
1298     registerComponents_ = config.registerComponents;
1299     auto env = reinterpret_cast<napi_env>(runtime_);
1300     auto entryPoint = config.entryPoint;
1301     hostWindowInfo_ = config.hostWindowInfo;
1302     CHECK_NULL_VOID(env);
1303     taskWrapper_ = std::make_shared<NG::UVTaskWrapperImpl>(env);
1304 
1305     StorageWrapper storageWrapper { .napiStorage_ = nullptr };
1306     CommonInitializeForm(nullptr, config.abcPath, storageWrapper);
1307     AddWatchSystemParameter();
1308 
1309     LOGI("[%{public}s][%{public}s][%{public}d]: InitializeDynamic, startUrl"
1310          ": %{public}s, entryPoint: %{public}s",
1311         bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str(), entryPoint.c_str());
1312     Platform::AceContainer::RunDynamicPage(instanceId_, startUrl_, "", entryPoint);
1313     auto distributedUI = std::make_shared<NG::DistributedUI>();
1314     uiManager_ = std::make_unique<DistributedUIManager>(instanceId_, distributedUI);
1315     auto container = Platform::AceContainer::GetContainer(instanceId_);
1316     container->SetDistributedUI(distributedUI);
1317     ContainerScope scope(instanceId_);
1318     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
1319     CHECK_NULL_VOID(pipelineContext);
1320     auto stageManager = pipelineContext->GetStageManager();
1321     CHECK_NULL_VOID(stageManager);
1322     auto stageNode = stageManager->GetStageNode();
1323     CHECK_NULL_VOID(stageNode);
1324     auto renderContext = stageNode->GetRenderContext();
1325     CHECK_NULL_VOID(renderContext);
1326     renderContext->UpdateWindowBlur();
1327 }
1328 
Initialize(OHOS::Rosen::Window * window,const std::string & url,napi_value storage,uint32_t focusWindowId)1329 void UIContentImpl::Initialize(
1330     OHOS::Rosen::Window* window, const std::string& url, napi_value storage, uint32_t focusWindowId)
1331 {
1332     if (window == nullptr) {
1333         LOGE("UIExtensionAbility [%{public}s][%{public}s][%{public}d][%{public}s] initialize ui instance failed, the"
1334              "window is invalid",
1335             bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str());
1336         return;
1337     }
1338     StorageWrapper storageWrapper { .napiStorage_ = storage };
1339     auto errorCode = CommonInitialize(window, url, storageWrapper, focusWindowId);
1340     if (errorCode != UIContentErrorCode::NO_ERRORS) {
1341         return;
1342     }
1343     AddWatchSystemParameter();
1344     auto container = Platform::AceContainer::GetContainer(instanceId_);
1345     CHECK_NULL_VOID(container);
1346     container->SetDrawReadyEventCallback();
1347     TAG_LOGI(AceLogTag::ACE_UIEXTENSIONCOMPONENT, "[%{public}s][%{public}s][%{public}d]: StartUIExtension: %{public}s",
1348         bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str());
1349     // run page.
1350     Platform::AceContainer::RunPage(instanceId_, startUrl_, "");
1351     auto distributedUI = std::make_shared<NG::DistributedUI>();
1352     uiManager_ = std::make_unique<DistributedUIManager>(instanceId_, distributedUI);
1353     Platform::AceContainer::GetContainer(instanceId_)->SetDistributedUI(distributedUI);
1354 #if !defined(ACE_UNITTEST)
1355     auto pipelineContext = NG::PipelineContext::GetCurrentContext();
1356     CHECK_NULL_VOID(pipelineContext);
1357     auto rootNode = pipelineContext->GetRootElement();
1358     NG::TransparentNodeDetector::GetInstance().PostCheckNodeTransparentTask(rootNode, startUrl_);
1359 #endif
1360 }
1361 
InitializeByName(OHOS::Rosen::Window * window,const std::string & name,napi_value storage,uint32_t focusWindowId)1362 void UIContentImpl::InitializeByName(OHOS::Rosen::Window *window,
1363     const std::string &name, napi_value storage, uint32_t focusWindowId)
1364 {
1365     if (window == nullptr) {
1366         TAG_LOGE(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
1367             "UIExtensionAbility [%{public}s][%{public}s][%{public}d][%{public}s]"
1368             "InitializeByName failed, the window is invalid",
1369             bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str());
1370         return;
1371     }
1372 
1373     StorageWrapper storageWrapper { .napiStorage_ = storage };
1374     auto errorCode = CommonInitialize(window, name, storageWrapper, focusWindowId);
1375     if (errorCode != UIContentErrorCode::NO_ERRORS) {
1376         TAG_LOGE(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
1377             "CommonInitialize failed when InitializeByName");
1378         return;
1379     }
1380 
1381     AddWatchSystemParameter();
1382     TAG_LOGI(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
1383         "[%{public}s][%{public}s][%{public}d]: StartUIExtensionByName: %{public}s",
1384         bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str());
1385     // run page.
1386     Platform::AceContainer::RunPage(instanceId_, startUrl_, "", true);
1387     auto distributedUI = std::make_shared<NG::DistributedUI>();
1388     uiManager_ = std::make_unique<DistributedUIManager>(instanceId_, distributedUI);
1389     auto container = Platform::AceContainer::GetContainer(instanceId_);
1390     CHECK_NULL_VOID(container);
1391     container->SetDistributedUI(distributedUI);
1392 #if !defined(ACE_UNITTEST)
1393     auto pipelineContext = NG::PipelineContext::GetContextByContainerId(instanceId_);
1394     CHECK_NULL_VOID(pipelineContext);
1395     auto rootNode = pipelineContext->GetRootElement();
1396     NG::TransparentNodeDetector::GetInstance().PostCheckNodeTransparentTask(rootNode, startUrl_);
1397 #endif
1398 }
1399 
GetUINapiContext()1400 napi_value UIContentImpl::GetUINapiContext()
1401 {
1402     auto container = Platform::AceContainer::GetContainer(instanceId_);
1403     ContainerScope scope(instanceId_);
1404     napi_value result = nullptr;
1405     auto frontend = container->GetFrontend();
1406     CHECK_NULL_RETURN(frontend, result);
1407     if (frontend->GetType() == FrontendType::DECLARATIVE_JS) {
1408 #ifdef NG_BUILD
1409         auto declarativeFrontend = AceType::DynamicCast<DeclarativeFrontendNG>(frontend);
1410 #else
1411         auto declarativeFrontend = AceType::DynamicCast<DeclarativeFrontend>(frontend);
1412 #endif
1413         CHECK_NULL_RETURN(declarativeFrontend, result);
1414         return declarativeFrontend->GetContextValue();
1415     }
1416 
1417     return result;
1418 }
1419 
GetUIAniContext()1420 ani_object UIContentImpl::GetUIAniContext()
1421 {
1422     auto container = Platform::AceContainer::GetContainer(instanceId_);
1423     ContainerScope scope(instanceId_);
1424     ani_object result = nullptr;
1425     auto frontend = container->GetFrontend();
1426     CHECK_NULL_RETURN(frontend, result);
1427     auto arktsFrontend = AceType::DynamicCast<ArktsFrontend>(frontend);
1428     CHECK_NULL_RETURN(arktsFrontend, result);
1429     result = arktsFrontend->CallGetUIContextFunc();
1430     return result;
1431 }
1432 
Restore(OHOS::Rosen::Window * window,const std::string & contentInfo,napi_value storage,ContentInfoType type)1433 UIContentErrorCode UIContentImpl::Restore(
1434     OHOS::Rosen::Window* window, const std::string& contentInfo, napi_value storage, ContentInfoType type)
1435 {
1436     LOGI("Restore with contentInfo size: %{public}d, ContentInfotype: %{public}d",
1437         static_cast<int32_t>(contentInfo.size()), static_cast<int32_t>(type));
1438     auto errorCode = UIContentErrorCode::NO_ERRORS;
1439     StorageWrapper storageWrapper { .napiStorage_ = storage };
1440     errorCode = CommonInitialize(window, contentInfo, storageWrapper);
1441     CHECK_ERROR_CODE_RETURN(errorCode);
1442     RouterRecoverRecord record;
1443     std::tie(record, errorCode) = Platform::AceContainer::RestoreRouterStack(instanceId_, contentInfo, type);
1444     startUrl_ = record.url;
1445     CHECK_ERROR_CODE_RETURN(errorCode);
1446     if (startUrl_.empty()) {
1447         LOGW("Restore start url is empty");
1448     }
1449     LOGI("[%{public}s][%{public}s][%{public}d]: Restore startUrl: %{public}s, isNamedRouter: %{public}s",
1450         bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str(),
1451         (record.isNamedRouter ? "yes" : "no"));
1452     return Platform::AceContainer::RunPage(instanceId_, startUrl_, record.params, record.isNamedRouter);
1453 }
1454 
Restore(OHOS::Rosen::Window * window,const std::string & contentInfo,ani_object storage,ContentInfoType type)1455 UIContentErrorCode UIContentImpl::Restore(
1456     OHOS::Rosen::Window* window, const std::string& contentInfo, ani_object storage, ContentInfoType type)
1457 {
1458     LOGI("Restore with contentInfo size: %{public}d, ContentInfotype: %{public}d",
1459         static_cast<int32_t>(contentInfo.size()), static_cast<int32_t>(type));
1460     auto errorCode = UIContentErrorCode::NO_ERRORS;
1461     StorageWrapper storageWrapper { .aniStorage_ = storage };
1462     errorCode = CommonInitialize(window, contentInfo, storageWrapper);
1463     CHECK_ERROR_CODE_RETURN(errorCode);
1464     RouterRecoverRecord record;
1465     std::tie(record, errorCode) = Platform::AceContainer::RestoreRouterStack(instanceId_, contentInfo, type);
1466     startUrl_ = record.url;
1467     CHECK_ERROR_CODE_RETURN(errorCode);
1468     if (startUrl_.empty()) {
1469         LOGW("Restore start url is empty");
1470     }
1471     LOGI("[%{public}s][%{public}s][%{public}d]: Restore startUrl: %{public}s, isNamedRouter: %{public}s",
1472         bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str(),
1473         (record.isNamedRouter ? "yes" : "no"));
1474     return Platform::AceContainer::RunPage(instanceId_, startUrl_, record.params, record.isNamedRouter);
1475 }
1476 
GetContentInfo(ContentInfoType type) const1477 std::string UIContentImpl::GetContentInfo(ContentInfoType type) const
1478 {
1479     LOGI("[%{public}s][%{public}s][%{public}d]: GetContentInfoType: %{public}d",
1480         bundleName_.c_str(), moduleName_.c_str(), instanceId_, type);
1481     return Platform::AceContainer::GetContentInfo(instanceId_, type);
1482 }
1483 
1484 // ArkTSCard start
CommonInitializeForm(OHOS::Rosen::Window * window,const std::string & contentInfo,StorageWrapper storageWrapper)1485 UIContentErrorCode UIContentImpl::CommonInitializeForm(
1486     OHOS::Rosen::Window* window, const std::string& contentInfo, StorageWrapper storageWrapper)
1487 {
1488     ACE_FUNCTION_TRACE();
1489     window_ = window;
1490     startUrl_ = contentInfo;
1491     auto errorCode = UIContentErrorCode::NO_ERRORS;
1492 
1493     if (window_) {
1494         if (StringUtils::StartWith(window->GetWindowName(), SUBWINDOW_TOAST_DIALOG_PREFIX)) {
1495             InitializeSubWindow(window_, true);
1496             return errorCode;
1497         }
1498         if (StringUtils::StartWith(window->GetWindowName(), SUBWINDOW_PREFIX)) {
1499             InitializeSubWindow(window_);
1500             return errorCode;
1501         }
1502     }
1503 
1504     auto context = context_.lock();
1505     static std::once_flag onceFlag;
1506     auto configuration = context->GetConfiguration();
1507     std::unordered_map<std::string, DeviceType> typeMap = { { "phone", DeviceType::PHONE }, { "tv", DeviceType::TV },
1508         { "watch", DeviceType::WATCH }, { "car", DeviceType::CAR }, { "tablet", DeviceType::TABLET },
1509         { "2in1", DeviceType::TWO_IN_ONE }, { "wearable", DeviceType::WEARABLE }, { "UNKNOWN", DeviceType::UNKNOWN } };
1510     if (configuration) {
1511         auto type = configuration->GetItem(OHOS::AAFwk::GlobalConfigurationKey::DEVICE_TYPE);
1512         if (typeMap.find(type) != typeMap.end()) {
1513             SystemProperties::SetDeviceType(typeMap[type]);
1514         }
1515     } else {
1516         LOGD("configuration is nullptr,use default type");
1517     }
1518     if (!isFormRender_) {
1519         std::call_once(onceFlag, [&context]() {
1520             SetHwIcuDirectory();
1521             Container::UpdateCurrent(INSTANCE_ID_PLATFORM);
1522             AceApplicationInfo::GetInstance().SetProcessName(context->GetBundleName());
1523             AceApplicationInfo::GetInstance().SetPackageName(context->GetBundleName());
1524             AceApplicationInfo::GetInstance().SetDataFileDirPath(context->GetFilesDir());
1525             AceApplicationInfo::GetInstance().SetUid(IPCSkeleton::GetCallingUid());
1526             AceApplicationInfo::GetInstance().SetPid(IPCSkeleton::GetCallingRealPid());
1527             CapabilityRegistry::Register();
1528             ImageFileCache::GetInstance().SetImageCacheFilePath(context->GetCacheDir());
1529         });
1530     }
1531 
1532     bool useNewPipe = true;
1533     int32_t deviceWidth = 0;
1534     int32_t deviceHeight = 0;
1535     float density = 1.0f;
1536     auto defaultDisplay = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
1537     if (defaultDisplay) {
1538         auto displayInfo = defaultDisplay->GetDisplayInfo();
1539         if (displayInfo) {
1540             density = displayInfo->GetDensityInCurResolution();
1541         }
1542         deviceWidth = defaultDisplay->GetWidth();
1543         deviceHeight = defaultDisplay->GetHeight();
1544         TAG_LOGI(AceLogTag::ACE_FORM,
1545             "[%{public}s][%{public}s][%{public}d]: CommonInitializeForm virtualPixelRatio: %{public}f, deviceWidth: "
1546             "%{public}d, deviceHeight: %{public}d",
1547             bundleName_.c_str(), moduleName_.c_str(), instanceId_, density, deviceWidth, deviceHeight);
1548     }
1549 
1550     SystemProperties::InitDeviceInfo(deviceWidth, deviceHeight, deviceHeight >= deviceWidth ? 0 : 1, density, false);
1551     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
1552     ColorMode colorMode = Container::CurrentColorMode();
1553     if (context) {
1554         auto resourceManager = context->GetResourceManager();
1555         if (resourceManager != nullptr) {
1556             resourceManager->GetResConfig(*resConfig);
1557             auto localeInfo = resConfig->GetLocaleInfo();
1558             Platform::AceApplicationInfoImpl::GetInstance().SetResourceManager(resourceManager);
1559             if (localeInfo != nullptr) {
1560                 auto language = localeInfo->getLanguage();
1561                 auto region = localeInfo->getCountry();
1562                 auto script = localeInfo->getScript();
1563                 AceApplicationInfo::GetInstance().SetLocale((language == nullptr) ? "" : language,
1564                     (region == nullptr) ? "" : region, (script == nullptr) ? "" : script, "");
1565             }
1566             if (resConfig->GetColorMode() == OHOS::Global::Resource::ColorMode::DARK) {
1567                 colorMode = ColorMode::DARK;
1568                 LOGI("Set dark mode");
1569             } else {
1570                 colorMode = ColorMode::LIGHT;
1571                 LOGI("Set light mode");
1572             }
1573             SystemProperties::SetDeviceAccess(
1574                 resConfig->GetInputDevice() == Global::Resource::InputDevice::INPUTDEVICE_POINTINGDEVICE);
1575         } else {
1576             auto config = context->GetConfiguration();
1577             if (config) {
1578                 auto configColorMode = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
1579                 colorMode = configColorMode == "dark" ? ColorMode::DARK : ColorMode::LIGHT;
1580             }
1581         }
1582     }
1583 
1584     auto abilityContext = OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(context);
1585     std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> info;
1586     if (abilityContext) {
1587         info = abilityContext->GetAbilityInfo();
1588     } else {
1589         auto extensionContext =
1590             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::ExtensionContext>(context);
1591         if (extensionContext) {
1592             info = extensionContext->GetAbilityInfo();
1593         }
1594     }
1595     if (info) {
1596         AceApplicationInfo::GetInstance().SetAbilityName(info->name);
1597     }
1598 
1599     RefPtr<AssetManagerImpl> assetManagerImpl = Referenced::MakeRefPtr<AssetManagerImpl>();
1600     bool isModelJson = info != nullptr ? info->isModuleJson : false;
1601     std::string moduleName = info != nullptr ? info->moduleName : "";
1602     auto appInfo = context != nullptr ? context->GetApplicationInfo() : nullptr;
1603     auto hapModuleInfo = context != nullptr ? context->GetHapModuleInfo() : nullptr;
1604     auto bundleName = info != nullptr ? info->bundleName : "";
1605     std::string moduleHapPath = info != nullptr ? info->hapPath : "";
1606     std::string resPath;
1607     std::string pageProfile;
1608     if (isFormRender_) {
1609         std::vector<std::string> basePaths;
1610         basePaths.emplace_back("assets/js/" + moduleName_ + "/");
1611         basePaths.emplace_back("assets/js/share/");
1612         basePaths.emplace_back("");
1613         basePaths.emplace_back("js/");
1614         basePaths.emplace_back("ets/");
1615         auto assetProvider = CreateAssetProviderImpl(hapPath_, basePaths, false);
1616         if (assetProvider) {
1617             assetManagerImpl->PushBack(std::move(assetProvider));
1618         }
1619     } else {
1620         if (isModelJson) {
1621             std::string hapPath = info != nullptr ? info->hapPath : "";
1622             // first use hap provider
1623             if (assetManagerImpl && !hapPath.empty()) {
1624                 auto hapAssetProviderImpl = AceType::MakeRefPtr<HapAssetProviderImpl>();
1625                 if (hapAssetProviderImpl->Initialize(hapPath, { "", "ets/", "resources/base/profile/" })) {
1626                     assetManagerImpl->PushBack(std::move(hapAssetProviderImpl));
1627                 }
1628             }
1629 
1630             if (appInfo) {
1631                 std::vector<OHOS::AppExecFwk::ModuleInfo> moduleList = appInfo->moduleInfos;
1632                 for (const auto& module : moduleList) {
1633                     if (module.moduleName == moduleName) {
1634                         std::regex pattern(ABS_BUNDLE_CODE_PATH + bundleName + FILE_SEPARATOR);
1635                         auto moduleSourceDir =
1636                             std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
1637                         resPath = moduleSourceDir + "/";
1638                         break;
1639                     }
1640                 }
1641             }
1642 
1643             // second use file provider, will remove later
1644             auto assetBasePathStr = { std::string("ets/"), std::string("resources/base/profile/") };
1645             if (assetManagerImpl && !resPath.empty()) {
1646                 auto assetProvider = AceType::MakeRefPtr<FileAssetProviderImpl>();
1647                 if (assetProvider->Initialize(resPath, assetBasePathStr)) {
1648                     assetManagerImpl->PushBack(std::move(assetProvider));
1649                 }
1650             }
1651 
1652             if (hapModuleInfo) {
1653                 pageProfile = hapModuleInfo->pages;
1654                 const std::string profilePrefix = "$profile:";
1655                 if (pageProfile.compare(0, profilePrefix.size(), profilePrefix) == 0) {
1656                     pageProfile = pageProfile.substr(profilePrefix.length()).append(".json");
1657                 }
1658             }
1659         } else {
1660             auto packagePathStr = context->GetBundleCodeDir();
1661             if (hapModuleInfo != nullptr) {
1662                 packagePathStr += "/" + hapModuleInfo->package + "/";
1663             }
1664             std::string srcPath = "";
1665             if (info != nullptr && !info->srcPath.empty()) {
1666                 srcPath = info->srcPath;
1667             }
1668 
1669             auto assetBasePathStr = { "assets/js/" + (srcPath.empty() ? "default" : srcPath) + "/",
1670                 std::string("assets/js/share/") };
1671             if (assetManagerImpl && !packagePathStr.empty()) {
1672                 auto fileAssetProvider = AceType::MakeRefPtr<FileAssetProviderImpl>();
1673                 if (fileAssetProvider->Initialize(packagePathStr, assetBasePathStr)) {
1674                     assetManagerImpl->PushBack(std::move(fileAssetProvider));
1675                 }
1676             }
1677             if (appInfo) {
1678                 std::vector<OHOS::AppExecFwk::ModuleInfo> moduleList = appInfo->moduleInfos;
1679                 for (const auto& module : moduleList) {
1680                     if (module.moduleName == moduleName) {
1681                         std::regex pattern(ABS_BUNDLE_CODE_PATH + bundleName + FILE_SEPARATOR);
1682                         auto moduleSourceDir =
1683                             std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
1684                         resPath = moduleSourceDir + "/assets/" + module.moduleName + "/";
1685                         break;
1686                     }
1687                 }
1688             }
1689         }
1690     }
1691 
1692     std::string hapPath; // hap path in sandbox
1693     if (!moduleHapPath.empty()) {
1694         if (moduleHapPath.find(ABS_BUNDLE_CODE_PATH) == std::string::npos) {
1695             hapPath = moduleHapPath;
1696         } else {
1697             auto pos = moduleHapPath.find_last_of('/');
1698             if (pos != std::string::npos) {
1699                 hapPath = LOCAL_BUNDLE_CODE_PATH + moduleHapPath.substr(pos + 1);
1700             }
1701         }
1702     }
1703 
1704 #ifdef PLUGIN_COMPONENT_SUPPORTED
1705     auto pluginUtils = std::make_shared<PluginUtilsImpl>();
1706     PluginManager::GetInstance().SetAceAbility(nullptr, pluginUtils);
1707 #endif
1708     // create container
1709     if (runtime_) {
1710         instanceId_ = isDynamicRender_ ?
1711             Container::GenerateId<DC_CONTAINER>() : Container::GenerateId<STAGE_CONTAINER>();
1712     } else {
1713         instanceId_ = Container::GenerateId<FA_SUBWINDOW_CONTAINER>();
1714     }
1715 #ifdef FORM_SUPPORTED
1716     auto formUtils = std::make_shared<FormUtilsImpl>();
1717     FormManager::GetInstance().SetFormUtils(formUtils);
1718 #endif
1719     if (isDynamicRender_) {
1720         ContainerScope::UpdateLocalCurrent(instanceId_);
1721     }
1722     auto container =
1723         AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, FrontendType::DECLARATIVE_JS, context_, info,
1724             std::make_unique<ContentEventCallback>(
1725                 [window = window_] {
1726                     CHECK_NULL_VOID(window);
1727                     window->PerformBack();
1728                 },
1729                 [context = context_](const std::string& address) {
1730                     auto sharedContext = context.lock();
1731                     CHECK_NULL_VOID(sharedContext);
1732                     auto abilityContext =
1733                         OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
1734                     CHECK_NULL_VOID(abilityContext);
1735                     LOGI("Start ability: %{private}s", address.c_str());
1736                     AAFwk::Want want;
1737                     want.AddEntity(Want::ENTITY_BROWSER);
1738                     want.SetUri(address);
1739                     want.SetAction(ACTION_VIEWDATA);
1740                     abilityContext->StartAbility(want, REQUEST_CODE);
1741                 }),
1742             taskWrapper_, false, false, useNewPipe);
1743 
1744     CHECK_NULL_RETURN(container, UIContentErrorCode::NULL_POINTER);
1745     container->SetIsFormRender(isFormRender_);
1746     container->SetIsDynamicRender(isDynamicRender_);
1747     container->SetUIContentType(uIContentType_);
1748     container->SetRegisterComponents(registerComponents_);
1749     container->SetIsFRSCardContainer(isFormRender_);
1750     container->SetColorMode(colorMode);
1751     if (window_) {
1752         container->SetWindowName(window_->GetWindowName());
1753         container->SetWindowId(window_->GetWindowId());
1754     }
1755 
1756     if (context) {
1757         auto token = context->GetToken();
1758         container->SetToken(token);
1759     }
1760 
1761     if (appInfo) {
1762         container->SetApiTargetVersion(appInfo->apiTargetVersion);
1763     }
1764 
1765     // Mark the relationship between windowId and containerId, it is 1:1
1766     if (window) {
1767         SubwindowManager::GetInstance()->AddContainerId(window->GetWindowId(), instanceId_);
1768     }
1769     AceEngine::Get().AddContainer(instanceId_, container);
1770     if (runtime_) {
1771         container->GetSettings().SetUsingSharedRuntime(true);
1772         container->SetSharedRuntime(runtime_);
1773     } else {
1774         container->GetSettings().SetUsingSharedRuntime(false);
1775     }
1776     container->SetPageProfile(pageProfile);
1777     container->Initialize();
1778     ContainerScope scope(instanceId_);
1779     auto front = container->GetFrontend();
1780     if (front) {
1781         front->UpdateState(Frontend::State::ON_CREATE);
1782         front->SetJsMessageDispatcher(container);
1783     }
1784     auto aceResCfg = container->GetResourceConfiguration();
1785     aceResCfg.SetOrientation(SystemProperties::GetDeviceOrientation());
1786     aceResCfg.SetDensity(SystemProperties::GetResolution());
1787     aceResCfg.SetDeviceType(SystemProperties::GetDeviceType());
1788     aceResCfg.SetColorMode(container->GetColorMode());
1789     aceResCfg.SetDeviceAccess(SystemProperties::GetDeviceAccess());
1790     aceResCfg.SetLanguage(AceApplicationInfo::GetInstance().GetLocaleTag());
1791     AddResConfigInfo(context, aceResCfg);
1792     if (isDynamicRender_) {
1793         auto runtimeContext = Platform::AceContainer::GetRuntimeContext(hostInstanceId_);
1794         if (runtimeContext) {
1795             AddSetAppColorModeToResConfig(runtimeContext->shared_from_this(), aceResCfg);
1796         }
1797     } else {
1798         AddSetAppColorModeToResConfig(context, aceResCfg);
1799     }
1800     if (isDynamicRender_) {
1801         if (std::regex_match(hapPath_, std::regex(".*\\.hap"))) {
1802             hapPath = hapPath_;
1803         } else {
1804             resPath = hapPath_;
1805         }
1806     } else if (isFormRender_) {
1807         resPath = "/data/bundles/" + bundleName_ + "/" + moduleName_ + "/";
1808         hapPath = hapPath_;
1809     }
1810     TAG_LOGI(AceLogTag::ACE_FORM,
1811         "[%{public}s][%{public}s][%{public}d]: CommonInitializeForm resPath = %{public}s hapPath = %{public}s",
1812         bundleName_.c_str(), moduleName_.c_str(), instanceId_, resPath.c_str(), hapPath.c_str());
1813     container->SetResourceConfiguration(aceResCfg);
1814     container->SetPackagePathStr(resPath);
1815     container->SetHapPath(hapPath);
1816     container->SetAssetManager(assetManagerImpl);
1817 
1818     if (!isFormRender_) {
1819         container->SetBundlePath(context->GetBundleCodeDir());
1820         container->SetFilesDataPath(context->GetFilesDir());
1821     }
1822 
1823     if (window_) {
1824         if (window_->IsDecorEnable()) {
1825             container->SetWindowModal(WindowModal::CONTAINER_MODAL);
1826         }
1827 
1828         dragWindowListener_ = new DragWindowListener(instanceId_);
1829         window_->RegisterDragListener(dragWindowListener_);
1830         if (!container->IsSceneBoardEnabled()) {
1831             occupiedAreaChangeListener_ = new OccupiedAreaChangeListener(instanceId_);
1832             window_->RegisterOccupiedAreaChangeListener(occupiedAreaChangeListener_);
1833         }
1834     }
1835 
1836     // create ace_view
1837     RefPtr<Platform::AceViewOhos> aceView = nullptr;
1838     if (isFormRender_ && !isDynamicRender_) {
1839         aceView = Platform::AceViewOhos::CreateView(instanceId_, true, container->GetSettings().usePlatformAsUIThread);
1840         Platform::AceViewOhos::SurfaceCreated(aceView, window_);
1841     } else {
1842         aceView = Platform::AceViewOhos::CreateView(instanceId_, false, container->GetSettings().usePlatformAsUIThread);
1843         Platform::AceViewOhos::SurfaceCreated(aceView, window_);
1844     }
1845 
1846     if (isFormRender_) {
1847         errorCode = Platform::AceContainer::SetViewNew(aceView, density, round(formWidth_),
1848             round(formHeight_), window_);
1849         CHECK_ERROR_CODE_RETURN(errorCode);
1850         auto frontend = AceType::DynamicCast<FormFrontendDeclarative>(container->GetFrontend());
1851         CHECK_NULL_RETURN(frontend, UIContentErrorCode::NULL_POINTER);
1852         frontend->SetBundleName(bundleName_);
1853         frontend->SetModuleName(moduleName_);
1854         // arkTSCard only support "esModule" compile mode
1855         frontend->SetIsBundle(false);
1856         container->SetBundleName(bundleName_);
1857     } else {
1858         errorCode = Platform::AceContainer::SetViewNew(aceView, density, 0, 0, window_);
1859         CHECK_ERROR_CODE_RETURN(errorCode);
1860     }
1861 
1862     if (isDynamicRender_) {
1863         if (hostWindowInfo_.focusWindowId != 0) {
1864             container->SetFocusWindowId(hostWindowInfo_.focusWindowId);
1865         }
1866 
1867         if (hostWindowInfo_.realHostWindowId > 0) {
1868             container->SetRealHostWindowId(hostWindowInfo_.realHostWindowId);
1869         }
1870         LOGI("DynamicRender: focusWindowId: %{public}u, realHostWindowId: %{public}d",
1871             hostWindowInfo_.focusWindowId, hostWindowInfo_.realHostWindowId);
1872     }
1873 
1874     // after frontend initialize
1875     if (window_ && window_->IsFocused()) {
1876         Focus();
1877     }
1878 
1879     if (isFormRender_ && !isFormRenderInit_) {
1880         container->UpdateFormSharedImage(formImageDataMap_);
1881         container->UpdateFormData(formData_);
1882         isFormRenderInit_ = true;
1883         TAG_LOGI(AceLogTag::ACE_FORM, "isFormRenderInit_ true");
1884     }
1885 
1886     if (isFormRender_) {
1887         Platform::AceViewOhos::SurfaceChanged(aceView, round(formWidth_), round(formHeight_),
1888             deviceHeight >= deviceWidth ? 0 : 1);
1889         container->CheckAndSetFontFamily();
1890         SetFontScaleAndWeightScale(container, instanceId_);
1891         // Set sdk version in module json mode for form
1892         auto pipeline = container->GetPipelineContext();
1893         if (pipeline && appInfo) {
1894             pipeline->SetMinPlatformVersion(appInfo->apiCompatibleVersion);
1895             pipeline->SetApiTargetVersion(container->GetApiTargetVersion());
1896         }
1897     } else {
1898         Platform::AceViewOhos::SurfaceChanged(aceView, 0, 0, deviceHeight >= deviceWidth ? 0 : 1);
1899     }
1900     // Set sdk version in module json mode
1901     if (isModelJson) {
1902         auto pipeline = container->GetPipelineContext();
1903         if (pipeline && appInfo) {
1904             pipeline->SetMinPlatformVersion(appInfo->apiCompatibleVersion);
1905             pipeline->SetApiTargetVersion(container->GetApiTargetVersion());
1906         }
1907     }
1908     if (runtime_ && !isFormRender_) { // ArkTSCard not support inherit local strorage from context
1909         auto nativeEngine = reinterpret_cast<NativeEngine*>(runtime_);
1910         auto storage = storageWrapper.napiStorage_.value();
1911         if (!storage) {
1912             container->SetLocalStorage(nullptr, context);
1913         } else {
1914             auto env = reinterpret_cast<napi_env>(nativeEngine);
1915             napi_ref ref = nullptr;
1916             napi_create_reference(env, storage, 1, &ref);
1917             container->SetLocalStorage(
1918                 reinterpret_cast<NativeReference*>(ref), context);
1919         }
1920     }
1921     if (context) {
1922         UpdateFontScale(context->GetConfiguration());
1923     }
1924     return UIContentErrorCode::NO_ERRORS;
1925 }
1926 
UpdateFontScale(const std::shared_ptr<OHOS::AppExecFwk::Configuration> & config)1927 void UIContentImpl::UpdateFontScale(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)
1928 {
1929     if (isFormRender_ && !fontScaleFollowSystem_) {
1930         TAG_LOGW(AceLogTag::ACE_FORM, "use form default size");
1931         return;
1932     }
1933     CHECK_NULL_VOID(config);
1934     auto maxAppFontScale = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::APP_FONT_MAX_SCALE);
1935     auto followSystem = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::APP_FONT_SIZE_SCALE);
1936     auto context = NG::PipelineContext::GetContextByContainerId(instanceId_);
1937     CHECK_NULL_VOID(context);
1938     auto isFollowSystem = followSystem == "followSystem";
1939     if (!followSystem.empty()) {
1940         context->SetFollowSystem(isFollowSystem);
1941     }
1942     if (!maxAppFontScale.empty()) {
1943         context->SetMaxAppFontScale(StringUtils::StringToFloat(maxAppFontScale));
1944     }
1945     if (!isFollowSystem) {
1946         context->SetFontScale(1.0f);
1947     }
1948 
1949     auto fontScale = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_FONT_SIZE_SCALE);
1950     if (!fontScale.empty()) {
1951         context->SetFontScale(StringUtils::StringToFloat(fontScale));
1952     }
1953 }
1954 
SetConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration> & config)1955 void UIContentImpl::SetConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)
1956 {
1957     if (config == nullptr) {
1958         UErrorCode status = U_ZERO_ERROR;
1959         icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status);
1960         AceApplicationInfo::GetInstance().SetLocale(locale.getLanguage(), locale.getCountry(), locale.getScript(), "");
1961         return;
1962     }
1963 
1964     auto deviceAccess = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE);
1965     auto languageTag = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE);
1966 
1967     if (!deviceAccess.empty()) {
1968         // Event of accessing mouse or keyboard
1969         SystemProperties::SetDeviceAccess(deviceAccess == "true");
1970     }
1971 
1972     if (!languageTag.empty()) {
1973         std::string language;
1974         std::string script;
1975         std::string region;
1976         Localization::ParseLocaleTag(languageTag, language, script, region, false);
1977         if (!language.empty() || !script.empty() || !region.empty()) {
1978             AceApplicationInfo::GetInstance().SetLocale(language, region, script, "");
1979         }
1980     }
1981     StoreConfiguration(config);
1982 }
1983 
StoreConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration> & config)1984 void UIContentImpl::StoreConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)
1985 {
1986     if (!config) {
1987         return;
1988     }
1989     TAG_LOGD(AceLogTag::ACE_WINDOW, "StoreConfiguration %{public}s", config->GetName().c_str());
1990     auto colorMode = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
1991     auto container = Platform::AceContainer::GetContainer(instanceId_);
1992     if (!colorMode.empty() && container) {
1993         container->SetColorMode(colorMode == "dark" ? ColorMode::DARK : ColorMode::LIGHT);
1994     }
1995 
1996     auto string2float = [](const std::string& str) {
1997         return StringUtils::StringToFloat(str);
1998     };
1999     auto fontScale = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_FONT_SIZE_SCALE);
2000     if (!fontScale.empty()) {
2001         SystemProperties::SetFontScale(string2float(fontScale));
2002     }
2003     auto fontWeightScale = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_FONT_WEIGHT_SCALE);
2004     if (!fontWeightScale.empty()) {
2005         SystemProperties::SetFontWeightScale(string2float(fontWeightScale));
2006     }
2007     auto deviceType = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::DEVICE_TYPE);
2008     if (!deviceType.empty()) {
2009         SystemProperties::SetConfigDeviceType(deviceType);
2010     }
2011     auto smartGesture = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_SMART_GESTURE_SWITCH);
2012     if (!smartGesture.empty()) {
2013         SystemProperties::SetFocusCanBeActive(smartGesture ==
2014             OHOS::AppExecFwk::ConfigurationInner::SMART_GESTURE_AUTO);
2015     }
2016 }
2017 
GetFormRootNode()2018 std::shared_ptr<Rosen::RSSurfaceNode> UIContentImpl::GetFormRootNode()
2019 {
2020     return Platform::AceContainer::GetFormSurfaceNode(instanceId_);
2021 }
2022 // ArkTSCard end
2023 
SetFontScaleAndWeightScale(const RefPtr<Platform::AceContainer> & container,int32_t instanceId)2024 void UIContentImpl::SetFontScaleAndWeightScale(const RefPtr<Platform::AceContainer>& container, int32_t instanceId)
2025 {
2026     float fontScale = SystemProperties::GetFontScale();
2027     float fontWeightScale = SystemProperties::GetFontWeightScale();
2028     if (isFormRender_ && !fontScaleFollowSystem_) {
2029         TAG_LOGW(AceLogTag::ACE_FORM, "setFontScale form default size");
2030         fontScale = 1.0f;
2031         fontWeightScale = 1.0f;
2032     }
2033     container->SetFontScale(instanceId, fontScale);
2034     container->SetFontWeightScale(instanceId, fontWeightScale);
2035 }
2036 
SetAceApplicationInfo(std::shared_ptr<OHOS::AbilityRuntime::Context> & context)2037 void UIContentImpl::SetAceApplicationInfo(std::shared_ptr<OHOS::AbilityRuntime::Context>& context)
2038 {
2039     SetHwIcuDirectory();
2040     Container::UpdateCurrent(INSTANCE_ID_PLATFORM);
2041     auto abilityContext = OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(context);
2042     if (abilityContext) {
2043         int32_t missionId = -1;
2044         abilityContext->GetMissionId(missionId);
2045         AceApplicationInfo::GetInstance().SetMissionId(missionId);
2046     }
2047     AceApplicationInfo::GetInstance().SetProcessName(context->GetBundleName());
2048     AceApplicationInfo::GetInstance().SetPackageName(context->GetBundleName());
2049     AceApplicationInfo::GetInstance().SetDataFileDirPath(context->GetFilesDir());
2050     AceApplicationInfo::GetInstance().SetApiTargetVersion(context->GetApplicationInfo()->apiTargetVersion);
2051     AceApplicationInfo::GetInstance().SetAppVersionName(context->GetApplicationInfo()->versionName);
2052     AceApplicationInfo::GetInstance().SetAppVersionCode(context->GetApplicationInfo()->versionCode);
2053     AceApplicationInfo::GetInstance().SetUid(IPCSkeleton::GetCallingUid());
2054     AceApplicationInfo::GetInstance().SetPid(IPCSkeleton::GetCallingRealPid());
2055     CapabilityRegistry::Register();
2056     ImageFileCache::GetInstance().SetImageCacheFilePath(context->GetCacheDir());
2057     XcollieInterface::GetInstance().SetTimerCount("HIT_EMPTY_WARNING", TIMEOUT_LIMIT, COUNT_LIMIT);
2058 
2059     auto task = [] {
2060         std::unordered_map<std::string, std::string> payload;
2061         std::unordered_map<std::string, std::string> reply;
2062         payload["bundleName"] = AceApplicationInfo::GetInstance().GetPackageName();
2063         payload["targetApiVersion"] = std::to_string(AceApplicationInfo::GetInstance().GetApiTargetVersion());
2064         g_isDynamicVsync = ResSchedReport::GetInstance().AppWhiteListCheck(payload, reply);
2065         ACE_SCOPED_TRACE_COMMERCIAL("SetVsyncPolicy(%d)", g_isDynamicVsync.load());
2066         OHOS::AppExecFwk::EventHandler::SetVsyncPolicy(g_isDynamicVsync);
2067     };
2068     BackgroundTaskExecutor::GetInstance().PostTask(task);
2069 }
2070 
SetDeviceProperties()2071 void UIContentImpl::SetDeviceProperties()
2072 {
2073     int32_t deviceWidth = 0;
2074     int32_t deviceHeight = 0;
2075     float density = 1.0f;
2076     float defaultDensity = 1.0f;
2077     int32_t devicePhysicalWidth = 0;
2078     int32_t devicePhysicalHeight = 0;
2079 
2080     bool isSceneBoardWindow = window_->GetType() == Rosen::WindowType::WINDOW_TYPE_SCENE_BOARD;
2081     if (isSceneBoardWindow) {
2082         auto screenProperties = Rosen::ScreenSessionManagerClient::GetInstance().GetAllScreensProperties();
2083         if (!screenProperties.empty()) {
2084             auto iter = screenProperties.begin();
2085             // GetDensityInCurResolution means dpi of current screen component.
2086             defaultDensity = iter->second.GetDensityInCurResolution();
2087             LOGI("SCB default density:%{public}f", defaultDensity);
2088         }
2089     }
2090 
2091     auto defaultDisplay = Rosen::DisplayManager::GetInstance().GetDisplayById(window_->GetDisplayId());
2092     if (!defaultDisplay) {
2093         defaultDisplay = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
2094     }
2095     sptr<Rosen::DisplayInfo> displayInfo;
2096     if (defaultDisplay) {
2097         displayInfo = defaultDisplay->GetDisplayInfoWithCache();
2098     }
2099     if (displayInfo) {
2100         density = displayInfo->GetVirtualPixelRatio();
2101         if (isSceneBoardWindow && !NearEqual(defaultDensity, 1.0f)) {
2102             density = defaultDensity;
2103         }
2104         deviceWidth = displayInfo->GetWidth();
2105         deviceHeight = displayInfo->GetHeight();
2106         devicePhysicalWidth = displayInfo->GetPhysicalWidth();
2107         devicePhysicalHeight = displayInfo->GetPhysicalHeight();
2108     }
2109     SystemProperties::InitDeviceInfo(deviceWidth, deviceHeight, deviceHeight >= deviceWidth ? 0 : 1, density, false);
2110     SystemProperties::SetDevicePhysicalWidth(devicePhysicalWidth);
2111     SystemProperties::SetDevicePhysicalHeight(devicePhysicalHeight);
2112 }
2113 
CreateContainer(std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> & info,FrontendType frontendType,bool useNewPipe)2114 RefPtr<Platform::AceContainer> UIContentImpl::CreateContainer(
2115     std::shared_ptr<OHOS::AppExecFwk::AbilityInfo>& info, FrontendType frontendType, bool useNewPipe)
2116 {
2117     auto container = AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, frontendType, context_, info,
2118         std::make_unique<ContentEventCallback>(
2119             [window = window_] {
2120                 CHECK_NULL_VOID(window);
2121                 TAG_LOGI(AceLogTag::ACE_ROUTER, "router back to window");
2122                 window->PerformBack();
2123             },
2124             [context = context_](const std::string& address) {
2125                 auto sharedContext = context.lock();
2126                 CHECK_NULL_VOID(sharedContext);
2127                 auto abilityContext =
2128                     OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
2129                 CHECK_NULL_VOID(abilityContext);
2130                 LOGI("startAbility: %{private}s", address.c_str());
2131                 AAFwk::Want want;
2132                 want.AddEntity(Want::ENTITY_BROWSER);
2133                 want.SetUri(address);
2134                 want.SetAction(ACTION_VIEWDATA);
2135                 abilityContext->StartAbility(want, REQUEST_CODE);
2136             }),
2137         false, false, useNewPipe);
2138     return container;
2139 }
2140 
CommonInitialize(OHOS::Rosen::Window * window,const std::string & contentInfo,StorageWrapper storageWrapper,uint32_t focusWindowId)2141 UIContentErrorCode UIContentImpl::CommonInitialize(
2142     OHOS::Rosen::Window* window, const std::string& contentInfo, StorageWrapper storageWrapper, uint32_t focusWindowId)
2143 {
2144     auto errorCode = UIContentErrorCode::NO_ERRORS;
2145     window_ = window;
2146     CHECK_NULL_RETURN(window_, UIContentErrorCode::NULL_WINDOW);
2147     auto windowName = window->GetWindowName();
2148     ACE_SCOPED_TRACE_COMMERCIAL("UI Initialize:%s", windowName.c_str());
2149     startUrl_ = contentInfo;
2150     if (StringUtils::StartWith(windowName, SUBWINDOW_TOAST_DIALOG_PREFIX)) {
2151         InitializeSubWindow(window_, true);
2152         return errorCode;
2153     }
2154     if (StringUtils::StartWith(windowName, SUBWINDOW_PREFIX)) {
2155         InitializeSubWindow(window_);
2156         return errorCode;
2157     }
2158     auto context = context_.lock();
2159     CHECK_NULL_RETURN(context, UIContentErrorCode::NULL_POINTER);
2160     auto configuration = context->GetConfiguration();
2161     std::unordered_map<std::string, DeviceType> typeMap = { { "phone", DeviceType::PHONE }, { "tv", DeviceType::TV },
2162         { "watch", DeviceType::WATCH }, { "car", DeviceType::CAR }, { "tablet", DeviceType::TABLET },
2163         { "2in1", DeviceType::TWO_IN_ONE }, { "wearable", DeviceType::WEARABLE }, { "UNKNOWN", DeviceType::UNKNOWN } };
2164     if (configuration) {
2165         auto type = configuration->GetItem(OHOS::AAFwk::GlobalConfigurationKey::DEVICE_TYPE);
2166         if (typeMap.find(type) != typeMap.end()) {
2167             SystemProperties::SetDeviceType(typeMap[type]);
2168         }
2169     } else {
2170         LOGD("configuration is nullptr,use default type");
2171     }
2172     static std::once_flag onceFlag;
2173     std::call_once(onceFlag, std::bind(&UIContentImpl::SetAceApplicationInfo, this, std::ref(context)));
2174     AceApplicationInfo::GetInstance().SetPackageName(context->GetBundleName());
2175     AceNewPipeJudgement::InitAceNewPipeConfig();
2176     auto apiCompatibleVersion = context->GetApplicationInfo()->apiCompatibleVersion;
2177     auto apiReleaseType = context->GetApplicationInfo()->apiReleaseType;
2178     auto apiTargetVersion = context->GetApplicationInfo()->apiTargetVersion;
2179     const auto& hapModuleInfo = context->GetHapModuleInfo();
2180     std::vector<OHOS::AppExecFwk::Metadata> metaData;
2181     if (hapModuleInfo) {
2182         metaData = hapModuleInfo->metadata;
2183     }
2184     bool closeArkTSPartialUpdate = std::any_of(metaData.begin(), metaData.end(), [](const auto& metaDataItem) {
2185         return metaDataItem.name == "ArkTSPartialUpdate" && metaDataItem.value == "false";
2186     });
2187 
2188     bool reusedNodeSkipMeasure = std::any_of(metaData.begin(), metaData.end(), [](const auto& metaDataItem) {
2189         return metaDataItem.name == "reusedNodeSkipMeasure" && metaDataItem.value == "true";
2190     });
2191     if (reusedNodeSkipMeasure) {
2192         EventReport::ReportReusedNodeSkipMeasureApp();
2193     }
2194     AceApplicationInfo::GetInstance().SetReusedNodeSkipMeasure(reusedNodeSkipMeasure);
2195     auto useNewPipe = AceNewPipeJudgement::QueryAceNewPipeEnabledStage(
2196         bundleName_, apiCompatibleVersion, apiTargetVersion, apiReleaseType, closeArkTSPartialUpdate);
2197     AceApplicationInfo::GetInstance().SetIsUseNewPipeline(useNewPipe);
2198     LOGI("[%{public}s][%{public}s][%{public}d]: UIContent: apiCompatibleVersion: %{public}d, apiTargetVersion: "
2199          "%{public}d, and apiReleaseType: %{public}s, "
2200          "useNewPipe: %{public}d",
2201         bundleName_.c_str(), moduleName_.c_str(), instanceId_, apiCompatibleVersion, apiTargetVersion,
2202         apiReleaseType.c_str(), useNewPipe);
2203 #ifndef NG_BUILD
2204 #ifdef ENABLE_ROSEN_BACKEND
2205     std::shared_ptr<OHOS::Rosen::RSUIDirector> rsUiDirector;
2206     if (SystemProperties::GetRosenBackendEnabled() && !useNewPipe) {
2207         RsAdapter::RsUIDirectorInit(rsUiDirector, window, context->GetCacheDir());
2208     }
2209 #endif
2210 #endif
2211     SetDeviceProperties();
2212     // init xml config for performance feature
2213     FeatureParamManager::GetInstance().Init(bundleName_);
2214     bool configChangePerform = std::any_of(metaData.begin(), metaData.end(), [](const auto& metaDataItem) {
2215         return metaDataItem.name == "configColorModeChangePerformanceInArkUI" && metaDataItem.value == "true";
2216     });
2217     if (configChangePerform) {
2218         SystemProperties::SetConfigChangePerform();
2219     }
2220     // Initialize performance check parameters
2221     AceChecker::InitPerformanceParameters();
2222     AcePerformanceCheck::Start();
2223     ColorMode colorMode = ColorMode::LIGHT;
2224 
2225     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
2226     auto resourceManager = context->GetResourceManager();
2227     if (resourceManager != nullptr) {
2228         resourceManager->GetResConfig(*resConfig);
2229         auto localeInfo = resConfig->GetLocaleInfo();
2230         Platform::AceApplicationInfoImpl::GetInstance().SetResourceManager(resourceManager);
2231         if (localeInfo != nullptr) {
2232             auto language = localeInfo->getLanguage();
2233             auto region = localeInfo->getCountry();
2234             auto script = localeInfo->getScript();
2235             AceApplicationInfo::GetInstance().SetLocale((language == nullptr) ? "" : language,
2236                 (region == nullptr) ? "" : region, (script == nullptr) ? "" : script, "");
2237         }
2238         colorMode =
2239             resConfig->GetColorMode() == OHOS::Global::Resource::ColorMode::DARK ? ColorMode::DARK : ColorMode::LIGHT;
2240         SystemProperties::SetDeviceAccess(
2241             resConfig->GetInputDevice() == Global::Resource::InputDevice::INPUTDEVICE_POINTINGDEVICE);
2242         LOGI("[%{public}s][%{public}s][%{public}d]: SetLanguage: %{public}s, colorMode: %{public}s, "
2243              "deviceAccess: %{public}d",
2244             bundleName_.c_str(), moduleName_.c_str(), instanceId_,
2245             AceApplicationInfo::GetInstance().GetLanguage().c_str(), colorMode == ColorMode::DARK ? "dark" : "light",
2246             SystemProperties::GetDeviceAccess());
2247     }
2248 
2249     auto abilityContext = OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(context);
2250     std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> info;
2251     if (abilityContext) {
2252         info = abilityContext->GetAbilityInfo();
2253     } else {
2254         auto extensionContext =
2255             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::ExtensionContext>(context);
2256         if (!extensionContext) {
2257             return UIContentErrorCode::NULL_POINTER;
2258         }
2259         info = extensionContext->GetAbilityInfo();
2260     }
2261     if (info) {
2262         AceApplicationInfo::GetInstance().SetAbilityName(info->name);
2263     }
2264     RefPtr<AssetManagerImpl> assetManagerImpl = Referenced::MakeRefPtr<AssetManagerImpl>();
2265     bool isModelJson = info != nullptr ? info->isModuleJson : false;
2266     std::string moduleName = info != nullptr ? info->moduleName : "";
2267     auto appInfo = context->GetApplicationInfo();
2268     auto bundleName = info != nullptr ? info->bundleName : "";
2269     auto abilityName = info != nullptr ? info->name : "";
2270     std::string moduleHapPath = info != nullptr ? info->hapPath : "";
2271     std::string resPath;
2272     std::string pageProfile;
2273     LOGI("[%{public}s][%{public}s][%{public}d]: Initialize UIContent isModelJson:%{public}s", bundleName_.c_str(),
2274         moduleName_.c_str(), instanceId_, isModelJson ? "true" : "false");
2275     if (isModelJson) {
2276         std::string hapPath = info != nullptr ? info->hapPath : "";
2277         // first use hap provider
2278         if (assetManagerImpl && !hapPath.empty()) {
2279             auto hapAssetProvider = AceType::MakeRefPtr<HapAssetProviderImpl>();
2280             if (hapAssetProvider->Initialize(hapPath, { "", "ets/", "resources/base/profile/" })) {
2281                 assetManagerImpl->PushBack(std::move(hapAssetProvider));
2282             }
2283         }
2284 
2285         if (appInfo) {
2286             std::vector<OHOS::AppExecFwk::ModuleInfo> moduleList = appInfo->moduleInfos;
2287             if (moduleList.empty()) {
2288                 resPath = "/";
2289             }
2290             for (const auto& module : moduleList) {
2291                 if (module.moduleName == moduleName) {
2292                     std::regex pattern(ABS_BUNDLE_CODE_PATH + bundleName + FILE_SEPARATOR);
2293                     auto moduleSourceDir = std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
2294                     resPath = moduleSourceDir + "/";
2295                     break;
2296                 }
2297             }
2298         }
2299 
2300         // second use file provider, will remove later
2301         auto assetBasePathStr = { std::string("ets/"), std::string("resources/base/profile/") };
2302         if (assetManagerImpl && !resPath.empty()) {
2303             auto fileAssetProvider = AceType::MakeRefPtr<FileAssetProviderImpl>();
2304             if (fileAssetProvider->Initialize(resPath, assetBasePathStr)) {
2305                 assetManagerImpl->PushBack(std::move(fileAssetProvider));
2306             }
2307         }
2308 
2309         if (hapModuleInfo) {
2310             pageProfile = hapModuleInfo->pages;
2311             const std::string profilePrefix = "$profile:";
2312             if (pageProfile.compare(0, profilePrefix.size(), profilePrefix) == 0) {
2313                 pageProfile = pageProfile.substr(profilePrefix.length()).append(".json");
2314             }
2315         }
2316     } else {
2317         auto packagePathStr = context->GetBundleCodeDir();
2318         if (hapModuleInfo != nullptr) {
2319             packagePathStr += "/" + hapModuleInfo->package + "/";
2320         }
2321         std::string srcPath = "";
2322         if (info != nullptr && !info->srcPath.empty()) {
2323             srcPath = info->srcPath;
2324         }
2325 
2326         auto assetBasePathStr = { "assets/js/" + (srcPath.empty() ? "default" : srcPath) + "/",
2327             std::string("assets/js/share/") };
2328 
2329         if (assetManagerImpl && !packagePathStr.empty()) {
2330             auto fileAssetProvider = AceType::MakeRefPtr<FileAssetProviderImpl>();
2331             if (fileAssetProvider->Initialize(packagePathStr, assetBasePathStr)) {
2332                 assetManagerImpl->PushBack(std::move(fileAssetProvider));
2333             }
2334         }
2335         if (appInfo) {
2336             std::vector<OHOS::AppExecFwk::ModuleInfo> moduleList = appInfo->moduleInfos;
2337             for (const auto& module : moduleList) {
2338                 if (module.moduleName == moduleName) {
2339                     std::regex pattern(ABS_BUNDLE_CODE_PATH + bundleName + FILE_SEPARATOR);
2340                     auto moduleSourceDir = std::regex_replace(module.moduleSourceDir, pattern, LOCAL_BUNDLE_CODE_PATH);
2341                     resPath = moduleSourceDir + "/assets/" + module.moduleName + "/";
2342                     break;
2343                 }
2344             }
2345         }
2346     }
2347 
2348     std::string hapPath; // hap path in sandbox
2349     if (!moduleHapPath.empty()) {
2350         if (moduleHapPath.find(ABS_BUNDLE_CODE_PATH) == std::string::npos) {
2351             hapPath = moduleHapPath;
2352         } else {
2353             auto pos = moduleHapPath.find_last_of('/');
2354             if (pos != std::string::npos) {
2355                 hapPath = LOCAL_BUNDLE_CODE_PATH + moduleHapPath.substr(pos + 1);
2356             }
2357         }
2358     }
2359 
2360 #ifdef PLUGIN_COMPONENT_SUPPORTED
2361     auto pluginUtils = std::make_shared<PluginUtilsImpl>();
2362     PluginManager::GetInstance().SetAceAbility(nullptr, pluginUtils);
2363 #endif
2364     // create container
2365     auto isCJFrontend = CJUtils::IsCJFrontendContext(context.get());
2366     if (runtime_ || isCJFrontend) {
2367         instanceId_ = Container::GenerateId<STAGE_CONTAINER>();
2368     } else {
2369         instanceId_ = Container::GenerateId<FA_SUBWINDOW_CONTAINER>();
2370     }
2371 #ifdef FORM_SUPPORTED
2372     auto formUtils = std::make_shared<FormUtilsImpl>();
2373     FormManager::GetInstance().SetFormUtils(formUtils);
2374 #endif
2375 #ifdef APS_ENABLE
2376     auto apsMonitor = std::make_shared<ApsMonitorImpl>(instanceId_);
2377     PerfMonitor::GetPerfMonitor()->SetApsMonitor(apsMonitor);
2378 #endif
2379     auto frontendType =  isCJFrontend? FrontendType::DECLARATIVE_CJ : FrontendType::DECLARATIVE_JS;
2380     if (vmType_ == VMType::ARK_NATIVE) {
2381         frontendType = FrontendType::ARK_TS;
2382     }
2383     if (appInfo->arkTSMode == AbilityRuntime::CODE_LANGUAGE_ARKTS_HYBRID) {
2384         if (vmType_ == VMType::ARK_NATIVE) {
2385             frontendType = FrontendType::STATIC_HYBRID_DYNAMIC;
2386         } else {
2387             frontendType = FrontendType::DYNAMIC_HYBRID_STATIC;
2388         }
2389     }
2390 
2391     auto container = CreateContainer(info, frontendType, useNewPipe);
2392     CHECK_NULL_RETURN(container, UIContentErrorCode::NULL_POINTER);
2393     container->SetUIContentType(uIContentType_);
2394     container->SetWindowName(window_->GetWindowName());
2395     container->SetWindowId(window_->GetWindowId());
2396     auto token = context->GetToken();
2397     container->SetToken(token);
2398     container->SetParentToken(parentToken_);
2399     container->SetColorMode(colorMode);
2400     if (!isCJFrontend) {
2401         container->SetPageUrlChecker(AceType::MakeRefPtr<PageUrlCheckerOhos>(context, info));
2402     }
2403     container->SetNavigationRoute(AceType::MakeRefPtr<NavigationRouteOhos>(context->GetBundleName()));
2404     // Mark the relationship between windowId and containerId, it is 1:1
2405     SubwindowManager::GetInstance()->AddContainerId(window->GetWindowId(), instanceId_);
2406     AceEngine::Get().AddContainer(instanceId_, container);
2407     ContainerScope::Add(instanceId_);
2408     if (runtime_) {
2409         container->GetSettings().SetUsingSharedRuntime(true);
2410         container->SetSharedRuntime(runtime_);
2411     } else if (isCJFrontend) {
2412         container->GetSettings().SetUsingSharedRuntime(true);
2413     } else {
2414         container->GetSettings().SetUsingSharedRuntime(false);
2415     }
2416     container->SetPageProfile(pageProfile);
2417     container->Initialize();
2418     ContainerScope scope(instanceId_);
2419     auto front = container->GetFrontend();
2420     if (front) {
2421         front->UpdateState(Frontend::State::ON_CREATE);
2422         front->SetJsMessageDispatcher(container);
2423     }
2424     auto aceResCfg = container->GetResourceConfiguration();
2425     aceResCfg.SetOrientation(SystemProperties::GetDeviceOrientation());
2426     aceResCfg.SetDensity(SystemProperties::GetResolution());
2427     aceResCfg.SetDeviceType(SystemProperties::GetDeviceType());
2428     aceResCfg.SetColorMode(container->GetColorMode());
2429     aceResCfg.SetDeviceAccess(SystemProperties::GetDeviceAccess());
2430     aceResCfg.SetLanguage(AceApplicationInfo::GetInstance().GetLocaleTag());
2431     AddResConfigInfo(context, aceResCfg);
2432     AddSetAppColorModeToResConfig(context, aceResCfg);
2433     container->SetResourceConfiguration(aceResCfg);
2434     container->SetPackagePathStr(resPath);
2435     container->SetHapPath(hapPath);
2436     container->SetAssetManager(assetManagerImpl);
2437 
2438     container->SetBundlePath(context->GetBundleCodeDir());
2439     container->SetFilesDataPath(context->GetFilesDir());
2440     container->SetBundleName(hapModuleInfo->bundleName);
2441     container->SetModuleName(hapModuleInfo->moduleName);
2442     container->SetIsModule(hapModuleInfo->compileMode == AppExecFwk::CompileMode::ES_MODULE);
2443     container->SetApiTargetVersion(apiTargetVersion);
2444 
2445     PerfMonitor::GetPerfMonitor()->SetApplicationInfo();
2446 
2447     // for atomic service
2448     container->SetInstallationFree(hapModuleInfo && hapModuleInfo->installationFree);
2449     if (hapModuleInfo->installationFree) {
2450         container->SetSharePanelCallback(
2451             [context = context_](const std::string& bundleName, const std::string& abilityName) {
2452                 auto sharedContext = context.lock();
2453                 CHECK_NULL_VOID(sharedContext);
2454                 auto abilityContext =
2455                     OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
2456                 CHECK_NULL_VOID(abilityContext);
2457                 auto abilityInfo = abilityContext->GetAbilityInfo();
2458                 AAFwk::Want want;
2459                 want.SetParam("abilityName", abilityInfo->name);
2460                 want.SetParam("bundleName", abilityInfo->bundleName);
2461                 want.SetParam("moduleName", abilityInfo->moduleName);
2462                 want.SetParam("hostPkgName", abilityInfo->bundleName);
2463                 want.SetElementName(bundleName, abilityName);
2464                 abilityContext->StartAbility(want, REQUEST_CODE);
2465             });
2466     }
2467 
2468     container->SetAbilityOnSearch([context = context_](const std::string& queryWord) {
2469         auto sharedContext = context.lock();
2470         CHECK_NULL_VOID(sharedContext);
2471         auto abilityContext =
2472             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
2473         CHECK_NULL_VOID(abilityContext);
2474         AAFwk::Want want;
2475         want.AddEntity(Want::ENTITY_BROWSER);
2476         want.SetAction(ACTION_SEARCH);
2477         want.SetParam(PARAM_QUERY_KEY, queryWord);
2478         abilityContext->StartAbility(want, REQUEST_CODE);
2479     });
2480 
2481     container->SetAbilityOnCalendar([context = context_](const std::map<std::string, std::string>& params) {
2482         auto sharedContext = context.lock();
2483         CHECK_NULL_VOID(sharedContext);
2484         auto abilityContext =
2485             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
2486         CHECK_NULL_VOID(abilityContext);
2487         AAFwk::Want want;
2488         auto bundleName = NG::ExpandedMenuPluginLoader::GetInstance().GetAPPName(TextDataDetectType::DATE_TIME);
2489         CHECK_NULL_VOID(!bundleName.empty());
2490         want.SetElementName(bundleName, ABILITYNAME_CALENDAR);
2491         for (const auto& param : params) {
2492             want.SetParam(param.first, param.second);
2493         }
2494         want.SetParam(ACTION_PARAM, ACRION_CALENDAR);
2495         abilityContext->StartAbility(want, REQUEST_CODE);
2496     });
2497 
2498     container->SetAbilityOnInstallAppInStore([context = context_](const std::string& appName) {
2499         auto sharedContext = context.lock();
2500         CHECK_NULL_VOID(sharedContext);
2501         auto abilityContext =
2502             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
2503         CHECK_NULL_VOID(abilityContext);
2504         AAFwk::Want want;
2505         want.SetAction(ACTION_APPDETAIL);
2506         auto urlPrefix = NG::ExpandedMenuPluginLoader::GetInstance().GetStoreUrlFront();
2507         auto url = urlPrefix + appName;
2508         want.SetUri(url);
2509         abilityContext->StartAbility(want, REQUEST_CODE);
2510     });
2511 
2512     container->SetOpenLinkOnMapSearch([context = context_](const std::string& address) {
2513         auto sharedContext = context.lock();
2514         CHECK_NULL_VOID(sharedContext);
2515         auto abilityContext =
2516             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
2517         CHECK_NULL_VOID(abilityContext);
2518         AAFwk::Want want;
2519         // In practical use, a prefix is required; this function is currently not in use as its logic has been reverted.
2520         auto url = address;
2521         want.SetUri(url);
2522         abilityContext->OpenLink(want, REQUEST_CODE);
2523     });
2524 
2525     container->SetAbilityOnJumpBrowser([context = context_](const std::string& address) {
2526         auto sharedContext = context.lock();
2527         CHECK_NULL_VOID(sharedContext);
2528         auto abilityContext =
2529             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
2530         CHECK_NULL_VOID(abilityContext);
2531         AAFwk::Want want;
2532         want.SetAction(ACTION_VIEWDATA);
2533         want.SetUri(address);
2534         auto appName = NG::ExpandedMenuPluginLoader::GetInstance().GetAPPName(TextDataDetectType::URL);
2535         want.SetBundle(appName);
2536         abilityContext->StartAbility(want, REQUEST_CODE);
2537     });
2538 
2539     if (window_->IsDecorEnable()) {
2540         container->SetWindowModal(WindowModal::CONTAINER_MODAL);
2541     }
2542     container->InitFoldStatusFromListener();
2543     dragWindowListener_ = new DragWindowListener(instanceId_);
2544     window_->RegisterDragListener(dragWindowListener_);
2545     if (!container->IsSceneBoardEnabled()) {
2546         occupiedAreaChangeListener_ = new OccupiedAreaChangeListener(instanceId_);
2547         window_->RegisterOccupiedAreaChangeListener(occupiedAreaChangeListener_);
2548     }
2549     waterfallModeChangeListener_ = new WaterfallModeChangeListener(instanceId_);
2550     window_->RegisterWaterfallModeChangeListener(waterfallModeChangeListener_);
2551     foldStatusListener_ = new FoldScreenListener(instanceId_);
2552     OHOS::Rosen::DisplayManager::GetInstance().RegisterFoldStatusListener(foldStatusListener_);
2553     foldDisplayModeListener_ = new FoldDisplayModeListener(instanceId_);
2554     OHOS::Rosen::DisplayManager::GetInstance().RegisterDisplayModeListener(foldDisplayModeListener_);
2555     if (window_->GetType() == Rosen::WindowType::WINDOW_TYPE_UI_EXTENSION) {
2556         windowRectChangeListener_ = new WindowRectChangeListener(instanceId_);
2557         window_->RegisterHostWindowRectChangeListener(windowRectChangeListener_);
2558     } else {
2559         windowRectChangeListener_ = new WindowRectChangeListener(instanceId_);
2560         window_->RegisterWindowRectChangeListener(windowRectChangeListener_);
2561     }
2562     displayIdChangeListener_ = new DisplayIdChangeListener(instanceId_);
2563     window_->RegisterDisplayIdChangeListener(displayIdChangeListener_);
2564 
2565     // create ace_view
2566     auto aceView =
2567         Platform::AceViewOhos::CreateView(instanceId_, false, container->GetSettings().usePlatformAsUIThread);
2568     Platform::AceViewOhos::SurfaceCreated(aceView, window_);
2569     int32_t deviceWidth = SystemProperties::GetDeviceWidth();
2570     int32_t deviceHeight = SystemProperties::GetDeviceHeight();
2571     double density = SystemProperties::GetResolution();
2572 #ifndef NG_BUILD
2573     if (!useNewPipe) {
2574         Ace::Platform::UIEnvCallback callback = nullptr;
2575 #ifdef ENABLE_ROSEN_BACKEND
2576         callback = [id = instanceId_, container, rsUiDirector](
2577                        const OHOS::Ace::RefPtr<OHOS::Ace::PipelineContext>& context) {
2578             if (rsUiDirector) {
2579                 ACE_SCOPED_TRACE("OHOS::Rosen::RSUIDirector::Create()");
2580                 if (!SystemProperties::GetMultiInstanceEnabled()) {
2581                     rsUiDirector->SetUITaskRunner(
2582                         [taskExecutor = container->GetTaskExecutor(), id](
2583                             const std::function<void()>& task, uint32_t delay) {
2584                             ContainerScope scope(id);
2585                             taskExecutor->PostDelayedTask(
2586                                 task, TaskExecutor::TaskType::UI, delay, "ArkUIRenderServiceTask", PriorityType::HIGH);
2587                         }, id);
2588                 } else {
2589                     rsUiDirector->SetUITaskRunner(
2590                         [taskExecutor = container->GetTaskExecutor(), id](
2591                             const std::function<void()>& task, uint32_t delay) {
2592                             ContainerScope scope(id);
2593                             taskExecutor->PostDelayedTask(
2594                                 task, TaskExecutor::TaskType::UI, delay, "ArkUIRenderServiceTask", PriorityType::HIGH);
2595                         }, 0, true);
2596                 }
2597                 auto context = AceType::DynamicCast<PipelineContext>(container->GetPipelineContext());
2598                 if (context != nullptr) {
2599                     context->SetRSUIDirector(rsUiDirector);
2600                 }
2601             }
2602         };
2603 #endif
2604         // set view
2605         Platform::AceContainer::SetView(aceView, density, 0, 0, window_, callback);
2606     } else {
2607         errorCode = Platform::AceContainer::SetViewNew(aceView, density, 0, 0, window_);
2608         CHECK_ERROR_CODE_RETURN(errorCode);
2609     }
2610 #else
2611     errorCode = Platform::AceContainer::SetViewNew(aceView, density, 0, 0, window_);
2612     CHECK_ERROR_CODE_RETURN(errorCode);
2613 #endif
2614     // set focus window id for ui extension after pipeline context created.
2615     if (focusWindowId != 0) {
2616         container->SetFocusWindowId(focusWindowId);
2617         auto uIExtensionContainerHandler = AceType::MakeRefPtr<NG::UIExtensionContainerHandler>();
2618         uIExtensionContainerHandler->SetHostParams(hostWindowInfo_.hostWantParams);
2619         container->RegisterContainerHandler(uIExtensionContainerHandler);
2620     }
2621 
2622     auto realHostWindowId = window_->GetRealParentId();
2623     if (realHostWindowId != 0) {
2624         container->SetRealHostWindowId(static_cast<uint32_t>(realHostWindowId));
2625     }
2626     LOGI("focusWindowId: %{public}u, realHostWindowId: %{public}d",
2627         focusWindowId, realHostWindowId);
2628 
2629     // after frontend initialize
2630     if (window_->IsFocused()) {
2631         Focus();
2632     }
2633 
2634     Platform::AceViewOhos::SurfaceChanged(aceView, 0, 0, deviceHeight >= deviceWidth ? 0 : 1);
2635     auto pipeline = container->GetPipelineContext();
2636     // Use metadata to control the center-alignment of text at line height.
2637     bool halfLeading = std::any_of(metaData.begin(), metaData.end(),
2638         [](const auto& metaDataItem) { return metaDataItem.name == "half_leading" && metaDataItem.value == "true"; });
2639     pipeline->SetHalfLeading(halfLeading);
2640     bool hasPreviewTextOption = std::any_of(metaData.begin(), metaData.end(),
2641         [pipelineWeak = AceType::WeakClaim(AceType::RawPtr(pipeline))](const auto& metaDataItem) {
2642                 if (metaDataItem.name == "can_preview_text") {
2643                     auto pipeline = pipelineWeak.Upgrade();
2644                     CHECK_NULL_RETURN(pipeline, false);
2645                     pipeline->SetSupportPreviewText(metaDataItem.value == "false");
2646                     return true;
2647                 }
2648                 return false;
2649             });
2650     pipeline->SetHasPreviewTextOption(hasPreviewTextOption);
2651     // Use metadata to control whether the cutout safeArea takes effect.
2652     bool useCutout = std::any_of(metaData.begin(), metaData.end(),
2653         [](const auto& metaDataItem) { return metaDataItem.name == "avoid_cutout" && metaDataItem.value == "true"; });
2654     if (pipeline) {
2655         auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(pipeline);
2656         if (pipelineContext) {
2657             auto safeAreaManager = pipelineContext->GetSafeAreaManager();
2658             if (safeAreaManager) {
2659                 safeAreaManager->SetUseCutout(useCutout);
2660             }
2661         }
2662     }
2663     pipeline->SetApiTargetVersion(container->GetApiTargetVersion());
2664     container->CheckAndSetFontFamily();
2665     SetFontScaleAndWeightScale(container, instanceId_);
2666     if (pipeline) {
2667         auto rsConfig = window_->GetKeyboardAnimationConfig();
2668         KeyboardAnimationCurve curveIn = {
2669             rsConfig.curveIn.curveType_, rsConfig.curveIn.curveParams_, rsConfig.curveIn.duration_};
2670         KeyboardAnimationCurve curveOut = {
2671             rsConfig.curveOut.curveType_, rsConfig.curveOut.curveParams_, rsConfig.curveOut.duration_};
2672         KeyboardAnimationConfig config = {curveIn, curveOut};
2673         pipeline->SetKeyboardAnimationConfig(config);
2674     }
2675     // Use metadata to control whether dirty mark is blocked.
2676     bool isOpenInvisibleFreeze = std::any_of(metaData.begin(), metaData.end(), [](const auto& metaDataItem) {
2677         return metaDataItem.name == "ArkUIInvisibleFreeze" && metaDataItem.value == "true";
2678     });
2679     LOGI("ArkUIInvisibleFreeze: %{public}d", isOpenInvisibleFreeze);
2680     pipeline->SetOpenInvisibleFreeze(isOpenInvisibleFreeze);
2681     // Set sdk version in module json mode
2682     if (isModelJson) {
2683         if (pipeline && appInfo) {
2684             LOGI("[%{public}s][%{public}s][%{public}d]: SetMinPlatformVersion is %{public}d", bundleName_.c_str(),
2685                 moduleName_.c_str(), instanceId_, appInfo->apiCompatibleVersion);
2686             pipeline->SetMinPlatformVersion(appInfo->apiCompatibleVersion);
2687         }
2688     }
2689     if (runtime_ && storageWrapper.napiStorage_.has_value()) { // 1.1 SetLocalStorage
2690         auto storage = storageWrapper.napiStorage_.value();
2691         auto nativeEngine = reinterpret_cast<NativeEngine*>(runtime_);
2692         if (!storage) {
2693             container->SetLocalStorage(nullptr, context);
2694         } else {
2695             auto env = reinterpret_cast<napi_env>(nativeEngine);
2696             napi_ref ref = nullptr;
2697             napi_create_reference(env, storage, 1, &ref);
2698             container->SetLocalStorage(reinterpret_cast<NativeReference*>(ref), context);
2699         }
2700     }
2701     if (runtime_ && storageWrapper.aniStorage_.has_value()) { // 1.2 SetAniLocalStorage
2702         auto storage = storageWrapper.aniStorage_.value();
2703         if (!storage) {
2704             container->SetAniLocalStorage(nullptr, context);
2705         } else {
2706             auto* env = reinterpret_cast<ani_env*>(runtime_);
2707             ani_ref ref;
2708             env->GlobalReference_Create(storage, &ref);
2709             container->SetAniLocalStorage(reinterpret_cast<void*>(ref), context);
2710         }
2711     }
2712 
2713     InitializeSafeArea(container);
2714 
2715     InitializeDisplayAvailableRect(container);
2716 
2717     // set container temp dir
2718     if (abilityContext) {
2719         if (!abilityContext->GetTempDir().empty()) {
2720             container->SetTempDir(abilityContext->GetTempDir());
2721         }
2722     }
2723 
2724     LayoutInspector::SetCallback(instanceId_);
2725 
2726     // setLogFunc of current app
2727     AddAlarmLogFunc(pipeline);
2728     if (pipeline) {
2729         auto taskExecutor = pipeline->GetTaskExecutor();
2730         if (taskExecutor) {
2731             InitUISessionManagerCallbacks(taskExecutor);
2732         }
2733     }
2734     UiSessionManager::GetInstance()->SaveBaseInfo(std::string("bundleName:")
2735                                                      .append(bundleName)
2736                                                      .append(",moduleName:")
2737                                                      .append(moduleName)
2738                                                      .append(",abilityName:")
2739                                                      .append(abilityName));
2740     UpdateFontScale(context->GetConfiguration());
2741     auto thpExtraManager = AceType::MakeRefPtr<NG::THPExtraManagerImpl>();
2742     if (thpExtraManager->Init()) {
2743         pipeline->SetTHPExtraManager(thpExtraManager);
2744     }
2745     return errorCode;
2746 }
2747 
GetIsSystemWindow(const RefPtr<Platform::AceContainer> & container)2748 bool GetIsSystemWindow(const RefPtr<Platform::AceContainer>& container)
2749 {
2750     auto pipeline = container->GetPipelineContext();
2751     CHECK_NULL_RETURN(pipeline, false);
2752     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(pipeline);
2753     CHECK_NULL_RETURN(pipelineContext, false);
2754     auto safeAreaManager = pipelineContext->GetSafeAreaManager();
2755     CHECK_NULL_RETURN(safeAreaManager, false);
2756     return safeAreaManager->GetWindowTypeConfig().isSystemWindow;
2757 }
2758 
InitializeSafeArea(const RefPtr<Platform::AceContainer> & container)2759 void UIContentImpl::InitializeSafeArea(const RefPtr<Platform::AceContainer>& container)
2760 {
2761     constexpr static int32_t PLATFORM_VERSION_TEN = 10;
2762     auto pipeline = container->GetPipelineContext();
2763     bool isSystemWindow =
2764         GetIsSystemWindow(container) && Container::GreatOrEqualAPITargetVersion(PlatformVersion::VERSION_EIGHTEEN);
2765     if (pipeline && pipeline->GetMinPlatformVersion() >= PLATFORM_VERSION_TEN) {
2766         if (pipeline->GetIsAppWindow() || container->IsUIExtensionWindow() || isSystemWindow) {
2767             avoidAreaChangedListener_ = new PretendChangedListener(instanceId_);
2768             window_->RegisterAvoidAreaChangeListener(avoidAreaChangedListener_);
2769             auto systemInsets = container->GetViewSafeAreaByType(Rosen::AvoidAreaType::TYPE_SYSTEM);
2770             auto cutoutInsets = container->GetViewSafeAreaByType(Rosen::AvoidAreaType::TYPE_CUTOUT);
2771             auto navInsets = container->GetViewSafeAreaByType(Rosen::AvoidAreaType::TYPE_NAVIGATION_INDICATOR);
2772             pipeline->UpdateSystemSafeAreaWithoutAnimation(systemInsets);
2773             pipeline->UpdateCutoutSafeAreaWithoutAnimation(cutoutInsets);
2774             pipeline->UpdateNavSafeAreaWithoutAnimation(navInsets);
2775             TAG_LOGI(ACE_SAFE_AREA,
2776                 "InitializeSafeArea systemInsets:%{public}s, cutoutInsets:%{public}s, navInsets:%{public}s",
2777                 systemInsets.ToString().c_str(), cutoutInsets.ToString().c_str(), navInsets.ToString().c_str());
2778         }
2779     }
2780 }
2781 
InitializeDisplayAvailableRect(const RefPtr<Platform::AceContainer> & container)2782 void UIContentImpl::InitializeDisplayAvailableRect(const RefPtr<Platform::AceContainer>& container)
2783 {
2784     auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
2785     auto& DMManager = Rosen::DisplayManager::GetInstance();
2786     auto window = container->GetUIWindow(instanceId_);
2787     uint64_t displayId = 0;
2788     if (window) {
2789         if (window->GetDisplayId() != DISPLAY_ID_INVALID) {
2790             displayId = window->GetDisplayId();
2791             listenedDisplayId_ = displayId;
2792         } else {
2793             TAG_LOGW(AceLogTag::ACE_WINDOW, "initialize display available rect invalid. window name is %{public}s",
2794                 window->GetWindowName().c_str());
2795         }
2796     }
2797     availableAreaChangedListener_ = new AvailableAreaChangedListener(instanceId_);
2798     DMManager.RegisterAvailableAreaListener(availableAreaChangedListener_, displayId);
2799     Rosen::DMRect availableArea;
2800     auto defaultDisplay = DMManager.GetDisplayById(displayId);
2801     if (pipeline && defaultDisplay) {
2802         Rosen::DMError ret = defaultDisplay->GetAvailableArea(availableArea);
2803         if (ret == Rosen::DMError::DM_OK) {
2804             pipeline->UpdateDisplayAvailableRect(ConvertDMRect2Rect(availableArea));
2805             TAG_LOGI(AceLogTag::ACE_WINDOW,
2806                 "Initialize displayId: %{public}u, availableRect: [%{public}d, %{public}d, %{public}d, %{public}d]",
2807                 (uint32_t)displayId, availableArea.posX_, availableArea.posY_, availableArea.width_,
2808                 availableArea.height_);
2809         } else {
2810             TAG_LOGE(AceLogTag::ACE_WINDOW, "Display failed to get availableArea, displayId: %{public}u",
2811                 (uint32_t)displayId);
2812         }
2813     }
2814 
2815     if (!defaultDisplay) {
2816         TAG_LOGE(AceLogTag::ACE_WINDOW, "DisplayManager failed to get display by id: %{public}u", (uint32_t)displayId);
2817     }
2818 }
2819 
Foreground()2820 void UIContentImpl::Foreground()
2821 {
2822     LOGI("[%{public}s][%{public}s][%{public}d]: window foreground", bundleName_.c_str(), moduleName_.c_str(),
2823         instanceId_);
2824     if (window_ != nullptr && window_->GetType() == Rosen::WindowType::WINDOW_TYPE_APP_MAIN_WINDOW) {
2825         PerfMonitor::GetPerfMonitor()->SetAppStartStatus();
2826         PerfMonitor::GetPerfMonitor()->NotifyAppJankStatsBegin();
2827     }
2828     if (!isDynamicRender_) {
2829         ContainerScope::UpdateRecentForeground(instanceId_);
2830     }
2831     Platform::AceContainer::OnShow(instanceId_);
2832     // set the flag isForegroundCalled to be true
2833     auto container = Platform::AceContainer::GetContainer(instanceId_);
2834     CHECK_NULL_VOID(container);
2835     auto pipelineContext = container->GetPipelineContext();
2836     CHECK_NULL_VOID(pipelineContext);
2837     pipelineContext->SetForegroundCalled(true);
2838 
2839     CHECK_NULL_VOID(window_);
2840     std::string windowName = window_->GetWindowName();
2841     Recorder::EventRecorder::Get().SetContainerInfo(windowName, instanceId_, true);
2842 }
2843 
Background()2844 void UIContentImpl::Background()
2845 {
2846     LOGI("[%{public}s][%{public}s][%{public}d]: window background", bundleName_.c_str(), moduleName_.c_str(),
2847         instanceId_);
2848     PerfMonitor::GetPerfMonitor()->NotifyAppJankStatsEnd();
2849     Platform::AceContainer::OnHide(instanceId_);
2850 
2851     CHECK_NULL_VOID(window_);
2852     std::string windowName = window_->GetWindowName();
2853     Recorder::EventRecorder::Get().SetContainerInfo(windowName, instanceId_, false);
2854 }
2855 
ReloadForm(const std::string & url)2856 void UIContentImpl::ReloadForm(const std::string& url)
2857 {
2858     startUrl_ = url;
2859     LOGI("[%{public}s][%{public}s][%{public}d]: ReloadForm startUrl = %{public}s", bundleName_.c_str(),
2860         moduleName_.c_str(), instanceId_, startUrl_.c_str());
2861     auto container = Platform::AceContainer::GetContainer(instanceId_);
2862     CHECK_NULL_VOID(container);
2863     auto assetManager = AceType::DynamicCast<AssetManagerImpl>(container->GetAssetManager());
2864     assetManager->ReloadProvider();
2865     container->UpdateResource();
2866     Platform::AceContainer::RunPage(instanceId_, startUrl_, "");
2867 }
2868 
GetFormSerializedGesture()2869 SerializedGesture UIContentImpl::GetFormSerializedGesture()
2870 {
2871     auto container = Platform::AceContainer::GetContainer(instanceId_);
2872     CHECK_NULL_RETURN(container, SerializedGesture {});
2873     auto pipelineContext = container->GetPipelineContext();
2874     CHECK_NULL_RETURN(pipelineContext, SerializedGesture {});
2875     return pipelineContext->GetSerializedGesture();
2876 }
2877 
Focus()2878 void UIContentImpl::Focus()
2879 {
2880     LOGI("[%{public}s][%{public}s][%{public}d]: window focus", bundleName_.c_str(), moduleName_.c_str(), instanceId_);
2881     if (!isDynamicRender_) {
2882         ContainerScope::UpdateRecentActive(instanceId_);
2883     }
2884     Platform::AceContainer::OnActive(instanceId_);
2885     CHECK_NULL_VOID(window_);
2886     std::string windowName = window_->GetWindowName();
2887     Recorder::EventRecorder::Get().SetFocusContainerInfo(windowName, instanceId_);
2888     auto container = AceEngine::Get().GetContainer(instanceId_);
2889     CHECK_NULL_VOID(container);
2890     auto pipelineContext = container->GetPipelineContext();
2891     CHECK_NULL_VOID(pipelineContext);
2892 }
2893 
UnFocus()2894 void UIContentImpl::UnFocus()
2895 {
2896     LOGI("[%{public}s][%{public}s][%{public}d]: window unfocus", bundleName_.c_str(), moduleName_.c_str(), instanceId_);
2897     Platform::AceContainer::OnInactive(instanceId_);
2898     auto container = AceEngine::Get().GetContainer(instanceId_);
2899     CHECK_NULL_VOID(container);
2900     auto pipelineContext = container->GetPipelineContext();
2901     CHECK_NULL_VOID(pipelineContext);
2902 }
2903 
ActiveWindow()2904 void UIContentImpl::ActiveWindow()
2905 {
2906     LOGI("[%{public}s][%{public}s][%{public}d]:window active", bundleName_.c_str(), moduleName_.c_str(), instanceId_);
2907     Platform::AceContainer::ActiveWindow(instanceId_);
2908 }
2909 
UnActiveWindow()2910 void UIContentImpl::UnActiveWindow()
2911 {
2912     LOGI("[%{public}s][%{public}s][%{public}d]:window unactive", bundleName_.c_str(), moduleName_.c_str(), instanceId_);
2913     Platform::AceContainer::UnActiveWindow(instanceId_);
2914 }
2915 
Destroy()2916 void UIContentImpl::Destroy()
2917 {
2918     LOGI("[%{public}s][%{public}s][%{public}d]: window destroy", bundleName_.c_str(), moduleName_.c_str(), instanceId_);
2919     auto container = AceEngine::Get().GetContainer(instanceId_);
2920     CHECK_NULL_VOID(container);
2921     // stop performance check and output json file
2922     AcePerformanceCheck::Stop();
2923     if (AceType::InstanceOf<Platform::DialogContainer>(container)) {
2924         Platform::DialogContainer::DestroyContainer(instanceId_);
2925     } else {
2926         Platform::AceContainer::DestroyContainer(instanceId_);
2927     }
2928     ContainerScope::RemoveAndCheck(instanceId_);
2929     UnregisterDisplayManagerCallback();
2930     SubwindowManager::GetInstance()->OnDestroyContainer(instanceId_);
2931 
2932     if (window_) {
2933         window_->UnregisterWaterfallModeChangeListener(waterfallModeChangeListener_);
2934         window_->UnregisterDisplayIdChangeListener(displayIdChangeListener_);
2935         if (windowRectChangeListener_) {
2936             if (window_->GetType() == Rosen::WindowType::WINDOW_TYPE_UI_EXTENSION) {
2937                 window_->UnregisterHostWindowRectChangeListener(windowRectChangeListener_);
2938             } else {
2939                 window_->UnregisterWindowRectChangeListener(windowRectChangeListener_);
2940             }
2941             windowRectChangeListener_ = nullptr;
2942         }
2943     }
2944 }
2945 
UnregisterDisplayManagerCallback()2946 void UIContentImpl::UnregisterDisplayManagerCallback()
2947 {
2948     auto& manager = Rosen::DisplayManager::GetInstance();
2949     if (foldStatusListener_) {
2950         manager.UnregisterFoldStatusListener(foldStatusListener_);
2951         foldStatusListener_ = nullptr;
2952     }
2953     if (foldDisplayModeListener_) {
2954         manager.UnregisterDisplayModeListener(foldDisplayModeListener_);
2955         foldDisplayModeListener_ = nullptr;
2956     }
2957     if (availableAreaChangedListener_) {
2958         manager.UnregisterAvailableAreaListener(availableAreaChangedListener_, listenedDisplayId_);
2959         availableAreaChangedListener_ = nullptr;
2960     }
2961 }
2962 
RegisterLinkJumpCallback()2963 void UIContentImpl::RegisterLinkJumpCallback()
2964 {
2965 #ifdef RESOURCE_SCHEDULE_SERVICE_ENABLE
2966     auto container = Platform::AceContainer::GetContainer(instanceId_);
2967     CHECK_NULL_VOID(container);
2968     auto pipelineContextBase = container->GetPipelineContext();
2969     CHECK_NULL_VOID(pipelineContextBase);
2970     auto pipeLineContext = AceType::DynamicCast<NG::PipelineContext>(pipelineContextBase);
2971     CHECK_NULL_VOID(pipeLineContext);
2972     auto bundleName = AceApplicationInfo::GetInstance().GetPackageName();
2973     TAG_LOGI(AceLogTag::ACE_TEXT, "[%{public}s]: UIContentImpl::RegisterLinkJumpCallback", bundleName.c_str());
2974     // check 1 : for efficiency, if not in whiteList, no need to call RSS interface and go IPC
2975     bool isAllowedLinkJump = false;
2976     // call RSS's inner api
2977     auto errorNo = OHOS::ResourceSchedule::ResSchedClient::GetInstance().IsAllowedLinkJump(isAllowedLinkJump);
2978     if (errorNo != NO_ERROR) {
2979         TAG_LOGW(AceLogTag::ACE_TEXT, "UIContentImpl::RegisterLinkJumpCallback, errorNo: %{public}i", errorNo);
2980         return;
2981     }
2982     if (!isAllowedLinkJump) { // check 1
2983         return;
2984     }
2985     TAG_LOGI(AceLogTag::ACE_TEXT, "UIContentImpl::RegisterLinkJumpCallback, LinkJump is Open");
2986     pipeLineContext->SetLinkJumpCallback([context = context_] (const std::string& link) {
2987         auto sharedContext = context.lock();
2988         CHECK_NULL_VOID(sharedContext);
2989         auto abilityContext =
2990             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(sharedContext);
2991         CHECK_NULL_VOID(abilityContext);
2992         AAFwk::Want want;
2993         want.AddEntity(Want::ENTITY_BROWSER);
2994         want.SetUri(link);
2995         want.SetAction(ACTION_VIEWDATA);
2996         abilityContext->StartAbility(want, REQUEST_CODE);
2997     });
2998 #endif // RESOURCE_SCHEDULE_SERVICE_ENABLE
2999 }
3000 
OnNewWant(const OHOS::AAFwk::Want & want)3001 void UIContentImpl::OnNewWant(const OHOS::AAFwk::Want& want)
3002 {
3003     LOGI("[%{public}s][%{public}s][%{public}d]: UIContent OnNewWant", bundleName_.c_str(), moduleName_.c_str(),
3004         instanceId_);
3005     std::string params = want.GetStringParam(START_PARAMS_KEY);
3006     Platform::AceContainer::OnNewRequest(instanceId_, params);
3007 }
3008 
GetBackgroundColor()3009 uint32_t UIContentImpl::GetBackgroundColor()
3010 {
3011     auto container = Platform::AceContainer::GetContainer(instanceId_);
3012     CHECK_NULL_RETURN(container, 0x000000);
3013     auto taskExecutor = container->GetTaskExecutor();
3014     CHECK_NULL_RETURN(taskExecutor, 0x000000);
3015     ContainerScope scope(instanceId_);
3016     uint32_t bgColor = 0x000000;
3017     taskExecutor->PostSyncTask(
3018         [&bgColor, container]() {
3019             CHECK_NULL_VOID(container);
3020             auto pipelineContext = container->GetPipelineContext();
3021             CHECK_NULL_VOID(pipelineContext);
3022             bgColor = pipelineContext->GetAppBgColor().GetValue();
3023         },
3024         TaskExecutor::TaskType::UI, "ArkUIGetAppBackgroundColor");
3025 
3026     LOGD("[%{public}s][%{public}s][%{public}d]: GetBackgroundColor:%{public}u",
3027         bundleName_.c_str(), moduleName_.c_str(), instanceId_, bgColor);
3028     return bgColor;
3029 }
3030 
SetBackgroundColor(uint32_t color)3031 void UIContentImpl::SetBackgroundColor(uint32_t color)
3032 {
3033     LOGI("[%{public}s][%{public}s][%{public}d]: SetBackgroundColor:%{public}u",
3034         bundleName_.c_str(), moduleName_.c_str(), instanceId_, color);
3035     auto container = AceEngine::Get().GetContainer(instanceId_);
3036     CHECK_NULL_VOID(container);
3037     auto aceContainer = AceType::DynamicCast<Platform::AceContainer>(container);
3038     if (aceContainer) {
3039         aceContainer->SetIsUseCustomBg(true);
3040     }
3041     ContainerScope scope(instanceId_);
3042     auto taskExecutor = container->GetTaskExecutor();
3043     CHECK_NULL_VOID(taskExecutor);
3044     taskExecutor->PostSyncTask(
3045         [container, bgColor = color]() {
3046             auto pipelineContext = container->GetPipelineContext();
3047             CHECK_NULL_VOID(pipelineContext);
3048             pipelineContext->SetAppBgColor(Color(bgColor));
3049             pipelineContext->ChangeDarkModeBrightness();
3050         },
3051         TaskExecutor::TaskType::UI, "ArkUISetAppBackgroundColor");
3052 }
3053 
SetWindowContainerColor(uint32_t activeColor,uint32_t inactiveColor)3054 void UIContentImpl::SetWindowContainerColor(uint32_t activeColor, uint32_t inactiveColor)
3055 {
3056     TAG_LOGI(AceLogTag::ACE_APPBAR,
3057         "[%{public}s][%{public}s][%{public}d]: SetWindowContainerColor:"
3058         "active color %{public}u, inactive color %{public}u",
3059         bundleName_.c_str(), moduleName_.c_str(), instanceId_, activeColor, inactiveColor);
3060     auto container = AceEngine::Get().GetContainer(instanceId_);
3061     CHECK_NULL_VOID(container);
3062     ContainerScope scope(instanceId_);
3063     auto taskExecutor = container->GetTaskExecutor();
3064     CHECK_NULL_VOID(taskExecutor);
3065     auto task = [container, activeColor, inactiveColor]() {
3066         auto pipelineContext = container->GetPipelineContext();
3067         CHECK_NULL_VOID(pipelineContext);
3068         pipelineContext->SetWindowContainerColor(Color(activeColor), Color(inactiveColor));
3069     };
3070     ExecuteUITask(std::move(task), "ArkUISetWindowContainerColor");
3071 }
3072 
GetAppPaintSize(OHOS::Rosen::Rect & paintRect)3073 void UIContentImpl::GetAppPaintSize(OHOS::Rosen::Rect& paintRect)
3074 {
3075     auto container = AceEngine::Get().GetContainer(instanceId_);
3076     CHECK_NULL_VOID(container);
3077     ContainerScope scope(instanceId_);
3078     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
3079     CHECK_NULL_VOID(pipelineContext);
3080     auto stageManager = pipelineContext->GetStageManager();
3081     CHECK_NULL_VOID(stageManager);
3082     auto stageNode = stageManager->GetStageNode();
3083     CHECK_NULL_VOID(stageNode);
3084     auto renderContext = stageNode->GetRenderContext();
3085     CHECK_NULL_VOID(renderContext);
3086     auto rect = renderContext->GetPaintRectWithoutTransform();
3087     auto offset = stageNode->GetPaintRectOffset(false, true);
3088     paintRect.posX_ = static_cast<int32_t>(offset.GetX());
3089     paintRect.posY_ = static_cast<int32_t>(offset.GetY());
3090     paintRect.width_ = static_cast<uint32_t>(rect.Width());
3091     paintRect.height_ = static_cast<uint32_t>(rect.Height());
3092 }
3093 
GetWindowPaintSize(OHOS::Rosen::Rect & paintRect)3094 void UIContentImpl::GetWindowPaintSize(OHOS::Rosen::Rect& paintRect)
3095 {
3096     auto container = AceEngine::Get().GetContainer(instanceId_);
3097     CHECK_NULL_VOID(container);
3098     ContainerScope scope(instanceId_);
3099     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
3100     CHECK_NULL_VOID(pipelineContext);
3101     CHECK_NULL_VOID(window_);
3102     auto windowRect = window_->GetRect();
3103     NG::RectInt rect;
3104     rect.SetRect(0, 0, windowRect.width_, windowRect.height_);
3105     pipelineContext->GetWindowPaintRectWithoutMeasureAndLayout(rect);
3106     paintRect.posX_ = static_cast<int32_t>(rect.GetX());
3107     paintRect.posY_ = static_cast<int32_t>(rect.GetY());
3108     paintRect.width_ = static_cast<uint32_t>(rect.Width());
3109     paintRect.height_ = static_cast<uint32_t>(rect.Height());
3110 }
3111 
ProcessBackPressed()3112 bool UIContentImpl::ProcessBackPressed()
3113 {
3114     LOGI("[%{public}s][%{public}s][%{public}d]: OnBackPressed called", bundleName_.c_str(), moduleName_.c_str(),
3115         instanceId_);
3116     Recorder::EventParamsBuilder builder;
3117     builder.SetEventType(Recorder::EventType::BACK_PRESSED);
3118     Recorder::EventRecorder::Get().OnEvent(std::move(builder));
3119     auto container = AceEngine::Get().GetContainer(instanceId_);
3120     CHECK_NULL_RETURN(container, false);
3121     if (container->IsUIExtensionWindow() && !container->WindowIsShow()) {
3122         return false;
3123     }
3124     auto taskExecutor = container->GetTaskExecutor();
3125     CHECK_NULL_RETURN(taskExecutor, false);
3126     auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
3127     if (pipeline) {
3128         auto uiExtMgr = pipeline->GetUIExtensionManager();
3129         if (uiExtMgr && uiExtMgr->OnBackPressed()) {
3130             LOGI("UIExtension consumed backpressed event");
3131             return true;
3132         }
3133     }
3134     bool ret = false;
3135     taskExecutor->PostSyncTask(
3136         [container, this, &ret]() {
3137             if (AceType::InstanceOf<Platform::DialogContainer>(container)) {
3138                 if (Platform::DialogContainer::OnBackPressed(instanceId_)) {
3139                     ret = true;
3140                 }
3141             } else {
3142                 PerfMonitor::GetPerfMonitor()->RecordInputEvent(LAST_UP, UNKNOWN_SOURCE, 0);
3143                 if (Platform::AceContainer::OnBackPressed(instanceId_)) {
3144                     ret = true;
3145                 }
3146             }
3147         },
3148         TaskExecutor::TaskType::UI, "ArkUIProcessBackPressed");
3149     return ret;
3150 }
3151 
ProcessPointerEvent(const std::shared_ptr<OHOS::MMI::PointerEvent> & pointerEvent)3152 bool UIContentImpl::ProcessPointerEvent(const std::shared_ptr<OHOS::MMI::PointerEvent>& pointerEvent)
3153 {
3154     auto container = AceType::DynamicCast<Platform::AceContainer>(AceEngine::Get().GetContainer(instanceId_));
3155     CHECK_NULL_RETURN(container, false);
3156     if (pointerEvent->GetPointerAction() != MMI::PointerEvent::POINTER_ACTION_MOVE) {
3157         TAG_LOGD(AceLogTag::ACE_INPUTTRACKING,
3158             "PointerEvent Process to ui_content, eventInfo: id:%{public}d, "
3159             "WindowName = " SEC_PLD(%{public}s) ", "
3160             "WindowId = %{public}d, ViewWidth = %{public}d, ViewHeight = %{public}d, "
3161             "ViewPosX = %{public}d, ViewPosY = %{public}d",
3162             pointerEvent->GetId(), SEC_PARAM(container->GetWindowName().c_str()), container->GetWindowId(),
3163             container->GetViewWidth(), container->GetViewHeight(), container->GetViewPosX(), container->GetViewPosY());
3164     }
3165     auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
3166     Platform::AceViewOhos::DispatchTouchEvent(aceView, pointerEvent);
3167     return true;
3168 }
3169 
ProcessPointerEvent(const std::shared_ptr<OHOS::MMI::PointerEvent> & pointerEvent,const std::function<void (bool)> & callback)3170 bool UIContentImpl::ProcessPointerEvent(
3171     const std::shared_ptr<OHOS::MMI::PointerEvent>& pointerEvent, const std::function<void(bool)>& callback)
3172 {
3173     if (!ProcessPointerEvent(pointerEvent)) {
3174         return false;
3175     }
3176     if (pointerEvent->GetButtonId() == MMI::PointerEvent::MOUSE_BUTTON_LEFT &&
3177         pointerEvent->GetPointerAction() == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN) {
3178         auto container = Platform::AceContainer::GetContainer(instanceId_);
3179         CHECK_NULL_RETURN(container, false);
3180         auto pipelineContext = container->GetPipelineContext();
3181         CHECK_NULL_RETURN(pipelineContext, false);
3182         auto context = AceType::DynamicCast<NG::PipelineContext>(pipelineContext);
3183         CHECK_NULL_RETURN(context, false);
3184         auto task = [context, finallyCallback = callback]() {
3185             CHECK_NULL_VOID(context);
3186             CHECK_NULL_VOID(finallyCallback);
3187             ContainerScope scope(context->GetInstanceId());
3188             auto dragDropManager = context->GetDragDropManager();
3189             CHECK_NULL_VOID(dragDropManager);
3190             auto isAnyDraggableHit = dragDropManager->IsAnyDraggableHit(context, MOUSE_PRESS_LEFT + MOUSE_BASE_ID);
3191             TAG_LOGI(AceLogTag::ACE_DRAG, "is any draggable node hit: %{public}d", isAnyDraggableHit);
3192             dragDropManager->SetIsAnyDraggableHit(false);
3193             finallyCallback(isAnyDraggableHit);
3194         };
3195 
3196         auto taskExecutor = container->GetTaskExecutor();
3197         CHECK_NULL_RETURN(taskExecutor, false);
3198         auto uiTaskRunner = SingleTaskExecutor::Make(taskExecutor, TaskExecutor::TaskType::UI);
3199         if (uiTaskRunner.IsRunOnCurrentThread()) {
3200             task();
3201         } else {
3202             taskExecutor->PostTask(
3203                 std::move(task), TaskExecutor::TaskType::UI, "ArkUIProcessPointerEvent", PriorityType::VIP);
3204         }
3205     } else {
3206         CHECK_NULL_RETURN(callback, false);
3207         callback(false);
3208     }
3209     return true;
3210 }
3211 
ProcessPointerEventWithCallback(const std::shared_ptr<OHOS::MMI::PointerEvent> & pointerEvent,const std::function<void ()> & callback)3212 bool UIContentImpl::ProcessPointerEventWithCallback(
3213     const std::shared_ptr<OHOS::MMI::PointerEvent>& pointerEvent, const std::function<void()>& callback)
3214 {
3215     auto container = AceType::DynamicCast<Platform::AceContainer>(AceEngine::Get().GetContainer(instanceId_));
3216     CHECK_NULL_RETURN(container, false);
3217     if (pointerEvent->GetPointerAction() != MMI::PointerEvent::POINTER_ACTION_MOVE) {
3218         TAG_LOGD(AceLogTag::ACE_INPUTTRACKING,
3219             "PointerEvent Process to ui_content, eventInfo: id:%{public}d, "
3220             "WindowName = " SEC_PLD(%{public}s) ", "
3221             "WindowId = %{public}d, ViewWidth = %{public}d, ViewHeight = %{public}d, "
3222             "ViewPosX = %{public}d, ViewPosY = %{public}d",
3223             pointerEvent->GetId(), SEC_PARAM(container->GetWindowName().c_str()), container->GetWindowId(),
3224             container->GetViewWidth(), container->GetViewHeight(), container->GetViewPosX(), container->GetViewPosY());
3225     }
3226     auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
3227     Platform::AceViewOhos::DispatchTouchEvent(aceView, pointerEvent, nullptr, callback);
3228     return true;
3229 }
3230 
ProcessKeyEvent(const std::shared_ptr<OHOS::MMI::KeyEvent> & touchEvent,bool isPreIme)3231 bool UIContentImpl::ProcessKeyEvent(const std::shared_ptr<OHOS::MMI::KeyEvent>& touchEvent, bool isPreIme)
3232 {
3233     TAG_LOGD(AceLogTag::ACE_INPUTTRACKING,
3234         "KeyEvent Process to ui_content, eventInfo: id:%{public}d, "
3235         "keyEvent info: keyCode is " SEC_PLD(%{private}d) ", "
3236         "keyAction is " SEC_PLD(%{public}d) ", keyActionTime is %{public}" PRId64,
3237         touchEvent->GetId(), SEC_PARAM(touchEvent->GetKeyCode()), SEC_PARAM(touchEvent->GetKeyAction()),
3238         touchEvent->GetActionTime());
3239     auto container = AceEngine::Get().GetContainer(instanceId_);
3240     CHECK_NULL_RETURN(container, false);
3241     auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
3242     return Platform::AceViewOhos::DispatchKeyEvent(aceView, touchEvent, isPreIme);
3243 }
3244 
ProcessAxisEvent(const std::shared_ptr<OHOS::MMI::AxisEvent> & axisEvent)3245 bool UIContentImpl::ProcessAxisEvent(const std::shared_ptr<OHOS::MMI::AxisEvent>& axisEvent)
3246 {
3247     return false;
3248 }
3249 
ProcessVsyncEvent(uint64_t timeStampNanos)3250 bool UIContentImpl::ProcessVsyncEvent(uint64_t timeStampNanos)
3251 {
3252     return false;
3253 }
3254 
BuildParsedConfig(Platform::ParsedConfig & parsedConfig,const std::shared_ptr<OHOS::AppExecFwk::Configuration> & config,const bool formFontUseDefault)3255 void BuildParsedConfig(Platform::ParsedConfig& parsedConfig,
3256     const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config, const bool formFontUseDefault)
3257 {
3258     parsedConfig.colorMode = config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
3259     parsedConfig.deviceAccess = config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE);
3260     parsedConfig.direction = config->GetItem(OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DIRECTION);
3261     parsedConfig.densitydpi = config->GetItem(OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DENSITYDPI);
3262     parsedConfig.fontFamily = config->GetItem(OHOS::AppExecFwk::ConfigurationInner::APPLICATION_FONT);
3263     parsedConfig.themeTag = config->GetItem("ohos.application.theme");
3264     parsedConfig.colorModeIsSetByApp = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::COLORMODE_IS_SET_BY_APP);
3265     parsedConfig.mcc = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_MCC);
3266     parsedConfig.mnc = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_MNC);
3267     parsedConfig.fontId = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_FONT_ID);
3268     // Process system language and preferred language
3269     auto isPreferredLanguage = config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::IS_PREFERRED_LANGUAGE);
3270     if (isPreferredLanguage == IS_PREFERRED_LANGUAGE) {
3271         parsedConfig.preferredLanguage = config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE);
3272     } else {
3273         parsedConfig.languageTag = config->GetItem(OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE);
3274     }
3275     // EtsCard Font followSytem disable
3276     if (formFontUseDefault) {
3277         parsedConfig.fontScale = "1.0";
3278         parsedConfig.fontWeightScale = "1.0";
3279     } else {
3280         parsedConfig.fontScale = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_FONT_SIZE_SCALE);
3281         parsedConfig.fontWeightScale = config->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_FONT_WEIGHT_SCALE);
3282     }
3283 }
3284 
UpdateConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration> & config)3285 void UIContentImpl::UpdateConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)
3286 {
3287     CHECK_NULL_VOID(config);
3288     StoreConfiguration(config);
3289     auto container = Platform::AceContainer::GetContainer(instanceId_);
3290     CHECK_NULL_VOID(container);
3291     auto taskExecutor = container->GetTaskExecutor();
3292     CHECK_NULL_VOID(taskExecutor);
3293     bool formFontUseDefault = isFormRender_ && !fontScaleFollowSystem_;
3294     taskExecutor->PostTask(
3295         [weakContainer = WeakPtr<Platform::AceContainer>(container), config, instanceId = instanceId_,
3296             bundleName = bundleName_, moduleName = moduleName_, formFontUseDefault]() {
3297             auto container = weakContainer.Upgrade();
3298             CHECK_NULL_VOID(container);
3299             Platform::ParsedConfig parsedConfig;
3300             BuildParsedConfig(parsedConfig, config, formFontUseDefault);
3301             container->UpdateConfiguration(parsedConfig, config->GetName());
3302             LOGI("[%{public}d][%{public}s][%{public}s] UpdateConfiguration, name:%{public}s",
3303                 instanceId, bundleName.c_str(), moduleName.c_str(), config->GetName().c_str());
3304         },
3305         TaskExecutor::TaskType::UI, "ArkUIUIContentUpdateConfiguration");
3306 }
3307 
UpdateConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration> & config,const std::shared_ptr<Global::Resource::ResourceManager> & resourceManager)3308 void UIContentImpl::UpdateConfiguration(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config,
3309     const std::shared_ptr<Global::Resource::ResourceManager>& resourceManager)
3310 {
3311     CHECK_NULL_VOID(config);
3312 
3313     RefPtr<ResourceAdapter> adapter = AceType::MakeRefPtr<ResourceAdapterImplV2>(resourceManager, instanceId_);
3314     ResourceManager::GetInstance().UpdateMainResourceAdapter(bundleName_, moduleName_, instanceId_, adapter);
3315 
3316     auto container = Platform::AceContainer::GetContainer(instanceId_);
3317     CHECK_NULL_VOID(container);
3318     auto pipeline = container->GetPipelineContext();
3319     CHECK_NULL_VOID(pipeline);
3320     pipeline->UpdateThemeManager(adapter);
3321 
3322     StoreConfiguration(config);
3323     auto taskExecutor = container->GetTaskExecutor();
3324     CHECK_NULL_VOID(taskExecutor);
3325     bool formFontUseDefault = isFormRender_ && !fontScaleFollowSystem_;
3326     taskExecutor->PostTask(
3327         [weakContainer = WeakPtr<Platform::AceContainer>(container), config, instanceId = instanceId_,
3328             bundleName = bundleName_, moduleName = moduleName_, formFontUseDefault]() {
3329             auto container = weakContainer.Upgrade();
3330             CHECK_NULL_VOID(container);
3331             Platform::ParsedConfig parsedConfig;
3332             BuildParsedConfig(parsedConfig, config, formFontUseDefault);
3333             container->UpdateConfiguration(parsedConfig, config->GetName(), true);
3334             LOGI("[%{public}d][%{public}s][%{public}s] UpdateConfiguration, name:%{public}s", instanceId,
3335                 bundleName.c_str(), moduleName.c_str(), config->GetName().c_str());
3336         },
3337         TaskExecutor::TaskType::UI, "ArkUIUIContentUpdateConfigurationWithResMgr");
3338 }
3339 
UpdateConfigurationSyncForAll(const std::shared_ptr<OHOS::AppExecFwk::Configuration> & config)3340 void UIContentImpl::UpdateConfigurationSyncForAll(const std::shared_ptr<OHOS::AppExecFwk::Configuration>& config)
3341 {
3342     CHECK_NULL_VOID(config);
3343 
3344     auto dialogContainer = Platform::DialogContainer::GetContainer(instanceId_);
3345     if (dialogContainer) {
3346         return;
3347     }
3348     if (isDynamicRender_ || isFormRender_) {
3349         return;
3350     }
3351 
3352     auto container = Platform::AceContainer::GetContainer(instanceId_);
3353     CHECK_NULL_VOID(container);
3354     bool formFontUseDefault = isFormRender_ && !fontScaleFollowSystem_;
3355     Platform::ParsedConfig parsedConfig;
3356     BuildParsedConfig(parsedConfig, config, formFontUseDefault);
3357     container->UpdateConfigurationSyncForAll(parsedConfig, config->GetName());
3358     LOGI("[%{public}d][%{public}s][%{public}s] UpdateConfigurationSyncForAll, name:%{public}s",
3359         instanceId_, bundleName_.c_str(), moduleName_.c_str(), config->GetName().c_str());
3360 }
3361 
AddKeyFrameAnimateEndCallback(const std::function<void ()> & callback)3362 void UIContentImpl::AddKeyFrameAnimateEndCallback(const std::function<void()>& callback)
3363 {
3364     ContainerScope scope(instanceId_);
3365     auto container = Platform::AceContainer::GetContainer(instanceId_);
3366     CHECK_NULL_VOID(container);
3367     auto pipelineContext = container->GetPipelineContext();
3368     auto context = AceType::DynamicCast<NG::PipelineContext>(pipelineContext);
3369     CHECK_NULL_VOID(context);
3370     TAG_LOGD(AceLogTag::ACE_WINDOW, "AddKeyFrameAnimateEndCallback");
3371     auto rootElement = context->GetRootElement();
3372     CHECK_NULL_VOID(rootElement);
3373     auto rosenRenderContext = AceType::DynamicCast<NG::RosenRenderContext>(rootElement->GetRenderContext());
3374     CHECK_NULL_VOID(rosenRenderContext);
3375     rosenRenderContext->AddKeyFrameAnimateEndCallback(callback);
3376 }
3377 
AddKeyFrameCanvasNodeCallback(const std::function<void (std::shared_ptr<Rosen::RSCanvasNode> & canvasNode,std::shared_ptr<OHOS::Rosen::RSTransaction> & rsTransaction)> & callback)3378 void UIContentImpl::AddKeyFrameCanvasNodeCallback(const std::function<
3379     void(std::shared_ptr<Rosen::RSCanvasNode>& canvasNode,
3380         std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction)>& callback)
3381 {
3382     TAG_LOGD(AceLogTag::ACE_WINDOW, "AddKeyFrameCanvasNodeCallback");
3383     addNodeCallback_ = callback;
3384 }
3385 
LinkKeyFrameCanvasNode(std::shared_ptr<OHOS::Rosen::RSCanvasNode> & canvasNode)3386 void UIContentImpl::LinkKeyFrameCanvasNode(std::shared_ptr<OHOS::Rosen::RSCanvasNode>& canvasNode)
3387 {
3388     ContainerScope scope(instanceId_);
3389     auto container = Platform::AceContainer::GetContainer(instanceId_);
3390     CHECK_NULL_VOID(container);
3391     auto pipelineContext = container->GetPipelineContext();
3392     auto context = AceType::DynamicCast<NG::PipelineContext>(pipelineContext);
3393     CHECK_NULL_VOID(context);
3394 #ifndef NG_BUILD
3395 #ifdef ENABLE_ROSEN_BACKEND
3396     if (SystemProperties::GetRosenBackendEnabled()) {
3397         CHECK_NULL_VOID(window_);
3398         auto surfaceNode = window_->GetSurfaceNode();
3399         CHECK_NULL_VOID(surfaceNode);
3400         CHECK_NULL_VOID(canvasNode);
3401         canvasNode->SetRSUIContext(surfaceNode->GetRSUIContext());
3402         TAG_LOGD(AceLogTag::ACE_WINDOW, "AddChild surfaceNode %{public}" PRIu64 "canvasNode %{public}" PRIu64 "",
3403             surfaceNode->GetId(), canvasNode->GetId());
3404         surfaceNode->AddChild(canvasNode, -1);
3405     }
3406 #endif
3407 #endif
3408     TAG_LOGD(AceLogTag::ACE_WINDOW, "LinkKeyFrameCanvasNode.");
3409     auto rootElement = context->GetRootElement();
3410     CHECK_NULL_VOID(rootElement);
3411     auto rosenRenderContext = AceType::DynamicCast<NG::RosenRenderContext>(rootElement->GetRenderContext());
3412     CHECK_NULL_VOID(rosenRenderContext);
3413     rosenRenderContext->LinkCanvasNodeToRootNode(context->GetRootElement());
3414 }
3415 
CacheAnimateInfo(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)3416 void UIContentImpl::CacheAnimateInfo(const ViewportConfig& config,
3417     OHOS::Rosen::WindowSizeChangeReason reason,
3418     const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction,
3419     const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas)
3420 {
3421     TAG_LOGD(AceLogTag::ACE_WINDOW, "CacheAnimateInfo.");
3422     cachedAnimateFlag_.store(true);
3423     cachedConfig_ = config;
3424     cachedReason_ = reason;
3425     cachedRsTransaction_ = rsTransaction;
3426     cachedAvoidAreas_ = avoidAreas;
3427 }
3428 
ExecKeyFrameCachedAnimateAction()3429 void UIContentImpl::ExecKeyFrameCachedAnimateAction()
3430 {
3431     TAG_LOGD(AceLogTag::ACE_WINDOW, "exec keyframe cache in");
3432     auto container = Platform::AceContainer::GetContainer(instanceId_);
3433     CHECK_NULL_VOID(container);
3434     auto taskExecutor = container->GetTaskExecutor();
3435     CHECK_NULL_VOID(taskExecutor);
3436 
3437     if (cachedAnimateFlag_.load()) {
3438         const uint32_t delay = 50;
3439         auto pipeline = container->GetPipelineContext();
3440         auto task = [cachedConfig = cachedConfig_, cachedReason = cachedReason_,
3441             cachedRsTransaction = cachedRsTransaction_, cachedAvoidAreas = cachedAvoidAreas_,
3442             weak = WeakPtr<PipelineBase>(pipeline), UICONTENT_IMPL_HELPER(content)] () {
3443             auto pipeline = weak.Upgrade();
3444             CHECK_NULL_VOID(pipeline);
3445             UICONTENT_IMPL_HELPER_GUARD(content, return);
3446             TAG_LOGD(AceLogTag::ACE_WINDOW, "exec keyframe cache");
3447             UICONTENT_IMPL_PTR(content)->UpdateViewportConfig(cachedConfig, cachedReason,
3448                 cachedRsTransaction, cachedAvoidAreas);
3449             pipeline->RequestFrame();
3450         };
3451         taskExecutor->PostDelayedTask(task, TaskExecutor::TaskType::UI, delay,
3452             "ArkUIExecKeyFrameCachedAnimateTask", PriorityType::HIGH);
3453     }
3454     cachedAnimateFlag_.store(false);
3455 }
3456 
SetRSSyncTransaction(OHOS::Rosen::RSSyncTransactionController ** transactionController,std::shared_ptr<Rosen::RSSyncTransactionHandler> & transactionHandler,const RefPtr<NG::PipelineContext> & context)3457 void UIContentImpl::SetRSSyncTransaction(OHOS::Rosen::RSSyncTransactionController** transactionController,
3458     std::shared_ptr<Rosen::RSSyncTransactionHandler>& transactionHandler, const RefPtr<NG::PipelineContext>& context)
3459 {
3460     if (SystemProperties::GetMultiInstanceEnabled()) {
3461         CHECK_NULL_VOID(context);
3462         auto window = context->GetWindow();
3463         CHECK_NULL_VOID(window);
3464         auto rsUIDirector = window->GetRSUIDirector();
3465         CHECK_NULL_VOID(rsUIDirector);
3466         auto rsUIContext = rsUIDirector->GetRSUIContext();
3467         CHECK_NULL_VOID(rsUIContext);
3468         transactionHandler = rsUIContext->GetSyncTransactionHandler();
3469     } else {
3470         auto rsSyncTransactionController = Rosen::RSSyncTransactionController::GetInstance();
3471         *transactionController = rsSyncTransactionController;
3472     }
3473 }
3474 
CloseSyncTransaction(OHOS::Rosen::RSSyncTransactionController * transactionController,std::shared_ptr<Rosen::RSSyncTransactionHandler> & transactionHandler)3475 void UIContentImpl::CloseSyncTransaction(OHOS::Rosen::RSSyncTransactionController* transactionController,
3476     std::shared_ptr<Rosen::RSSyncTransactionHandler>& transactionHandler)
3477 {
3478     if (transactionController) {
3479         transactionController->CloseSyncTransaction();
3480     } else if (transactionHandler) {
3481         transactionHandler->CloseSyncTransaction();
3482     }
3483 }
3484 
KeyFrameDragStartPolicy(RefPtr<NG::PipelineContext> context)3485 void UIContentImpl::KeyFrameDragStartPolicy(RefPtr<NG::PipelineContext> context)
3486 {
3487     if (!context) {
3488         TAG_LOGE(AceLogTag::ACE_WINDOW, "context is null.");
3489         return;
3490     }
3491     OHOS::Rosen::RSSyncTransactionController* transactionController = nullptr;
3492     std::shared_ptr<Rosen::RSSyncTransactionHandler> transactionHandler;
3493     SetRSSyncTransaction(&transactionController, transactionHandler, context);
3494     std::shared_ptr<Rosen::RSTransaction> rsTransaction;
3495     if (transactionController) {
3496         transactionController->OpenSyncTransaction();
3497         rsTransaction = transactionController->GetRSTransaction();
3498     } else if (transactionHandler) {
3499         transactionHandler->OpenSyncTransaction();
3500         rsTransaction = transactionHandler->GetRSTransaction();
3501     } else {
3502         TAG_LOGE(AceLogTag::ACE_WINDOW, "transactionController and handler invalid");
3503         return;
3504     }
3505     auto rootElement = context->GetRootElement();
3506     if (!rootElement) {
3507         CloseSyncTransaction(transactionController, transactionHandler);
3508         return;
3509     }
3510     auto rosenRenderContext = AceType::DynamicCast<NG::RosenRenderContext>(rootElement->GetRenderContext());
3511     if (!rosenRenderContext) {
3512         CloseSyncTransaction(transactionController, transactionHandler);
3513         return;
3514     }
3515     rosenRenderContext->CreateCanvasNode();
3516     canvasNode_ = rosenRenderContext->GetCanvasNode();
3517     if (addNodeCallback_ && canvasNode_) {
3518         TAG_LOGI(AceLogTag::ACE_WINDOW, "rsTransaction addNodeCallback_.");
3519         addNodeCallback_(canvasNode_, rsTransaction);
3520     }
3521     CloseSyncTransaction(transactionController, transactionHandler);
3522     std::function<void()> callbackCachedAnimation = std::bind(&UIContentImpl::ExecKeyFrameCachedAnimateAction, this);
3523     CHECK_NULL_VOID(callbackCachedAnimation);
3524     rosenRenderContext->AddKeyFrameCachedAnimateActionCallback(callbackCachedAnimation);
3525 }
3526 
KeyFrameActionPolicy(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)3527 bool UIContentImpl::KeyFrameActionPolicy(const ViewportConfig& config,
3528     OHOS::Rosen::WindowSizeChangeReason reason,
3529     const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction,
3530     const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas)
3531 {
3532     if (!config.GetKeyFrameConfig().enableKeyFrame_) {
3533         return false;
3534     }
3535 
3536     ContainerScope scope(instanceId_);
3537     auto container = Platform::AceContainer::GetContainer(instanceId_);
3538     CHECK_NULL_RETURN(container, true);
3539     auto pipelineContext = container->GetPipelineContext();
3540     auto context = AceType::DynamicCast<NG::PipelineContext>(pipelineContext);
3541     CHECK_NULL_RETURN(context, true);
3542 
3543     bool animateRes = true;
3544     auto rootElement = context->GetRootElement();
3545     CHECK_NULL_RETURN(rootElement, true);
3546     auto rosenRenderContext = AceType::DynamicCast<NG::RosenRenderContext>(rootElement->GetRenderContext());
3547     CHECK_NULL_RETURN(rosenRenderContext, true);
3548     switch (reason) {
3549         case OHOS::Rosen::WindowSizeChangeReason::DRAG_START:
3550             if (!rosenRenderContext->GetIsDraggingFlag()) {
3551                 if (rosenRenderContext->GetCanvasNode()) {
3552                     rosenRenderContext->SetReDraggingFlag(true);
3553                 }
3554                 rosenRenderContext->SetIsDraggingFlag(true);
3555                 KeyFrameDragStartPolicy(context);
3556             }
3557             return true;
3558         case OHOS::Rosen::WindowSizeChangeReason::DRAG_END:
3559             rosenRenderContext->SetIsDraggingFlag(false);
3560             [[fallthrough]];
3561         case OHOS::Rosen::WindowSizeChangeReason::DRAG:
3562             animateRes = rosenRenderContext->SetCanvasNodeOpacityAnimation(
3563                 config.GetKeyFrameConfig().animationDuration_,
3564                 config.GetKeyFrameConfig().animationDelay_,
3565                 reason == OHOS::Rosen::WindowSizeChangeReason::DRAG_END);
3566             if (!animateRes) {
3567                 CacheAnimateInfo(config, reason, rsTransaction, avoidAreas);
3568                 return true;
3569             }
3570             return false;
3571         default:
3572             return true;
3573     }
3574     return false;
3575 }
3576 
SetUIExtensionImeShow(const Rect & keyboardRect,int32_t instanceId)3577 void SetUIExtensionImeShow(const Rect& keyboardRect, int32_t instanceId)
3578 {
3579     auto container = Platform::AceContainer::GetContainer(instanceId);
3580     CHECK_NULL_VOID(container);
3581     auto taskExecutor = container->GetTaskExecutor();
3582     CHECK_NULL_VOID(taskExecutor);
3583     if (GreatNotEqual(keyboardRect.Height(), 0.0f)) {
3584         taskExecutor->PostTask(
3585             [id = instanceId] {
3586                 ContainerScope scope(id);
3587                 auto pipeline = NG::PipelineContext::GetCurrentContext();
3588                 CHECK_NULL_VOID(pipeline);
3589                 pipeline->SetUIExtensionImeShow(true);
3590             }, TaskExecutor::TaskType::UI, "ArkUISetUIExtensionImeShow");
3591     } else {
3592         taskExecutor->PostTask(
3593             [id = instanceId] {
3594                 ContainerScope scope(id);
3595                 auto pipeline = NG::PipelineContext::GetCurrentContext();
3596                 CHECK_NULL_VOID(pipeline);
3597                 pipeline->SetUIExtensionImeShow(false);
3598             }, TaskExecutor::TaskType::UI, "ArkUISetUIExtensionImeHide");
3599     }
3600 }
3601 
UIExtensionKeyboardAvoid(const RefPtr<PipelineBase> & pipelineContext,int32_t instanceId,const Rect keyboardRect,const sptr<OHOS::Rosen::OccupiedAreaChangeInfo> & info)3602 bool UIExtensionKeyboardAvoid(const RefPtr<PipelineBase>& pipelineContext,
3603     int32_t instanceId, const Rect keyboardRect, const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info)
3604 {
3605     auto pipeline = AceType::DynamicCast<NG::PipelineContext>(pipelineContext);
3606     CHECK_NULL_RETURN(pipeline, false);
3607     ContainerScope scope(instanceId);
3608     auto uiExtensionManager = pipeline->GetUIExtensionManager();
3609     CHECK_NULL_RETURN(uiExtensionManager, false);
3610     SetUIExtensionImeShow(keyboardRect, instanceId);
3611 
3612     if (uiExtensionManager->NotifyOccupiedAreaChangeInfo(info)) {
3613         TAG_LOGI(AceLogTag::ACE_KEYBOARD, "uiExtension consumed");
3614         ContainerScope scope(instanceId);
3615         auto container = Platform::AceContainer::GetContainer(instanceId);
3616         CHECK_NULL_RETURN(container, false);
3617         auto context = container->GetPipelineContext();
3618         CHECK_NULL_RETURN(context, false);
3619         context->OnVirtualKeyboardAreaChange(Rect(), 0, 0);
3620         return true;
3621     }
3622     return false;
3623 }
3624 
LaterAvoid(const Rect & keyboardRect,double positionY,double height)3625 bool UIContentImpl::LaterAvoid(const Rect& keyboardRect, double positionY, double height)
3626 {
3627     auto container = Platform::AceContainer::GetContainer(instanceId_);
3628     CHECK_NULL_RETURN(container, false);
3629     auto context = container->GetPipelineContext();
3630     CHECK_NULL_RETURN(context, false);
3631     auto pipeline = AceType::DynamicCast<NG::PipelineContext>(context);
3632     CHECK_NULL_RETURN(pipeline, false);
3633     auto textFieldManager = AceType::DynamicCast<NG::TextFieldManagerNG>(pipeline->GetTextFieldManager());
3634     CHECK_NULL_RETURN(textFieldManager, false);
3635     auto windowManager = pipeline->GetWindowManager();
3636     CHECK_NULL_RETURN(windowManager, false);
3637     auto windowMode = windowManager->GetWindowMode();
3638     if (windowMode == WindowMode::WINDOW_MODE_FLOATING || windowMode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY) {
3639         textFieldManager->SetLaterAvoid(false);
3640         return false;
3641     }
3642     bool isRotate = false;
3643     auto displayInfo = container->GetDisplayInfo();
3644     if (displayInfo) {
3645         auto dmRotation = static_cast<int32_t>(displayInfo->GetRotation());
3646         isRotate = lastRotation != -1 && lastRotation != dmRotation;
3647         lastRotation = dmRotation;
3648     } else {
3649         lastRotation = -1;
3650     }
3651     auto triggerAvoidTaskOrientation = textFieldManager->GetContextTriggerAvoidTaskOrientation();
3652     textFieldManager->SetContextTriggerAvoidTaskOrientation(-1);
3653     if ((isRotate && lastRotation == triggerAvoidTaskOrientation) ||
3654         (textFieldManager->GetLaterAvoid() && NearEqual(0.0f, keyboardRect.Height()))) {
3655         TAG_LOGI(AceLogTag::ACE_KEYBOARD, "no need to later avoid, trigger avoid now");
3656         textFieldManager->SetLaterAvoid(false);
3657         return false;
3658     }
3659     auto laterRect = textFieldManager->GetLaterAvoidKeyboardRect();
3660     if (textFieldManager->GetLaterAvoid() && NearEqual(laterRect.Height(), keyboardRect.Height())) {
3661         TAG_LOGI(AceLogTag::ACE_KEYBOARD, "will trigger avoid later, ignore this notify");
3662         return true;
3663     }
3664     // do not avoid immediately when device is in rotation, trigger it after context trigger root rect update
3665     if (textFieldManager->GetLaterAvoid() || isRotate) {
3666         TAG_LOGI(AceLogTag::ACE_KEYBOARD, "rotation change to %{public}d, later avoid %{public}s %{public}f"
3667             "%{public}f", lastRotation, keyboardRect.ToString().c_str(), positionY, height);
3668         NG::LaterAvoidInfo laterAvoidInfo = {true, keyboardRect, positionY, height, lastRotation };
3669         textFieldManager->SetLaterAvoidArgs(laterAvoidInfo);
3670         return true;
3671     }
3672     return false;
3673 }
3674 
SetKeyboardInfo(const RefPtr<PipelineBase> & pipelineContext,float height)3675 void SetKeyboardInfo(const RefPtr<PipelineBase>& pipelineContext, float height)
3676 {
3677     auto pipeline = AceType::DynamicCast<NG::PipelineContext>(pipelineContext);
3678     CHECK_NULL_VOID(pipeline);
3679     auto safeAreaManager = pipeline->GetSafeAreaManager();
3680     CHECK_NULL_VOID(safeAreaManager);
3681     safeAreaManager->SetKeyboardInfo(height);
3682 }
3683 
KeyboardAvoid(OHOS::Rosen::WindowSizeChangeReason reason,int32_t instanceId,const RefPtr<PipelineBase> & pipelineContext,const sptr<OHOS::Rosen::OccupiedAreaChangeInfo> & info,const RefPtr<Platform::AceContainer> & container)3684 void KeyboardAvoid(OHOS::Rosen::WindowSizeChangeReason reason, int32_t instanceId,
3685     const RefPtr<PipelineBase>& pipelineContext, const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info,
3686     const RefPtr<Platform::AceContainer>& container)
3687 {
3688     CHECK_NULL_VOID(info);
3689     if (reason != OHOS::Rosen::WindowSizeChangeReason::OCCUPIED_AREA_CHANGE) {
3690         return;
3691     }
3692     auto rect = info->rect_;
3693     Rect keyboardRect = Rect(rect.posX_, rect.posY_, rect.width_, rect.height_);
3694     SetKeyboardInfo(pipelineContext, keyboardRect.Height());
3695     if (UIExtensionKeyboardAvoid(pipelineContext, instanceId, keyboardRect, info)) {
3696         return;
3697     }
3698     if (container->IsSceneBoardWindow()) {
3699         TAG_LOGD(AceLogTag::ACE_KEYBOARD, "SceneBoard window, no keyboard avoidance");
3700         return;
3701     }
3702     ACE_LAYOUT_SCOPED_TRACE("KeyboardAvoid keyboardRect %s", keyboardRect.ToString().c_str());
3703     auto curWindow = pipelineContext->GetCurrentWindowRect();
3704     double textFieldPositionY = info->textFieldPositionY_;
3705     double textFieldHeight = info->textFieldHeight_;
3706     textFieldPositionY -= curWindow.Top();
3707     ContainerScope scope(instanceId);
3708     pipelineContext->OnVirtualKeyboardAreaChange(keyboardRect, textFieldPositionY, textFieldHeight);
3709 }
3710 
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,const sptr<OHOS::Rosen::OccupiedAreaChangeInfo> & info)3711 void UIContentImpl::UpdateViewportConfig(const ViewportConfig& config, OHOS::Rosen::WindowSizeChangeReason reason,
3712     const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction,
3713     const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas,
3714     const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info)
3715 {
3716     if (KeyFrameActionPolicy(config, reason, rsTransaction, avoidAreas)) {
3717         return;
3718     }
3719 
3720     if (SystemProperties::GetWindowRectResizeEnabled()) {
3721         PerfMonitor::GetPerfMonitor()->RecordWindowRectResize(static_cast<OHOS::Ace::WindowSizeChangeReason>(reason),
3722             bundleName_);
3723     }
3724     UpdateViewportConfigWithAnimation(config, reason, {}, rsTransaction, avoidAreas, info);
3725 }
3726 
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,const sptr<OHOS::Rosen::OccupiedAreaChangeInfo> & info)3727 void UIContentImpl::UpdateViewportConfigWithAnimation(const ViewportConfig& config,
3728     OHOS::Rosen::WindowSizeChangeReason reason, AnimationOption animationOpt,
3729     const std::shared_ptr<OHOS::Rosen::RSTransaction>& rsTransaction,
3730     const std::map<OHOS::Rosen::AvoidAreaType, OHOS::Rosen::AvoidArea>& avoidAreas,
3731     const sptr<OHOS::Rosen::OccupiedAreaChangeInfo>& info)
3732 {
3733     std::string stringifiedMap = StringifyAvoidAreas(avoidAreas);
3734     if (info) {
3735         auto rect = info->rect_;
3736         Rect keyboardRect = Rect(rect.posX_, rect.posY_, rect.width_, rect.height_);
3737         if (SystemProperties::GetSyncDebugTraceEnabled()) {
3738             ACE_LAYOUT_SCOPED_TRACE(
3739                 "[%s][%s][%d]: UpdateViewportConfig %s, windowSizeChangeReason %d, is rsTransaction nullptr %d, %s,"
3740                 " keyboardRect %s", bundleName_.c_str(), moduleName_.c_str(), instanceId_, config.ToString().c_str(),
3741                 static_cast<uint32_t>(reason), rsTransaction == nullptr, stringifiedMap.c_str(),
3742                 keyboardRect.ToString().c_str());
3743         }
3744         TAG_LOGI(ACE_LAYOUT,
3745             "[%{public}s][%{public}s][%{public}d]: UpdateViewportConfig %{public}s, windowSizeChangeReason %{public}d,"
3746             " is rsTransaction nullptr %{public}d, %{public}s, keyboardRect %{public}s", bundleName_.c_str(),
3747             moduleName_.c_str(), instanceId_, config.ToString().c_str(), static_cast<uint32_t>(reason),
3748             rsTransaction == nullptr, stringifiedMap.c_str(), keyboardRect.ToString().c_str());
3749     } else {
3750         if (SystemProperties::GetSyncDebugTraceEnabled()) {
3751             ACE_LAYOUT_SCOPED_TRACE(
3752                 "[%s][%s][%d]: UpdateViewportConfig %s, windowSizeChangeReason %d, is rsTransaction nullptr %d, %s,"
3753                 " keyboardInfo is null",
3754                 bundleName_.c_str(), moduleName_.c_str(), instanceId_, config.ToString().c_str(),
3755                 static_cast<uint32_t>(reason), rsTransaction == nullptr, stringifiedMap.c_str());
3756         }
3757         TAG_LOGI(ACE_LAYOUT,
3758             "[%{public}s][%{public}s][%{public}d]: UpdateViewportConfig %{public}s, windowSizeChangeReason %{public}d,"
3759             " is rsTransaction nullptr %{public}d, %{public}s, keyboardInfo is null", bundleName_.c_str(),
3760             moduleName_.c_str(), instanceId_, config.ToString().c_str(), static_cast<uint32_t>(reason),
3761             rsTransaction == nullptr, stringifiedMap.c_str());
3762     }
3763 
3764     if (reason == OHOS::Rosen::WindowSizeChangeReason::PAGE_ROTATION) {
3765         TAG_LOGI(AceLogTag::ACE_NAVIGATION, "save PAGE_ROTATION as ROTATION");
3766         reason = OHOS::Rosen::WindowSizeChangeReason::ROTATION;
3767     }
3768     if (lastReason_ == OHOS::Rosen::WindowSizeChangeReason::UNDEFINED) {
3769         lastReason_ = reason;
3770     }
3771     bool reasonDragFlag = GetWindowSizeChangeReason(lastReason_, reason);
3772     lastReason_ = reason;
3773 
3774     if (!g_isDragging && !g_isDynamicVsync && (reason == OHOS::Rosen::WindowSizeChangeReason::DRAG ||
3775         reason == OHOS::Rosen::WindowSizeChangeReason::DRAG_START)) {
3776         OHOS::AppExecFwk::EventHandler::SetVsyncPolicy(true);
3777         ACE_SCOPED_TRACE_COMMERCIAL("SetVsyncPolicy(true)");
3778         g_isDragging = true;
3779     }
3780 
3781     bool isOrientationChanged = static_cast<int32_t>(SystemProperties::GetDeviceOrientation()) != config.Orientation();
3782     SystemProperties::SetDeviceOrientation(config.Orientation());
3783     TAG_LOGD(
3784         AceLogTag::ACE_WINDOW, "Update orientation to : %{public}d", static_cast<uint32_t>(config.Orientation()));
3785     ContainerScope scope(instanceId_);
3786     auto container = Platform::AceContainer::GetContainer(instanceId_);
3787     CHECK_NULL_VOID(container);
3788     container->SetCurrentDisplayOrientation(static_cast<DisplayOrientation>(config.Orientation()));
3789     auto pipelineContext = container->GetPipelineContext();
3790     auto context = AceType::DynamicCast<NG::PipelineContext>(pipelineContext);
3791     if (container->IsSubContainer()) {
3792         auto rect = NG::RectF(config.Left(), config.Top(), config.Width(), config.Height());
3793         SubwindowManager::GetInstance()->SetRect(rect, instanceId_);
3794         TAG_LOGI(AceLogTag::ACE_WINDOW, "UpdateViewportConfig for subContainer: %{public}s",
3795             rect.ToString().c_str());
3796     }
3797     // The density of sub windows related to dialog needs to be consistent with the main window.
3798     auto modifyConfig = config;
3799     if (instanceId_ >= MIN_SUBCONTAINER_ID) {
3800         auto parentContainer = Platform::AceContainer::GetContainer(container->GetParentId());
3801         CHECK_NULL_VOID(parentContainer);
3802         if (parentContainer->IsSceneBoardWindow()) {
3803             auto parentPipeline = parentContainer->GetPipelineContext();
3804             CHECK_NULL_VOID(parentPipeline);
3805             modifyConfig.SetDensity(parentPipeline->GetDensity());
3806         }
3807     }
3808     auto taskExecutor = container->GetTaskExecutor();
3809     CHECK_NULL_VOID(taskExecutor);
3810     auto updateforceSplitTask = [context, width = config.Width()]() {
3811         CHECK_NULL_VOID(context);
3812         auto forceSplitMgr = context->GetForceSplitManager();
3813         CHECK_NULL_VOID(forceSplitMgr);
3814         forceSplitMgr->UpdateIsInForceSplitMode(width);
3815     };
3816     auto updateDensityTask = [container, modifyConfig]() {
3817         auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
3818         CHECK_NULL_VOID(aceView);
3819         Platform::AceViewOhos::SetViewportMetrics(aceView, modifyConfig); // update density into pipeline
3820     };
3821     auto updateDeviceOrientationTask = [container, modifyConfig, reason]() {
3822         if (reason == OHOS::Rosen::WindowSizeChangeReason::ROTATION) {
3823             container->UpdateResourceOrientation(modifyConfig.Orientation());
3824         }
3825     };
3826     auto updateDisplayIdAndAreaTask = [container, context, modifyConfig, UICONTENT_IMPL_HELPER(content)]() {
3827         auto displayId = modifyConfig.DisplayId();
3828         if (displayId == DISPLAY_ID_INVALID) {
3829             TAG_LOGE(AceLogTag::ACE_WINDOW, "Invalid display id.");
3830             return;
3831         }
3832         if (container->GetCurrentDisplayId() != displayId) {
3833             container->SetCurrentDisplayId(displayId);
3834             auto currentDisplay = Rosen::DisplayManager::GetInstance().GetDisplayById(displayId);
3835             if (context && currentDisplay) {
3836                 Rosen::DMRect availableArea;
3837                 Rosen::DMError ret = currentDisplay->GetAvailableArea(availableArea);
3838                 if (ret == Rosen::DMError::DM_OK) {
3839                     context->UpdateDisplayAvailableRect(ConvertDMRect2Rect(availableArea));
3840                 }
3841             }
3842         }
3843         UICONTENT_IMPL_HELPER_GUARD(content, return);
3844         UICONTENT_IMPL_PTR(content)->ChangeDisplayAvailableAreaListener(displayId);
3845     };
3846     if (taskExecutor->WillRunOnCurrentThread(TaskExecutor::TaskType::UI)) {
3847         updateforceSplitTask();
3848         updateDensityTask(); // ensure density has been updated before load first page
3849         updateDeviceOrientationTask();
3850         updateDisplayIdAndAreaTask();
3851     } else {
3852         taskExecutor->PostTask(
3853             std::move(updateforceSplitTask), TaskExecutor::TaskType::UI, "ArkUIUpdateForceSplit");
3854         taskExecutor->PostTask(std::move(updateDensityTask), TaskExecutor::TaskType::UI, "ArkUIUpdateDensity");
3855         taskExecutor->PostTask(
3856             std::move(updateDeviceOrientationTask), TaskExecutor::TaskType::UI, "ArkUIDeviceOrientation");
3857         taskExecutor->PostTask(
3858             std::move(updateDisplayIdAndAreaTask), TaskExecutor::TaskType::UI, "ArkUIUpdateDisplayIdAndArea");
3859     }
3860     RefPtr<NG::SafeAreaManager> safeAreaManager = nullptr;
3861 
3862     std::map<OHOS::Rosen::AvoidAreaType, NG::SafeAreaInsets> updatingInsets;
3863     if (context) {
3864         context->FireSizeChangeByRotateCallback(isOrientationChanged, rsTransaction);
3865         if (reason == OHOS::Rosen::WindowSizeChangeReason::DRAG_START ||
3866             reason == OHOS::Rosen::WindowSizeChangeReason::DRAG_END) {
3867             bool isDragging = reason == OHOS::Rosen::WindowSizeChangeReason::DRAG_START;
3868             if (!g_isDynamicVsync && !isDragging) {
3869                 OHOS::AppExecFwk::EventHandler::SetVsyncPolicy(false);
3870                 ACE_SCOPED_TRACE_COMMERCIAL("SetVsyncPolicy(false)");
3871                 g_isDragging = false;
3872             }
3873             taskExecutor->PostTask(
3874                 [weak = AceType::WeakClaim(AceType::RawPtr(context)), isDragging]() {
3875                     auto pipelineContext = weak.Upgrade();
3876                     CHECK_NULL_VOID(pipelineContext);
3877                     pipelineContext->SetIsWindowSizeDragging(isDragging);
3878                 }, TaskExecutor::TaskType::UI, "ArkUIWindowSizeDragStartEnd", PriorityType::VIP);
3879         }
3880     }
3881 
3882     if (viewportConfigMgr_->IsConfigsEqual(config) && (rsTransaction == nullptr) && reasonDragFlag) {
3883         TAG_LOGD(ACE_LAYOUT, "UpdateViewportConfig return in advance");
3884         taskExecutor->PostTask([context, config, avoidAreas, reason, instanceId = instanceId_,
3885             pipelineContext, info, container] {
3886                 if (avoidAreas.empty() && !info) {
3887                     return;
3888                 }
3889                 if (ParseAvoidAreasUpdate(context, avoidAreas, config)) {
3890                     context->AnimateOnSafeAreaUpdate();
3891                 }
3892                 AvoidAreasUpdateOnUIExtension(context, avoidAreas);
3893                 if (pipelineContext) {
3894                     TAG_LOGD(ACE_KEYBOARD, "KeyboardAvoid in advance");
3895                     KeyboardAvoid(reason, instanceId, pipelineContext, info, container);
3896                 }
3897             },
3898             TaskExecutor::TaskType::UI, "ArkUIUpdateOriginAvoidAreaAndExecuteKeyboardAvoid");
3899         return;
3900     }
3901 
3902     auto taskId = viewportConfigMgr_->MakeTaskId();
3903     auto task = [config = modifyConfig, container, reason, rsTransaction, rsWindow = window_,
3904                     instanceId = instanceId_, info, isDynamicRender = isDynamicRender_, animationOpt, avoidAreas,
3905                     taskId, viewportConfigMgr = viewportConfigMgr_]() {
3906         container->SetWindowPos(config.Left(), config.Top());
3907         auto pipelineContext = container->GetPipelineContext();
3908         if (pipelineContext) {
3909             UpdateSafeArea(pipelineContext, avoidAreas, config, container);
3910             if (reason != OHOS::Rosen::WindowSizeChangeReason::ROOT_SCENE_CHANGE) {
3911                 pipelineContext->SetDisplayWindowRectInfo(
3912                     Rect(Offset(config.Left(), config.Top()), Size(config.Width(), config.Height())));
3913             } else {
3914                 // when the reason is ROOT_SCENE_CHANGE, the offset of the window should be (0, 0).
3915                 pipelineContext->SetDisplayWindowRectInfo(
3916                     Rect(Offset(0, 0), Size(config.Width(), config.Height())));
3917             }
3918             pipelineContext->SetWindowSizeChangeReason(static_cast<OHOS::Ace::WindowSizeChangeReason>(reason));
3919             TAG_LOGD(AceLogTag::ACE_WINDOW, "Update displayWindowRect in UpdateViewportConfig to : %{public}s",
3920                 pipelineContext->GetDisplayWindowRectInfo().ToString().c_str());
3921             if (rsWindow) {
3922                 pipelineContext->SetIsLayoutFullScreen(
3923                     rsWindow->GetWindowMode() == Rosen::WindowMode::WINDOW_MODE_FULLSCREEN);
3924                 auto isNeedAvoidWindowMode = IsNeedAvoidWindowMode(rsWindow);
3925                 pipelineContext->SetIsNeedAvoidWindow(isNeedAvoidWindowMode);
3926             }
3927             if (reason == OHOS::Rosen::WindowSizeChangeReason::ROTATION) {
3928                 pipelineContext->FlushBuild();
3929                 pipelineContext->StartWindowAnimation();
3930                 container->NotifyDirectionUpdate();
3931             }
3932         }
3933         auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
3934         CHECK_NULL_VOID(aceView);
3935         Platform::AceViewOhos::TransformHintChanged(aceView, config.TransformHint());
3936         if (isDynamicRender && animationOpt.IsValid()) {
3937             AnimationUtils::Animate(animationOpt, [pipelineContext, aceView, config, reason, rsTransaction] {
3938                 ContainerScope scope(aceView->GetInstanceId());
3939                 Platform::AceViewOhos::SurfaceChanged(aceView, config.Width(), config.Height(), config.Orientation(),
3940                     static_cast<WindowSizeChangeReason>(reason), rsTransaction);
3941                 pipelineContext->OnSurfaceChanged(
3942                     config.Width(), config.Height(), static_cast<WindowSizeChangeReason>(reason), rsTransaction);
3943                 pipelineContext->FlushUITasks(true);
3944             }, nullptr, nullptr, pipelineContext);
3945         } else {
3946             Platform::AceViewOhos::SurfaceChanged(aceView, config.Width(), config.Height(), config.Orientation(),
3947                 static_cast<WindowSizeChangeReason>(reason), rsTransaction);
3948         }
3949         Platform::AceViewOhos::SurfacePositionChanged(aceView, config.Left(), config.Top());
3950         SubwindowManager::GetInstance()->OnWindowSizeChanged(container->GetInstanceId(),
3951             Rect(Offset(config.Left(), config.Top()), Size(config.Width(), config.Height())),
3952             static_cast<WindowSizeChangeReason>(reason));
3953         viewportConfigMgr->UpdateViewConfigTaskDone(taskId);
3954         if (pipelineContext) {
3955             TAG_LOGD(ACE_KEYBOARD, "KeyboardAvoid in the UpdateViewportConfig task");
3956             KeyboardAvoid(reason, instanceId, pipelineContext, info, container);
3957         }
3958     };
3959     auto changeBrightnessTask = [container]() {
3960         auto pipelineContext = container->GetPipelineContext();
3961         if (pipelineContext) {
3962             pipelineContext->ChangeDarkModeBrightness();
3963         }
3964     };
3965     taskExecutor->PostTask(std::move(changeBrightnessTask), TaskExecutor::TaskType::UI, "ArkUIUpdateBrightness");
3966     AceViewportConfig aceViewportConfig(modifyConfig, reason, rsTransaction);
3967     bool isReasonRotationOrDPI = (reason == OHOS::Rosen::WindowSizeChangeReason::ROTATION ||
3968         reason == OHOS::Rosen::WindowSizeChangeReason::UPDATE_DPI_SYNC ||
3969         reason == OHOS::Rosen::WindowSizeChangeReason::RESIZE_WITH_ANIMATION);
3970     if (container->IsUseStageModel() && isReasonRotationOrDPI) {
3971         if (container->IsUIExtensionWindow()) {
3972             pipelineContext->AddUIExtensionCallbackEvent(NG::UIExtCallbackEventId::ON_AREA_CHANGED);
3973         }
3974         viewportConfigMgr_->UpdateConfigSync(aceViewportConfig, std::move(task));
3975         if (rsTransaction != nullptr) {
3976             viewportConfigMgr_->CancelAllPromiseTaskLocked();
3977         } else if (reason == OHOS::Rosen::WindowSizeChangeReason::UPDATE_DPI_SYNC) {
3978             viewportConfigMgr_->CancelUselessTaskLocked();
3979             viewportConfigMgr_->CancelAllPromiseTaskLocked();
3980         }
3981     } else if (rsTransaction != nullptr || !avoidAreas.empty()) {
3982         // When rsTransaction is not nullptr, the task contains animation. It shouldn't be cancled.
3983         // When avoidAreas need updating, the task shouldn't be cancelled.
3984         viewportConfigMgr_->UpdatePromiseConfig(aceViewportConfig, std::move(task), container, taskId,
3985             "ArkUIPromiseViewportConfig");
3986     } else {
3987         if (container->IsUIExtensionWindow()) {
3988             pipelineContext->AddUIExtensionCallbackEvent(NG::UIExtCallbackEventId::ON_AREA_CHANGED);
3989         }
3990         viewportConfigMgr_->UpdateConfig(aceViewportConfig, std::move(task), container, "ArkUIUpdateViewportConfig");
3991     }
3992     viewportConfigMgr_->StoreConfig(aceViewportConfig);
3993     viewportConfigMgr_->StoreInfo(info);
3994     UIExtensionUpdateViewportConfig(config);
3995 }
3996 
UIExtensionUpdateViewportConfig(const ViewportConfig & config)3997 void UIContentImpl::UIExtensionUpdateViewportConfig(const ViewportConfig& config)
3998 {
3999     auto container = Platform::AceContainer::GetContainer(instanceId_);
4000     CHECK_NULL_VOID(container);
4001     auto taskExecutor = container->GetTaskExecutor();
4002     CHECK_NULL_VOID(taskExecutor);
4003     auto context = NG::PipelineContext::GetCurrentContext();
4004     CHECK_NULL_VOID(context);
4005     auto updateSessionViewportConfigTask = [id = instanceId_, config]() {
4006         ContainerScope scope(id);
4007         auto context = NG::PipelineContext::GetCurrentContext();
4008         CHECK_NULL_VOID(context);
4009         auto uiExtMgr = context->GetUIExtensionManager();
4010         if (uiExtMgr) {
4011             uiExtMgr->UpdateSessionViewportConfig(config);
4012         }
4013     };
4014     taskExecutor->PostTask(
4015         std::move(updateSessionViewportConfigTask), TaskExecutor::TaskType::UI, "ArkUIUpdateSessionViewportConfig");
4016 }
4017 
SetIgnoreViewSafeArea(bool ignoreViewSafeArea)4018 void UIContentImpl::SetIgnoreViewSafeArea(bool ignoreViewSafeArea)
4019 {
4020     TAG_LOGI(ACE_SAFE_AREA, "[%{public}s][%{public}s][%{public}d]: SetIgnoreViewSafeArea:%{public}u",
4021         bundleName_.c_str(), moduleName_.c_str(), instanceId_, ignoreViewSafeArea);
4022     auto container = AceEngine::Get().GetContainer(instanceId_);
4023     CHECK_NULL_VOID(container);
4024     ContainerScope scope(instanceId_);
4025     auto pipeline = container->GetPipelineContext();
4026     const static int32_t PLATFORM_VERSION_TEN = 10;
4027     CHECK_NULL_VOID(pipeline && pipeline->GetMinPlatformVersion() >= PLATFORM_VERSION_TEN &&
4028                     (pipeline->GetIsAppWindow() || container->IsUIExtensionWindow()));
4029     auto taskExecutor = container->GetTaskExecutor();
4030     CHECK_NULL_VOID(taskExecutor);
4031     taskExecutor->PostSyncTask(
4032         [container, ignoreSafeArea = ignoreViewSafeArea]() {
4033             auto pipelineContext = container->GetPipelineContext();
4034             CHECK_NULL_VOID(pipelineContext);
4035             pipelineContext->SetIgnoreViewSafeArea(ignoreSafeArea);
4036         },
4037         TaskExecutor::TaskType::UI, "ArkUISetIgnoreViewSafeArea");
4038 }
4039 
UpdateWindowMode(OHOS::Rosen::WindowMode mode,bool hasDecor)4040 void UIContentImpl::UpdateWindowMode(OHOS::Rosen::WindowMode mode, bool hasDecor)
4041 {
4042     LOGI("[%{public}s][%{public}s][%{public}d]: UpdateWindowMode: %{public}d, hasDecor: %{public}d",
4043         bundleName_.c_str(), moduleName_.c_str(), instanceId_, mode, hasDecor);
4044     UpdateDecorVisible(mode == OHOS::Rosen::WindowMode::WINDOW_MODE_FLOATING, hasDecor);
4045     NotifyWindowMode(mode);
4046 }
4047 
NotifyWindowMode(OHOS::Rosen::WindowMode mode)4048 void UIContentImpl::NotifyWindowMode(OHOS::Rosen::WindowMode mode)
4049 {
4050     LOGI("[%{public}s][%{public}s][%{public}d]: NotifyWindowMode mode = %{public}d",
4051         bundleName_.c_str(), moduleName_.c_str(), instanceId_, mode);
4052     auto container = Platform::AceContainer::GetContainer(instanceId_);
4053     CHECK_NULL_VOID(container);
4054     auto taskExecutor = container->GetTaskExecutor();
4055     CHECK_NULL_VOID(taskExecutor);
4056     auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
4057     CHECK_NULL_VOID(pipeline);
4058     taskExecutor->PostTask(
4059         [weak = WeakPtr<NG::PipelineContext>(pipeline), mode]() {
4060             auto pipeline = weak.Upgrade();
4061             CHECK_NULL_VOID(pipeline);
4062             auto uiExtMgr = pipeline->GetUIExtensionManager();
4063             CHECK_NULL_VOID(uiExtMgr);
4064             uiExtMgr->NotifyWindowMode(mode);
4065         },
4066         TaskExecutor::TaskType::UI, "ArkUINotifyWindowMode");
4067 }
4068 
UpdateWindowBlur()4069 void UIContentImpl::UpdateWindowBlur()
4070 {
4071     ContainerScope scope(instanceId_);
4072     auto container = Platform::AceContainer::GetContainer(instanceId_);
4073     CHECK_NULL_VOID(container);
4074     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
4075     CHECK_NULL_VOID(pipelineContext);
4076     auto stageManager = pipelineContext->GetStageManager();
4077     CHECK_NULL_VOID(stageManager);
4078     auto stageNode = stageManager->GetStageNode();
4079     CHECK_NULL_VOID(stageNode);
4080     auto renderContext = stageNode->GetRenderContext();
4081     CHECK_NULL_VOID(renderContext);
4082     renderContext->UpdateWindowBlur();
4083 }
4084 
UpdateDecorVisible(bool visible,bool hasDecor)4085 void UIContentImpl::UpdateDecorVisible(bool visible, bool hasDecor)
4086 {
4087     std::lock_guard<std::mutex> lock(updateDecorVisibleMutex_);
4088     LOGI("[%{public}s][%{public}s][%{public}d]: UpdateWindowVisible: %{public}d, hasDecor: %{public}d",
4089         bundleName_.c_str(), moduleName_.c_str(), instanceId_, visible, hasDecor);
4090     ContainerScope scope(instanceId_);
4091     auto taskExecutor = Container::CurrentTaskExecutor();
4092     CHECK_NULL_VOID(taskExecutor);
4093     auto task = [instanceId = instanceId_, visible, hasDecor]() {
4094         auto container = Platform::AceContainer::GetContainer(instanceId);
4095         CHECK_NULL_VOID(container);
4096         auto pipelineContext = container->GetPipelineContext();
4097         CHECK_NULL_VOID(pipelineContext);
4098         pipelineContext->ShowContainerTitle(visible, hasDecor);
4099         pipelineContext->ChangeDarkModeBrightness();
4100     };
4101 
4102     // Cancel the pending task
4103     updateDecorVisibleTask_.Cancel();
4104     auto uiTaskRunner = SingleTaskExecutor::Make(taskExecutor, TaskExecutor::TaskType::UI);
4105     if (uiTaskRunner.IsRunOnCurrentThread()) {
4106         task();
4107     } else {
4108         updateDecorVisibleTask_ = SingleTaskExecutor::CancelableTask(std::move(task));
4109         taskExecutor->PostTask(updateDecorVisibleTask_,
4110             TaskExecutor::TaskType::UI, "ArkUIUpdateDecorVisible");
4111     }
4112 }
4113 
SetUIContentType(UIContentType uIContentType)4114 void UIContentImpl::SetUIContentType(UIContentType uIContentType)
4115 {
4116     uIContentType_ = uIContentType;
4117     auto container = Platform::AceContainer::GetContainer(instanceId_);
4118     CHECK_NULL_VOID(container);
4119     container->SetUIContentType(uIContentType);
4120 }
4121 
SetHostParams(const OHOS::AAFwk::WantParams & params)4122 void UIContentImpl::SetHostParams(const OHOS::AAFwk::WantParams& params)
4123 {
4124     if (hostWindowInfo_.hostWantParams == nullptr) {
4125         hostWindowInfo_.hostWantParams = std::make_shared<OHOS::AAFwk::Want>();
4126     }
4127 
4128     hostWindowInfo_.hostWantParams->SetParams(params);
4129     auto container = Platform::AceContainer::GetContainer(instanceId_);
4130     CHECK_NULL_VOID(container);
4131     auto containerHandler = container->GetContainerHandler();
4132     CHECK_NULL_VOID(containerHandler);
4133     auto uIExtensionContainerHandler =
4134         AceType::DynamicCast<NG::UIExtensionContainerHandler>(containerHandler);
4135     CHECK_NULL_VOID(uIExtensionContainerHandler);
4136     uIExtensionContainerHandler->SetHostParams(hostWindowInfo_.hostWantParams);
4137 }
4138 
UpdateMaximizeMode(OHOS::Rosen::MaximizeMode mode)4139 void UIContentImpl::UpdateMaximizeMode(OHOS::Rosen::MaximizeMode mode)
4140 {
4141     LOGI("[%{public}s][%{public}s][%{public}d]: UpdateMaximizeMode: %{public}d", bundleName_.c_str(),
4142         moduleName_.c_str(), instanceId_, mode);
4143     auto container = Platform::AceContainer::GetContainer(instanceId_);
4144     CHECK_NULL_VOID(container);
4145     ContainerScope scope(instanceId_);
4146     auto taskExecutor = container->GetTaskExecutor();
4147     CHECK_NULL_VOID(taskExecutor);
4148     auto task = [container, mode]() {
4149         auto pipelineContext = container->GetPipelineContext();
4150         CHECK_NULL_VOID(pipelineContext);
4151         auto windowManager = pipelineContext->GetWindowManager();
4152         CHECK_NULL_VOID(windowManager);
4153         windowManager->SetCurrentWindowMaximizeMode(static_cast<OHOS::Ace::MaximizeMode>(mode));
4154         pipelineContext->ShowContainerTitle(true, true, true);
4155     };
4156     auto uiTaskRunner = SingleTaskExecutor::Make(taskExecutor, TaskExecutor::TaskType::UI);
4157     if (uiTaskRunner.IsRunOnCurrentThread()) {
4158         task();
4159     } else {
4160         taskExecutor->PostTask(std::move(task), TaskExecutor::TaskType::UI, "ArkUIUpdateMaximizeMode");
4161     }
4162 }
4163 
NeedSoftKeyboard()4164 bool UIContentImpl::NeedSoftKeyboard()
4165 {
4166     auto container = AceEngine::Get().GetContainer(instanceId_);
4167     CHECK_NULL_RETURN(container, false);
4168     auto pipeline = container->GetPipelineContext();
4169     CHECK_NULL_RETURN(pipeline, false);
4170     return pipeline->NeedSoftKeyboard();
4171 }
4172 
SetOnWindowFocused(const std::function<void ()> & callback)4173 void UIContentImpl::SetOnWindowFocused(const std::function<void()>& callback)
4174 {
4175     auto container = AceEngine::Get().GetContainer(instanceId_);
4176     CHECK_NULL_VOID(container);
4177     auto pipeline = container->GetPipelineContext();
4178     CHECK_NULL_VOID(pipeline);
4179     pipeline->SetOnWindowFocused(callback);
4180 }
4181 
AddFocusActiveChangeCallback(const std::function<void (bool isFocusAvtive)> & callback)4182 int32_t UIContentImpl::AddFocusActiveChangeCallback(const std::function<void(bool isFocusAvtive)>& callback)
4183 {
4184     auto container = Platform::AceContainer::GetContainer(instanceId_);
4185     CHECK_NULL_RETURN(container, 0);
4186     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
4187     CHECK_NULL_RETURN(pipelineContext, 0);
4188     auto focusManager = pipelineContext->GetOrCreateFocusManager();
4189     CHECK_NULL_RETURN(focusManager, 0);
4190     return focusManager->AddFocusActiveChangeCallback(callback);
4191 }
4192 
RemoveFocusActiveChangeCallback(int32_t handler)4193 void UIContentImpl::RemoveFocusActiveChangeCallback(int32_t handler)
4194 {
4195     auto container = Platform::AceContainer::GetContainer(instanceId_);
4196     CHECK_NULL_VOID(container);
4197     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
4198     CHECK_NULL_VOID(pipelineContext);
4199     auto focusManager = pipelineContext->GetOrCreateFocusManager();
4200     CHECK_NULL_VOID(focusManager);
4201     focusManager->RemoveFocusActiveChangeCallback(handler);
4202 }
4203 
HideWindowTitleButton(bool hideSplit,bool hideMaximize,bool hideMinimize,bool hideClose)4204 void UIContentImpl::HideWindowTitleButton(bool hideSplit, bool hideMaximize, bool hideMinimize, bool hideClose)
4205 {
4206     LOGI("[%{public}s][%{public}s][%{public}d]: HideWindowTitleButton hideSplit: %{public}d, hideMaximize: %{public}d, "
4207          "hideMinimize: %{public}d, hideClose: %{public}d",
4208         bundleName_.c_str(), moduleName_.c_str(), instanceId_, hideSplit, hideMaximize, hideMinimize, hideClose);
4209     auto container = Platform::AceContainer::GetContainer(instanceId_);
4210     CHECK_NULL_VOID(container);
4211     ContainerScope scope(instanceId_);
4212     auto taskExecutor = Container::CurrentTaskExecutor();
4213     CHECK_NULL_VOID(taskExecutor);
4214     auto task = [container, hideSplit, hideMaximize, hideMinimize, hideClose]() {
4215         auto pipelineContext = container->GetPipelineContext();
4216         CHECK_NULL_VOID(pipelineContext);
4217         pipelineContext->SetContainerButtonHide(hideSplit, hideMaximize, hideMinimize, hideClose);
4218     };
4219     ExecuteUITask(std::move(task), "ArkUIHideWindowTitleButton");
4220 }
4221 
UpdateTitleInTargetPos(bool isShow,int32_t height)4222 void UIContentImpl::UpdateTitleInTargetPos(bool isShow, int32_t height)
4223 {
4224     LOGI("[%{public}s][%{public}s][%{public}d]: UpdateTitleInTargetPos, isShow: %{public}d, height: "
4225          "%{public}d",
4226         bundleName_.c_str(), moduleName_.c_str(), instanceId_, isShow, height);
4227     auto container = Platform::AceContainer::GetContainer(instanceId_);
4228     CHECK_NULL_VOID(container);
4229     ContainerScope scope(instanceId_);
4230     auto taskExecutor = Container::CurrentTaskExecutor();
4231     CHECK_NULL_VOID(taskExecutor);
4232     auto task = [container, isShow, height]() {
4233         auto pipelineContext = container->GetPipelineContext();
4234         CHECK_NULL_VOID(pipelineContext);
4235         pipelineContext->UpdateTitleInTargetPos(isShow, height);
4236     };
4237     ExecuteUITask(std::move(task), "ArkUIUpdateTitleInTargetPos");
4238 }
4239 
NotifyRotationAnimationEnd()4240 void UIContentImpl::NotifyRotationAnimationEnd()
4241 {
4242     auto container = Platform::AceContainer::GetContainer(instanceId_);
4243     CHECK_NULL_VOID(container);
4244     ContainerScope scope(instanceId_);
4245     auto taskExecutor = Container::CurrentTaskExecutor();
4246     CHECK_NULL_VOID(taskExecutor);
4247     taskExecutor->PostTask(
4248         [container]() {
4249             auto pipelineContext = container->GetPipelineContext();
4250             if (pipelineContext) {
4251                 pipelineContext->StopWindowAnimation();
4252             }
4253         },
4254         TaskExecutor::TaskType::UI, "ArkUINotifyRotationAnimationEnd");
4255 }
4256 
DumpInfo(const std::vector<std::string> & params,std::vector<std::string> & info)4257 void UIContentImpl::DumpInfo(const std::vector<std::string>& params, std::vector<std::string>& info)
4258 {
4259     std::string currentPid = std::to_string(getpid());
4260     for (auto param : params) {
4261         if (param == currentPid) {
4262             LOGE("DumpInfo pid has appeared");
4263             return;
4264         }
4265     }
4266     auto container = Platform::AceContainer::GetContainer(instanceId_);
4267     CHECK_NULL_VOID(container);
4268     auto taskExecutor = container->GetTaskExecutor();
4269     CHECK_NULL_VOID(taskExecutor);
4270     auto ret = taskExecutor->PostSyncTaskTimeout(
4271         [&]() { container->Dump(params, info); }, TaskExecutor::TaskType::UI, 1500, "ArkUIDumpInfo"); // timeout 1.5s
4272     if (!ret) {
4273         LOGE("DumpInfo failed");
4274     }
4275 }
4276 
UpdateDialogResourceConfiguration(RefPtr<Container> & container,const std::shared_ptr<OHOS::AbilityRuntime::Context> & context)4277 void UIContentImpl::UpdateDialogResourceConfiguration(RefPtr<Container>& container,
4278     const std::shared_ptr<OHOS::AbilityRuntime::Context>& context)
4279 {
4280     auto dialogContainer = AceType::DynamicCast<Platform::DialogContainer>(container);
4281     if (dialogContainer) {
4282         std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
4283         CHECK_NULL_VOID(context);
4284         auto resourceManager = context->GetResourceManager();
4285         if (resourceManager != nullptr) {
4286             resourceManager->GetResConfig(*resConfig);
4287             CHECK_NULL_VOID(resConfig);
4288             if (resConfig->GetColorMode() == OHOS::Global::Resource::ColorMode::DARK) {
4289                 dialogContainer->SetColorMode(ColorMode::DARK);
4290             } else {
4291                 dialogContainer->SetColorMode(ColorMode::LIGHT);
4292             }
4293         }
4294         auto aceResCfg = dialogContainer->GetResourceConfiguration();
4295         aceResCfg.SetOrientation(SystemProperties::GetDeviceOrientation());
4296         aceResCfg.SetDensity(SystemProperties::GetResolution());
4297         aceResCfg.SetDeviceType(SystemProperties::GetDeviceType());
4298         aceResCfg.SetColorMode(dialogContainer->GetColorMode());
4299         aceResCfg.SetDeviceAccess(SystemProperties::GetDeviceAccess());
4300         aceResCfg.SetColorModeIsSetByApp(true);
4301         aceResCfg.SetLanguage(AceApplicationInfo::GetInstance().GetLocaleTag());
4302         dialogContainer->SetResourceConfiguration(aceResCfg);
4303     }
4304 }
4305 
IfNeedTouchOutsideListener(const std::string & windowName)4306 bool UIContentImpl::IfNeedTouchOutsideListener(const std::string& windowName)
4307 {
4308     return !StringUtils::StartWith(windowName, SUBWINDOW_TOAST_PREFIX) ||
4309         Container::LessThanAPITargetVersion(PlatformVersion::VERSION_TWENTY);
4310 }
4311 
InitializeSubWindow(OHOS::Rosen::Window * window,bool isDialog)4312 void UIContentImpl::InitializeSubWindow(OHOS::Rosen::Window* window, bool isDialog)
4313 {
4314     window_ = window;
4315     CHECK_NULL_VOID(window_);
4316     LOGI("InitSubwindow: %{public}s", window->GetWindowName().c_str());
4317     RefPtr<Container> container;
4318     instanceId_ = Container::GenerateId<COMPONENT_SUBWINDOW_CONTAINER>();
4319     int32_t deviceWidth = 0;
4320     int32_t deviceHeight = 0;
4321     float density = 1.0f;
4322     uint64_t displayId = 0;
4323     if (window && window->GetDisplayId() != DISPLAY_ID_INVALID) {
4324         displayId = window->GetDisplayId();
4325     } else if (window) {
4326         TAG_LOGW(AceLogTag::ACE_SUB_WINDOW, "initialize subWindow display invalid. window name is %{public}s",
4327             window->GetWindowName().c_str());
4328     }
4329     auto defaultDisplay = Rosen::DisplayManager::GetInstance().GetDisplayById(displayId);
4330     if (defaultDisplay) {
4331         auto displayInfo = defaultDisplay->GetDisplayInfo();
4332         if (displayInfo) {
4333             density = displayInfo->GetDensityInCurResolution();
4334         }
4335         deviceWidth = defaultDisplay->GetWidth();
4336         deviceHeight = defaultDisplay->GetHeight();
4337     }
4338     SystemProperties::InitDeviceInfo(deviceWidth, deviceHeight, deviceHeight >= deviceWidth ? 0 : 1, density, false);
4339     std::weak_ptr<OHOS::AppExecFwk::AbilityInfo> abilityInfo;
4340     auto context = context_.lock();
4341     bool isCJFrontend = CJUtils::IsCJFrontendContext(context.get());
4342     auto frontendType = isCJFrontend ? FrontendType::DECLARATIVE_CJ : FrontendType::DECLARATIVE_JS;
4343     if (isDialog) {
4344         UErrorCode status = U_ZERO_ERROR;
4345         icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status);
4346         AceApplicationInfo::GetInstance().SetLocale(locale.getLanguage(), locale.getCountry(), locale.getScript(), "");
4347         container = AceType::MakeRefPtr<Platform::DialogContainer>(instanceId_, FrontendType::DECLARATIVE_JS);
4348         UpdateDialogResourceConfiguration(container, context);
4349     } else {
4350 #ifdef NG_BUILD
4351         container = AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, frontendType,
4352             context, abilityInfo, std::make_unique<ContentEventCallback>([] {
4353                 // Sub-window ,just return.
4354             }), false, true, true);
4355 #else
4356         if (Container::IsCurrentUseNewPipeline()) {
4357             container = AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, frontendType,
4358                 context, abilityInfo, std::make_unique<ContentEventCallback>([] {
4359                     // Sub-window ,just return.
4360                 }), false, true, true);
4361         } else {
4362             container = AceType::MakeRefPtr<Platform::AceContainer>(instanceId_, frontendType,
4363                 context, abilityInfo, std::make_unique<ContentEventCallback>([] {
4364                     // Sub-window ,just return.
4365                 }), false, true);
4366         }
4367 #endif
4368     }
4369     if (context) {
4370         if (context->GetApplicationInfo()) {
4371             auto appInfo = context->GetApplicationInfo();
4372             container->SetApiTargetVersion(appInfo->apiTargetVersion);
4373         }
4374 
4375         container->SetBundlePath(context->GetBundleCodeDir());
4376         container->SetFilesDataPath(context->GetFilesDir());
4377     } else {
4378         // if window don't have context,like service eject a toast,find target version in bundle.
4379         auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
4380         CHECK_NULL_VOID(systemAbilityMgr);
4381         auto bundleObj = systemAbilityMgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
4382         CHECK_NULL_VOID(bundleObj);
4383         auto bundleMgrProxy = iface_cast<AppExecFwk::IBundleMgr>(bundleObj);
4384         CHECK_NULL_VOID(bundleMgrProxy);
4385         AppExecFwk::BundleInfo bundleInfo;
4386         bundleMgrProxy->GetBundleInfoForSelf(
4387             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE), bundleInfo);
4388         container->SetApiTargetVersion(bundleInfo.targetVersion % 1000);
4389     }
4390     container->InitFoldStatusFromListener();
4391     SubwindowManager::GetInstance()->AddContainerId(window->GetWindowId(), instanceId_);
4392     AceEngine::Get().AddContainer(instanceId_, container);
4393     touchOutsideListener_ = new TouchOutsideListener(instanceId_);
4394     window_->RegisterTouchOutsideListener(touchOutsideListener_);
4395     dragWindowListener_ = new DragWindowListener(instanceId_);
4396     window_->RegisterDragListener(dragWindowListener_);
4397     if (!container->IsSceneBoardEnabled()) {
4398         occupiedAreaChangeListener_ = new OccupiedAreaChangeListener(instanceId_);
4399         window_->RegisterOccupiedAreaChangeListener(occupiedAreaChangeListener_);
4400     }
4401     foldStatusListener_ = new FoldScreenListener(instanceId_);
4402     waterfallModeChangeListener_ = new WaterfallModeChangeListener(instanceId_);
4403     window_->RegisterWaterfallModeChangeListener(waterfallModeChangeListener_);
4404     OHOS::Rosen::DisplayManager::GetInstance().RegisterFoldStatusListener(foldStatusListener_);
4405     foldDisplayModeListener_ = new FoldDisplayModeListener(instanceId_, isDialog);
4406     OHOS::Rosen::DisplayManager::GetInstance().RegisterDisplayModeListener(foldDisplayModeListener_);
4407 
4408     auto isAppOrSystemWindow = window_->IsAppWindow() || window_->IsSystemWindow();
4409     if (Container::GreatOrEqualAPITargetVersion(PlatformVersion::VERSION_SIXTEEN) && isAppOrSystemWindow) {
4410         avoidAreaChangedListener_ = new PretendChangedListener(instanceId_);
4411         window_->RegisterAvoidAreaChangeListener(avoidAreaChangedListener_);
4412     }
4413 }
4414 
SetNextFrameLayoutCallback(std::function<void ()> && callback)4415 void UIContentImpl::SetNextFrameLayoutCallback(std::function<void()>&& callback)
4416 {
4417     CHECK_NULL_VOID(callback);
4418     auto container = Platform::AceContainer::GetContainer(instanceId_);
4419     CHECK_NULL_VOID(container);
4420     auto pipelineContext = container->GetPipelineContext();
4421     CHECK_NULL_VOID(pipelineContext);
4422     pipelineContext->SetNextFrameLayoutCallback(std::move(callback));
4423 }
4424 
SetFrameLayoutFinishCallback(std::function<void ()> && callback)4425 void UIContentImpl::SetFrameLayoutFinishCallback(std::function<void()>&& callback)
4426 {
4427     CHECK_NULL_VOID(callback);
4428     auto container = Platform::AceContainer::GetContainer(instanceId_);
4429     CHECK_NULL_VOID(container);
4430     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
4431     CHECK_NULL_VOID(pipelineContext);
4432     pipelineContext->AddPersistAfterLayoutTask(std::move(callback));
4433     LOGI("[%{public}s][%{public}s][%{public}d]: SetFrameLayoutFinishCallback", bundleName_.c_str(),
4434         moduleName_.c_str(), instanceId_);
4435 }
4436 
NotifyMemoryLevel(int32_t level)4437 void UIContentImpl::NotifyMemoryLevel(int32_t level)
4438 {
4439     LOGI("[%{public}s][%{public}s][%{public}d]: NotifyMemoryLevel: %{public}d",
4440         bundleName_.c_str(), moduleName_.c_str(), instanceId_, level);
4441     auto container = Platform::AceContainer::GetContainer(instanceId_);
4442     CHECK_NULL_VOID(container);
4443     auto pipelineContext = container->GetPipelineContext();
4444     CHECK_NULL_VOID(pipelineContext);
4445     ContainerScope scope(instanceId_);
4446     pipelineContext->NotifyMemoryLevel(level);
4447 }
4448 
SetAppWindowTitle(const std::string & title)4449 void UIContentImpl::SetAppWindowTitle(const std::string& title)
4450 {
4451     auto container = Platform::AceContainer::GetContainer(instanceId_);
4452     CHECK_NULL_VOID(container);
4453     auto pipelineContext = container->GetPipelineContext();
4454     CHECK_NULL_VOID(pipelineContext);
4455     ContainerScope scope(instanceId_);
4456     LOGI("[%{public}s][%{public}s][%{public}d]: setAppTitle", bundleName_.c_str(), moduleName_.c_str(), instanceId_);
4457     pipelineContext->SetAppTitle(title);
4458 }
4459 
SetAppWindowIcon(const std::shared_ptr<Media::PixelMap> & pixelMap)4460 void UIContentImpl::SetAppWindowIcon(const std::shared_ptr<Media::PixelMap>& pixelMap)
4461 {
4462     std::lock_guard<std::mutex> lock(setAppWindowIconMutex_);
4463     LOGI("[%{public}s][%{public}s][%{public}d]: setAppIcon", bundleName_.c_str(), moduleName_.c_str(), instanceId_);
4464     auto container = Platform::AceContainer::GetContainer(instanceId_);
4465     CHECK_NULL_VOID(container);
4466     ContainerScope scope(instanceId_);
4467     auto taskExecutor = Container::CurrentTaskExecutor();
4468     CHECK_NULL_VOID(taskExecutor);
4469     auto task = [container, pixelMap]() {
4470         auto pipelineContext = container->GetPipelineContext();
4471         CHECK_NULL_VOID(pipelineContext);
4472         pipelineContext->SetAppIcon(AceType::MakeRefPtr<PixelMapOhos>(pixelMap));
4473     };
4474 
4475     // Cancel the pending task
4476     setAppWindowIconTask_.Cancel();
4477     auto uiTaskRunner = SingleTaskExecutor::Make(taskExecutor, TaskExecutor::TaskType::UI);
4478     if (uiTaskRunner.IsRunOnCurrentThread()) {
4479         task();
4480     } else {
4481         setAppWindowIconTask_ = SingleTaskExecutor::CancelableTask(std::move(task));
4482         taskExecutor->PostTask(setAppWindowIconTask_,
4483             TaskExecutor::TaskType::UI, "ArkUISetAppWindowIcon");
4484     }
4485 }
4486 
UpdateFormData(const std::string & data)4487 void UIContentImpl::UpdateFormData(const std::string& data)
4488 {
4489     if (isFormRenderInit_) {
4490         auto container = Platform::AceContainer::GetContainer(instanceId_);
4491         CHECK_NULL_VOID(container);
4492         container->UpdateFormData(data);
4493     } else {
4494         formData_ = data;
4495     }
4496 }
4497 
UpdateFormSharedImage(const std::map<std::string,sptr<OHOS::AppExecFwk::FormAshmem>> & imageDataMap)4498 void UIContentImpl::UpdateFormSharedImage(const std::map<std::string, sptr<OHOS::AppExecFwk::FormAshmem>>& imageDataMap)
4499 {
4500     if (isFormRenderInit_) {
4501         auto container = Platform::AceContainer::GetContainer(instanceId_);
4502         CHECK_NULL_VOID(container);
4503         container->UpdateFormSharedImage(imageDataMap);
4504     } else {
4505         formImageDataMap_ = imageDataMap;
4506     }
4507 }
4508 
SetActionEventHandler(std::function<void (const std::string & action)> && actionCallback)4509 void UIContentImpl::SetActionEventHandler(std::function<void(const std::string& action)>&& actionCallback)
4510 {
4511     CHECK_NULL_VOID(actionCallback);
4512     auto container = Platform::AceContainer::GetContainer(instanceId_);
4513     CHECK_NULL_VOID(container);
4514     auto pipelineContext = container->GetPipelineContext();
4515     CHECK_NULL_VOID(pipelineContext);
4516     pipelineContext->SetActionEventHandler(std::move(actionCallback));
4517 }
4518 
SetFormLinkInfoUpdateHandler(std::function<void (const std::vector<std::string> &)> && callback)4519 void UIContentImpl::SetFormLinkInfoUpdateHandler(std::function<void(const std::vector<std::string>&)>&& callback)
4520 {
4521     CHECK_NULL_VOID(callback);
4522     auto container = Platform::AceContainer::GetContainer(instanceId_);
4523     CHECK_NULL_VOID(container);
4524     auto pipelineContext = container->GetPipelineContext();
4525     CHECK_NULL_VOID(pipelineContext);
4526     pipelineContext->SetFormLinkInfoUpdateHandler(std::move(callback));
4527 }
4528 
RegisterAccessibilityChildTree(uint32_t parentWindowId,int32_t parentTreeId,int64_t parentElementId)4529 void UIContentImpl::RegisterAccessibilityChildTree(
4530     uint32_t parentWindowId, int32_t parentTreeId, int64_t parentElementId)
4531 {
4532     auto container = Platform::AceContainer::GetContainer(instanceId_);
4533     CHECK_NULL_VOID(container);
4534     auto front = container->GetFrontend();
4535     CHECK_NULL_VOID(front);
4536     auto accessibilityManager = front->GetAccessibilityManager();
4537     CHECK_NULL_VOID(accessibilityManager);
4538     accessibilityManager->RegisterInteractionOperationAsChildTree(parentWindowId, parentTreeId, parentElementId);
4539 }
4540 
SetAccessibilityGetParentRectHandler(std::function<void (int32_t &,int32_t &)> && callback)4541 void UIContentImpl::SetAccessibilityGetParentRectHandler(std::function<void(int32_t&, int32_t&)>&& callback)
4542 {
4543     auto container = Platform::AceContainer::GetContainer(instanceId_);
4544     CHECK_NULL_VOID(container);
4545     auto front = container->GetFrontend();
4546     CHECK_NULL_VOID(front);
4547     auto accessibilityManager = front->GetAccessibilityManager();
4548     CHECK_NULL_VOID(accessibilityManager);
4549     accessibilityManager->SetAccessibilityGetParentRectHandler(std::move(callback));
4550 }
4551 
SetAccessibilityGetParentRectHandler(std::function<void (AccessibilityParentRectInfo &)> && callback)4552 void UIContentImpl::SetAccessibilityGetParentRectHandler(
4553     std::function<void(AccessibilityParentRectInfo&)>&& callback)
4554 {
4555     auto container = Platform::AceContainer::GetContainer(instanceId_);
4556     CHECK_NULL_VOID(container);
4557     auto front = container->GetFrontend();
4558     CHECK_NULL_VOID(front);
4559     auto accessibilityManager = front->GetAccessibilityManager();
4560     CHECK_NULL_VOID(accessibilityManager);
4561     accessibilityManager->SetAccessibilityGetParentRectHandler(std::move(callback));
4562 }
4563 
DeregisterAccessibilityChildTree()4564 void UIContentImpl::DeregisterAccessibilityChildTree()
4565 {
4566     auto container = Platform::AceContainer::GetContainer(instanceId_);
4567     CHECK_NULL_VOID(container);
4568     auto front = container->GetFrontend();
4569     CHECK_NULL_VOID(front);
4570     auto accessibilityManager = front->GetAccessibilityManager();
4571     CHECK_NULL_VOID(accessibilityManager);
4572     accessibilityManager->DeregisterInteractionOperationAsChildTree();
4573 }
4574 
AccessibilityDumpChildInfo(const std::vector<std::string> & params,std::vector<std::string> & info)4575 void UIContentImpl::AccessibilityDumpChildInfo(const std::vector<std::string>& params, std::vector<std::string>& info)
4576 {
4577     auto container = Platform::AceContainer::GetContainer(instanceId_);
4578     CHECK_NULL_VOID(container);
4579     container->Dump(params, info);
4580 }
4581 
SetErrorEventHandler(std::function<void (const std::string &,const std::string &)> && errorCallback)4582 void UIContentImpl::SetErrorEventHandler(std::function<void(const std::string&, const std::string&)>&& errorCallback)
4583 {
4584     CHECK_NULL_VOID(errorCallback);
4585     auto container = Platform::AceContainer::GetContainer(instanceId_);
4586     CHECK_NULL_VOID(container);
4587     auto front = container->GetFrontend();
4588     CHECK_NULL_VOID(front);
4589     return front->SetErrorEventHandler(std::move(errorCallback));
4590 }
4591 
OnFormSurfaceChange(float width,float height,OHOS::Rosen::WindowSizeChangeReason type,const std::shared_ptr<Rosen::RSTransaction> & rsTransaction)4592 void UIContentImpl::OnFormSurfaceChange(float width, float height, OHOS::Rosen::WindowSizeChangeReason type,
4593     const std::shared_ptr<Rosen::RSTransaction>& rsTransaction)
4594 {
4595     auto container = Platform::AceContainer::GetContainer(instanceId_);
4596     CHECK_NULL_VOID(container);
4597     int32_t formWidth = round(width);
4598     int32_t formHeight = round(height);
4599     auto aceView = AceType::DynamicCast<Platform::AceViewOhos>(container->GetAceView());
4600     Platform::AceViewOhos::ChangeViewSize(aceView, formWidth, formHeight);
4601     auto pipelineContext = container->GetPipelineContext();
4602     CHECK_NULL_VOID(pipelineContext);
4603     ContainerScope scope(instanceId_);
4604     auto density = pipelineContext->GetDensity();
4605     pipelineContext->SetRootSize(density, formWidth, formHeight);
4606     pipelineContext->OnSurfaceChanged(formWidth, formHeight, static_cast<WindowSizeChangeReason>(type), rsTransaction);
4607 }
4608 
SetFormBackgroundColor(const std::string & color)4609 void UIContentImpl::SetFormBackgroundColor(const std::string& color)
4610 {
4611     LOGI("[%{public}s][%{public}s][%{public}d]: SetFormBackgroundColor: %{public}s",
4612         bundleName_.c_str(), moduleName_.c_str(), instanceId_, color.c_str());
4613     if (!Rosen::RSSystemProperties::GetUniRenderEnabled()) {
4614         // cannot set transparent background effects in not-uniform-render mode
4615         return;
4616     }
4617     Color bgColor;
4618     if (!Color::ParseColorString(color, bgColor)) {
4619         return;
4620     }
4621     auto container = AceEngine::Get().GetContainer(instanceId_);
4622     CHECK_NULL_VOID(container);
4623     auto aceContainer = AceType::DynamicCast<Platform::AceContainer>(container);
4624     if (aceContainer) {
4625         aceContainer->SetIsUseCustomBg(true);
4626     }
4627     ContainerScope scope(instanceId_);
4628     auto taskExecutor = container->GetTaskExecutor();
4629     CHECK_NULL_VOID(taskExecutor);
4630     taskExecutor->PostSyncTask(
4631         [container, bgColor]() {
4632             auto pipelineContext = container->GetPipelineContext();
4633             CHECK_NULL_VOID(pipelineContext);
4634             pipelineContext->SetAppBgColor(bgColor);
4635         },
4636         TaskExecutor::TaskType::UI, "ArkUISetFormBackgroundColor");
4637 }
4638 
SetFontScaleFollowSystem(const bool fontScaleFollowSystem)4639 void UIContentImpl::SetFontScaleFollowSystem(const bool fontScaleFollowSystem)
4640 {
4641     LOGD("SetFontScaleFollowSystem: %{public}d", fontScaleFollowSystem);
4642     fontScaleFollowSystem_ = fontScaleFollowSystem;
4643 }
4644 
SetFormRenderingMode(int8_t renderMode)4645 void UIContentImpl::SetFormRenderingMode(int8_t renderMode)
4646 {
4647     auto container = Platform::AceContainer::GetContainer(instanceId_);
4648     CHECK_NULL_VOID(container);
4649     auto pipelineContext = container->GetPipelineContext();
4650     CHECK_NULL_VOID(pipelineContext);
4651     pipelineContext->SetFormRenderingMode(renderMode);
4652 }
4653 
SetFormEnableBlurBackground(bool enableBlurBackground)4654 void UIContentImpl::SetFormEnableBlurBackground(bool enableBlurBackground)
4655 {
4656     auto container = Platform::AceContainer::GetContainer(instanceId_);
4657     CHECK_NULL_VOID(container);
4658     auto pipelineContext = container->GetPipelineContext();
4659     CHECK_NULL_VOID(pipelineContext);
4660     pipelineContext->SetFormEnableBlurBackground(enableBlurBackground);
4661 }
4662 
GetResourcePaths(std::vector<std::string> & resourcesPaths,std::string & assetRootPath,std::vector<std::string> & assetBasePaths,std::string & resFolderName)4663 void UIContentImpl::GetResourcePaths(std::vector<std::string>& resourcesPaths, std::string& assetRootPath,
4664     std::vector<std::string>& assetBasePaths, std::string& resFolderName)
4665 {
4666     auto container = Platform::AceContainer::GetContainer(instanceId_);
4667     CHECK_NULL_VOID(container);
4668     ContainerScope scope(instanceId_);
4669     auto taskExecutor = Container::CurrentTaskExecutor();
4670     CHECK_NULL_VOID(taskExecutor);
4671     taskExecutor->PostTask(
4672         [container]() {
4673             auto pipelineContext = container->GetPipelineContext();
4674             CHECK_NULL_VOID(pipelineContext);
4675         },
4676         TaskExecutor::TaskType::PLATFORM, "ArkUIGetResourcePaths");
4677 }
4678 
SetResourcePaths(const std::vector<std::string> & resourcesPaths,const std::string & assetRootPath,const std::vector<std::string> & assetBasePaths)4679 void UIContentImpl::SetResourcePaths(const std::vector<std::string>& resourcesPaths, const std::string& assetRootPath,
4680     const std::vector<std::string>& assetBasePaths)
4681 {
4682     auto container = Platform::AceContainer::GetContainer(instanceId_);
4683     CHECK_NULL_VOID(container);
4684     ContainerScope scope(instanceId_);
4685     auto taskExecutor = Container::CurrentTaskExecutor();
4686     CHECK_NULL_VOID(taskExecutor);
4687     taskExecutor->PostTask(
4688         [container, resourcesPaths, assetRootPath, assetBasePaths]() {
4689             auto pipelineContext = container->GetPipelineContext();
4690             CHECK_NULL_VOID(pipelineContext);
4691             auto assetManager = pipelineContext->GetAssetManager();
4692             CHECK_NULL_VOID(assetManager);
4693             auto themeManager = pipelineContext->GetThemeManager();
4694             CHECK_NULL_VOID(themeManager);
4695 
4696             if (resourcesPaths.empty() && assetRootPath.empty()) {
4697                 return;
4698             }
4699 
4700             if (!assetRootPath.empty()) {
4701                 auto fileAssetProviderImpl = AceType::MakeRefPtr<FileAssetProviderImpl>();
4702                 if (fileAssetProviderImpl->Initialize(assetRootPath, assetBasePaths)) {
4703                     assetManager->PushBack(std::move(fileAssetProviderImpl));
4704                 }
4705                 return;
4706             }
4707             for (auto iter = resourcesPaths.begin(); iter != resourcesPaths.end(); iter++) {
4708                 auto hapAssetProviderImpl = AceType::MakeRefPtr<HapAssetProviderImpl>();
4709                 if (hapAssetProviderImpl->Initialize(*iter, assetBasePaths)) {
4710                     assetManager->PushBack(std::move(hapAssetProviderImpl));
4711                 }
4712             }
4713         },
4714         TaskExecutor::TaskType::PLATFORM, "ArkUISetResourcePaths");
4715 }
4716 
SetIsFocusActive(bool isFocusActive)4717 void UIContentImpl::SetIsFocusActive(bool isFocusActive)
4718 {
4719     auto container = Platform::AceContainer::GetContainer(instanceId_);
4720     CHECK_NULL_VOID(container);
4721     ContainerScope scope(instanceId_);
4722     auto taskExecutor = Container::CurrentTaskExecutor();
4723     CHECK_NULL_VOID(taskExecutor);
4724     taskExecutor->PostTask(
4725         [container, isFocusActive]() {
4726             auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
4727             CHECK_NULL_VOID(pipelineContext);
4728             ContainerScope scope(container->GetInstanceId());
4729             pipelineContext->SetIsFocusActive(isFocusActive);
4730         },
4731         TaskExecutor::TaskType::UI, "ArkUISetIsFocusActive");
4732 }
4733 
UpdateResource()4734 void UIContentImpl::UpdateResource()
4735 {
4736     auto container = Platform::AceContainer::GetContainer(instanceId_);
4737     CHECK_NULL_VOID(container);
4738     auto taskExecutor = container->GetTaskExecutor();
4739     CHECK_NULL_VOID(taskExecutor);
4740     taskExecutor->PostTask([container]() { container->UpdateResource(); },
4741         TaskExecutor::TaskType::UI, "ArkUIUpdateResource");
4742 }
4743 
CreateModalUIExtension(const AAFwk::Want & want,const ModalUIExtensionCallbacks & callbacks,const ModalUIExtensionConfig & config)4744 int32_t UIContentImpl::CreateModalUIExtension(
4745     const AAFwk::Want& want, const ModalUIExtensionCallbacks& callbacks, const ModalUIExtensionConfig& config)
4746 {
4747     auto container = Platform::AceContainer::GetContainer(instanceId_);
4748     CHECK_NULL_RETURN(container, 0);
4749     ContainerScope scope(instanceId_);
4750     auto taskExecutor = Container::CurrentTaskExecutor();
4751     CHECK_NULL_RETURN(taskExecutor, 0);
4752     int32_t sessionId = 0;
4753     taskExecutor->PostSyncTask(
4754         [container, &sessionId, want, callbacks = callbacks, config = config, window = window_,
4755             instanceId = instanceId_]() {
4756             auto flag = want.GetBoolParam(USE_GLOBAL_UICONTENT, false);
4757             if (flag && CreateGlobalModalUIExtension(want, sessionId, callbacks, config, instanceId, window)) {
4758                 return;
4759             }
4760 
4761             auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
4762             CHECK_NULL_VOID(pipeline);
4763             auto overlay = pipeline->GetOverlayManager();
4764             CHECK_NULL_VOID(overlay);
4765             sessionId = overlay->CreateModalUIExtension(want, callbacks, config);
4766         },
4767         TaskExecutor::TaskType::UI, "ArkUICreateModalUIExtension");
4768     TAG_LOGI(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
4769         "[%{public}s][%{public}s][%{public}d]: create modal page, "
4770         "sessionId=%{public}d, isProhibitBack=%{public}d, isAsyncModalBinding=%{public}d, "
4771         "isAllowedBeCovered=%{public}d, prohibitedRemoveByRouter=%{public}d, "
4772         "isAllowAddChildBelowModalUec=%{public}d, prohibitedRemoveByNavigation=%{public}d",
4773         bundleName_.c_str(), moduleName_.c_str(), instanceId_, sessionId, config.isProhibitBack,
4774         config.isAsyncModalBinding, config.isAllowedBeCovered, config.prohibitedRemoveByRouter,
4775         config.isAllowAddChildBelowModalUec, config.prohibitedRemoveByNavigation);
4776     return sessionId;
4777 }
4778 
CloseModalUIExtension(int32_t sessionId)4779 void UIContentImpl::CloseModalUIExtension(int32_t sessionId)
4780 {
4781     TAG_LOGI(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
4782         "[%{public}s][%{public}s][%{public}d]: close modal page, "
4783         "sessionId=%{public}d",
4784         bundleName_.c_str(), moduleName_.c_str(), instanceId_, sessionId);
4785     if (sessionId == 0) {
4786         LOGW("UIExtension refuse to close modal page");
4787         return;
4788     }
4789     auto container = Platform::AceContainer::GetContainer(instanceId_);
4790     CHECK_NULL_VOID(container);
4791     ContainerScope scope(instanceId_);
4792     auto taskExecutor = Container::CurrentTaskExecutor();
4793     CHECK_NULL_VOID(taskExecutor);
4794     taskExecutor->PostTask(
4795         [container, sessionId]() {
4796             if (CloseGlobalModalUIExtension(container->GetInstanceId(), sessionId, "")) {
4797                 return;
4798             }
4799 
4800             auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
4801             CHECK_NULL_VOID(pipeline);
4802             auto overlay = pipeline->GetOverlayManager();
4803             CHECK_NULL_VOID(overlay);
4804             overlay->CloseModalUIExtension(sessionId);
4805         },
4806         TaskExecutor::TaskType::UI, "ArkUICloseModalUIExtension");
4807 }
4808 
UpdateModalUIExtensionConfig(int32_t sessionId,const ModalUIExtensionAllowedUpdateConfig & config)4809 void UIContentImpl::UpdateModalUIExtensionConfig(
4810     int32_t sessionId, const ModalUIExtensionAllowedUpdateConfig& config)
4811 {
4812     TAG_LOGI(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
4813         "[%{public}s][%{public}s][%{public}d]: UpdateModalUIExtensionConfig with "
4814         "sessionId: %{public}d",
4815         bundleName_.c_str(), moduleName_.c_str(), instanceId_, sessionId);
4816     if (sessionId == 0) {
4817         TAG_LOGI(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
4818             "UIExtension refuse to UpdateModalUIExtensionConfig");
4819         return;
4820     }
4821 
4822     auto container = Platform::AceContainer::GetContainer(instanceId_);
4823     CHECK_NULL_VOID(container);
4824     ContainerScope scope(instanceId_);
4825     auto taskExecutor = container->GetTaskExecutor();
4826     CHECK_NULL_VOID(taskExecutor);
4827     taskExecutor->PostTask(
4828         [container, sessionId, config]() {
4829             auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
4830             CHECK_NULL_VOID(pipeline);
4831             auto overlay = pipeline->GetOverlayManager();
4832             CHECK_NULL_VOID(overlay);
4833             overlay->UpdateModalUIExtensionConfig(sessionId, config);
4834         },
4835         TaskExecutor::TaskType::UI, "ArkUIUpdateModalUIExtensionConfig");
4836 }
4837 
SetParentToken(sptr<IRemoteObject> token)4838 void UIContentImpl::SetParentToken(sptr<IRemoteObject> token)
4839 {
4840     parentToken_ = token;
4841 }
4842 
GetParentToken()4843 sptr<IRemoteObject> UIContentImpl::GetParentToken()
4844 {
4845     return parentToken_;
4846 }
4847 
CheckNeedAutoSave()4848 bool UIContentImpl::CheckNeedAutoSave()
4849 {
4850     auto container = Platform::AceContainer::GetContainer(instanceId_);
4851     CHECK_NULL_RETURN(container, false);
4852     auto taskExecutor = container->GetTaskExecutor();
4853     CHECK_NULL_RETURN(taskExecutor, false);
4854     ContainerScope scope(instanceId_);
4855     bool needAutoSave = false;
4856     taskExecutor->PostSyncTask(
4857         [&needAutoSave, container]() {
4858             CHECK_NULL_VOID(container);
4859             auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
4860             CHECK_NULL_VOID(pipelineContext);
4861             needAutoSave = pipelineContext->CheckNeedAutoSave();
4862         },
4863         TaskExecutor::TaskType::UI, "ArkUICheckNeedAutoSave");
4864 
4865     TAG_LOGI(AceLogTag::ACE_AUTO_FILL, "UIContentImpl CheckNeedAutoSave, value is %{public}d", needAutoSave);
4866     return needAutoSave;
4867 }
4868 
DumpViewData(AbilityBase::ViewData & viewData,AbilityBase::AutoFillType & type)4869 bool UIContentImpl::DumpViewData(AbilityBase::ViewData& viewData, AbilityBase::AutoFillType& type)
4870 {
4871     auto container = Platform::AceContainer::GetContainer(instanceId_);
4872     CHECK_NULL_RETURN(container, false);
4873     auto taskExecutor = container->GetTaskExecutor();
4874     CHECK_NULL_RETURN(taskExecutor, false);
4875     ContainerScope scope(instanceId_);
4876     bool ret = false;
4877     taskExecutor->PostSyncTask(
4878         [this, &ret, &viewData]() {
4879             auto viewDataWrap = ViewDataWrap::CreateViewDataWrap();
4880             CHECK_NULL_VOID(viewDataWrap);
4881             ret = DumpViewData(nullptr, viewDataWrap);
4882             auto viewDataWrapOhos = AceType::DynamicCast<ViewDataWrapOhos>(viewDataWrap);
4883             CHECK_NULL_VOID(viewDataWrapOhos);
4884             viewData = viewDataWrapOhos->GetViewData();
4885         },
4886         TaskExecutor::TaskType::UI, "ArkUIDumpViewData");
4887     type = ViewDataWrap::ViewDataToType(viewData);
4888     TAG_LOGI(AceLogTag::ACE_AUTO_FILL, "UIContentImpl DumpViewData, ret is %{public}d", ret);
4889     return ret;
4890 }
4891 
DumpViewData(const RefPtr<NG::FrameNode> & node,RefPtr<ViewDataWrap> viewDataWrap,bool skipSubAutoFillContainer,bool needsRecordData)4892 bool UIContentImpl::DumpViewData(const RefPtr<NG::FrameNode>& node, RefPtr<ViewDataWrap> viewDataWrap,
4893     bool skipSubAutoFillContainer, bool needsRecordData)
4894 {
4895     CHECK_NULL_RETURN(viewDataWrap, false);
4896     auto context = context_.lock();
4897     auto abilityContext = OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::AbilityContext>(context);
4898     std::shared_ptr<OHOS::AppExecFwk::AbilityInfo> info;
4899     if (abilityContext) {
4900         info = abilityContext->GetAbilityInfo();
4901     } else {
4902         auto extensionContext =
4903             OHOS::AbilityRuntime::Context::ConvertTo<OHOS::AbilityRuntime::ExtensionContext>(context);
4904         if (extensionContext) {
4905             info = extensionContext->GetAbilityInfo();
4906         } else {
4907             TAG_LOGE(AceLogTag::ACE_AUTO_FILL, "context is not AbilityContext or ExtensionContext.");
4908             return false;
4909         }
4910     }
4911     CHECK_NULL_RETURN(info, false);
4912     viewDataWrap->SetAbilityName(info->name);
4913     viewDataWrap->SetModuleName(info->moduleName);
4914     viewDataWrap->SetBundleName(info->bundleName);
4915     TAG_LOGI(AceLogTag::ACE_AUTO_FILL, "bundleName=[%{private}s], moduleName=[%{private}s], abilityName=[%{private}s]",
4916         info->bundleName.c_str(), info->moduleName.c_str(), info->name.c_str());
4917     auto container = Platform::AceContainer::GetContainer(instanceId_);
4918     CHECK_NULL_RETURN(container, false);
4919     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
4920     CHECK_NULL_RETURN(pipelineContext, false);
4921     return pipelineContext->DumpPageViewData(node, viewDataWrap, skipSubAutoFillContainer, needsRecordData);
4922 }
4923 
SearchElementInfoByAccessibilityId(int64_t elementId,int32_t mode,int64_t baseParent,std::list<Accessibility::AccessibilityElementInfo> & output)4924 void UIContentImpl::SearchElementInfoByAccessibilityId(
4925     int64_t elementId, int32_t mode, int64_t baseParent, std::list<Accessibility::AccessibilityElementInfo>& output)
4926 {
4927     auto container = Platform::AceContainer::GetContainer(instanceId_);
4928     CHECK_NULL_VOID(container);
4929     container->SearchElementInfoByAccessibilityIdNG(elementId, mode, baseParent, output);
4930 }
4931 
SearchElementInfosByText(int64_t elementId,const std::string & text,int64_t baseParent,std::list<Accessibility::AccessibilityElementInfo> & output)4932 void UIContentImpl::SearchElementInfosByText(int64_t elementId, const std::string& text, int64_t baseParent,
4933     std::list<Accessibility::AccessibilityElementInfo>& output)
4934 {
4935     auto container = Platform::AceContainer::GetContainer(instanceId_);
4936     CHECK_NULL_VOID(container);
4937     container->SearchElementInfosByTextNG(elementId, text, baseParent, output);
4938 }
4939 
FindFocusedElementInfo(int64_t elementId,int32_t focusType,int64_t baseParent,Accessibility::AccessibilityElementInfo & output)4940 void UIContentImpl::FindFocusedElementInfo(
4941     int64_t elementId, int32_t focusType, int64_t baseParent, Accessibility::AccessibilityElementInfo& output)
4942 {
4943     auto container = Platform::AceContainer::GetContainer(instanceId_);
4944     CHECK_NULL_VOID(container);
4945     container->FindFocusedElementInfoNG(elementId, focusType, baseParent, output);
4946 }
4947 
FocusMoveSearch(int64_t elementId,int32_t direction,int64_t baseParent,Accessibility::AccessibilityElementInfo & output)4948 void UIContentImpl::FocusMoveSearch(
4949     int64_t elementId, int32_t direction, int64_t baseParent, Accessibility::AccessibilityElementInfo& output)
4950 {
4951     auto container = Platform::AceContainer::GetContainer(instanceId_);
4952     CHECK_NULL_VOID(container);
4953     container->FocusMoveSearchNG(elementId, direction, baseParent, output);
4954 }
4955 
ProcessFormVisibleChange(bool isVisible)4956 void UIContentImpl::ProcessFormVisibleChange(bool isVisible)
4957 {
4958     auto container = Platform::AceContainer::GetContainer(instanceId_);
4959     CHECK_NULL_VOID(container);
4960     ContainerScope scope(instanceId_);
4961     auto taskExecutor = Container::CurrentTaskExecutor();
4962     CHECK_NULL_VOID(taskExecutor);
4963     taskExecutor->PostTask(
4964         [container, isVisible]() {
4965             auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
4966             CHECK_NULL_VOID(pipeline);
4967             auto mgr = pipeline->GetFormVisibleManager();
4968             if (mgr) {
4969                 mgr->HandleFormVisibleChangeEvent(isVisible);
4970             }
4971         },
4972         TaskExecutor::TaskType::UI, "ArkUIUIExtensionVisibleChange");
4973 }
4974 
NotifyExecuteAction(int64_t elementId,const std::map<std::string,std::string> & actionArguments,int32_t action,int64_t offset)4975 bool UIContentImpl::NotifyExecuteAction(
4976     int64_t elementId, const std::map<std::string, std::string>& actionArguments, int32_t action, int64_t offset)
4977 {
4978     auto container = Platform::AceContainer::GetContainer(instanceId_);
4979     CHECK_NULL_RETURN(container, false);
4980     return container->NotifyExecuteAction(elementId, actionArguments, action, offset);
4981 }
4982 
HandleAccessibilityHoverEvent(float pointX,float pointY,int32_t sourceType,int32_t eventType,int64_t timeMs)4983 void UIContentImpl::HandleAccessibilityHoverEvent(float pointX, float pointY, int32_t sourceType,
4984     int32_t eventType, int64_t timeMs)
4985 {
4986     auto container = Platform::AceContainer::GetContainer(instanceId_);
4987     CHECK_NULL_VOID(container);
4988     TAG_LOGI(AceLogTag::ACE_ACCESSIBILITY, "HandleAccessibilityHoverEvent Point:[%{public}f, %{public}f] "
4989         "source:%{public}d type:%{public}d time:%{public}" PRId64,
4990         pointX, pointY, sourceType, eventType, timeMs);
4991     container->HandleAccessibilityHoverEvent(pointX, pointY, sourceType, eventType, timeMs);
4992 }
4993 
RecycleForm()4994 std::string UIContentImpl::RecycleForm()
4995 {
4996     auto container = Platform::AceContainer::GetContainer(instanceId_);
4997     std::string statusData;
4998     CHECK_NULL_RETURN(container, statusData);
4999     auto pipeline = container->GetPipelineContext();
5000     CHECK_NULL_RETURN(pipeline, statusData);
5001     return pipeline->OnFormRecycle();
5002 }
5003 
RecoverForm(const std::string & statusData)5004 void UIContentImpl::RecoverForm(const std::string& statusData)
5005 {
5006     auto container = Platform::AceContainer::GetContainer(instanceId_);
5007     CHECK_NULL_VOID(container);
5008     auto pipeline = container->GetPipelineContext();
5009     CHECK_NULL_VOID(pipeline);
5010     return pipeline->OnFormRecover(statusData);
5011 }
5012 
CreateCustomPopupParam(bool isShow,const CustomPopupUIExtensionConfig & config)5013 RefPtr<PopupParam> UIContentImpl::CreateCustomPopupParam(bool isShow, const CustomPopupUIExtensionConfig& config)
5014 {
5015     auto popupParam = AceType::MakeRefPtr<PopupParam>();
5016     popupParam->SetIsShow(isShow);
5017     popupParam->SetUseCustomComponent(true);
5018     popupParam->SetShowInSubWindow(config.isShowInSubWindow);
5019     popupParam->SetShadow(GetPopupShadow());
5020     if (config.isAutoCancel.has_value()) {
5021         popupParam->SetHasAction(!config.isAutoCancel.value());
5022     }
5023 
5024     if (config.isEnableArrow.has_value()) {
5025         popupParam->SetEnableArrow(config.isEnableArrow.value());
5026     }
5027 
5028     if (config.targetOffset.has_value()) {
5029         PopupOffset targetOffset = config.targetOffset.value();
5030         DimensionUnit unit = static_cast<DimensionUnit>(targetOffset.unit);
5031         if (unit != DimensionUnit::PERCENT) { // not support percent settings
5032             CalcDimension dx(targetOffset.deltaX, unit);
5033             CalcDimension dy(targetOffset.deltaY, unit);
5034             popupParam->SetTargetOffset(Offset(dx.ConvertToPx(), dy.ConvertToPx()));
5035         }
5036     }
5037 
5038     if (config.targetSpace.has_value()) {
5039         PopupLength targetSpace = config.targetSpace.value();
5040         DimensionUnit unit = static_cast<DimensionUnit>(targetSpace.unit);
5041         popupParam->SetTargetSpace(CalcDimension(targetSpace.length, unit));
5042     }
5043 
5044     if (config.arrowOffset.has_value()) {
5045         PopupLength arrowOffset = config.arrowOffset.value();
5046         DimensionUnit unit = static_cast<DimensionUnit>(arrowOffset.unit);
5047         popupParam->SetArrowOffset(CalcDimension(arrowOffset.length, unit));
5048     }
5049 
5050     if (config.placement.has_value()) {
5051         popupParam->SetPlacement(static_cast<Placement>(config.placement.value()));
5052     }
5053 
5054     if (config.backgroundColor.has_value()) {
5055         popupParam->SetBackgroundColor(Color(config.backgroundColor.value()));
5056     }
5057 
5058     if (config.maskColor.has_value()) {
5059         popupParam->SetMaskColor(Color(config.maskColor.value()));
5060     }
5061     return popupParam;
5062 }
5063 
GetPopupShadow()5064 Shadow UIContentImpl::GetPopupShadow()
5065 {
5066     Shadow shadow;
5067     auto container = Container::Current();
5068     CHECK_NULL_RETURN(container, shadow);
5069     auto colorMode = container->GetColorMode();
5070     auto pipelineContext = container->GetPipelineContext();
5071     CHECK_NULL_RETURN(pipelineContext, shadow);
5072     auto shadowTheme = pipelineContext->GetTheme<ShadowTheme>();
5073     CHECK_NULL_RETURN(shadowTheme, shadow);
5074     auto popupTheme = pipelineContext->GetTheme<PopupTheme>();
5075     CHECK_NULL_RETURN(popupTheme, shadow);
5076     auto popupShadowStyle = popupTheme->GetPopupShadowStyle();
5077     return shadowTheme->GetShadow(popupShadowStyle, colorMode);
5078 }
5079 
OnPopupStateChange(const std::string & event,const CustomPopupUIExtensionConfig & config,int32_t nodeId)5080 void UIContentImpl::OnPopupStateChange(
5081     const std::string& event, const CustomPopupUIExtensionConfig& config, int32_t nodeId)
5082 {
5083     if (config.onStateChange) {
5084         config.onStateChange(event);
5085     }
5086 
5087     auto visible = JsonUtil::ParseJsonString(event);
5088     CHECK_NULL_VOID(visible);
5089     bool isVisible = visible->GetBool("isVisible");
5090     if (isVisible) {
5091         return;
5092     }
5093 
5094     LOGD("Created custom popup is invisible");
5095     ContainerScope scope(instanceId_);
5096     customPopupConfigMap_.erase(nodeId);
5097     popupUIExtensionRecords_.erase(nodeId);
5098 }
5099 
SetCustomPopupConfig(int32_t nodeId,const CustomPopupUIExtensionConfig & config,int32_t popupId)5100 void UIContentImpl::SetCustomPopupConfig(int32_t nodeId, const CustomPopupUIExtensionConfig& config, int32_t popupId)
5101 {
5102     customPopupConfigMap_[nodeId] = config;
5103     popupUIExtensionRecords_[nodeId] = popupId;
5104 }
5105 
GetTargetNode(int32_t & nodeIdLabel,RefPtr<NG::FrameNode> & targetNode,const CustomPopupUIExtensionConfig & config)5106 bool UIContentImpl::GetTargetNode(
5107     int32_t& nodeIdLabel, RefPtr<NG::FrameNode>& targetNode, const CustomPopupUIExtensionConfig& config)
5108 {
5109     if (config.nodeId > -1) {
5110         nodeIdLabel = config.nodeId;
5111         targetNode = ElementRegister::GetInstance()->GetSpecificItemById<NG::FrameNode>(nodeIdLabel);
5112         CHECK_NULL_RETURN(targetNode, false);
5113     } else if (!config.inspectorId.empty()) {
5114         targetNode = NG::Inspector::GetFrameNodeByKey(config.inspectorId);
5115         CHECK_NULL_RETURN(targetNode, false);
5116         nodeIdLabel = targetNode->GetId();
5117     } else {
5118         CHECK_NULL_RETURN(targetNode, false);
5119     }
5120     return true;
5121 }
5122 
CreateCustomPopupUIExtension(const AAFwk::Want & want,const ModalUIExtensionCallbacks & callbacks,const CustomPopupUIExtensionConfig & config)5123 int32_t UIContentImpl::CreateCustomPopupUIExtension(
5124     const AAFwk::Want& want, const ModalUIExtensionCallbacks& callbacks, const CustomPopupUIExtensionConfig& config)
5125 {
5126     ContainerScope scope(instanceId_);
5127     auto taskExecutor = Container::CurrentTaskExecutor();
5128     CHECK_NULL_RETURN(taskExecutor, 0);
5129     int32_t nodeId = 0;
5130     taskExecutor->PostSyncTask(
5131         [want, &nodeId, callbacks = callbacks, config = config, this]() {
5132             int32_t nodeIdLabel = -1;
5133             RefPtr<NG::FrameNode> targetNode = nullptr;
5134             if (!GetTargetNode(nodeIdLabel, targetNode, config)) {
5135                 return;
5136             }
5137             if (customPopupConfigMap_.find(nodeIdLabel) != customPopupConfigMap_.end()) {
5138                 LOGW("Nodeid=%{public}d has unclosed popup, cannot create new", nodeIdLabel);
5139                 return;
5140             }
5141             auto popupParam = CreateCustomPopupParam(true, config);
5142             popupParam->SetBlockEvent(false);
5143             NG::InnerModalUIExtensionConfig innerModalUIExtensionConfig;
5144             innerModalUIExtensionConfig.isModal = false;
5145             auto uiExtNode = ModalUIExtension::Create(want, callbacks, innerModalUIExtensionConfig);
5146             auto focusHub = uiExtNode->GetFocusHub();
5147             if (focusHub) {
5148                 focusHub->SetFocusable(config.isFocusable);
5149             }
5150             if (config.targetSize.has_value()) {
5151                 auto layoutProperty = uiExtNode->GetLayoutProperty();
5152                 CHECK_NULL_VOID(layoutProperty);
5153                 PopupSize targetSize = config.targetSize.value();
5154                 DimensionUnit unit = static_cast<DimensionUnit>(targetSize.unit);
5155                 auto width = NG::CalcLength(targetSize.width, unit);
5156                 auto height = NG::CalcLength(targetSize.height, unit);
5157                 layoutProperty->UpdateUserDefinedIdealSize(NG::CalcSize(width, height));
5158             }
5159             uiExtNode->MarkModifyDone();
5160             nodeId = nodeIdLabel;
5161             popupParam->SetOnStateChange([config, nodeId, UICONTENT_IMPL_HELPER(content)](const std::string& event) {
5162                 UICONTENT_IMPL_HELPER_GUARD(content, return);
5163                 UICONTENT_IMPL_PTR(content)->OnPopupStateChange(event, config, nodeId);
5164             });
5165             NG::ViewAbstract::BindPopup(popupParam, targetNode, AceType::DynamicCast<NG::UINode>(uiExtNode));
5166             SetCustomPopupConfig(nodeId, config, uiExtNode->GetId());
5167         },
5168         TaskExecutor::TaskType::UI, "ArkUIUIExtensionCreateCustomPopup");
5169     TAG_LOGI(
5170         AceLogTag::ACE_UIEXTENSIONCOMPONENT, "Create custom popup with UIExtension end, nodeId=%{public}d", nodeId);
5171     return nodeId;
5172 }
5173 
DestroyCustomPopupUIExtension(int32_t nodeId)5174 void UIContentImpl::DestroyCustomPopupUIExtension(int32_t nodeId)
5175 {
5176     TAG_LOGI(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
5177         "[%{public}s][%{public}s][%{public}d]: Destroy custom popup start, nodeId=%{public}d", bundleName_.c_str(),
5178         moduleName_.c_str(), instanceId_, nodeId);
5179     auto container = Platform::AceContainer::GetContainer(instanceId_);
5180     CHECK_NULL_VOID(container);
5181     ContainerScope scope(instanceId_);
5182     auto taskExecutor = Container::CurrentTaskExecutor();
5183     CHECK_NULL_VOID(taskExecutor);
5184     auto popupConfig = customPopupConfigMap_.find(nodeId);
5185     if (popupConfig == customPopupConfigMap_.end()) {
5186         LOGW("Node doesn't hava popup or closed already");
5187         return;
5188     }
5189     auto config = popupConfig->second;
5190     taskExecutor->PostTask(
5191         [container, nodeId, config, UICONTENT_IMPL_HELPER(content)]() {
5192             UICONTENT_IMPL_HELPER_GUARD(content, return);
5193             auto targetNode =
5194                 AceType::DynamicCast<NG::FrameNode>(ElementRegister::GetInstance()->GetUINodeById(nodeId));
5195             CHECK_NULL_VOID(targetNode);
5196             auto popupParam = UICONTENT_IMPL_PTR(content)->CreateCustomPopupParam(false, config);
5197             popupParam->SetBlockEvent(false);
5198             NG::ViewAbstract::BindPopup(popupParam, targetNode, nullptr);
5199             UICONTENT_IMPL_PTR(content)->customPopupConfigMap_.erase(nodeId);
5200             UICONTENT_IMPL_PTR(content)->popupUIExtensionRecords_.erase(nodeId);
5201         },
5202         TaskExecutor::TaskType::UI, "ArkUIUIExtensionDestroyCustomPopup");
5203 }
5204 
UpdateCustomPopupUIExtension(const CustomPopupUIExtensionConfig & config)5205 void UIContentImpl::UpdateCustomPopupUIExtension(const CustomPopupUIExtensionConfig& config)
5206 {
5207     ContainerScope scope(instanceId_);
5208     auto taskExecutor = Container::CurrentTaskExecutor();
5209     CHECK_NULL_VOID(taskExecutor);
5210     taskExecutor->PostSyncTask(
5211         [config, this]() {
5212             int32_t targetId = config.nodeId;
5213             auto record = popupUIExtensionRecords_.find(targetId);
5214             int32_t uiExtNodeId = (record != popupUIExtensionRecords_.end()) ? record->second : 0;
5215             auto uiExtNode = NG::FrameNode::GetFrameNode(V2::UI_EXTENSION_COMPONENT_ETS_TAG, uiExtNodeId);
5216             CHECK_NULL_VOID(uiExtNode);
5217             if (config.targetSize.has_value()) {
5218                 auto layoutProperty = uiExtNode->GetLayoutProperty();
5219                 CHECK_NULL_VOID(layoutProperty);
5220                 PopupSize targetSize = config.targetSize.value();
5221                 DimensionUnit unit = static_cast<DimensionUnit>(targetSize.unit);
5222                 auto width = NG::CalcLength(targetSize.width, unit);
5223                 auto height = NG::CalcLength(targetSize.height, unit);
5224                 layoutProperty->UpdateUserDefinedIdealSize(NG::CalcSize(width, height));
5225             }
5226             auto popupParam = CreateCustomPopupParam(true, config);
5227             popupParam->SetIsCaretMode(false);
5228             popupParam->SetBlockEvent(false);
5229             auto popupConfig = customPopupConfigMap_.find(targetId);
5230             if (popupConfig != customPopupConfigMap_.end()) {
5231                 auto createConfig = popupConfig->second;
5232                 popupParam->SetShowInSubWindow(createConfig.isShowInSubWindow);
5233                 popupParam->SetOnStateChange(
5234                     [createConfig, targetId, UICONTENT_IMPL_HELPER(content)](const std::string& event) {
5235                         UICONTENT_IMPL_HELPER_GUARD(content, return);
5236                         UICONTENT_IMPL_PTR(content)->OnPopupStateChange(event, createConfig, targetId);
5237                     });
5238             }
5239             auto targetNode =
5240                 AceType::DynamicCast<NG::FrameNode>(ElementRegister::GetInstance()->GetUINodeById(targetId));
5241             CHECK_NULL_VOID(targetNode);
5242             NG::ViewAbstract::BindPopup(popupParam, targetNode, nullptr);
5243         },
5244         TaskExecutor::TaskType::UI, "ArkUIUIExtensionUpdateCustomPopup");
5245 }
5246 
SetContainerModalTitleVisible(bool customTitleSettedShow,bool floatingTitleSettedShow)5247 void UIContentImpl::SetContainerModalTitleVisible(bool customTitleSettedShow, bool floatingTitleSettedShow)
5248 {
5249     ContainerScope scope(instanceId_);
5250     auto taskExecutor = Container::CurrentTaskExecutor();
5251     CHECK_NULL_VOID(taskExecutor);
5252     auto task = [customTitleSettedShow, floatingTitleSettedShow]() {
5253         auto pipeline = NG::PipelineContext::GetCurrentContext();
5254         CHECK_NULL_VOID(pipeline);
5255         pipeline->SetContainerModalTitleVisible(customTitleSettedShow, floatingTitleSettedShow);
5256     };
5257     auto uiTaskRunner = SingleTaskExecutor::Make(taskExecutor, TaskExecutor::TaskType::UI);
5258     if (uiTaskRunner.IsRunOnCurrentThread()) {
5259         task();
5260     } else {
5261         taskExecutor->PostTask(std::move(task), TaskExecutor::TaskType::UI, "ArkUISetContainerModalTitleVisible");
5262     }
5263 }
5264 
GetContainerModalTitleVisible(bool isImmersive)5265 bool UIContentImpl::GetContainerModalTitleVisible(bool isImmersive)
5266 {
5267     ContainerScope scope(instanceId_);
5268     auto pipeline = NG::PipelineContext::GetCurrentContext();
5269     CHECK_NULL_RETURN(pipeline, false);
5270     return NG::ContainerModalViewEnhance::GetContainerModalTitleVisible(pipeline, isImmersive);
5271 }
5272 
SetContainerModalTitleHeight(int32_t height)5273 void UIContentImpl::SetContainerModalTitleHeight(int32_t height)
5274 {
5275     ContainerScope scope(instanceId_);
5276     auto taskExecutor = Container::CurrentTaskExecutor();
5277     CHECK_NULL_VOID(taskExecutor);
5278     auto task = [height]() {
5279         auto pipeline = NG::PipelineContext::GetCurrentContext();
5280         CHECK_NULL_VOID(pipeline);
5281         pipeline->SetContainerModalTitleHeight(height);
5282     };
5283     auto uiTaskRunner = SingleTaskExecutor::Make(taskExecutor, TaskExecutor::TaskType::UI);
5284     if (uiTaskRunner.IsRunOnCurrentThread()) {
5285         task();
5286     } else {
5287         taskExecutor->PostTask(std::move(task), TaskExecutor::TaskType::UI, "ArkUISetContainerModalTitleHeight");
5288     }
5289 }
5290 
SetContainerButtonStyle(const Rosen::DecorButtonStyle & buttonStyle)5291 void UIContentImpl::SetContainerButtonStyle(const Rosen::DecorButtonStyle& buttonStyle)
5292 {
5293     auto container = Platform::AceContainer::GetContainer(instanceId_);
5294     CHECK_NULL_VOID(container);
5295     ContainerScope scope(instanceId_);
5296     auto taskExecutor = Container::CurrentTaskExecutor();
5297     CHECK_NULL_VOID(taskExecutor);
5298     Ace::DecorButtonStyle decorButtonStyle;
5299     ConvertDecorButtonStyle(buttonStyle, decorButtonStyle);
5300     taskExecutor->PostTask(
5301         [container, decorButtonStyle]() {
5302             auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
5303             CHECK_NULL_VOID(pipelineContext);
5304             NG::ContainerModalViewEnhance::SetContainerButtonStyle(pipelineContext, decorButtonStyle);
5305         },
5306         TaskExecutor::TaskType::UI, "SetContainerButtonStyle");
5307 }
5308 
GetContainerModalTitleHeight()5309 int32_t UIContentImpl::GetContainerModalTitleHeight()
5310 {
5311     ContainerScope scope(instanceId_);
5312     auto pipeline = NG::PipelineContext::GetCurrentContext();
5313     CHECK_NULL_RETURN(pipeline, -1);
5314     return pipeline->GetContainerModalTitleHeight();
5315 }
5316 
GetContainerModalButtonsRect(Rosen::Rect & containerModal,Rosen::Rect & buttons)5317 bool UIContentImpl::GetContainerModalButtonsRect(Rosen::Rect& containerModal, Rosen::Rect& buttons)
5318 {
5319     NG::RectF floatContainerModal;
5320     NG::RectF floatButtons;
5321     ContainerScope scope(instanceId_);
5322     auto pipeline = NG::PipelineContext::GetCurrentContext();
5323     CHECK_NULL_RETURN(pipeline, false);
5324     if (!pipeline->GetContainerModalButtonsRect(floatContainerModal, floatButtons)) {
5325         return false;
5326     }
5327     containerModal = ConvertToRSRect(floatContainerModal);
5328     buttons = ConvertToRSRect(floatButtons);
5329     return true;
5330 }
5331 
SubscribeContainerModalButtonsRectChange(std::function<void (Rosen::Rect & containerModal,Rosen::Rect & buttons)> && callback)5332 void UIContentImpl::SubscribeContainerModalButtonsRectChange(
5333     std::function<void(Rosen::Rect& containerModal, Rosen::Rect& buttons)>&& callback)
5334 {
5335     ContainerScope scope(instanceId_);
5336     auto pipeline = NG::PipelineContext::GetCurrentContext();
5337     CHECK_NULL_VOID(pipeline);
5338 
5339     if (callback == nullptr) {
5340         pipeline->SubscribeContainerModalButtonsRectChange(nullptr);
5341         return;
5342     }
5343     std::function<void(NG::RectF&, NG::RectF&)> wrapFunc = [cb = std::move(callback)](NG::RectF& floatContainerModal,
5344                                                                NG::RectF& floatButtons) {
5345         Rosen::Rect containerModal = ConvertToRSRect(floatContainerModal);
5346         Rosen::Rect buttons = ConvertToRSRect(floatButtons);
5347         cb(containerModal, buttons);
5348     };
5349     pipeline->SubscribeContainerModalButtonsRectChange(std::move(wrapFunc));
5350 }
5351 
ChangeSensitiveNodes(bool isSensitive)5352 void UIContentImpl::ChangeSensitiveNodes(bool isSensitive)
5353 {
5354     auto container = Platform::AceContainer::GetContainer(instanceId_);
5355     CHECK_NULL_VOID(container);
5356     ContainerScope scope(instanceId_);
5357     auto pipeline = container->GetPipelineContext();
5358     CHECK_NULL_VOID(pipeline);
5359     auto taskExecutor = container->GetTaskExecutor();
5360     CHECK_NULL_VOID(taskExecutor);
5361     taskExecutor->PostTask(
5362         [pipeline, isSensitive]() { pipeline->ChangeSensitiveNodes(isSensitive); },
5363         TaskExecutor::TaskType::UI, "ArkUIChangeSensitiveNodes");
5364 }
5365 
UpdateTransform(const OHOS::Rosen::Transform & transform)5366 void UIContentImpl::UpdateTransform(const OHOS::Rosen::Transform& transform)
5367 {
5368     auto container = Platform::AceContainer::GetContainer(instanceId_);
5369     CHECK_NULL_VOID(container);
5370     ContainerScope scope(instanceId_);
5371     auto taskExecutor = Container::CurrentTaskExecutor();
5372     CHECK_NULL_VOID(taskExecutor);
5373     auto windowScale = transform.scaleX_;
5374     taskExecutor->PostTask(
5375         [container, windowScale]() { container->SetWindowScale(windowScale); },
5376         TaskExecutor::TaskType::UI, "ArkUISetWindowScale");
5377 }
5378 
AddWatchSystemParameter()5379 void UIContentImpl::AddWatchSystemParameter()
5380 {
5381     auto container = Platform::AceContainer::GetContainer(instanceId_);
5382     CHECK_NULL_VOID(container);
5383     container->AddWatchSystemParameter();
5384 }
5385 
GetOverlayNodePositions() const5386 std::vector<Ace::RectF> UIContentImpl::GetOverlayNodePositions() const
5387 {
5388     auto container = Platform::AceContainer::GetContainer(instanceId_);
5389     ContainerScope scope(instanceId_);
5390     CHECK_NULL_RETURN(container, {});
5391     return container->GetOverlayNodePositions();
5392 }
5393 
RegisterOverlayNodePositionsUpdateCallback(const std::function<void (std::vector<Ace::RectF>)> & callback) const5394 void UIContentImpl::RegisterOverlayNodePositionsUpdateCallback(
5395     const std::function<void(std::vector<Ace::RectF>)>& callback) const
5396 {
5397     auto container = Platform::AceContainer::GetContainer(instanceId_);
5398     ContainerScope scope(instanceId_);
5399     CHECK_NULL_VOID(container);
5400     container->RegisterOverlayNodePositionsUpdateCallback(std::move(callback));
5401 }
5402 
SetContentNodeGrayScale(float grayscale)5403 void UIContentImpl::SetContentNodeGrayScale(float grayscale)
5404 {
5405     if (LessNotEqual(grayscale, 0.001f)) {
5406         grayscale = 0.0f;
5407     }
5408     if (GreatNotEqual(grayscale, 1.0)) {
5409         grayscale = 1.0f;
5410     }
5411     auto container = Platform::AceContainer::GetContainer(instanceId_);
5412     CHECK_NULL_VOID(container);
5413     ContainerScope scope(instanceId_);
5414     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
5415     CHECK_NULL_VOID(pipelineContext);
5416     auto rootElement = pipelineContext->GetRootElement();
5417     CHECK_NULL_VOID(rootElement);
5418     auto renderContext = rootElement->GetRenderContext();
5419     CHECK_NULL_VOID(renderContext);
5420     renderContext->UpdateFrontGrayScale(Dimension(grayscale));
5421     pipelineContext->SetDragNodeGrayscale(grayscale);
5422 }
5423 
PreLayout()5424 void UIContentImpl::PreLayout()
5425 {
5426     auto container = Platform::AceContainer::GetContainer(instanceId_);
5427     CHECK_NULL_VOID(container);
5428     ContainerScope scope(instanceId_);
5429     auto taskExecutor = container->GetTaskExecutor();
5430     CHECK_NULL_VOID(taskExecutor);
5431     taskExecutor->PostSyncTask(
5432         [instanceId = instanceId_] {
5433             TAG_LOGI(AceLogTag::ACE_WINDOW, "PreLayoutBegin");
5434             auto container = Platform::AceContainer::GetContainer(instanceId);
5435             CHECK_NULL_VOID(container);
5436             auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
5437             CHECK_NULL_VOID(pipelineContext);
5438             auto stageManager = pipelineContext->GetStageManager();
5439             CHECK_NULL_VOID(stageManager);
5440             auto stageNode = stageManager->GetStageNode();
5441             CHECK_NULL_VOID(stageNode);
5442             auto renderContext = stageNode->GetRenderContext();
5443             CHECK_NULL_VOID(renderContext);
5444             auto paintRectf = renderContext->GetPaintRectWithoutTransform();
5445             if (LessOrEqual(static_cast<uint32_t>(paintRectf.Width()), 0) ||
5446                 LessOrEqual(static_cast<uint32_t>(paintRectf.Height()), 0)) {
5447                 TAG_LOGW(AceLogTag::ACE_WINDOW, "width:%{public}f, height:%{public}f", paintRectf.Width(),
5448                     paintRectf.Height());
5449                 return;
5450             }
5451             pipelineContext->PreLayout(pipelineContext->GetTimeFromExternalTimer(), 0);
5452         },
5453         TaskExecutor::TaskType::UI, "ArkUIPreLayout");
5454     TAG_LOGI(AceLogTag::ACE_WINDOW, "ArkUIPreLayoutEnd");
5455 }
5456 
SetStatusBarItemColor(uint32_t color)5457 void UIContentImpl::SetStatusBarItemColor(uint32_t color)
5458 {
5459     ContainerScope scope(instanceId_);
5460     auto container = Platform::AceContainer::GetContainer(instanceId_);
5461     CHECK_NULL_VOID(container);
5462     auto appBar = container->GetAppBar();
5463     CHECK_NULL_VOID(appBar);
5464     appBar->SetStatusBarItemColor(IsDarkColor(color));
5465 }
5466 
SetForceSplitEnable(bool isForceSplit,const std::string & homePage,bool isRouter,bool ignoreOrientation)5467 void UIContentImpl::SetForceSplitEnable(
5468     bool isForceSplit, const std::string& homePage, bool isRouter, bool ignoreOrientation)
5469 {
5470     ContainerScope scope(instanceId_);
5471     auto container = Platform::AceContainer::GetContainer(instanceId_);
5472     CHECK_NULL_VOID(container);
5473     auto context = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
5474     CHECK_NULL_VOID(context);
5475     auto taskExecutor = container->GetTaskExecutor();
5476     CHECK_NULL_VOID(taskExecutor);
5477     auto forceSplitTask = [weakContext = WeakPtr(context), isForceSplit, homePage, isRouter, ignoreOrientation]() {
5478         auto context = weakContext.Upgrade();
5479         CHECK_NULL_VOID(context);
5480         auto forceSplitMgr = context->GetForceSplitManager();
5481         CHECK_NULL_VOID(forceSplitMgr);
5482         forceSplitMgr->SetForceSplitEnable(isForceSplit, ignoreOrientation);
5483         if (isRouter) {
5484             auto stageManager = context->GetStageManager();
5485             CHECK_NULL_VOID(stageManager);
5486             stageManager->SetForceSplitEnable(isForceSplit, homePage, ignoreOrientation);
5487             return;
5488         }
5489         auto navManager = context->GetNavigationManager();
5490         CHECK_NULL_VOID(navManager);
5491         navManager->SetForceSplitEnable(isForceSplit, homePage, ignoreOrientation);
5492     };
5493     if (taskExecutor->WillRunOnCurrentThread(TaskExecutor::TaskType::UI)) {
5494         forceSplitTask();
5495         return;
5496     }
5497     taskExecutor->PostTask(std::move(forceSplitTask), TaskExecutor::TaskType::UI,
5498         isRouter ? "ArkUISetForceSplitEnable" : "ArkUISetNavigationForceSplitEnable");
5499 }
5500 
SetForceSplitConfig(const std::string & configJsonStr)5501 void UIContentImpl::SetForceSplitConfig(const std::string& configJsonStr)
5502 {
5503     ContainerScope scope(instanceId_);
5504     auto container = Platform::AceContainer::GetContainer(instanceId_);
5505     CHECK_NULL_VOID(container);
5506     auto context = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
5507     CHECK_NULL_VOID(context);
5508     NG::ForceSplitConfig config;
5509     if (!NG::ForceSplitUtils::ParseForceSplitConfig(configJsonStr, config)) {
5510         TAG_LOGE(AceLogTag::ACE_NAVIGATION, "Failed to parse forceSplit config!");
5511         return;
5512     }
5513     TAG_LOGI(AceLogTag::ACE_NAVIGATION, "ForceSplitConfig: enableHook:%{public}d, navId:%{public}s,"
5514         "navDepth:%{public}s", config.isArkUIHookEnabled,
5515         (config.navigationId.has_value() ? config.navigationId.value().c_str() : "NA"),
5516         (config.navigationDepth.has_value() ? std::to_string(config.navigationDepth.value()).c_str() : "NA"));
5517     context->SetIsArkUIHookEnabled(config.isArkUIHookEnabled);
5518     auto navManager = context->GetNavigationManager();
5519     CHECK_NULL_VOID(navManager);
5520     navManager->SetForceSplitNavigationId(config.navigationId);
5521     navManager->SetForceSplitNavigationDepth(config.navigationDepth);
5522 }
5523 
ProcessDestructCallbacks()5524 void UIContentImpl::ProcessDestructCallbacks()
5525 {
5526     std::vector<std::function<void()>> tempCallbacks;
5527     {
5528         std::shared_lock<std::shared_mutex> reportLock(destructMutex_);
5529         tempCallbacks.reserve(destructCallbacks_.size());
5530         for (auto& [_, callback] : destructCallbacks_) {
5531             tempCallbacks.emplace_back(callback);
5532         }
5533     }
5534     for (auto& callback : tempCallbacks) {
5535         callback();
5536     }
5537 }
5538 
EnableContainerModalGesture(bool isEnable)5539 void UIContentImpl::EnableContainerModalGesture(bool isEnable)
5540 {
5541     LOGI("[%{public}s][%{public}s][%{public}d]: EnableContainerModalGesture: %{public}d",
5542         bundleName_.c_str(), moduleName_.c_str(), instanceId_, isEnable);
5543     auto container = Platform::AceContainer::GetContainer(instanceId_);
5544     CHECK_NULL_VOID(container);
5545     ContainerScope scope(instanceId_);
5546     auto taskExecutor = Container::CurrentTaskExecutor();
5547     CHECK_NULL_VOID(taskExecutor);
5548     taskExecutor->PostTask(
5549         [containerWeak = AceType::WeakClaim(AceType::RawPtr(container)), isEnable]() {
5550             auto container = containerWeak.Upgrade();
5551             CHECK_NULL_VOID(container);
5552             auto pipelineContext = container->GetPipelineContext();
5553             CHECK_NULL_VOID(pipelineContext);
5554             pipelineContext->EnableContainerModalGesture(isEnable);
5555         },
5556         TaskExecutor::TaskType::UI, "ArkUIEnableContainerModalGesture");
5557 }
5558 
GetContainerFloatingTitleVisible()5559 bool UIContentImpl::GetContainerFloatingTitleVisible()
5560 {
5561     LOGI("[%{public}s][%{public}s][%{public}d]: GetContainerFloatingTitleVisible",
5562         bundleName_.c_str(), moduleName_.c_str(), instanceId_);
5563     auto container = Platform::AceContainer::GetContainer(instanceId_);
5564     CHECK_NULL_RETURN(container, false);
5565     auto pipelineContext = container->GetPipelineContext();
5566     CHECK_NULL_RETURN(pipelineContext, false);
5567     return pipelineContext->GetContainerFloatingTitleVisible();
5568 }
5569 
GetContainerCustomTitleVisible()5570 bool UIContentImpl::GetContainerCustomTitleVisible()
5571 {
5572     LOGI("[%{public}s][%{public}s][%{public}d]: GetContainerCustomTitleVisible",
5573         bundleName_.c_str(), moduleName_.c_str(), instanceId_);
5574     auto container = Platform::AceContainer::GetContainer(instanceId_);
5575     CHECK_NULL_RETURN(container, false);
5576     auto pipelineContext = container->GetPipelineContext();
5577     CHECK_NULL_RETURN(pipelineContext, false);
5578     return pipelineContext->GetContainerCustomTitleVisible();
5579 }
5580 
GetContainerControlButtonVisible()5581 bool UIContentImpl::GetContainerControlButtonVisible()
5582 {
5583     LOGI("[%{public}s][%{public}s][%{public}d]: GetContainerControlButtonVisible",
5584         bundleName_.c_str(), moduleName_.c_str(), instanceId_);
5585     auto container = Platform::AceContainer::GetContainer(instanceId_);
5586     CHECK_NULL_RETURN(container, false);
5587     auto pipelineContext = container->GetPipelineContext();
5588     CHECK_NULL_RETURN(pipelineContext, false);
5589     return pipelineContext->GetContainerControlButtonVisible();
5590 }
5591 
OnContainerModalEvent(const std::string & name,const std::string & value)5592 void UIContentImpl::OnContainerModalEvent(const std::string& name, const std::string& value)
5593 {
5594     ContainerScope scope(instanceId_);
5595     auto taskExecutor = Container::CurrentTaskExecutor();
5596     CHECK_NULL_VOID(taskExecutor);
5597     auto task = [name, value, instanceId = instanceId_]() {
5598         auto container = Platform::AceContainer::GetContainer(instanceId);
5599         CHECK_NULL_VOID(container);
5600         auto pipelineBase = container->GetPipelineContext();
5601         CHECK_NULL_VOID(pipelineBase);
5602         auto pipeline = AceType::DynamicCast<NG::PipelineContext>(pipelineBase);
5603         CHECK_NULL_VOID(pipeline);
5604         NG::ContainerModalViewEnhance::OnContainerModalEvent(pipeline, name, value);
5605     };
5606     auto uiTaskRunner = SingleTaskExecutor::Make(taskExecutor, TaskExecutor::TaskType::UI);
5607     if (uiTaskRunner.IsRunOnCurrentThread()) {
5608         task();
5609     } else {
5610         taskExecutor->PostTask(std::move(task), TaskExecutor::TaskType::UI, "ArkUIOnContainerModalEvent");
5611     }
5612 }
5613 
ExecuteUITask(std::function<void ()> task,const std::string & name)5614 void UIContentImpl::ExecuteUITask(std::function<void()> task, const std::string& name)
5615 {
5616     auto taskExecutor = Container::CurrentTaskExecutor();
5617     CHECK_NULL_VOID(taskExecutor);
5618     auto uiTaskRunner = SingleTaskExecutor::Make(taskExecutor, TaskExecutor::TaskType::UI);
5619     if (uiTaskRunner.IsRunOnCurrentThread()) {
5620         task();
5621     } else {
5622         taskExecutor->PostTask(std::move(task), TaskExecutor::TaskType::UI, name);
5623     }
5624 }
5625 
UpdateSingleHandTransform(const OHOS::Rosen::SingleHandTransform & transform)5626 void UIContentImpl::UpdateSingleHandTransform(const OHOS::Rosen::SingleHandTransform& transform)
5627 {
5628     auto container = Platform::AceContainer::GetContainer(instanceId_);
5629     CHECK_NULL_VOID(container);
5630     auto aceContainer = AceType::DynamicCast<Platform::AceContainer>(container);
5631     CHECK_NULL_VOID(aceContainer);
5632     ContainerScope scope(instanceId_);
5633     auto taskExecutor = Container::CurrentTaskExecutor();
5634     CHECK_NULL_VOID(taskExecutor);
5635     taskExecutor->PostTask(
5636         [id = instanceId_, aceContainer, singleHandTransform = Platform::SingleHandTransform(transform.posX,
5637             transform.posY, transform.scaleX, transform.scaleY)]() {
5638             aceContainer->SetSingleHandTransform(singleHandTransform);
5639             auto context = NG::PipelineContext::GetContextByContainerId(id);
5640             CHECK_NULL_VOID(context);
5641             auto uiExtManager = context->GetUIExtensionManager();
5642             CHECK_NULL_VOID(uiExtManager);
5643             uiExtManager->TransferAccessibilityRectInfo();
5644         }, TaskExecutor::TaskType::UI, "ArkUISetSingleHandTransform");
5645 }
5646 
ConfigCustomWindowMask(bool enable)5647 bool UIContentImpl::ConfigCustomWindowMask(bool enable)
5648 {
5649     auto container = Platform::AceContainer::GetContainer(instanceId_);
5650     CHECK_NULL_RETURN(container, false);
5651     auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
5652     CHECK_NULL_RETURN(pipelineContext, false);
5653     return NG::ContainerModalView::ConfigCustomWindowMask(pipelineContext, enable);
5654 }
5655 
GetWindowSizeChangeReason(OHOS::Rosen::WindowSizeChangeReason lastReason,OHOS::Rosen::WindowSizeChangeReason reason)5656 bool UIContentImpl::GetWindowSizeChangeReason(OHOS::Rosen::WindowSizeChangeReason lastReason,
5657     OHOS::Rosen::WindowSizeChangeReason reason)
5658 {
5659     bool reasonDragFlag = true;
5660     if (lastReason == OHOS::Rosen::WindowSizeChangeReason::DRAG_START &&
5661             reason == OHOS::Rosen::WindowSizeChangeReason::DRAG) {
5662         reasonDragFlag = false;
5663     }
5664     if (lastReason == OHOS::Rosen::WindowSizeChangeReason::DRAG &&
5665             reason == OHOS::Rosen::WindowSizeChangeReason::DRAG) {
5666         reasonDragFlag = false;
5667     }
5668     if (lastReason == OHOS::Rosen::WindowSizeChangeReason::DRAG &&
5669             reason == OHOS::Rosen::WindowSizeChangeReason::DRAG_END) {
5670         reasonDragFlag = false;
5671     }
5672     if (lastReason == OHOS::Rosen::WindowSizeChangeReason::SPLIT_DRAG_START &&
5673             reason == OHOS::Rosen::WindowSizeChangeReason::SPLIT_DRAG) {
5674         reasonDragFlag = false;
5675     }
5676     if (lastReason == OHOS::Rosen::WindowSizeChangeReason::SPLIT_DRAG &&
5677             reason == OHOS::Rosen::WindowSizeChangeReason::SPLIT_DRAG) {
5678         reasonDragFlag = false;
5679     }
5680     if (lastReason == OHOS::Rosen::WindowSizeChangeReason::SPLIT_DRAG &&
5681             reason == OHOS::Rosen::WindowSizeChangeReason::SPLIT_DRAG_END) {
5682         reasonDragFlag = false;
5683     }
5684     return reasonDragFlag;
5685 }
5686 
GetRSNodeByStringID(const std::string & stringId)5687 std::shared_ptr<Rosen::RSNode> UIContentImpl::GetRSNodeByStringID(const std::string& stringId)
5688 {
5689     auto container = Platform::AceContainer::GetContainer(instanceId_);
5690     CHECK_NULL_RETURN(container, nullptr);
5691     auto taskExecutor = container->GetTaskExecutor();
5692     CHECK_NULL_RETURN(taskExecutor, nullptr);
5693     std::shared_ptr<Rosen::RSNode> rsNode;
5694     taskExecutor->PostSyncTask(
5695         [id = instanceId_, &rsNode, stringId]() {
5696             ContainerScope scope(id);
5697             auto frameNode = NG::Inspector::GetFrameNodeByKey(stringId, true, true);
5698             CHECK_NULL_VOID(frameNode);
5699             auto renderContext = AceType::DynamicCast<NG::RosenRenderContext>(frameNode->GetRenderContext());
5700             CHECK_NULL_VOID(renderContext);
5701             rsNode = renderContext->GetRSNode();
5702         },
5703         TaskExecutor::TaskType::UI, "ArkUIGetRSNodeByStringID");
5704     if (!rsNode) {
5705         LOGE("Cannot find RSNode by stringId: %{public}s", stringId.c_str());
5706     }
5707     return rsNode;
5708 }
5709 
SetTopWindowBoundaryByID(const std::string & stringId)5710 void UIContentImpl::SetTopWindowBoundaryByID(const std::string& stringId)
5711 {
5712     auto container = Platform::AceContainer::GetContainer(instanceId_);
5713     CHECK_NULL_VOID(container);
5714     auto taskExecutor = container->GetTaskExecutor();
5715     CHECK_NULL_VOID(taskExecutor);
5716     taskExecutor->PostSyncTask(
5717         [id = instanceId_, stringId]() {
5718             ContainerScope scope(id);
5719             auto frameNode = NG::Inspector::GetFrameNodeByKey(stringId, true, true);
5720             CHECK_NULL_VOID(frameNode);
5721             frameNode->SetTopWindowBoundary(true);
5722         },
5723         TaskExecutor::TaskType::UI, "ArkUISetTopWindowBoundaryByID");
5724 }
5725 
sendCommandCallbackInner(const WeakPtr<TaskExecutor> & taskExecutor)5726 void sendCommandCallbackInner(const WeakPtr<TaskExecutor>& taskExecutor)
5727 {
5728     auto sendCommandCallback = [weakTaskExecutor = taskExecutor](int32_t value) {
5729         KeyEvent keyEvent;
5730         keyEvent.action = KeyAction::DOWN;
5731         keyEvent.code = static_cast<KeyCode>(value);
5732         keyEvent.pressedCodes = { keyEvent.code };
5733 
5734         auto taskExecutor = weakTaskExecutor.Upgrade();
5735         CHECK_NULL_VOID(taskExecutor);
5736         taskExecutor->PostTask(
5737             [keyEvent]() {
5738                 auto pipeline = NG::PipelineContext::GetCurrentContextSafely();
5739                 CHECK_NULL_VOID(pipeline);
5740                 pipeline->OnNonPointerEvent(keyEvent);
5741             },
5742             TaskExecutor::TaskType::UI, "UiSessionSendCommandKeyCode");
5743     };
5744     UiSessionManager::GetInstance()->SaveSendCommandFunction(sendCommandCallback);
5745 }
5746 
InitUISessionManagerCallbacks(const WeakPtr<TaskExecutor> & taskExecutor)5747 void UIContentImpl::InitUISessionManagerCallbacks(const WeakPtr<TaskExecutor>& taskExecutor)
5748 {
5749     // set get inspector tree function for ui session manager
5750     auto callback = [weakTaskExecutor = taskExecutor](bool onlyNeedVisible) {
5751         auto taskExecutor = weakTaskExecutor.Upgrade();
5752         CHECK_NULL_VOID(taskExecutor);
5753         taskExecutor->PostTask(
5754             [onlyNeedVisible]() {
5755                 auto pipeline = NG::PipelineContext::GetCurrentContextSafely();
5756                 CHECK_NULL_VOID(pipeline);
5757                 if (onlyNeedVisible) {
5758                     pipeline->GetInspectorTree(true);
5759                 } else {
5760                     pipeline->GetInspectorTree(false);
5761                     UiSessionManager::GetInstance()->WebTaskNumsChange(-1);
5762                 }
5763             },
5764             TaskExecutor::TaskType::UI, "UiSessionGetInspectorTree",
5765             TaskExecutor::GetPriorityTypeWithCheck(PriorityType::VIP));
5766     };
5767     UiSessionManager::GetInstance()->SaveInspectorTreeFunction(callback);
5768     auto webCallback = [weakTaskExecutor = taskExecutor](bool isRegister) {
5769         auto taskExecutor = weakTaskExecutor.Upgrade();
5770         CHECK_NULL_VOID(taskExecutor);
5771         taskExecutor->PostTask(
5772             [isRegister]() {
5773                 auto pipeline = NG::PipelineContext::GetCurrentContextSafely();
5774                 CHECK_NULL_VOID(pipeline);
5775                 pipeline->NotifyAllWebPattern(isRegister);
5776             },
5777             TaskExecutor::TaskType::UI, "UiSessionRegisterWebPattern",
5778             TaskExecutor::GetPriorityTypeWithCheck(PriorityType::VIP));
5779     };
5780     UiSessionManager::GetInstance()->SaveRegisterForWebFunction(webCallback);
5781     SetupGetPixelMapCallback(taskExecutor);
5782     RegisterGetCurrentPageName();
5783     InitSendCommandFunctionsCallbacks(taskExecutor);
5784     sendCommandCallbackInner(taskExecutor);
5785     SaveGetCurrentInstanceId();
5786     RegisterExeAppAIFunction();
5787 }
5788 
SetupGetPixelMapCallback(const WeakPtr<TaskExecutor> & taskExecutor)5789 void UIContentImpl::SetupGetPixelMapCallback(const WeakPtr<TaskExecutor>& taskExecutor)
5790 {
5791     auto getPixelMapCallback = [weakTaskExecutor = taskExecutor]() {
5792         auto taskExecutor = weakTaskExecutor.Upgrade();
5793         CHECK_NULL_VOID(taskExecutor);
5794         taskExecutor->PostTask(
5795             []() {
5796                 auto pipeline = NG::PipelineContext::GetCurrentContextSafely();
5797                 CHECK_NULL_VOID(pipeline);
5798                 pipeline->GetAllPixelMap();
5799             },
5800             TaskExecutor::TaskType::UI, "UiSessionGetPixelMap");
5801     };
5802     UiSessionManager::GetInstance()->SaveGetPixelMapFunction(getPixelMapCallback);
5803 }
5804 
SaveGetCurrentInstanceId()5805 void UIContentImpl::SaveGetCurrentInstanceId()
5806 {
5807     static std::once_flag onceFlag;
5808     std::call_once(onceFlag, []() {
5809         auto saveInstanceIdCallback = []() -> int32_t {
5810             auto pipeline = NG::PipelineContext::GetCurrentContextSafely();
5811             CHECK_NULL_RETURN(pipeline, -1);
5812             return pipeline->GetInstanceId();
5813         };
5814         UiSessionManager::GetInstance()->SaveGetCurrentInstanceIdCallback(saveInstanceIdCallback);
5815     });
5816 }
5817 
RegisterGetCurrentPageName()5818 void UIContentImpl::RegisterGetCurrentPageName()
5819 {
5820     auto getPageNameCallback = []() -> std::string {
5821         auto pipeline = NG::PipelineContext::GetCurrentContextSafely();
5822         CHECK_NULL_RETURN(pipeline, "");
5823         return pipeline->GetCurrentPageNameCallback();
5824     };
5825     UiSessionManager::GetInstance()->RegisterPipeLineGetCurrentPageName(getPageNameCallback);
5826 }
5827 
InitSendCommandFunctionsCallbacks(const WeakPtr<TaskExecutor> & taskExecutor)5828 void UIContentImpl::InitSendCommandFunctionsCallbacks(const WeakPtr<TaskExecutor>& taskExecutor)
5829 {
5830     auto sendCommandAsync = [weakTaskExecutor = taskExecutor](int32_t id, const std::string& command) {
5831         auto taskExecutor = weakTaskExecutor.Upgrade();
5832         if (!taskExecutor) {
5833             LOGI("Task executor is null");
5834             return 11;
5835         }
5836         int32_t result = 12;
5837         taskExecutor->PostSyncTask(
5838             [id, command, &result]() {
5839                 auto node = AceType::DynamicCast<NG::FrameNode>(ElementRegister::GetInstance()->GetUINodeById(id));
5840                 if (!node) {
5841                     LOGI("UiSessionSendCommandAsyncPattern: Node is null for id: %{public}d", id);
5842                     result = 13;
5843                     return;
5844                 }
5845                 result = node->OnRecvCommand(command);
5846             },
5847             TaskExecutor::TaskType::UI, "UiSessionSendCommandAsyncPattern");
5848         return result;
5849     };
5850     UiSessionManager::GetInstance()->SaveForSendCommandAsyncFunction(sendCommandAsync);
5851     auto sendCommand = [weakTaskExecutor = taskExecutor](int32_t id, const std::string& command) {
5852         auto taskExecutor = weakTaskExecutor.Upgrade();
5853         CHECK_NULL_VOID(taskExecutor);
5854         taskExecutor->PostTask(
5855             [id, command]() {
5856                 auto node = AceType::DynamicCast<NG::FrameNode>(ElementRegister::GetInstance()->GetUINodeById(id));
5857                 if (!node) {
5858                     LOGI("UiSessionSendCommandPattern: Node is null for id: %{public}d", id);
5859                     return;
5860                 }
5861                 node->OnRecvCommand(command);
5862             },
5863             TaskExecutor::TaskType::UI, "UiSessionSendCommandPattern");
5864     };
5865     UiSessionManager::GetInstance()->SaveForSendCommandFunction(sendCommand);
5866 }
5867 
SendUIExtProprty(uint32_t code,const AAFwk::Want & data,uint8_t subSystemId)5868 bool UIContentImpl::SendUIExtProprty(uint32_t code, const AAFwk::Want& data, uint8_t subSystemId)
5869 {
5870     auto container = Platform::AceContainer::GetContainer(instanceId_);
5871     CHECK_NULL_RETURN(container, false);
5872     auto aceContainer = AceType::DynamicCast<Platform::AceContainer>(container);
5873     CHECK_NULL_RETURN(aceContainer, false);
5874     ContainerScope scope(instanceId_);
5875     auto taskExecutor = Container::CurrentTaskExecutor();
5876     CHECK_NULL_RETURN(taskExecutor, false);
5877     taskExecutor->PostTask(
5878         [instanceId = instanceId_, code, data, subSystemId]() {
5879             auto context = NG::PipelineContext::GetContextByContainerId(instanceId);
5880             CHECK_NULL_VOID(context);
5881             auto uiExtManager = context->GetUIExtensionManager();
5882             CHECK_NULL_VOID(uiExtManager);
5883             uiExtManager->UpdateWMSUIExtProperty(static_cast<Ace::NG::UIContentBusinessCode>(code),
5884                 data, static_cast<Ace::NG::RSSubsystemId>(subSystemId));
5885         }, TaskExecutor::TaskType::UI, "ArkUISendUIExtProprty");
5886     return true;
5887 }
5888 
SendUIExtProprtyByPersistentId(uint32_t code,const AAFwk::Want & data,const std::unordered_set<int32_t> & persistentIds,uint8_t subSystemId)5889 bool UIContentImpl::SendUIExtProprtyByPersistentId(uint32_t code, const AAFwk::Want& data,
5890         const std::unordered_set<int32_t>& persistentIds, uint8_t subSystemId)
5891 {
5892     auto container = Platform::AceContainer::GetContainer(instanceId_);
5893     CHECK_NULL_RETURN(container, false);
5894     auto aceContainer = AceType::DynamicCast<Platform::AceContainer>(container);
5895     CHECK_NULL_RETURN(aceContainer, false);
5896     auto taskExecutor = container->GetTaskExecutor();
5897     CHECK_NULL_RETURN(taskExecutor, false);
5898     taskExecutor->PostTask(
5899         [instanceId = instanceId_, code, data, persistentIds, subSystemId]() {
5900             auto context = NG::PipelineContext::GetContextByContainerId(instanceId);
5901             CHECK_NULL_VOID(context);
5902             auto uiExtManager = context->GetUIExtensionManager();
5903             CHECK_NULL_VOID(uiExtManager);
5904             uiExtManager->UpdateWMSUIExtPropertyByPersistentId(static_cast<Ace::NG::UIContentBusinessCode>(code),
5905                 data, persistentIds, static_cast<Ace::NG::RSSubsystemId>(subSystemId));
5906         }, TaskExecutor::TaskType::UI, "ArkUISendUIExtProprtyByPersistentId");
5907     return true;
5908 }
5909 
EnableContainerModalCustomGesture(bool enable)5910 void UIContentImpl::EnableContainerModalCustomGesture(bool enable)
5911 {
5912     auto container = Platform::AceContainer::GetContainer(instanceId_);
5913     CHECK_NULL_VOID(container);
5914     ContainerScope scope(instanceId_);
5915     auto taskExecutor = Container::CurrentTaskExecutor();
5916     CHECK_NULL_VOID(taskExecutor);
5917     taskExecutor->PostTask(
5918         [container, enable]() {
5919             auto pipelineContext = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
5920             CHECK_NULL_VOID(pipelineContext);
5921             NG::ContainerModalPattern::EnableContainerModalCustomGesture(pipelineContext, enable);
5922         },
5923         TaskExecutor::TaskType::UI, "EnableContainerModalCustomGesture");
5924 }
5925 
ChangeDisplayAvailableAreaListener(uint64_t displayId)5926 void UIContentImpl::ChangeDisplayAvailableAreaListener(uint64_t displayId)
5927 {
5928     if (listenedDisplayId_ != displayId && availableAreaChangedListener_) {
5929         auto& manager = Rosen::DisplayManager::GetInstance();
5930         manager.UnregisterAvailableAreaListener(availableAreaChangedListener_, listenedDisplayId_);
5931         listenedDisplayId_ = displayId;
5932         manager.RegisterAvailableAreaListener(availableAreaChangedListener_, listenedDisplayId_);
5933     }
5934 }
5935 
ConvertDecorButtonStyle(const Rosen::DecorButtonStyle & buttonStyle,Ace::DecorButtonStyle & decorButtonStyle)5936 void UIContentImpl::ConvertDecorButtonStyle(const Rosen::DecorButtonStyle& buttonStyle,
5937     Ace::DecorButtonStyle& decorButtonStyle)
5938 {
5939     decorButtonStyle.buttonBackgroundCornerRadius = buttonStyle.buttonBackgroundCornerRadius;
5940     decorButtonStyle.buttonBackgroundSize = buttonStyle.buttonBackgroundSize;
5941     decorButtonStyle.buttonIconSize = buttonStyle.buttonIconSize;
5942     decorButtonStyle.closeButtonRightMargin = buttonStyle.closeButtonRightMargin;
5943     decorButtonStyle.colorMode = buttonStyle.colorMode;
5944     decorButtonStyle.spacingBetweenButtons = buttonStyle.spacingBetweenButtons;
5945 }
5946 
SetIntentParam(const std::string & intentInfoSerialized,const std::function<void ()> && loadPageCallback,bool isColdStart)5947 void UIContentImpl::SetIntentParam(const std::string& intentInfoSerialized,
5948     const std::function<void()>&& loadPageCallback, bool isColdStart)
5949 {
5950     if (!isColdStart) {
5951         auto container = Platform::AceContainer::GetContainer(instanceId_);
5952         CHECK_NULL_VOID(container);
5953         ContainerScope scope(instanceId_);
5954         container->DistributeIntentInfo(intentInfoSerialized, false, std::move(loadPageCallback));
5955         container->RunIntentPage();
5956         return;
5957     }
5958     intentInfoSerialized_ = intentInfoSerialized;
5959     loadPageCallback_ = std::move(loadPageCallback);
5960 }
5961 
GetTopNavDestinationInfo(bool onlyFullScreen,bool needParam)5962 std::string UIContentImpl::GetTopNavDestinationInfo(bool onlyFullScreen, bool needParam)
5963 {
5964     std::string serializedEmpty = "{}";
5965     auto container = Platform::AceContainer::GetContainer(instanceId_);
5966     CHECK_NULL_RETURN(container, serializedEmpty);
5967     ContainerScope scope(instanceId_);
5968     auto frontend = container->GetFrontend();
5969     CHECK_NULL_RETURN(frontend, serializedEmpty);
5970     return frontend->GetTopNavDestinationInfo(onlyFullScreen, needParam);
5971 }
5972 
RestoreNavDestinationInfo(const std::string & navDestinationInfo,bool isColdStart)5973 void UIContentImpl::RestoreNavDestinationInfo(const std::string& navDestinationInfo, bool isColdStart)
5974 {
5975     if (isColdStart) {
5976         restoreNavDestinationInfo_ = navDestinationInfo;
5977         return;
5978     }
5979     RestoreNavDestinationInfoInner(navDestinationInfo, false);
5980 }
5981 
RestoreNavDestinationInfoInner(const std::string & navDestinationInfo,bool isColdStart)5982 void UIContentImpl::RestoreNavDestinationInfoInner(const std::string& navDestinationInfo, bool isColdStart)
5983 {
5984     TAG_LOGI(AceLogTag::ACE_NAVIGATION,
5985         "will restore navDestination info, isColdStart? %{public}s", isColdStart ? "yes" : "no");
5986     auto container = Platform::AceContainer::GetContainer(instanceId_);
5987     CHECK_NULL_VOID(container);
5988     ContainerScope scope(instanceId_);
5989     auto pipeline = AceType::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
5990     CHECK_NULL_VOID(pipeline);
5991     auto navigationManager = pipeline->GetNavigationManager();
5992     CHECK_NULL_VOID(navigationManager);
5993     navigationManager->RestoreNavDestinationInfo(navDestinationInfo, isColdStart);
5994 }
5995 
RunIntentPageIfNeeded()5996 void UIContentImpl::RunIntentPageIfNeeded()
5997 {
5998     if (!intentInfoSerialized_.empty()) {
5999         auto container = Platform::AceContainer::GetContainer(instanceId_);
6000         if (container) {
6001             TAG_LOGI(AceLogTag::ACE_ROUTER, "intentInfo exist, will distribute intentInfo");
6002             ContainerScope scope(instanceId_);
6003             container->DistributeIntentInfo(intentInfoSerialized_, true, std::move(loadPageCallback_));
6004             intentInfoSerialized_ = "";
6005             loadPageCallback_ = nullptr;
6006         }
6007     }
6008 }
6009 
InitializeWithAniStorage(OHOS::Rosen::Window * window,const std::string & url,ani_object storage)6010 UIContentErrorCode UIContentImpl::InitializeWithAniStorage(
6011     OHOS::Rosen::Window* window, const std::string& url, ani_object storage)
6012 {
6013     StorageWrapper storageWrapper { .aniStorage_ = storage };
6014     auto errorCode = InitializeInner(window, url, storageWrapper, false);
6015     AddWatchSystemParameter();
6016     return errorCode;
6017 }
6018 
InitializeWithAniStorage(OHOS::Rosen::Window * window,const std::string & url,ani_object storage,uint32_t focusWindowId)6019 UIContentErrorCode UIContentImpl::InitializeWithAniStorage(
6020     OHOS::Rosen::Window* window, const std::string& url, ani_object storage, uint32_t focusWindowId)
6021 {
6022     auto errorCode = UIContentErrorCode::NO_ERRORS;
6023     if (window == nullptr) {
6024         LOGE("UIExtensionAbility [%{public}s][%{public}s][%{public}d][%{public}s] initialize ui instance failed, the"
6025              "window is invalid",
6026             bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str());
6027         return errorCode;
6028     }
6029     StorageWrapper storageWrapper { .aniStorage_ = storage };
6030     errorCode = CommonInitialize(window, url, storageWrapper, focusWindowId);
6031     if (errorCode != UIContentErrorCode::NO_ERRORS) {
6032         return errorCode;
6033     }
6034     AddWatchSystemParameter();
6035 
6036     TAG_LOGI(AceLogTag::ACE_UIEXTENSIONCOMPONENT, "[%{public}s][%{public}s][%{public}d]: StartUIExtension: %{public}s",
6037         bundleName_.c_str(), moduleName_.c_str(), instanceId_, startUrl_.c_str());
6038     // run page.
6039     Platform::AceContainer::RunPage(instanceId_, startUrl_, "");
6040     auto distributedUI = std::make_shared<NG::DistributedUI>();
6041     uiManager_ = std::make_unique<DistributedUIManager>(instanceId_, distributedUI);
6042     Platform::AceContainer::GetContainer(instanceId_)->SetDistributedUI(distributedUI);
6043 #if !defined(ACE_UNITTEST)
6044     auto pipelineContext = NG::PipelineContext::GetCurrentContext();
6045     CHECK_NULL_RETURN(pipelineContext, errorCode);
6046     auto rootNode = pipelineContext->GetRootElement();
6047     NG::TransparentNodeDetector::GetInstance().PostCheckNodeTransparentTask(rootNode, startUrl_);
6048 #endif
6049     return errorCode;
6050 }
6051 
InitializeWithAniStorage(OHOS::Rosen::Window * window,const std::shared_ptr<std::vector<uint8_t>> & content,ani_object storage)6052 UIContentErrorCode UIContentImpl::InitializeWithAniStorage(
6053     OHOS::Rosen::Window* window, const std::shared_ptr<std::vector<uint8_t>>& content, ani_object storage)
6054 {
6055     std::string contentName = "";
6056     return InitializeWithAniStorage(window, content, storage, contentName);
6057 }
6058 
InitializeWithAniStorage(OHOS::Rosen::Window * window,const std::shared_ptr<std::vector<uint8_t>> & content,ani_object storage,const std::string & contentName)6059 UIContentErrorCode UIContentImpl::InitializeWithAniStorage(OHOS::Rosen::Window* window,
6060     const std::shared_ptr<std::vector<uint8_t>>& content, ani_object storage, const std::string& contentName)
6061 {
6062     auto errorCode = UIContentErrorCode::NO_ERRORS;
6063     StorageWrapper storageWrapper { .aniStorage_ = storage };
6064     errorCode = CommonInitialize(window, "", storageWrapper);
6065     CHECK_ERROR_CODE_RETURN(errorCode);
6066     AddWatchSystemParameter();
6067     if (content) {
6068         LOGI("Initialize by buffer, size:%{public}zu", content->size());
6069         // run page.
6070         errorCode = Platform::AceContainer::RunPage(instanceId_, content, contentName);
6071         CHECK_ERROR_CODE_RETURN(errorCode);
6072     } else {
6073         LOGE("Initialize failed, buffer is null");
6074     }
6075     auto distributedUI = std::make_shared<NG::DistributedUI>();
6076     uiManager_ = std::make_unique<DistributedUIManager>(instanceId_, distributedUI);
6077     Platform::AceContainer::GetContainer(instanceId_)->SetDistributedUI(distributedUI);
6078     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionSubWindow(isUIExtensionSubWindow_);
6079     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionAbilityProcess(isUIExtensionAbilityProcess_);
6080     Platform::AceContainer::GetContainer(instanceId_)->SetUIExtensionAbilityHost(isUIExtensionAbilityHost_);
6081     return errorCode;
6082 }
6083 
InitializeByNameWithAniStorage(OHOS::Rosen::Window * window,const std::string & name,ani_object storage)6084 UIContentErrorCode UIContentImpl::InitializeByNameWithAniStorage(
6085     OHOS::Rosen::Window* window, const std::string& name, ani_object storage)
6086 {
6087     StorageWrapper storageWrapper { .aniStorage_ = storage };
6088     auto errorCode = InitializeInner(window, name, storageWrapper, true);
6089     AddWatchSystemParameter();
6090     return errorCode;
6091 }
6092 
RegisterExeAppAIFunction()6093 void UIContentImpl::RegisterExeAppAIFunction()
6094 {
6095     auto exeAppAIFunctionCallback = [](
6096         const std::string& funcName, const std::string& params) -> uint32_t {
6097         static constexpr uint32_t AI_CALL_ENV_INVALID = 4;
6098         auto pipeline = NG::PipelineContext::GetCurrentContextSafely();
6099         CHECK_NULL_RETURN(pipeline, AI_CALL_ENV_INVALID);
6100         return pipeline->ExeAppAIFunctionCallback(funcName, params);
6101     };
6102     UiSessionManager::GetInstance()->RegisterPipeLineExeAppAIFunction(exeAppAIFunctionCallback);
6103 }
6104 } // namespace OHOS::Ace
6105