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