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