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