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