• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 "window_session_impl.h"
17 
18 #include <cstdlib>
19 
20 #include <common/rs_common_def.h>
21 #include <filesystem>
22 #include <float_wrapper.h>
23 #include <fstream>
24 #include <ipc_skeleton.h>
25 #include <hisysevent.h>
26 #include <parameters.h>
27 #include <int_wrapper.h>
28 #ifdef IMF_ENABLE
29 #include <input_method_controller.h>
30 #endif // IMF_ENABLE
31 #include <transaction/rs_interfaces.h>
32 #include <transaction/rs_transaction.h>
33 
34 #include "color_parser.h"
35 #include "common/include/fold_screen_state_internel.h"
36 #include "common/include/fold_screen_common.h"
37 #include "display_info.h"
38 #include "display_manager.h"
39 #include "extension/extension_business_info.h"
40 #include "hitrace_meter.h"
41 #include "rs_adapter.h"
42 #include "scene_board_judgement.h"
43 #include "session_helper.h"
44 #include "session_permission.h"
45 #include "key_event.h"
46 #include "session/container/include/window_event_channel.h"
47 #include "session_manager/include/session_manager.h"
48 #include "vsync_station.h"
49 #include "window_adapter.h"
50 #include "window_inspector.h"
51 #include "window_manager_hilog.h"
52 #include "window_helper.h"
53 #include "color_parser.h"
54 #include "singleton_container.h"
55 #include "sys_cap_util.h"
56 #include "perform_reporter.h"
57 #include "picture_in_picture_manager.h"
58 #include "parameters.h"
59 #include "floating_ball_manager.h"
60 #include "sys_cap_util.h"
61 
62 namespace OHOS::Accessibility {
63 class AccessibilityEventInfo;
64 }
65 namespace OHOS {
66 namespace Rosen {
67 namespace {
68 constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, HILOG_DOMAIN_WINDOW, "WindowSessionImpl"};
69 constexpr int32_t FORCE_SPLIT_MODE = 5;
70 constexpr int32_t NAV_FORCE_SPLIT_MODE = 6;
71 constexpr int32_t API_VERSION_18 = 18;
72 constexpr uint32_t API_VERSION_MOD = 1000;
73 constexpr int32_t  WINDOW_ROTATION_CHANGE = 50;
74 constexpr uint32_t INVALID_TARGET_API_VERSION = 0;
75 constexpr uint32_t OPAQUE = 0xFF000000;
76 constexpr int32_t WINDOW_CONNECT_TIMEOUT = 3000;
77 constexpr int32_t WINDOW_LIFECYCLE_TIMEOUT = 100;
78 
79 /*
80  * DFX
81  */
82 const std::string SET_UIEXTENSION_DESTROY_TIMEOUT_LISTENER_TASK_NAME = "SetUIExtDestroyTimeoutListener";
83 const std::string BUTTON_BACKGROUND_CORNER_RADIUS = "buttonBackgroundCornerRadius";
84 const std::string BUTTON_BACKGROUND_SIZE = "buttonBackgroundSize";
85 const std::string BUTTON_ICON_SIZE = "buttonIconSize";
86 const std::string CLOSE_BUTTON_RIGHT_MARGIN = "closeButtonRightMargin";
87 const std::string BUTTON_COLOR_MODE = "colorMode";
88 const std::string BUTTON_SPACING_BETWEEN = "spacingBetweenButtons";
89 const std::string DECOR_BUTTON_STYLE_CHANGE = "decor_button_style_change";
90 constexpr int64_t SET_UIEXTENSION_DESTROY_TIMEOUT_TIME_MS = 4000;
91 
92 const std::string SCB_BACK_VISIBILITY = "scb_back_visibility";
93 const std::string SCB_COMPATIBLE_MAXIMIZE_VISIBILITY = "scb_compatible_maximize_visibility";
94 
GetAceContentInfoType(BackupAndRestoreType type)95 Ace::ContentInfoType GetAceContentInfoType(BackupAndRestoreType type)
96 {
97     auto contentInfoType = Ace::ContentInfoType::NONE;
98     switch (type) {
99         case BackupAndRestoreType::CONTINUATION:
100             contentInfoType = Ace::ContentInfoType::CONTINUATION;
101             break;
102         case BackupAndRestoreType::APP_RECOVERY:
103             contentInfoType = Ace::ContentInfoType::APP_RECOVERY;
104             break;
105         case BackupAndRestoreType::RESOURCESCHEDULE_RECOVERY:
106             contentInfoType = Ace::ContentInfoType::RESOURCESCHEDULE_RECOVERY;
107             break;
108         case BackupAndRestoreType::NONE:
109             [[fallthrough]];
110         default:
111             break;
112     }
113     return contentInfoType;
114 }
115 
FillViewportConfig(Rect rect,float density,int32_t orientation,uint32_t transformHint,uint64_t displayId)116 Ace::ViewportConfig FillViewportConfig(
117     Rect rect, float density, int32_t orientation, uint32_t transformHint, uint64_t displayId)
118 {
119     Ace::ViewportConfig config;
120     config.SetSize(rect.width_, rect.height_);
121     config.SetPosition(rect.posX_, rect.posY_);
122     config.SetDensity(density);
123     config.SetOrientation(orientation);
124     config.SetTransformHint(transformHint);
125     config.SetDisplayId(displayId);
126     return config;
127 }
128 }
129 
130 std::map<int32_t, std::vector<sptr<ISystemBarPropertyListener>>> WindowSessionImpl::systemBarPropertyListeners_;
131 std::map<int32_t, std::vector<sptr<IWindowLifeCycle>>> WindowSessionImpl::lifecycleListeners_;
132 std::map<int32_t, std::vector<sptr<IWindowStageLifeCycle>>> WindowSessionImpl::windowStageLifecycleListeners_;
133 std::map<int32_t, std::vector<sptr<IDisplayMoveListener>>> WindowSessionImpl::displayMoveListeners_;
134 std::map<int32_t, std::vector<sptr<IWindowChangeListener>>> WindowSessionImpl::windowChangeListeners_;
135 std::map<int32_t, std::vector<sptr<IWindowCrossAxisListener>>> WindowSessionImpl::windowCrossAxisListeners_;
136 std::map<int32_t, std::vector<sptr<IAvoidAreaChangedListener>>> WindowSessionImpl::avoidAreaChangeListeners_;
137 std::map<int32_t, std::vector<sptr<IDialogDeathRecipientListener>>> WindowSessionImpl::dialogDeathRecipientListeners_;
138 std::map<int32_t, std::vector<sptr<IDialogTargetTouchListener>>> WindowSessionImpl::dialogTargetTouchListener_;
139 std::map<int32_t, std::vector<sptr<IOccupiedAreaChangeListener>>> WindowSessionImpl::occupiedAreaChangeListeners_;
140 std::map<int32_t, std::vector<sptr<IKBWillShowListener>>> WindowSessionImpl::keyboardWillShowListeners_;
141 std::map<int32_t, std::vector<sptr<IKBWillHideListener>>> WindowSessionImpl::keyboardWillHideListeners_;
142 std::map<int32_t, std::vector<sptr<IKeyboardDidShowListener>>> WindowSessionImpl::keyboardDidShowListeners_;
143 std::map<int32_t, std::vector<sptr<IKeyboardDidHideListener>>> WindowSessionImpl::keyboardDidHideListeners_;
144 std::map<int32_t, std::vector<sptr<IScreenshotListener>>> WindowSessionImpl::screenshotListeners_;
145 std::unordered_map<int32_t, std::vector<IScreenshotAppEventListenerSptr>>
146     WindowSessionImpl::screenshotAppEventListeners_;
147 std::map<int32_t, std::vector<sptr<ITouchOutsideListener>>> WindowSessionImpl::touchOutsideListeners_;
148 std::map<int32_t, std::vector<IWindowVisibilityListenerSptr>> WindowSessionImpl::windowVisibilityChangeListeners_;
149 std::mutex WindowSessionImpl::displayIdChangeListenerMutex_;
150 std::map<int32_t, std::vector<IDisplayIdChangeListenerSptr>> WindowSessionImpl::displayIdChangeListeners_;
151 std::mutex WindowSessionImpl::systemDensityChangeListenerMutex_;
152 std::unordered_map<int32_t, std::vector<ISystemDensityChangeListenerSptr>>
153     WindowSessionImpl::systemDensityChangeListeners_;
154 std::recursive_mutex WindowSessionImpl::acrossDisplaysChangeListenerMutex_;
155 std::unordered_map<int32_t, std::vector<IAcrossDisplaysChangeListenerSptr>>
156     WindowSessionImpl::acrossDisplaysChangeListeners_;
157 std::map<int32_t, std::vector<IWindowNoInteractionListenerSptr>> WindowSessionImpl::windowNoInteractionListeners_;
158 std::map<int32_t, std::vector<sptr<IWindowTitleButtonRectChangedListener>>>
159     WindowSessionImpl::windowTitleButtonRectChangeListeners_;
160 std::map<int32_t, std::vector<sptr<IWindowRectChangeListener>>> WindowSessionImpl::windowRectChangeListeners_;
161 std::map<int32_t, std::vector<sptr<IRectChangeInGlobalDisplayListener>>>
162     WindowSessionImpl::rectChangeInGlobalDisplayListeners_;
163 std::map<int32_t, std::vector<sptr<IExtensionSecureLimitChangeListener>>>
164     WindowSessionImpl::secureLimitChangeListeners_;
165 std::map<int32_t, sptr<ISubWindowCloseListener>> WindowSessionImpl::subWindowCloseListeners_;
166 std::map<int32_t, sptr<IMainWindowCloseListener>> WindowSessionImpl::mainWindowCloseListeners_;
167 std::map<int32_t, sptr<IPreferredOrientationChangeListener>> WindowSessionImpl::preferredOrientationChangeListener_;
168 std::map<int32_t, sptr<IWindowOrientationChangeListener>> WindowSessionImpl::windowOrientationChangeListener_;
169 std::unordered_map<int32_t, std::vector<sptr<IWindowWillCloseListener>>> WindowSessionImpl::windowWillCloseListeners_;
170 std::map<int32_t, std::vector<sptr<ISwitchFreeMultiWindowListener>>> WindowSessionImpl::switchFreeMultiWindowListeners_;
171 std::map<int32_t, std::vector<sptr<IWindowHighlightChangeListener>>> WindowSessionImpl::highlightChangeListeners_;
172 std::map<int32_t, std::vector<sptr<IWindowRotationChangeListener>>> WindowSessionImpl::windowRotationChangeListeners_;
173 std::recursive_mutex WindowSessionImpl::lifeCycleListenerMutex_;
174 std::recursive_mutex WindowSessionImpl::windowStageLifeCycleListenerMutex_;
175 std::recursive_mutex WindowSessionImpl::windowChangeListenerMutex_;
176 std::recursive_mutex WindowSessionImpl::windowCrossAxisListenerMutex_;
177 std::recursive_mutex WindowSessionImpl::avoidAreaChangeListenerMutex_;
178 std::recursive_mutex WindowSessionImpl::dialogDeathRecipientListenerMutex_;
179 std::recursive_mutex WindowSessionImpl::dialogTargetTouchListenerMutex_;
180 std::recursive_mutex WindowSessionImpl::occupiedAreaChangeListenerMutex_;
181 std::recursive_mutex WindowSessionImpl::keyboardWillShowListenerMutex_;
182 std::recursive_mutex WindowSessionImpl::keyboardWillHideListenerMutex_;
183 std::recursive_mutex WindowSessionImpl::keyboardDidShowListenerMutex_;
184 std::recursive_mutex WindowSessionImpl::keyboardDidHideListenerMutex_;
185 std::recursive_mutex WindowSessionImpl::screenshotListenerMutex_;
186 std::recursive_mutex WindowSessionImpl::screenshotAppEventListenerMutex_;
187 std::recursive_mutex WindowSessionImpl::touchOutsideListenerMutex_;
188 std::recursive_mutex WindowSessionImpl::windowVisibilityChangeListenerMutex_;
189 std::recursive_mutex WindowSessionImpl::windowNoInteractionListenerMutex_;
190 std::recursive_mutex WindowSessionImpl::windowStatusChangeListenerMutex_;
191 std::recursive_mutex WindowSessionImpl::windowStatusDidChangeListenerMutex_;
192 std::recursive_mutex WindowSessionImpl::windowTitleButtonRectChangeListenerMutex_;
193 std::mutex WindowSessionImpl::displayMoveListenerMutex_;
194 std::mutex WindowSessionImpl::windowRectChangeListenerMutex_;
195 std::mutex WindowSessionImpl::rectChangeInGlobalDisplayListenerMutex_;
196 std::mutex WindowSessionImpl::secureLimitChangeListenerMutex_;
197 std::mutex WindowSessionImpl::subWindowCloseListenersMutex_;
198 std::mutex WindowSessionImpl::mainWindowCloseListenersMutex_;
199 std::recursive_mutex WindowSessionImpl::windowWillCloseListenersMutex_;
200 std::mutex WindowSessionImpl::switchFreeMultiWindowListenerMutex_;
201 std::mutex WindowSessionImpl::preferredOrientationChangeListenerMutex_;
202 std::mutex WindowSessionImpl::windowOrientationChangeListenerMutex_;
203 std::mutex WindowSessionImpl::highlightChangeListenerMutex_;
204 std::mutex WindowSessionImpl::systemBarPropertyListenerMutex_;
205 std::mutex WindowSessionImpl::waterfallModeChangeListenerMutex_;
206 std::unordered_map<int32_t, std::vector<sptr<IWaterfallModeChangeListener>>>
207     WindowSessionImpl::waterfallModeChangeListeners_;
208 std::mutex WindowSessionImpl::windowRotationChangeListenerMutex_;
209 std::map<std::string, std::pair<int32_t, sptr<WindowSessionImpl>>> WindowSessionImpl::windowSessionMap_;
210 std::shared_mutex WindowSessionImpl::windowSessionMutex_;
211 std::set<sptr<WindowSessionImpl>> g_windowExtensionSessionSet_;
212 std::shared_mutex WindowSessionImpl::windowExtensionSessionMutex_;
213 std::recursive_mutex WindowSessionImpl::subWindowSessionMutex_;
214 std::map<int32_t, std::vector<sptr<WindowSessionImpl>>> WindowSessionImpl::subWindowSessionMap_;
215 std::map<int32_t, std::vector<sptr<IWindowStatusChangeListener>>> WindowSessionImpl::windowStatusChangeListeners_;
216 std::map<int32_t, std::vector<sptr<IWindowStatusDidChangeListener>>> WindowSessionImpl::windowStatusDidChangeListeners_;
217 bool WindowSessionImpl::isUIExtensionAbilityProcess_ = false;
218 std::atomic<bool> WindowSessionImpl::defaultDensityEnabledGlobalConfig_ = false;
219 
220 #define CALL_LIFECYCLE_LISTENER(windowLifecycleCb, listeners) \
221     do {                                                      \
222         for (auto& listener : (listeners)) {                  \
223             if (listener != nullptr) {            \
224                 listener->windowLifecycleCb();    \
225             }                                                 \
226         }                                                     \
227     } while (0)
228 
229 #define CALL_LIFECYCLE_LISTENER_WITH_PARAM(windowLifecycleCb, listeners, param) \
230     do {                                                                        \
231         for (auto& listener : (listeners)) {                                    \
232             if (listener != nullptr) {                                         \
233                 listener->windowLifecycleCb(param);                 \
234             }                                                                   \
235         }                                                                       \
236     } while (0)
237 
238 #define CALL_UI_CONTENT(uiContentCb)                                           \
239     do {                                                                       \
240         std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();   \
241         if (uiContent != nullptr) {                                            \
242             uiContent->uiContentCb();                                          \
243         }                                                                      \
244     } while (0)
245 
246 #define CHECK_HOST_SESSION_RETURN_IF_NULL(hostSession)                         \
247     do {                                                                       \
248         if ((hostSession) == nullptr) {                                        \
249             TLOGE(WmsLogTag::DEFAULT, "hostSession is null");                  \
250             return;                                                            \
251         }                                                                      \
252     } while (false)
253 
254 #define CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, ret)              \
255     do {                                                                       \
256         if ((hostSession) == nullptr) {                                        \
257             TLOGE(WmsLogTag::DEFAULT, "hostSession is null");                  \
258             return ret;                                                        \
259         }                                                                      \
260     } while (false)
261 
262 #define CHECK_UI_CONTENT_RETURN_IF_NULL(uiContent)                             \
263     do {                                                                       \
264         if ((uiContent) == nullptr) {                                          \
265             TLOGE(WmsLogTag::WMS_LIFE, "uiContent is null");                   \
266             return;                                                            \
267         }                                                                      \
268     } while (false)
269 
WindowSessionImpl(const sptr<WindowOption> & option)270 WindowSessionImpl::WindowSessionImpl(const sptr<WindowOption>& option)
271 {
272     WLOGFD("[WMSCom] Constructor");
273     property_ = sptr<WindowSessionProperty>::MakeSptr();
274     WindowType optionWindowType = option->GetWindowType();
275     SessionInfo sessionInfo;
276     sessionInfo.bundleName_ = option->GetBundleName();
277     property_->SetSessionInfo(sessionInfo);
278     property_->SetWindowName(option->GetWindowName());
279     property_->SetRequestRect(option->GetWindowRect());
280     property_->SetWindowType(optionWindowType);
281     property_->SetFocusable(option->GetFocusable());
282     property_->SetTouchable(option->GetTouchable());
283     property_->SetDisplayId(option->GetDisplayId());
284     property_->SetParentId(option->GetParentId());
285     property_->SetTurnScreenOn(option->IsTurnScreenOn());
286     property_->SetKeepScreenOn(option->IsKeepScreenOn());
287     property_->SetViewKeepScreenOn(option->IsViewKeepScreenOn());
288     property_->SetWindowMode(option->GetWindowMode());
289     property_->SetWindowFlags(option->GetWindowFlags());
290     property_->SetCallingSessionId(option->GetCallingWindow());
291     property_->SetIsUIExtFirstSubWindow(option->GetIsUIExtFirstSubWindow());
292     property_->SetTopmost(option->GetWindowTopmost());
293     property_->SetSubWindowZLevel(option->GetSubWindowZLevel());
294     property_->SetZIndex(option->GetZIndex());
295     property_->SetRealParentId(option->GetRealParentId());
296     property_->SetParentWindowType(option->GetParentWindowType());
297     property_->SetUIExtensionUsage(static_cast<UIExtensionUsage>(option->GetUIExtensionUsage()));
298     property_->SetIsUIExtAnySubWindow(option->GetIsUIExtAnySubWindow());
299     property_->SetIsSystemKeyboard(option->IsSystemKeyboard());
300     property_->SetConstrainedModal(option->IsConstrainedModal());
301     property_->SetSubWindowOutlineEnabled(option->IsSubWindowOutlineEnabled());
302     layoutCallback_ = sptr<FutureCallback>::MakeSptr();
303     getTargetInfoCallback_ = sptr<FutureCallback>::MakeSptr();
304     getRotationResultFuture_ = sptr<FutureCallback>::MakeSptr();
305     updateRectCallback_ = sptr<FutureCallback>::MakeSptr();
306     isMainHandlerAvailable_ = option->GetMainHandlerAvailable();
307     isIgnoreSafeArea_ = WindowHelper::IsSubWindow(optionWindowType);
308     windowOption_ = option;
309     handler_ = std::make_shared<AppExecFwk::EventHandler>(AppExecFwk::EventRunner::GetMainEventRunner());
310 
311     RSAdapterUtil::InitRSUIDirector(rsUIDirector_, true, true);
312     if (WindowHelper::IsSubWindow(GetType())) {
313         property_->SetDecorEnable(option->GetSubWindowDecorEnable());
314     }
315     surfaceNode_ = CreateSurfaceNode(property_->GetWindowName(), optionWindowType);
316     if (surfaceNode_ != nullptr) {
317         vsyncStation_ = std::make_shared<VsyncStation>(surfaceNode_->GetId());
318     }
319     WindowHelper::SplitStringByDelimiter(
320         system::GetParameter("const.window.containerColorLists", ""), ",", containerColorList_);
321     SetDefaultDensityEnabledValue(defaultDensityEnabledGlobalConfig_);
322 }
323 
IsPcWindow() const324 bool WindowSessionImpl::IsPcWindow() const
325 {
326     return windowSystemConfig_.IsPcWindow();
327 }
328 
IsPadWindow() const329 bool WindowSessionImpl::IsPadWindow() const
330 {
331     return windowSystemConfig_.IsPadWindow();
332 }
333 
IsPcOrFreeMultiWindowCapabilityEnabled() const334 bool WindowSessionImpl::IsPcOrFreeMultiWindowCapabilityEnabled() const
335 {
336     return WindowSessionImpl::IsPcOrPadFreeMultiWindowMode() ||
337         property_->GetIsPcAppInPad() ||
338         IsDeviceFeatureCapableForFreeMultiWindow();
339 }
340 
IsPcOrPadFreeMultiWindowMode() const341 bool WindowSessionImpl::IsPcOrPadFreeMultiWindowMode() const
342 {
343     return windowSystemConfig_.IsPcWindow() || IsFreeMultiWindowMode();
344 }
345 
IsPadAndNotFreeMutiWindowCompatibleMode() const346 bool WindowSessionImpl::IsPadAndNotFreeMutiWindowCompatibleMode() const
347 {
348     return property_->GetPcAppInpadCompatibleMode() &&
349         !IsFreeMultiWindowMode();
350 }
351 
IsSceneBoardEnabled() const352 bool WindowSessionImpl::IsSceneBoardEnabled() const
353 {
354     return SceneBoardJudgement::IsSceneBoardEnabled();
355 }
356 
357 // method will be instead after ace fix
GetCompatibleModeInPc() const358 bool WindowSessionImpl::GetCompatibleModeInPc() const
359 {
360     return property_->IsAdaptToImmersive();
361 }
362 
IsAdaptToCompatibleImmersive() const363 bool WindowSessionImpl::IsAdaptToCompatibleImmersive() const
364 {
365     auto property = GetPropertyByContext();
366     return property->IsAdaptToImmersive();
367 }
368 
IsAdaptToSimulationScale() const369 bool WindowSessionImpl::IsAdaptToSimulationScale() const
370 {
371     auto property = GetPropertyByContext();
372     return property->IsAdaptToSimulationScale();
373 }
374 
IsAdaptToProportionalScale() const375 bool WindowSessionImpl::IsAdaptToProportionalScale() const
376 {
377     auto property = GetPropertyByContext();
378     return property->IsAdaptToProportionalScale();
379 }
380 
IsInCompatScaleMode() const381 bool WindowSessionImpl::IsInCompatScaleMode() const
382 {
383     auto property = GetPropertyByContext();
384     return property->IsAdaptToSimulationScale() || property->IsAdaptToProportionalScale();
385 }
386 
IsInCompatScaleStatus() const387 bool WindowSessionImpl::IsInCompatScaleStatus() const
388 {
389     return IsInCompatScaleMode() && (!NearEqual(compatScaleX_, 1.0f) || !NearEqual(compatScaleY_, 1.0f));
390 }
391 
IsAdaptToSubWindow() const392 bool WindowSessionImpl::IsAdaptToSubWindow() const
393 {
394     auto property = GetPropertyByContext();
395     return property->IsAdaptToSubWindow();
396 }
397 
MakeSubOrDialogWindowDragableAndMoveble()398 void WindowSessionImpl::MakeSubOrDialogWindowDragableAndMoveble()
399 {
400     if (IsPcOrFreeMultiWindowCapabilityEnabled() && windowOption_ != nullptr) {
401         TLOGI(WmsLogTag::WMS_PC, "Called %{public}d.", GetPersistentId());
402         // The context of the UEC child window is not the context of the main window
403         auto mainWindow = FindMainWindowWithContext();
404         // The child Windows created by compatible applications are mounted within the parent window,
405         // with the same specifications as the mobile phone. No child Windows with title bars are created
406         if (mainWindow && mainWindow->IsAdaptToSubWindow()) {
407             TLOGE(WmsLogTag::WMS_COMPAT, "compat sub window not has title");
408             return;
409         }
410         if (WindowHelper::IsSubWindow(property_->GetWindowType())) {
411             TLOGI(WmsLogTag::WMS_PC, "create subwindow, title: %{public}s, decorEnable: %{public}d",
412                 windowOption_->GetSubWindowTitle().c_str(), windowOption_->GetSubWindowDecorEnable());
413             property_->SetDecorEnable(windowOption_->GetSubWindowDecorEnable());
414             property_->SetDragEnabled(windowOption_->GetSubWindowDecorEnable());
415             UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_DRAGENABLED);
416             subWindowTitle_ = windowOption_->GetSubWindowTitle();
417         }
418         bool isDialog = WindowHelper::IsDialogWindow(property_->GetWindowType());
419         if (isDialog) {
420             bool dialogDecorEnable = windowOption_->GetDialogDecorEnable();
421             property_->SetDecorEnable(dialogDecorEnable);
422             property_->SetDragEnabled(dialogDecorEnable);
423             UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_DRAGENABLED);
424             dialogTitle_ = windowOption_->GetDialogTitle();
425             TLOGI(WmsLogTag::WMS_PC, "create dialogWindow, title: %{public}s, decorEnable: %{public}d",
426                 dialogTitle_.c_str(), dialogDecorEnable);
427         }
428     }
429 }
430 
SetSubWindowZLevelToProperty()431 void WindowSessionImpl::SetSubWindowZLevelToProperty()
432 {
433     if (WindowHelper::IsNormalSubWindow(property_->GetWindowType(), property_->GetWindowFlags())) {
434         property_->SetSubWindowZLevel(windowOption_->GetSubWindowZLevel());
435     }
436 }
437 
CreateSurfaceNode(const std::string & name,WindowType type)438 RSSurfaceNode::SharedPtr WindowSessionImpl::CreateSurfaceNode(const std::string& name, WindowType type)
439 {
440     struct RSSurfaceNodeConfig rsSurfaceNodeConfig;
441     rsSurfaceNodeConfig.SurfaceNodeName = name;
442     RSSurfaceNodeType rsSurfaceNodeType = RSSurfaceNodeType::DEFAULT;
443     switch (type) {
444         case WindowType::WINDOW_TYPE_BOOT_ANIMATION:
445         case WindowType::WINDOW_TYPE_POINTER:
446             rsSurfaceNodeType = RSSurfaceNodeType::SELF_DRAWING_WINDOW_NODE;
447             break;
448         case WindowType::WINDOW_TYPE_APP_MAIN_WINDOW:
449             rsSurfaceNodeType = RSSurfaceNodeType::APP_WINDOW_NODE;
450             break;
451         case WindowType::WINDOW_TYPE_UI_EXTENSION:
452             TLOGD(WmsLogTag::WMS_UIEXT, "uiExtensionUsage=%{public}u", property_->GetUIExtensionUsage());
453             if (SessionHelper::IsSecureUIExtension(property_->GetUIExtensionUsage())) {
454                 rsSurfaceNodeType = RSSurfaceNodeType::UI_EXTENSION_SECURE_NODE;
455             } else {
456                 rsSurfaceNodeType = RSSurfaceNodeType::UI_EXTENSION_COMMON_NODE;
457             }
458             break;
459         case WindowType::WINDOW_TYPE_PIP:
460             rsSurfaceNodeType = RSSurfaceNodeType::APP_WINDOW_NODE;
461             break;
462         case WindowType::WINDOW_TYPE_MAGNIFICATION:
463             rsSurfaceNodeType = RSSurfaceNodeType::ABILITY_MAGNIFICATION_NODE;
464             break;
465         default:
466             rsSurfaceNodeType = RSSurfaceNodeType::DEFAULT;
467             break;
468     }
469     auto surfaceNode = RSSurfaceNode::Create(
470         rsSurfaceNodeConfig, rsSurfaceNodeType, true, property_->IsConstrainedModal(), GetRSUIContext());
471     RSAdapterUtil::SetSkipCheckInMultiInstance(surfaceNode, true);
472     TLOGD(WmsLogTag::WMS_SCB, "Create RSSurfaceNode: %{public}s, name: %{public}s",
473           RSAdapterUtil::RSNodeToStr(surfaceNode).c_str(), name.c_str());
474     return surfaceNode;
475 }
476 
~WindowSessionImpl()477 WindowSessionImpl::~WindowSessionImpl()
478 {
479     WLOGFD("[WMSCom] id: %{public}d", GetPersistentId());
480     Destroy(true, false);
481 }
482 
GetWindowId() const483 uint32_t WindowSessionImpl::GetWindowId() const
484 {
485     return static_cast<uint32_t>(GetPersistentId()) & 0xffffffff; // 0xffffffff: to get low 32 bits
486 }
487 
GetDisplayId() const488 uint64_t WindowSessionImpl::GetDisplayId() const
489 {
490     return property_->GetDisplayId();
491 }
492 
GetParentId() const493 int32_t WindowSessionImpl::GetParentId() const
494 {
495     // 0xffffffff: to get low 32 bits
496     uint32_t parentID = static_cast<uint32_t>(property_->GetParentPersistentId()) & 0x7fffffff;
497     return static_cast<int32_t>(parentID);
498 }
499 
IsWindowSessionInvalid() const500 bool WindowSessionImpl::IsWindowSessionInvalid() const
501 {
502     bool res = ((GetHostSession() == nullptr) || (GetPersistentId() == INVALID_SESSION_ID) ||
503         (state_ == WindowState::STATE_DESTROYED));
504     if (res) {
505         TLOGW(WmsLogTag::WMS_LIFE, "already destroyed or not created! id: %{public}d state_: %{public}u",
506             GetPersistentId(), state_);
507     }
508     return res;
509 }
510 
IsMainHandlerAvailable() const511 bool WindowSessionImpl::IsMainHandlerAvailable() const
512 {
513     TLOGI(WmsLogTag::DEFAULT, "id:%{public}d, isAvailable:%{public}u",
514         GetPersistentId(), isMainHandlerAvailable_);
515     return isMainHandlerAvailable_;
516 }
517 
GetPersistentId() const518 int32_t WindowSessionImpl::GetPersistentId() const
519 {
520     return property_->GetPersistentId();
521 }
522 
GetProperty() const523 sptr<WindowSessionProperty> WindowSessionImpl::GetProperty() const
524 {
525     return property_;
526 }
527 
GetSystemSessionConfig() const528 SystemSessionConfig WindowSessionImpl::GetSystemSessionConfig() const
529 {
530     return windowSystemConfig_;
531 }
532 
GetHostSession() const533 sptr<ISession> WindowSessionImpl::GetHostSession() const
534 {
535     std::lock_guard<std::mutex> lock(hostSessionMutex_);
536     return hostSession_;
537 }
538 
GetColorSpaceFromSurfaceGamut(GraphicColorGamut colorGamut)539 ColorSpace WindowSessionImpl::GetColorSpaceFromSurfaceGamut(GraphicColorGamut colorGamut)
540 {
541     if (colorGamut == GraphicColorGamut::GRAPHIC_COLOR_GAMUT_SRGB) {
542         return ColorSpace::COLOR_SPACE_DEFAULT;
543     } else if (colorGamut == GraphicColorGamut::GRAPHIC_COLOR_GAMUT_DCI_P3) {
544         return ColorSpace::COLOR_SPACE_WIDE_GAMUT;
545     } else {
546         WLOGFE("try to get not exist ColorSpace");
547         return ColorSpace::COLOR_SPACE_DEFAULT;
548     }
549 }
550 
GetSurfaceGamutFromColorSpace(ColorSpace colorSpace)551 GraphicColorGamut WindowSessionImpl::GetSurfaceGamutFromColorSpace(ColorSpace colorSpace)
552 {
553     if (colorSpace == ColorSpace::COLOR_SPACE_DEFAULT) {
554         return GraphicColorGamut::GRAPHIC_COLOR_GAMUT_SRGB;
555     } else if (colorSpace == ColorSpace::COLOR_SPACE_WIDE_GAMUT) {
556         return GraphicColorGamut::GRAPHIC_COLOR_GAMUT_DCI_P3;
557     } else {
558         WLOGFE("try to get not exist colorGamut");
559         return GraphicColorGamut::GRAPHIC_COLOR_GAMUT_SRGB;
560     }
561 }
562 
IsSupportWideGamut()563 bool WindowSessionImpl::IsSupportWideGamut()
564 {
565     return true;
566 }
567 
SetColorSpace(ColorSpace colorSpace)568 void WindowSessionImpl::SetColorSpace(ColorSpace colorSpace)
569 {
570     if (IsWindowSessionInvalid() || surfaceNode_ == nullptr) {
571         TLOGE(WmsLogTag::DEFAULT, "session is invalid");
572         return;
573     }
574     auto colorGamut = GetSurfaceGamutFromColorSpace(colorSpace);
575     surfaceNode_->SetColorSpace(colorGamut);
576 }
577 
GetColorSpace()578 ColorSpace WindowSessionImpl::GetColorSpace()
579 {
580     if (IsWindowSessionInvalid() || surfaceNode_ == nullptr) {
581         TLOGE(WmsLogTag::DEFAULT, "session is invalid");
582         return ColorSpace::COLOR_SPACE_DEFAULT;
583     }
584     GraphicColorGamut colorGamut = surfaceNode_->GetColorSpace();
585     return GetColorSpaceFromSurfaceGamut(colorGamut);
586 }
587 
WindowSessionCreateCheck()588 WMError WindowSessionImpl::WindowSessionCreateCheck()
589 {
590     if (vsyncStation_ == nullptr || !vsyncStation_->IsVsyncReceiverCreated()) {
591         return WMError::WM_ERROR_NULLPTR;
592     }
593     const auto& name = property_->GetWindowName();
594     std::shared_lock<std::shared_mutex> lock(windowSessionMutex_);
595     // check window name, same window names are forbidden
596     if (windowSessionMap_.find(name) != windowSessionMap_.end()) {
597         WLOGFE("WindowName(%{public}s) already exists.", name.c_str());
598         return WMError::WM_ERROR_REPEAT_OPERATION;
599     }
600 
601     // check if camera floating window is already exists
602     if (property_->GetWindowType() == WindowType::WINDOW_TYPE_FLOAT_CAMERA ||
603         property_->GetWindowType() == WindowType::WINDOW_TYPE_PIP) {
604         for (const auto& item : windowSessionMap_) {
605             if (item.second.second && item.second.second->property_ &&
606                 item.second.second->property_->GetWindowType() == WindowType::WINDOW_TYPE_FLOAT_CAMERA) {
607                     WLOGFE("Camera floating window is already exists.");
608                 return WMError::WM_ERROR_REPEAT_OPERATION;
609             }
610         }
611         uint32_t accessTokenId = static_cast<uint32_t>(IPCSkeleton::GetCallingTokenID());
612         property_->SetAccessTokenId(accessTokenId);
613         TLOGI(WmsLogTag::DEFAULT, "Create camera float window, TokenId=%{private}u", accessTokenId);
614     }
615     return WMError::WM_OK;
616 }
617 
SetDefaultDisplayIdIfNeed()618 void WindowSessionImpl::SetDefaultDisplayIdIfNeed()
619 {
620     TLOGD(WmsLogTag::DEFAULT, "in");
621     auto displayId = property_->GetDisplayId();
622     if (displayId == DISPLAY_ID_INVALID) {
623         auto defaultDisplayId = SingletonContainer::IsDestroyed() ? DISPLAY_ID_INVALID :
624             SingletonContainer::Get<DisplayManager>().GetDefaultDisplayId();
625         defaultDisplayId = (defaultDisplayId == DISPLAY_ID_INVALID) ? 0 : defaultDisplayId;
626         property_->SetDisplayId(defaultDisplayId);
627         property_->SetIsFollowParentWindowDisplayId(true);
628         TLOGI(WmsLogTag::DEFAULT, "%{public}" PRIu64, defaultDisplayId);
629     }
630 }
631 
632 /** @note @window.hierarchy */
GetSubWindowZLevelByFlags(WindowType type,uint32_t windowFlags,bool isTopmost)633 int32_t WindowSessionImpl::GetSubWindowZLevelByFlags(WindowType type, uint32_t windowFlags, bool isTopmost)
634 {
635     if (WindowHelper::IsApplicationModalSubWindow(type, windowFlags)) {
636         if (isTopmost) {
637             return APPLICATION_MODALITY_SUB_WINDOW_Z_LEVEL + TOPMOST_SUB_WINDOW_Z_LEVEL;
638         }
639         return APPLICATION_MODALITY_SUB_WINDOW_Z_LEVEL;
640     } else if (WindowHelper::IsModalSubWindow(type, windowFlags)) {
641         if (isTopmost) {
642             return MODALITY_SUB_WINDOW_Z_LEVEL + TOPMOST_SUB_WINDOW_Z_LEVEL;
643         }
644         return MODALITY_SUB_WINDOW_Z_LEVEL;
645     } else if (WindowHelper::IsToastSubWindow(type, windowFlags)) {
646         return TOAST_SUB_WINDOW_Z_LEVEL;
647     } else if (WindowHelper::IsTextMenuSubWindow(type, windowFlags)) {
648         return TEXT_MENU_SUB_WINDOW_Z_LEVEL;
649     } else if (WindowHelper::IsDialogWindow(type)) {
650         return DIALOG_SUB_WINDOW_Z_LEVEL;
651     }
652     return NORMAL_SUB_WINDOW_Z_LEVEL;
653 }
654 
Connect()655 WMError WindowSessionImpl::Connect()
656 {
657     TLOGI(WmsLogTag::WMS_LIFE, "in");
658     auto hostSession = GetHostSession();
659     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_NULLPTR);
660     sptr<ISessionStage> iSessionStage(this);
661     auto windowEventChannel = sptr<WindowEventChannel>::MakeSptr(iSessionStage);
662     windowEventChannel->SetIsUIExtension(property_->GetWindowType() == WindowType::WINDOW_TYPE_UI_EXTENSION);
663     windowEventChannel->SetUIExtensionUsage(property_->GetUIExtensionUsage());
664     sptr<IWindowEventChannel> iWindowEventChannel(windowEventChannel);
665     auto context = GetContext();
666     sptr<IRemoteObject> token = context ? context->GetToken() : nullptr;
667     if (token) {
668         property_->SetTokenState(true);
669     }
670     auto ret = hostSession->Connect(
671         iSessionStage, iWindowEventChannel, surfaceNode_, windowSystemConfig_, property_,
672         token, identityToken_);
673     if (SysCapUtil::GetBundleName() != AppExecFwk::Constants::SCENE_BOARD_BUNDLE_NAME &&
674         WindowHelper::IsMainWindow(GetType())) {
675         auto startTime = std::chrono::duration_cast<std::chrono::milliseconds>(
676             std::chrono::system_clock::now().time_since_epoch()).count();
677         updateRectCallback_->GetUpdateRectResult(WINDOW_CONNECT_TIMEOUT);
678         auto endTime = std::chrono::duration_cast<std::chrono::milliseconds>(
679             std::chrono::system_clock::now().time_since_epoch()).count();
680         auto waitTime = endTime - startTime;
681         if (waitTime >= WINDOW_CONNECT_TIMEOUT) {
682             TLOGW(WmsLogTag::WMS_LIFE, "Connect timeout, persistentId:%{public}d", GetPersistentId());
683         }
684     }
685     TLOGI(WmsLogTag::WMS_LIFE, "Window Connect [name:%{public}s, id:%{public}d, type:%{public}u], ret:%{public}u",
686         property_->GetWindowName().c_str(), GetPersistentId(), property_->GetWindowType(), ret);
687     if (IsInCompatScaleMode() || WindowHelper::IsUIExtensionWindow(GetType())) {
688         RegisterWindowScaleCallback();
689     }
690     return static_cast<WMError>(ret);
691 }
692 
GetWindowWithId(uint32_t windowId)693 sptr<WindowSessionImpl> WindowSessionImpl::GetWindowWithId(uint32_t windowId)
694 {
695     std::shared_lock<std::shared_mutex> lock(windowSessionMutex_);
696     if (windowSessionMap_.empty()) {
697         TLOGD(WmsLogTag::WMS_SYSTEM, "Please create mainWindow First!");
698         return nullptr;
699     }
700     for (const auto& [_, pair] : windowSessionMap_) {
701         auto& window = pair.second;
702         if (window && windowId == window->GetWindowId()) {
703             TLOGD(WmsLogTag::WMS_SYSTEM, "find window %{public}s, id %{public}d",
704                 window->GetWindowName().c_str(), windowId);
705             return window;
706         }
707     }
708     TLOGD(WmsLogTag::WMS_SYSTEM, "Cannot find Window!");
709     return nullptr;
710 }
711 
GetScaleWindow(uint32_t windowId)712 sptr<WindowSessionImpl> WindowSessionImpl::GetScaleWindow(uint32_t windowId)
713 {
714     sptr<WindowSessionImpl> window = GetWindowWithId(windowId);
715     if (window) {
716         TLOGD(WmsLogTag::WMS_COMPAT, "find window id:%{public}d", windowId);
717         return window;
718     }
719     if (isUIExtensionAbilityProcess_) {
720         std::shared_lock<std::shared_mutex> lock(windowExtensionSessionMutex_);
721         for (const auto& window : GetWindowExtensionSessionSet()) {
722             if (window && static_cast<uint32_t>(window->GetProperty()->GetParentId()) == windowId) {
723                 TLOGD(WmsLogTag::WMS_COMPAT, "find extension window id:%{public}d", window->GetPersistentId());
724                 return window;
725             }
726         }
727     }
728     {
729         std::shared_lock<std::shared_mutex> lock(windowSessionMutex_);
730         for (const auto& [_, pair] : windowSessionMap_) {
731             auto& window = pair.second;
732             if (window && window->IsFocused()) {
733                 TLOGD(WmsLogTag::WMS_COMPAT, "find focus window id:%{public}d", window->GetPersistentId());
734                 return window;
735             }
736         }
737     }
738     return nullptr;
739 }
740 
GetWindowScaleCoordinate(uint32_t windowId,CursorInfo & cursorInfo)741 WMError WindowSessionImpl::GetWindowScaleCoordinate(uint32_t windowId, CursorInfo& cursorInfo)
742 {
743     sptr<WindowSessionImpl> window = GetScaleWindow(windowId);
744     if (!window) {
745         TLOGE(WmsLogTag::WMS_COMPAT, "find window id:%{public}d failed", windowId);
746         return WMError::WM_ERROR_INVALID_WINDOW;
747     }
748     auto windowType = window->GetType();
749     if (WindowHelper::IsSubWindow(windowType)) {
750         if (window->GetProperty()->GetIsUIExtensionAbilityProcess()) {
751             TLOGD(WmsLogTag::WMS_COMPAT, "id:%{public}d extension sub window", windowId);
752             return WMError::WM_OK;
753         }
754         window = window->FindMainWindowWithContext();
755     }
756     if (!window || !window->IsInCompatScaleStatus()) {
757         TLOGD(WmsLogTag::WMS_COMPAT, "window id:%{public}d not scale", windowId);
758         return WMError::WM_OK;
759     }
760     Rect windowRect = window->GetRect();
761     if (WindowHelper::IsUIExtensionWindow(windowType)) {
762         windowRect = window->GetHostWindowRect(windowId);
763     }
764     float scaleX = window->compatScaleX_;
765     float scaleY = window->compatScaleY_;
766     int32_t cursorX = cursorInfo.left - windowRect.posX_;
767     int32_t cursorY = cursorInfo.top - windowRect.posY_;
768     // 2: x scale computational formula
769     cursorInfo.left = round(windowRect.posX_ + scaleX * cursorX + (1 - scaleX) * windowRect.width_ / 2);
770     // 2: y scale computational formula
771     cursorInfo.top = round(windowRect.posY_ + scaleY * cursorY + (1 - scaleY) * windowRect.height_ / 2);
772     cursorInfo.width *= scaleX;
773     cursorInfo.height *= scaleY;
774     return WMError::WM_OK;
775 }
776 
RegisterWindowScaleCallback()777 void WindowSessionImpl::RegisterWindowScaleCallback()
778 {
779     static bool isRegister = false;
780     if (isRegister) {
781         TLOGD(WmsLogTag::WMS_COMPAT, "not registered");
782         return;
783     }
784 #ifdef IMF_ENABLE
785     auto instance = MiscServices::InputMethodController::GetInstance();
786     if (!instance) {
787         TLOGD(WmsLogTag::WMS_COMPAT, "get inputMethod instance failed");
788         return;
789     }
790     auto callback = [] (uint32_t windowId, MiscServices::CursorInfo& cursorInfo) {
791         CursorInfo info = { cursorInfo.left, cursorInfo.top, cursorInfo.width, cursorInfo.height };
792         WMError ret = GetWindowScaleCoordinate(windowId, info);
793         cursorInfo = { info.left, info.top, info.width, info.height };
794         return static_cast<int32_t>(ret);
795     };
796     instance->RegisterWindowScaleCallbackHandler(std::move(callback));
797 #endif
798     isRegister = true;
799 }
800 
ConsumePointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)801 void WindowSessionImpl::ConsumePointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
802 {
803     NotifyPointerEvent(pointerEvent);
804 }
805 
ConsumeKeyEvent(std::shared_ptr<MMI::KeyEvent> & keyEvent)806 void WindowSessionImpl::ConsumeKeyEvent(std::shared_ptr<MMI::KeyEvent>& keyEvent)
807 {
808     bool isConsumed = false;
809     NotifyKeyEvent(keyEvent, isConsumed, false);
810 }
811 
ConsumeBackEvent()812 void WindowSessionImpl::ConsumeBackEvent()
813 {
814     TLOGI(WmsLogTag::WMS_EVENT, "in");
815     HandleBackEvent();
816 }
817 
IsDialogSessionBackGestureEnabled()818 bool WindowSessionImpl::IsDialogSessionBackGestureEnabled()
819 {
820     return dialogSessionBackGestureEnabled_;
821 }
822 
PreNotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent)823 bool WindowSessionImpl::PreNotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
824 {
825     TLOGI(WmsLogTag::WMS_EVENT, "id: %{public}d", keyEvent->GetId());
826     if (auto uiContent = GetUIContentSharedPtr()) {
827         return uiContent->ProcessKeyEvent(keyEvent, true);
828     }
829     return false;
830 }
831 
NotifyOnKeyPreImeEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent)832 bool WindowSessionImpl::NotifyOnKeyPreImeEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
833 {
834     return PreNotifyKeyEvent(keyEvent);
835 }
836 
GetSubWindows(int32_t parentPersistentId,std::vector<sptr<WindowSessionImpl>> & subWindows)837 void WindowSessionImpl::GetSubWindows(int32_t parentPersistentId, std::vector<sptr<WindowSessionImpl>>& subWindows)
838 {
839     std::lock_guard<std::recursive_mutex> lock(subWindowSessionMutex_);
840     auto iter = subWindowSessionMap_.find(parentPersistentId);
841     if (iter == subWindowSessionMap_.end()) {
842         TLOGD(WmsLogTag::WMS_SUB, "parent window: %{public}d has no child node", parentPersistentId);
843         return;
844     }
845     subWindows = iter->second;
846 }
847 
UpdateSubWindowStateAndNotify(int32_t parentPersistentId,const WindowState newState)848 void WindowSessionImpl::UpdateSubWindowStateAndNotify(int32_t parentPersistentId, const WindowState newState)
849 {
850     std::vector<sptr<WindowSessionImpl>> subWindows;
851     GetSubWindows(parentPersistentId, subWindows);
852     if (subWindows.empty()) {
853         TLOGD(WmsLogTag::WMS_SUB, "parent window: %{public}d, its subWindowMap is empty", parentPersistentId);
854         return;
855     }
856 
857     // when parent window hide and subwindow whose state is shown should hide and notify user
858     if (newState == WindowState::STATE_HIDDEN) {
859         for (auto subwindow : subWindows) {
860             if (subwindow != nullptr && subwindow->GetWindowState() == WindowState::STATE_SHOWN) {
861                 subwindow->state_ = WindowState::STATE_HIDDEN;
862                 subwindow->NotifyAfterBackground();
863                 TLOGD(WmsLogTag::WMS_SUB, "Notify subWindow background, id:%{public}d", subwindow->GetPersistentId());
864                 UpdateSubWindowStateAndNotify(subwindow->GetPersistentId(), newState);
865             }
866         }
867     // when parent window show and subwindow whose state is shown should show and notify user
868     } else if (newState == WindowState::STATE_SHOWN) {
869         for (auto subwindow : subWindows) {
870             if (subwindow != nullptr && subwindow->GetWindowState() == WindowState::STATE_HIDDEN &&
871                 subwindow->GetRequestWindowState() == WindowState::STATE_SHOWN) {
872                 subwindow->state_ = WindowState::STATE_SHOWN;
873                 subwindow->NotifyAfterForeground();
874                 TLOGD(WmsLogTag::WMS_SUB, "Notify subWindow foreground, id:%{public}d", subwindow->GetPersistentId());
875                 UpdateSubWindowStateAndNotify(subwindow->GetPersistentId(), newState);
876             }
877         }
878     }
879 }
880 
Show(uint32_t reason,bool withAnimation,bool withFocus)881 WMError WindowSessionImpl::Show(uint32_t reason, bool withAnimation, bool withFocus)
882 {
883     return Show(reason, withAnimation, withFocus, false);
884 }
885 
Show(uint32_t reason,bool withAnimation,bool withFocus,bool waitAttach)886 WMError WindowSessionImpl::Show(uint32_t reason, bool withAnimation, bool withFocus, bool waitAttach)
887 {
888     TLOGI(WmsLogTag::WMS_LIFE, "name:%{public}s, id:%{public}d, type:%{public}u, reason:%{public}u, state:%{public}u",
889         property_->GetWindowName().c_str(), property_->GetPersistentId(), GetType(), reason, state_);
890     if (IsWindowSessionInvalid()) {
891         WLOGFE("session is invalid");
892         return WMError::WM_ERROR_INVALID_WINDOW;
893     }
894     if (state_ == WindowState::STATE_SHOWN) {
895         TLOGD(WmsLogTag::WMS_LIFE, "alreay shown [name:%{public}s, id:%{public}d, type: %{public}u]",
896             property_->GetWindowName().c_str(), GetPersistentId(), property_->GetWindowType());
897         NotifyAfterForeground(true, false);
898         return WMError::WM_OK;
899     }
900 
901     auto hostSession = GetHostSession();
902     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
903     WSError ret = hostSession->Foreground(property_);
904     // delete after replace WSError with WMError
905     WMError res = static_cast<WMError>(ret);
906     if (res == WMError::WM_OK) {
907         UpdateSubWindowStateAndNotify(GetPersistentId(), WindowState::STATE_SHOWN);
908         state_ = WindowState::STATE_SHOWN;
909         requestState_ = WindowState::STATE_SHOWN;
910         NotifyAfterForeground();
911     } else {
912         NotifyForegroundFailed(res);
913     }
914     return res;
915 }
916 
Hide(uint32_t reason,bool withAnimation,bool isFromInnerkits)917 WMError WindowSessionImpl::Hide(uint32_t reason, bool withAnimation, bool isFromInnerkits)
918 {
919     return Hide(reason, withAnimation, isFromInnerkits, false);
920 }
921 
Hide(uint32_t reason,bool withAnimation,bool isFromInnerkits,bool waitDetach)922 WMError WindowSessionImpl::Hide(uint32_t reason, bool withAnimation, bool isFromInnerkits, bool waitDetach)
923 {
924     TLOGI(WmsLogTag::WMS_LIFE, "id:%{public}d Hide, reason:%{public}u, state:%{public}u",
925         GetPersistentId(), reason, state_);
926     if (IsWindowSessionInvalid()) {
927         WLOGFE("session is invalid");
928         return WMError::WM_ERROR_INVALID_WINDOW;
929     }
930     if (state_ == WindowState::STATE_HIDDEN || state_ == WindowState::STATE_CREATED) {
931         TLOGD(WmsLogTag::WMS_LIFE, "alreay hidden [name:%{public}s, id:%{public}d, type: %{public}u]",
932             property_->GetWindowName().c_str(), GetPersistentId(), property_->GetWindowType());
933         NotifyBackgroundFailed(WMError::WM_DO_NOTHING);
934         return WMError::WM_OK;
935     }
936     UpdateSubWindowStateAndNotify(GetPersistentId(), WindowState::STATE_HIDDEN);
937     state_ = WindowState::STATE_HIDDEN;
938     requestState_ = WindowState::STATE_HIDDEN;
939     NotifyAfterBackground();
940     return WMError::WM_OK;
941 }
942 
RemoveSubWindow(int32_t parentPersistentId)943 void WindowSessionImpl::RemoveSubWindow(int32_t parentPersistentId)
944 {
945     const int32_t persistentId = GetPersistentId();
946     TLOGI(WmsLogTag::WMS_SUB, "Id: %{public}d, parentId: %{public}d", persistentId, parentPersistentId);
947     std::lock_guard<std::recursive_mutex> lock(subWindowSessionMutex_);
948     auto subIter = subWindowSessionMap_.find(parentPersistentId);
949     if (subIter == subWindowSessionMap_.end()) {
950         TLOGW(WmsLogTag::WMS_SUB, "find parentPersistentId: %{public}d failed", parentPersistentId);
951         return;
952     }
953     auto& subWindows = subIter->second;
954     for (auto iter = subWindows.begin(); iter != subWindows.end(); iter++) {
955         auto subWindow = *iter;
956         if (subWindow != nullptr && subWindow->GetPersistentId() == persistentId) {
957             TLOGD(WmsLogTag::WMS_SUB, "erase persistentId: %{public}d", persistentId);
958             subWindows.erase(iter);
959             break;
960         } else {
961             TLOGD(WmsLogTag::WMS_SUB, "Exists other sub window, persistentId: %{public}d", persistentId);
962         }
963     }
964 }
965 
DestroySubWindow()966 void WindowSessionImpl::DestroySubWindow()
967 {
968     int32_t parentPersistentId = property_->GetParentPersistentId();
969     const int32_t persistentId = GetPersistentId();
970     if (property_->GetIsUIExtFirstSubWindow()) {
971         auto extensionWindow = FindExtensionWindowWithContext();
972         if (extensionWindow != nullptr) {
973             parentPersistentId = extensionWindow->GetPersistentId();
974         }
975     }
976     // remove from subWindowMap_ when destroy sub window
977     RemoveSubWindow(parentPersistentId);
978     {
979         std::lock_guard<std::recursive_mutex> lock(subWindowSessionMutex_);
980         auto subIter = subWindowSessionMap_.find(parentPersistentId);
981         if (subIter != subWindowSessionMap_.end() && property_->GetIsUIExtFirstSubWindow() &&
982             subWindowSessionMap_.empty()) {
983             auto extensionWindow = FindExtensionWindowWithContext();
984             if (extensionWindow != nullptr && extensionWindow->GetUIContentSharedPtr() == nullptr) {
985                 extensionWindow->AddSetUIExtensionDestroyTimeoutCheck();
986             }
987         }
988     }
989     // remove from subWindowMap_ when destroy parent window
990     std::vector<sptr<WindowSessionImpl>> subWindows;
991     GetSubWindows(persistentId, subWindows);
992     for (auto iter = subWindows.begin(); iter != subWindows.end(); iter = subWindows.begin()) {
993         auto subWindow = *iter;
994         if (subWindow == nullptr) {
995             TLOGW(WmsLogTag::WMS_SUB, "Destroy sub window which is nullptr");
996             subWindows.erase(iter);
997             continue;
998         }
999         bool isExtDestroyed = subWindow->property_->GetIsUIExtFirstSubWindow();
1000         TLOGD(WmsLogTag::WMS_SUB, "Destroy sub window, persistentId: %{public}d, isExtDestroyed: %{public}d",
1001             subWindow->GetPersistentId(), isExtDestroyed);
1002         auto ret = subWindow->Destroy(isExtDestroyed);
1003         if (ret != WMError::WM_OK) {
1004             TLOGE(WmsLogTag::WMS_SUB, "Destroy failed. persistentId: %{public}d", subWindow->GetPersistentId());
1005             subWindows.erase(iter);
1006         }
1007     }
1008     {
1009         std::lock_guard<std::recursive_mutex> lock(subWindowSessionMutex_);
1010         auto mainIter = subWindowSessionMap_.find(persistentId);
1011         if (mainIter != subWindowSessionMap_.end()) {
1012             mainIter->second.clear();
1013             subWindowSessionMap_.erase(mainIter);
1014         }
1015     }
1016 }
1017 
Destroy(bool needNotifyServer,bool needClearListener,uint32_t reason)1018 WMError WindowSessionImpl::Destroy(bool needNotifyServer, bool needClearListener, uint32_t reason)
1019 {
1020     TLOGI(WmsLogTag::WMS_LIFE, "id:%{public}d Destroy, state:%{public}u, needNotifyServer:%{public}d, "
1021         "needClearListener:%{public}d, reason:%{public}u", GetPersistentId(), state_, needNotifyServer,
1022         needClearListener, reason);
1023     if (IsWindowSessionInvalid()) {
1024         WLOGFW("session is invalid");
1025         return WMError::WM_ERROR_INVALID_WINDOW;
1026     }
1027     if (auto hostSession = GetHostSession()) {
1028         hostSession->Disconnect();
1029     }
1030     NotifyBeforeDestroy(GetWindowName());
1031     {
1032         std::lock_guard<std::recursive_mutex> lock(mutex_);
1033         state_ = WindowState::STATE_DESTROYED;
1034         requestState_ = WindowState::STATE_DESTROYED;
1035     }
1036     DestroySubWindow();
1037     {
1038         std::lock_guard<std::mutex> lock(hostSessionMutex_);
1039         hostSession_ = nullptr;
1040     }
1041     {
1042         std::unique_lock<std::shared_mutex> lock(windowSessionMutex_);
1043         windowSessionMap_.erase(property_->GetWindowName());
1044     }
1045     NotifyAfterDestroy();
1046     if (needClearListener) {
1047         ClearListenersById(GetPersistentId());
1048     }
1049     auto context = GetContext();
1050     if (context) {
1051         context.reset();
1052     }
1053     ClearVsyncStation();
1054     return WMError::WM_OK;
1055 }
1056 
Destroy(uint32_t reason)1057 WMError WindowSessionImpl::Destroy(uint32_t reason)
1058 {
1059     return Destroy(true, true, reason);
1060 }
1061 
SetActive(bool active)1062 WSError WindowSessionImpl::SetActive(bool active)
1063 {
1064     WLOGFD("active status: %{public}d", active);
1065     if (active) {
1066         NotifyAfterActive();
1067     } else {
1068         NotifyAfterInactive();
1069     }
1070     return WSError::WS_OK;
1071 }
1072 
1073 /** @note @window.layout */
UpdateRect(const WSRect & rect,SizeChangeReason reason,const SceneAnimationConfig & config,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)1074 WSError WindowSessionImpl::UpdateRect(const WSRect& rect, SizeChangeReason reason,
1075     const SceneAnimationConfig& config, const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
1076 {
1077     // delete after replace ws_common.h with wm_common.h
1078     auto wmReason = static_cast<WindowSizeChangeReason>(reason);
1079     Rect wmRect = { rect.posX_, rect.posY_, rect.width_, rect.height_ };
1080     auto preRect = GetRect();
1081     if (preRect.width_ != wmRect.width_ || preRect.height_ != wmRect.height_) {
1082         windowSizeChanged_ = true;
1083     }
1084     property_->SetWindowRect(wmRect);
1085     property_->SetRequestRect(wmRect);
1086 
1087     TLOGI(WmsLogTag::WMS_LAYOUT, "%{public}s, preRect:%{public}s, reason:%{public}u,"
1088         "[name:%{public}s, id:%{public}d], clientDisplayId: %{public}" PRIu64,
1089         rect.ToString().c_str(), preRect.ToString().c_str(), wmReason,
1090         GetWindowName().c_str(), GetPersistentId(), property_->GetDisplayId());
1091     TLOGD(WmsLogTag::WMS_LAYOUT, "hasRSTransaction:%{public}d, duration:%{public}d" PRIu64,
1092         config.rsTransaction_ != nullptr, config.animationDuration_);
1093     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER,
1094         "WindowSessionImpl::UpdateRect id: %d [%d, %d, %u, %u] reason: %u hasRSTransaction: %u", GetPersistentId(),
1095         wmRect.posX_, wmRect.posY_, wmRect.width_, wmRect.height_, wmReason, config.rsTransaction_ != nullptr);
1096     if (handler_ != nullptr && (wmReason == WindowSizeChangeReason::ROTATION ||
1097         wmReason == WindowSizeChangeReason::SNAPSHOT_ROTATION)) {
1098         postTaskDone_ = false;
1099         UpdateRectForRotation(wmRect, preRect, wmReason, config, avoidAreas);
1100     } else if (handler_ != nullptr && wmReason == WindowSizeChangeReason::PAGE_ROTATION) {
1101         UpdateRectForPageRotation(wmRect, preRect, wmReason, config, avoidAreas);
1102     } else if (handler_ != nullptr && wmReason == WindowSizeChangeReason::RESIZE_WITH_ANIMATION) {
1103         RectAnimationConfig rectAnimationConfig = property_->GetRectAnimationConfig();
1104         TLOGI(WmsLogTag::WMS_LAYOUT, "rectAnimationConfig.duration: %{public}d", rectAnimationConfig.duration);
1105         postTaskDone_ = false;
1106         UpdateRectForResizeWithAnimation(wmRect, preRect, wmReason, rectAnimationConfig,
1107             config.rsTransaction_, avoidAreas);
1108     } else {
1109         UpdateRectForOtherReason(wmRect, preRect, wmReason, config.rsTransaction_, avoidAreas);
1110     }
1111 
1112     if (wmReason == WindowSizeChangeReason::MOVE || wmReason == WindowSizeChangeReason::RESIZE ||
1113         wmReason == WindowSizeChangeReason::MOVE_WITH_ANIMATION ||
1114         wmReason == WindowSizeChangeReason::RESIZE_WITH_ANIMATION) {
1115         layoutCallback_->OnUpdateSessionRect(wmRect, wmReason, GetPersistentId());
1116     }
1117     NotifyFirstValidLayoutUpdate(preRect, wmRect);
1118     return WSError::WS_OK;
1119 }
1120 
1121 /** @note @window.layout */
UpdateVirtualPixelRatio(const sptr<Display> & display)1122 void WindowSessionImpl::UpdateVirtualPixelRatio(const sptr<Display>& display)
1123 {
1124     if (display == nullptr) {
1125         TLOGE(WmsLogTag::WMS_LAYOUT, "display is null when rotation!");
1126         return;
1127     }
1128     sptr<DisplayInfo> displayInfo = display->GetDisplayInfo();
1129     if (displayInfo == nullptr) {
1130         TLOGE(WmsLogTag::WMS_LAYOUT, "displayInfo is null when rotation!");
1131         return;
1132     }
1133     virtualPixelRatio_ = GetVirtualPixelRatio(displayInfo);
1134     TLOGD(WmsLogTag::WMS_LAYOUT, "virtualPixelRatio: %{public}f", virtualPixelRatio_);
1135 }
1136 
UpdateRectForRotation(const Rect & wmRect,const Rect & preRect,WindowSizeChangeReason wmReason,const SceneAnimationConfig & config,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)1137 void WindowSessionImpl::UpdateRectForRotation(const Rect& wmRect, const Rect& preRect,
1138     WindowSizeChangeReason wmReason, const SceneAnimationConfig& config,
1139     const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
1140 {
1141     handler_->PostTask([weak = wptr(this), wmReason, wmRect, preRect, config, avoidAreas]() mutable {
1142         HITRACE_METER_NAME(HITRACE_TAG_WINDOW_MANAGER, "WindowSessionImpl::UpdateRectForRotation");
1143         auto window = weak.promote();
1144         if (!window) {
1145             return;
1146         }
1147         auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(window->property_->GetDisplayId());
1148         sptr<DisplayInfo> displayInfo = display ? display->GetDisplayInfo() : nullptr;
1149         window->UpdateVirtualPixelRatio(display);
1150         auto rsUIContext = window->GetRSUIContext();
1151         const std::shared_ptr<RSTransaction>& rsTransaction = config.rsTransaction_;
1152         if (rsTransaction) {
1153             RSTransactionAdapter::FlushImplicitTransaction(rsUIContext);
1154             rsTransaction->Begin();
1155         }
1156         window->rotationAnimationCount_++;
1157         RSAnimationTimingProtocol protocol;
1158         protocol.SetDuration(config.animationDuration_);
1159         // animation curve: cubic [0.2, 0.0, 0.2, 1.0]
1160         auto curve = RSAnimationTimingCurve::CreateCubicCurve(0.2, 0.0, 0.2, 1.0);
1161         RSNode::OpenImplicitAnimation(rsUIContext, protocol, curve, [weak]() {
1162             auto window = weak.promote();
1163             if (!window) {
1164                 return;
1165             }
1166             window->rotationAnimationCount_--;
1167             if (window->rotationAnimationCount_ == 0) {
1168                 window->NotifyRotationAnimationEnd();
1169             }
1170         });
1171         if (wmReason == WindowSizeChangeReason::SNAPSHOT_ROTATION) {
1172             wmReason = WindowSizeChangeReason::ROTATION;
1173         }
1174         if ((wmRect != preRect) || (wmReason != window->lastSizeChangeReason_)) {
1175             window->NotifySizeChange(wmRect, wmReason);
1176             window->lastSizeChangeReason_ = wmReason;
1177         }
1178         window->UpdateViewportConfig(wmRect, wmReason, rsTransaction, displayInfo, avoidAreas);
1179         RSNode::CloseImplicitAnimation(rsUIContext);
1180         if (rsTransaction) {
1181             rsTransaction->Commit();
1182         } else {
1183             RSTransactionAdapter::FlushImplicitTransaction(rsUIContext);
1184         }
1185         window->postTaskDone_ = true;
1186     }, "WMS_WindowSessionImpl_UpdateRectForRotation");
1187 }
1188 
1189 
UpdateRectForPageRotation(const Rect & wmRect,const Rect & preRect,WindowSizeChangeReason wmReason,const SceneAnimationConfig & config,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)1190 void WindowSessionImpl::UpdateRectForPageRotation(const Rect& wmRect, const Rect& preRect,
1191     WindowSizeChangeReason wmReason, const SceneAnimationConfig& config,
1192     const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
1193 {
1194     handler_->PostImmediateTask(
1195         [weak = wptr(this), wmReason, wmRect, preRect, config, avoidAreas]() mutable {
1196             HITRACE_METER_NAME(HITRACE_TAG_WINDOW_MANAGER, "WindowSessionImpl::UpdateRectForPageRotation");
1197             auto window = weak.promote();
1198             if (!window) {
1199                 return;
1200             }
1201             auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(window->property_->GetDisplayId());
1202             if (display == nullptr) {
1203                 TLOGE(WmsLogTag::WMS_ROTATION, "display is null!");
1204                 return;
1205             }
1206             sptr<DisplayInfo> displayInfo = display->GetDisplayInfo();
1207             if (displayInfo == nullptr) {
1208                 TLOGE(WmsLogTag::WMS_ROTATION, "displayInfo is null!");
1209                 return;
1210             }
1211             window->UpdateVirtualPixelRatio(display);
1212             const std::shared_ptr<RSTransaction>& rsTransaction = config.rsTransaction_;
1213             if (rsTransaction) {
1214                 RSTransactionAdapter::FlushImplicitTransaction(window->GetRSUIContext());
1215                 rsTransaction->Begin();
1216             }
1217             if ((wmRect != preRect) || (wmReason != window->lastSizeChangeReason_)) {
1218                 window->NotifySizeChange(wmRect, wmReason);
1219                 window->lastSizeChangeReason_ = wmReason;
1220             }
1221             window->NotifyClientOrientationChange();
1222             DisplayOrientation windowOrientation = window->GetCurrentWindowOrientation();
1223             DisplayOrientation displayOrientation = displayInfo->GetDisplayOrientation();
1224             TLOGI(WmsLogTag::WMS_ROTATION,
1225                 "windowOrientation: %{public}d, targetdisplayOrientation: %{public}d, "
1226                 "windowRect: %{public}s, preRect: %{public}s, id: %{public}d",
1227                 static_cast<int32_t>(windowOrientation), static_cast<int32_t>(displayOrientation),
1228                 wmRect.ToString().c_str(), preRect.ToString().c_str(), window->GetPersistentId());
1229             if (wmRect != preRect || windowOrientation != displayOrientation) {
1230                 window->UpdateViewportConfig(wmRect, wmReason, rsTransaction, displayInfo, avoidAreas);
1231             }
1232             if (rsTransaction) {
1233                 rsTransaction->Commit();
1234             } else {
1235                 RSTransactionAdapter::FlushImplicitTransaction(window->GetRSUIContext());
1236             }
1237             window->postTaskDone_ = true;
1238         },
1239         "WMS_WindowSessionImpl_UpdateRectForPageRotation");
1240 }
1241 
UpdateCurrentWindowOrientation(DisplayOrientation displayOrientation)1242 void WindowSessionImpl::UpdateCurrentWindowOrientation(DisplayOrientation displayOrientation)
1243 {
1244     windowOrientation_ = displayOrientation;
1245 }
1246 
GetCurrentWindowOrientation() const1247 DisplayOrientation WindowSessionImpl::GetCurrentWindowOrientation() const
1248 {
1249     return windowOrientation_;
1250 }
1251 
UpdateRectForOtherReasonTask(const Rect & wmRect,const Rect & preRect,WindowSizeChangeReason wmReason,const std::shared_ptr<RSTransaction> & rsTransaction,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)1252 void WindowSessionImpl::UpdateRectForOtherReasonTask(const Rect& wmRect, const Rect& preRect,
1253     WindowSizeChangeReason wmReason, const std::shared_ptr<RSTransaction>& rsTransaction,
1254     const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
1255 {
1256     if ((wmRect != preRect) || (wmReason != lastSizeChangeReason_)
1257         || !postTaskDone_ || notifySizeChangeFlag_) {
1258         NotifySizeChange(wmRect, wmReason);
1259         SetNotifySizeChangeFlag(false);
1260         lastSizeChangeReason_ = wmReason;
1261         postTaskDone_ = true;
1262     }
1263     UpdateViewportConfig(wmRect, wmReason, rsTransaction, nullptr, avoidAreas);
1264     UpdateFrameLayoutCallbackIfNeeded(wmReason);
1265 }
1266 
CheckIfNeedCommitRsTransaction(WindowSizeChangeReason wmReason)1267 bool WindowSessionImpl::CheckIfNeedCommitRsTransaction(WindowSizeChangeReason wmReason)
1268 {
1269     if (wmReason == WindowSizeChangeReason::FULL_TO_SPLIT ||
1270         wmReason == WindowSizeChangeReason::FULL_TO_FLOATING || wmReason == WindowSizeChangeReason::RECOVER ||
1271         wmReason == WindowSizeChangeReason::MAXIMIZE) {
1272         return false;
1273     }
1274     return true;
1275 }
1276 
UpdateRectForOtherReason(const Rect & wmRect,const Rect & preRect,WindowSizeChangeReason wmReason,const std::shared_ptr<RSTransaction> & rsTransaction,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)1277 void WindowSessionImpl::UpdateRectForOtherReason(const Rect& wmRect, const Rect& preRect,
1278     WindowSizeChangeReason wmReason, const std::shared_ptr<RSTransaction>& rsTransaction,
1279     const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
1280 {
1281     if (handler_ == nullptr) {
1282         UpdateRectForOtherReasonTask(wmRect, preRect, wmReason, rsTransaction, avoidAreas);
1283         return;
1284     }
1285 
1286     auto task = [weak = wptr(this), wmReason, wmRect, preRect, rsTransaction, avoidAreas] {
1287         auto window = weak.promote();
1288         if (!window) {
1289             TLOGE(WmsLogTag::WMS_LAYOUT, "window is null, updateViewPortConfig failed");
1290             return;
1291         }
1292         bool ifNeedCommitRsTransaction = window->CheckIfNeedCommitRsTransaction(wmReason);
1293         if (rsTransaction && ifNeedCommitRsTransaction) {
1294             RSTransactionAdapter::FlushImplicitTransaction(window->GetRSUIContext());
1295             rsTransaction->Begin();
1296         }
1297         if (wmReason == WindowSizeChangeReason::DRAG) {
1298             window->UpdateRectForOtherReasonTask(window->GetRect(), preRect, wmReason, rsTransaction, avoidAreas);
1299             window->isDragTaskPostDone_.store(true);
1300         } else {
1301             window->UpdateRectForOtherReasonTask(wmRect, preRect, wmReason, rsTransaction, avoidAreas);
1302         }
1303         if (rsTransaction && ifNeedCommitRsTransaction) {
1304             rsTransaction->Commit();
1305         }
1306     };
1307     if (wmReason == WindowSizeChangeReason::DRAG) {
1308         bool isDragTaskPostDone = true;
1309         if (isDragTaskPostDone_.compare_exchange_strong(isDragTaskPostDone, false)) {
1310             handler_->PostTask(task, "WMS_WindowSessionImpl_UpdateRectForOtherReason");
1311         }
1312     } else {
1313         handler_->PostTask(task, "WMS_WindowSessionImpl_UpdateRectForOtherReason");
1314     }
1315 }
1316 
UpdateRectForResizeWithAnimation(const Rect & wmRect,const Rect & preRect,WindowSizeChangeReason wmReason,const RectAnimationConfig & rectAnimationConfig,const std::shared_ptr<RSTransaction> & rsTransaction,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)1317 void WindowSessionImpl::UpdateRectForResizeWithAnimation(const Rect& wmRect, const Rect& preRect,
1318     WindowSizeChangeReason wmReason, const RectAnimationConfig& rectAnimationConfig,
1319     const std::shared_ptr<RSTransaction>& rsTransaction,
1320     const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
1321 {
1322     if (handler_ == nullptr) {
1323         TLOGE(WmsLogTag::WMS_LAYOUT, "handler is null!");
1324         return;
1325     }
1326     auto task = [weakThis = wptr(this), wmReason, wmRect, preRect, rectAnimationConfig,
1327         rsTransaction, avoidAreas]() mutable {
1328         HITRACE_METER_NAME(HITRACE_TAG_WINDOW_MANAGER, "WindowSessionImpl::UpdateRectForResizeWithAnimation");
1329         auto window = weakThis.promote();
1330         if (!window) {
1331             TLOGNE(WmsLogTag::WMS_LAYOUT, "window is null, updateRectForResizeWithAnimation failed");
1332             return;
1333         }
1334         auto rsUIContext = window->GetRSUIContext();
1335         if (rsTransaction) {
1336             RSTransactionAdapter::FlushImplicitTransaction(rsUIContext);
1337             rsTransaction->Begin();
1338         }
1339         RSAnimationTimingProtocol protocol;
1340         protocol.SetDuration(rectAnimationConfig.duration);
1341         auto curve = RSAnimationTimingCurve::CreateCubicCurve(rectAnimationConfig.x1,
1342             rectAnimationConfig.y1, rectAnimationConfig.x2, rectAnimationConfig.y2);
1343         RSNode::OpenImplicitAnimation(rsUIContext, protocol, curve, nullptr);
1344         if (wmRect != preRect || wmReason != window->lastSizeChangeReason_) {
1345             window->NotifySizeChange(wmRect, wmReason);
1346             window->lastSizeChangeReason_ = wmReason;
1347         }
1348         window->UpdateViewportConfig(wmRect, wmReason, rsTransaction, nullptr, avoidAreas);
1349         RSNode::CloseImplicitAnimation(rsUIContext);
1350         if (rsTransaction) {
1351             rsTransaction->Commit();
1352         } else {
1353             RSTransactionAdapter::FlushImplicitTransaction(rsUIContext);
1354         }
1355         window->postTaskDone_ = true;
1356     };
1357     handler_->PostTask(task, "WMS_WindowSessionImpl_UpdateRectForResizeWithAnimation");
1358 }
1359 
NotifyAfterUIContentReady()1360 void WindowSessionImpl::NotifyAfterUIContentReady()
1361 {
1362     auto uiContent = GetUIContentSharedPtr();
1363     CHECK_UI_CONTENT_RETURN_IF_NULL(uiContent);
1364     if (IsNeedRenotifyTransform()) {
1365         auto transform = GetCurrentTransform();
1366         TLOGI(WmsLogTag::WMS_LAYOUT, "Renotify transform, id:%{public}d, scaleX:%{public}f, scaleY:%{public}f",
1367             GetPersistentId(), transform.scaleX_, transform.scaleY_);
1368         uiContent->UpdateTransform(transform);
1369         SetNeedRenotifyTransform(false);
1370     }
1371 }
1372 
NotifyRotationAnimationEnd()1373 void WindowSessionImpl::NotifyRotationAnimationEnd()
1374 {
1375     auto task = [weak = wptr(this)] {
1376         auto window = weak.promote();
1377         if (!window) {
1378             TLOGE(WmsLogTag::WMS_DIALOG, "window is null");
1379             return;
1380         }
1381         std::shared_ptr<Ace::UIContent> uiContent = window->GetUIContentSharedPtr();
1382         if (uiContent == nullptr) {
1383             WLOGFW("uiContent is null!");
1384             return;
1385         }
1386         uiContent->NotifyRotationAnimationEnd();
1387     };
1388     if (handler_ == nullptr) {
1389         TLOGW(WmsLogTag::WMS_DIALOG, "handler is null!");
1390         task();
1391     } else {
1392         handler_->PostTask(task, "WMS_WindowSessionImpl_NotifyRotationAnimationEnd");
1393     }
1394 }
1395 
FlushLayoutSize(int32_t width,int32_t height)1396 void WindowSessionImpl::FlushLayoutSize(int32_t width, int32_t height)
1397 {
1398     if (!WindowHelper::IsMainWindow(GetType())) {
1399         return;
1400     }
1401     WSRect rect = { 0, 0, width, height };
1402     bool windowSizeChanged = true;
1403     bool enableFrameLayoutFinishCb = true;
1404     if (windowSizeChanged_.compare_exchange_strong(windowSizeChanged, false) ||
1405         enableFrameLayoutFinishCb_.compare_exchange_strong(enableFrameLayoutFinishCb, false) || layoutRect_ != rect) {
1406         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER,
1407             "NotifyFrameLayoutFinishFromApp, id: %u, rect: %s, notifyListener: %d",
1408             GetWindowId(), rect.ToString().c_str(), enableFrameLayoutFinishCb_.load());
1409         TLOGI(WmsLogTag::WMS_PATTERN,
1410             "NotifyFrameLayoutFinishFromApp, id: %{public}u, rect: %{public}s, notifyListener: %{public}d",
1411             GetWindowId(), rect.ToString().c_str(), enableFrameLayoutFinishCb_.load());
1412         if (auto session = GetHostSession()) {
1413             session->NotifyFrameLayoutFinishFromApp(enableFrameLayoutFinishCb_, rect);
1414         }
1415         layoutRect_ = rect;
1416         enableFrameLayoutFinishCb_ = false;
1417     }
1418 }
1419 
NotifySnapshotUpdate()1420 WMError WindowSessionImpl::NotifySnapshotUpdate()
1421 {
1422     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "NotifySnapshotUpdate, id: %u", GetWindowId());
1423     TLOGI(WmsLogTag::WMS_PATTERN, "id: %{public}u", GetWindowId());
1424     if (auto session = GetHostSession()) {
1425         return session->NotifySnapshotUpdate();
1426     }
1427     TLOGE(WmsLogTag::WMS_PATTERN, "session is nullptr");
1428     return WMError::WM_ERROR_INVALID_SESSION;
1429 }
1430 
GetTitleButtonVisible(bool & hideMaximizeButton,bool & hideMinimizeButton,bool & hideSplitButton,bool & hideCloseButton)1431 void WindowSessionImpl::GetTitleButtonVisible(bool& hideMaximizeButton, bool& hideMinimizeButton,
1432     bool& hideSplitButton, bool& hideCloseButton)
1433 {
1434     if (!IsPcOrPadFreeMultiWindowMode()) {
1435         TLOGE(WmsLogTag::WMS_DECOR, "device not support");
1436         return;
1437     }
1438     if (hideMaximizeButton > !windowTitleVisibleFlags_.isMaximizeVisible) {
1439         TLOGW(WmsLogTag::WMS_DECOR, "isMaximizeVisible param INVALID");
1440     }
1441     hideMaximizeButton = hideMaximizeButton || (!windowTitleVisibleFlags_.isMaximizeVisible);
1442     if (hideMinimizeButton > !windowTitleVisibleFlags_.isMinimizeVisible) {
1443         TLOGW(WmsLogTag::WMS_DECOR, "isMinimizeVisible param INVALID");
1444     }
1445     hideMinimizeButton = hideMinimizeButton || (!windowTitleVisibleFlags_.isMinimizeVisible);
1446     if (hideSplitButton > !windowTitleVisibleFlags_.isSplitVisible) {
1447         TLOGW(WmsLogTag::WMS_DECOR, "isSplitVisible param INVALID");
1448     }
1449     hideSplitButton = hideSplitButton || (!windowTitleVisibleFlags_.isSplitVisible) || !isSplitButtonVisible_;
1450     if (hideCloseButton > !windowTitleVisibleFlags_.isCloseVisible) {
1451         TLOGW(WmsLogTag::WMS_DECOR, "isCloseVisible param INVALID");
1452     }
1453     hideCloseButton = hideCloseButton || (!windowTitleVisibleFlags_.isCloseVisible);
1454 }
1455 
UpdateDensity()1456 void WindowSessionImpl::UpdateDensity()
1457 {
1458     auto preRect = GetRect();
1459     UpdateViewportConfig(preRect, WindowSizeChangeReason::UNDEFINED);
1460     WLOGFI("[%{public}d, %{public}d, %{public}u, %{public}u]",
1461         preRect.posX_, preRect.posY_, preRect.width_, preRect.height_);
1462 }
1463 
SetUniqueVirtualPixelRatio(bool useUniqueDensity,float virtualPixelRatio)1464 void WindowSessionImpl::SetUniqueVirtualPixelRatio(bool useUniqueDensity, float virtualPixelRatio)
1465 {
1466     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "old {useUniqueDensity: %{public}d, virtualPixelRatio: %{public}f}, "
1467         "new {useUniqueDensity: %{public}d, virtualPixelRatio: %{public}f}",
1468         useUniqueDensity_, virtualPixelRatio_, useUniqueDensity, virtualPixelRatio);
1469     bool oldUseUniqueDensity = useUniqueDensity_;
1470     useUniqueDensity_ = useUniqueDensity;
1471     if (useUniqueDensity_) {
1472         float oldVirtualPixelRatio = virtualPixelRatio_;
1473         virtualPixelRatio_ = virtualPixelRatio;
1474         if (!MathHelper::NearZero(oldVirtualPixelRatio - virtualPixelRatio)) {
1475             UpdateDensity();
1476             SetUniqueVirtualPixelRatioForSub(useUniqueDensity, virtualPixelRatio);
1477         }
1478     } else {
1479         if (oldUseUniqueDensity) {
1480             UpdateDensity();
1481             SetUniqueVirtualPixelRatioForSub(useUniqueDensity, virtualPixelRatio);
1482         }
1483     }
1484 }
1485 
CopyUniqueDensityParameter(sptr<WindowSessionImpl> parentWindow)1486 void WindowSessionImpl::CopyUniqueDensityParameter(sptr<WindowSessionImpl> parentWindow)
1487 {
1488     if (parentWindow) {
1489         useUniqueDensity_ = parentWindow->useUniqueDensity_;
1490         virtualPixelRatio_ = parentWindow->virtualPixelRatio_;
1491     }
1492 }
1493 
FindMainWindowWithContext() const1494 sptr<WindowSessionImpl> WindowSessionImpl::FindMainWindowWithContext() const
1495 {
1496     auto context = GetContext();
1497     if (context == nullptr) {
1498         return nullptr;
1499     }
1500     std::shared_lock<std::shared_mutex> lock(windowSessionMutex_);
1501     for (const auto& winPair : windowSessionMap_) {
1502         auto win = winPair.second.second;
1503         if (win && win->GetType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW &&
1504             context.get() == win->GetContext().get()) {
1505             return win;
1506         }
1507     }
1508     TLOGD(WmsLogTag::WMS_MAIN, "Can not find main window, not app type");
1509     return nullptr;
1510 }
1511 
FindExtensionWindowWithContext() const1512 sptr<WindowSessionImpl> WindowSessionImpl::FindExtensionWindowWithContext() const
1513 {
1514     auto context = GetContext();
1515     if (context == nullptr) {
1516         return nullptr;
1517     }
1518     std::shared_lock<std::shared_mutex> lock(windowExtensionSessionMutex_);
1519     for (const auto& window : GetWindowExtensionSessionSet()) {
1520         if (window && context.get() == window->GetContext().get()) {
1521             return window;
1522         }
1523     }
1524     return nullptr;
1525 }
1526 
GetPropertyByContext() const1527 sptr<WindowSessionProperty> WindowSessionImpl::GetPropertyByContext() const
1528 {
1529     if (!WindowHelper::IsSubWindow(GetType())) {
1530        return property_;
1531     }
1532     if (property_->GetIsUIExtensionAbilityProcess()) {
1533         auto extensionWindow = FindExtensionWindowWithContext();
1534         return extensionWindow != nullptr ? extensionWindow->GetProperty() : property_;
1535     }
1536     auto mainWindow = FindMainWindowWithContext();
1537     return mainWindow != nullptr ? mainWindow->GetProperty() : property_;
1538 }
1539 
SetUniqueVirtualPixelRatioForSub(bool useUniqueDensity,float virtualPixelRatio)1540 void WindowSessionImpl::SetUniqueVirtualPixelRatioForSub(bool useUniqueDensity, float virtualPixelRatio)
1541 {
1542     std::vector<sptr<WindowSessionImpl>> subWindows;
1543     GetSubWindows(GetPersistentId(), subWindows);
1544     for (auto& subWindowSession : subWindows) {
1545         if (subWindowSession != nullptr) {
1546             subWindowSession->SetUniqueVirtualPixelRatio(useUniqueDensity, virtualPixelRatio);
1547         }
1548     }
1549 }
1550 
UpdateOrientation()1551 WSError WindowSessionImpl::UpdateOrientation()
1552 {
1553     TLOGD(WmsLogTag::DMS, "wid: %{public}d", GetPersistentId());
1554     return WSError::WS_OK;
1555 }
1556 
UpdateDisplayId(uint64_t displayId)1557 WSError WindowSessionImpl::UpdateDisplayId(uint64_t displayId)
1558 {
1559     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "wid: %{public}d, displayId: %{public}" PRIu64, GetPersistentId(), displayId);
1560     property_->SetDisplayId(displayId);
1561     return WSError::WS_OK;
1562 }
1563 
UpdateFocus(bool isFocused)1564 WSError WindowSessionImpl::UpdateFocus(bool isFocused)
1565 {
1566     TLOGI(WmsLogTag::WMS_FOCUS, "focus: %{public}u, id: %{public}d", isFocused, GetPersistentId());
1567     isFocused_ = isFocused;
1568     if (isFocused) {
1569         std::string bundleName = IsAnco() && property_->GetAncoRealBundleName() != "" ?
1570             property_->GetAncoRealBundleName() : property_->GetSessionInfo().bundleName_;
1571         HiSysEventWrite(
1572             OHOS::HiviewDFX::HiSysEvent::Domain::WINDOW_MANAGER,
1573             "FOCUS_WINDOW",
1574             OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR,
1575             "PID", getpid(),
1576             "UID", getuid(),
1577             "BUNDLE_NAME", bundleName,
1578             "WINDOW_TYPE", static_cast<uint32_t>(GetType()));
1579         NotifyAfterFocused();
1580     } else {
1581         NotifyAfterUnfocused();
1582     }
1583     return WSError::WS_OK;
1584 }
1585 
IsFocused() const1586 bool WindowSessionImpl::IsFocused() const
1587 {
1588     if (IsWindowSessionInvalid()) {
1589         TLOGE(WmsLogTag::WMS_FOCUS, "Session is invalid");
1590         return false;
1591     }
1592 
1593     TLOGD(WmsLogTag::WMS_FOCUS, "window id=%{public}d, isFocused=%{public}d", GetPersistentId(), isFocused_.load());
1594     return isFocused_;
1595 }
1596 
RequestFocus() const1597 WMError WindowSessionImpl::RequestFocus() const
1598 {
1599     if (IsWindowSessionInvalid()) {
1600         WLOGFD("session is invalid");
1601         return WMError::WM_ERROR_INVALID_WINDOW;
1602     }
1603     return SingletonContainer::Get<WindowAdapter>().RequestFocusStatus(GetPersistentId(), true);
1604 }
1605 
1606 /** @note @window.focus */
RequestFocusByClient(bool isFocused) const1607 WMError WindowSessionImpl::RequestFocusByClient(bool isFocused) const
1608 {
1609     if (!SessionPermission::IsSystemCalling()) {
1610         TLOGE(WmsLogTag::WMS_FOCUS, "permission denied!");
1611         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1612     }
1613     if (IsWindowSessionInvalid()) {
1614         TLOGD(WmsLogTag::WMS_FOCUS, "session is invalid");
1615         return WMError::WM_ERROR_INVALID_WINDOW;
1616     }
1617     auto hostSession = GetHostSession();
1618     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
1619     auto ret = hostSession->RequestFocus(isFocused);
1620     return static_cast<WMError>(ret);
1621 }
1622 
IsNotifyInteractiveDuplicative(bool interactive)1623 bool WindowSessionImpl::IsNotifyInteractiveDuplicative(bool interactive)
1624 {
1625     if (interactive == interactive_ && hasFirstNotifyInteractive_) {
1626         return true;
1627     }
1628     hasFirstNotifyInteractive_ = true;
1629     if (interactive_ != interactive) {
1630         interactive_ = interactive;
1631     }
1632     return false;
1633 }
1634 
NotifyForegroundInteractiveStatus(bool interactive)1635 void WindowSessionImpl::NotifyForegroundInteractiveStatus(bool interactive)
1636 {
1637     TLOGI(WmsLogTag::WMS_LIFE, "interactive: %{public}d, state: %{public}d", interactive, state_);
1638     if (IsWindowSessionInvalid() || state_ != WindowState::STATE_SHOWN) {
1639         return;
1640     }
1641     if (IsNotifyInteractiveDuplicative(interactive)) {
1642         return;
1643     }
1644     if (interactive) {
1645         bool useControlState = property_->GetUseControlState();
1646         TLOGI(WmsLogTag::WMS_LIFE, "useControlState: %{public}d, persistentId: %{public}d", useControlState,
1647             GetPersistentId());
1648         if (!useControlState) {
1649             NotifyAfterLifecycleResumed();
1650         }
1651         NotifyAfterResumed();
1652     } else {
1653         NotifyAfterPaused();
1654         NotifyAfterLifecyclePaused();
1655     }
1656 }
1657 
NotifyAppUseControlStatus(bool isUseControl)1658 void WindowSessionImpl::NotifyAppUseControlStatus(bool isUseControl)
1659 {
1660     {
1661         std::lock_guard<std::mutex> lock(appUseControlMutex_);
1662         isAppUseControl_ = isUseControl;
1663     }
1664     property_->SetUseControlState(isUseControl);
1665     TLOGI(WmsLogTag::WMS_LIFE, "isUseControl: %{public}d, state_: %{public}d, persistentId: %{public}d",
1666         isUseControl, state_, GetPersistentId());
1667     if (IsWindowSessionInvalid() || state_ != WindowState::STATE_SHOWN) {
1668         return;
1669     }
1670     if (isUseControl) {
1671         NotifyAfterLifecyclePaused();
1672     } else {
1673         NotifyAfterLifecycleResumed();
1674     }
1675 }
1676 
NotifyLifecyclePausedStatus()1677 void WindowSessionImpl::NotifyLifecyclePausedStatus()
1678 {
1679     TLOGI(WmsLogTag::WMS_LIFE, "in");
1680     if (IsWindowSessionInvalid() || state_ != WindowState::STATE_SHOWN) {
1681         return;
1682     }
1683     NotifyAfterLifecyclePaused();
1684 }
1685 
UpdateWindowMode(WindowMode mode)1686 WSError WindowSessionImpl::UpdateWindowMode(WindowMode mode)
1687 {
1688     return WSError::WS_OK;
1689 }
1690 
1691 /** @note @window.layout */
GetVirtualPixelRatio()1692 float WindowSessionImpl::GetVirtualPixelRatio()
1693 {
1694     TLOGD(WmsLogTag::WMS_LAYOUT, "virtualPixelRatio: %{public}f", virtualPixelRatio_);
1695     return virtualPixelRatio_;
1696 }
1697 
GetVirtualPixelRatio(const sptr<DisplayInfo> & displayInfo)1698 float WindowSessionImpl::GetVirtualPixelRatio(const sptr<DisplayInfo>& displayInfo)
1699 {
1700     if (useUniqueDensity_) {
1701         return virtualPixelRatio_;
1702     }
1703     return displayInfo->GetVirtualPixelRatio();
1704 }
1705 
GetVirtualPixelRatio(float & vpr)1706 WMError WindowSessionImpl::GetVirtualPixelRatio(float& vpr)
1707 {
1708     auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
1709     if (display == nullptr) {
1710         TLOGE(WmsLogTag::WMS_LAYOUT, "get display failed displayId: %{public}" PRIu64, property_->GetDisplayId());
1711         return WMError::WM_ERROR_NULLPTR;
1712     }
1713     auto displayInfo = display->GetDisplayInfo();
1714     if (displayInfo == nullptr) {
1715         TLOGE(WmsLogTag::WMS_LAYOUT, "get display info failed displayId: %{public}" PRIu64, property_->GetDisplayId());
1716         return WMError::WM_ERROR_NULLPTR;
1717     }
1718     vpr = GetVirtualPixelRatio(displayInfo);
1719     if (MathHelper::NearZero(vpr)) {
1720         TLOGE(WmsLogTag::WMS_LAYOUT, "get decor height failed, because of wrong vpr: %{public}f", vpr);
1721         return WMError::WM_ERROR_INVALID_WINDOW;
1722     }
1723     return WMError::WM_OK;
1724 }
1725 
1726 /** @note @window.layout */
UpdateViewportConfig(const Rect & rect,WindowSizeChangeReason reason,const std::shared_ptr<RSTransaction> & rsTransaction,const sptr<DisplayInfo> & info,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)1727 void WindowSessionImpl::UpdateViewportConfig(const Rect& rect, WindowSizeChangeReason reason,
1728     const std::shared_ptr<RSTransaction>& rsTransaction, const sptr<DisplayInfo>& info,
1729     const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
1730 {
1731     // update avoid areas to listeners
1732     if (reason != WindowSizeChangeReason::OCCUPIED_AREA_CHANGE) {
1733         for (const auto& [type, avoidArea] : avoidAreas) {
1734             TLOGD(WmsLogTag::WMS_IMMS, "avoid type %{public}u area %{public}s",
1735                 type, avoidArea.ToString().c_str());
1736             if ((lastAvoidAreaMap_.find(type) == lastAvoidAreaMap_.end() && type != AvoidAreaType::TYPE_CUTOUT) ||
1737                 lastAvoidAreaMap_[type] != avoidArea) {
1738                 lastAvoidAreaMap_[type] = avoidArea;
1739                 NotifyAvoidAreaChange(new AvoidArea(avoidArea), type);
1740             }
1741         }
1742     }
1743 
1744     sptr<DisplayInfo> displayInfo;
1745     if (info == nullptr) {
1746         auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
1747         if (display == nullptr) {
1748             WLOGFE("display is null!");
1749             return;
1750         }
1751         displayInfo = display->GetDisplayInfo();
1752     } else {
1753         displayInfo = info;
1754     }
1755     if (displayInfo == nullptr) {
1756         WLOGFE("displayInfo is null!");
1757         return;
1758     }
1759     if (rect.width_ <= 0 || rect.height_ <= 0) {
1760         TLOGW(WmsLogTag::WMS_LAYOUT, "invalid width: %{public}d, height: %{public}d, id: %{public}d",
1761               rect.width_, rect.height_, GetPersistentId());
1762         return;
1763     }
1764     auto rotation =  ONE_FOURTH_FULL_CIRCLE_DEGREE * static_cast<uint32_t>(displayInfo->GetOriginRotation());
1765     auto deviceRotation = static_cast<uint32_t>(displayInfo->GetDefaultDeviceRotationOffset());
1766     uint32_t transformHint = (rotation + deviceRotation) % FULL_CIRCLE_DEGREE;
1767     float density = GetVirtualPixelRatio(displayInfo);
1768     UpdateCurrentWindowOrientation(displayInfo->GetDisplayOrientation());
1769     int32_t orientation = static_cast<int32_t>(displayInfo->GetDisplayOrientation());
1770     virtualPixelRatio_ = density;
1771     auto config = FillViewportConfig(rect, density, orientation, transformHint, GetDisplayId());
1772     if (reason == WindowSizeChangeReason::DRAG_END && keyFramePolicy_.stopping_) {
1773         TLOGI(WmsLogTag::WMS_LAYOUT, "key frame stop");
1774         keyFramePolicy_.stopping_ = false;
1775         config.SetKeyFrameConfig(true, keyFramePolicy_.animationDuration_, keyFramePolicy_.animationDelay_);
1776     } else {
1777         config.SetKeyFrameConfig(keyFramePolicy_.running_, keyFramePolicy_.animationDuration_,
1778             keyFramePolicy_.animationDelay_);
1779     }
1780     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1781     if (uiContent == nullptr) {
1782         WLOGFW("uiContent is null!");
1783         return;
1784     }
1785     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER,
1786         "WindowSessionimpl::UpdateViewportConfig id:%d [%d, %d, %u, %u] reason:%u orientation:%d", GetPersistentId(),
1787         rect.posX_, rect.posY_, rect.width_, rect.height_, reason, orientation);
1788     if (reason == WindowSizeChangeReason::OCCUPIED_AREA_CHANGE && !avoidAreas.empty()) {
1789         uiContent->UpdateViewportConfig(config, reason, rsTransaction, avoidAreas, occupiedAreaInfo_);
1790     } else {
1791         uiContent->UpdateViewportConfig(config, reason, rsTransaction, lastAvoidAreaMap_, occupiedAreaInfo_);
1792     }
1793 
1794     if (WindowHelper::IsUIExtensionWindow(GetType())) {
1795         TLOGD(WmsLogTag::WMS_LAYOUT, "Id: %{public}d, reason: %{public}d, windowRect: %{public}s, "
1796             "displayOrientation: %{public}d, config[%{public}u, %{public}u, %{public}u, "
1797             "%{public}f]", GetPersistentId(), reason, rect.ToString().c_str(), orientation,
1798             rotation, deviceRotation, transformHint, virtualPixelRatio_);
1799     } else {
1800         TLOGI(WmsLogTag::WMS_LAYOUT, "Id: %{public}d, reason: %{public}d, windowRect: %{public}s, "
1801             "displayOrientation: %{public}d, config[%{public}u, %{public}u, %{public}u, "
1802             "%{public}f]", GetPersistentId(), reason, rect.ToString().c_str(), orientation,
1803             rotation, deviceRotation, transformHint, virtualPixelRatio_);
1804     }
1805 }
1806 
GetFloatingWindowParentId()1807 int32_t WindowSessionImpl::GetFloatingWindowParentId()
1808 {
1809     auto context = GetContext();
1810     if (context.get() == nullptr) {
1811         return INVALID_SESSION_ID;
1812     }
1813     std::shared_lock<std::shared_mutex> lock(windowSessionMutex_);
1814     for (const auto& winPair : windowSessionMap_) {
1815         if (winPair.second.second && WindowHelper::IsMainWindow(winPair.second.second->GetType()) &&
1816             context.get() == winPair.second.second->GetContext().get()) {
1817             WLOGFD("Find parent, [parentName: %{public}s, selfPersistentId: %{public}d]",
1818                 winPair.second.second->GetProperty()->GetWindowName().c_str(), GetPersistentId());
1819             return winPair.second.second->GetProperty()->GetPersistentId();
1820         }
1821     }
1822     return INVALID_SESSION_ID;
1823 }
1824 
GetRect() const1825 Rect WindowSessionImpl::GetRect() const
1826 {
1827     return property_->GetWindowRect();
1828 }
1829 
UpdateTitleButtonVisibility()1830 void WindowSessionImpl::UpdateTitleButtonVisibility()
1831 {
1832     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1833     if (uiContent == nullptr || !IsDecorEnable()) {
1834         return;
1835     }
1836     WindowType windowType = GetType();
1837     bool isSubWindow = WindowHelper::IsSubWindow(windowType);
1838     bool isDialogWindow = WindowHelper::IsDialogWindow(windowType);
1839     if (IsPcOrFreeMultiWindowCapabilityEnabled() && (isSubWindow || isDialogWindow)) {
1840         uiContent->HideWindowTitleButton(true, !windowOption_->GetSubWindowMaximizeSupported(), true, false);
1841         return;
1842     }
1843     auto windowModeSupportType = property_->GetWindowModeSupportType();
1844     bool hideSplitButton = !(windowModeSupportType & WindowModeSupport::WINDOW_MODE_SUPPORT_SPLIT_PRIMARY);
1845     // not support fullscreen in split and floating mode, or not support float in fullscreen mode
1846     bool hideMaximizeButton = (!(windowModeSupportType & WindowModeSupport::WINDOW_MODE_SUPPORT_FULLSCREEN) &&
1847         (GetWindowMode() == WindowMode::WINDOW_MODE_FLOATING || WindowHelper::IsSplitWindowMode(GetWindowMode()))) ||
1848         (!(windowModeSupportType & WindowModeSupport::WINDOW_MODE_SUPPORT_FLOATING) &&
1849          GetWindowMode() == WindowMode::WINDOW_MODE_FULLSCREEN);
1850     bool hideMinimizeButton = false;
1851     bool hideCloseButton = false;
1852     GetTitleButtonVisible(hideMaximizeButton, hideMinimizeButton, hideSplitButton, hideCloseButton);
1853     hideMaximizeButton = hideMaximizeButton && !grayOutMaximizeButton_;
1854     TLOGI(WmsLogTag::WMS_DECOR, "[hideSplit, hideMaximize, hideMinimizeButton, hideCloseButton]:"
1855         "[%{public}d, %{public}d, %{public}d, %{public}d]",
1856         hideSplitButton, hideMaximizeButton, hideMinimizeButton, hideCloseButton);
1857     bool isSuperFoldDisplayDevice = FoldScreenStateInternel::IsSuperFoldDisplayDevice();
1858     HideTitleButton(hideSplitButton, hideMaximizeButton, hideMinimizeButton, hideCloseButton);
1859     if (isSuperFoldDisplayDevice) {
1860         handler_->PostTask([weakThis = wptr(this), where = __func__] {
1861             auto window = weakThis.promote();
1862             if (window == nullptr) {
1863                 TLOGNE(WmsLogTag::WMS_LAYOUT_PC, "%{public}s window is null", where);
1864                 return;
1865             }
1866             std::shared_ptr<Ace::UIContent> uiContent = window->GetUIContentSharedPtr();
1867             if (uiContent == nullptr || !window->IsDecorEnable()) {
1868                 TLOGND(WmsLogTag::WMS_LAYOUT_PC, "%{public}s uiContent unavailable", where);
1869                 return;
1870             }
1871             uiContent->OnContainerModalEvent(WINDOW_WATERFALL_VISIBILITY_EVENT,
1872                 window->supportEnterWaterfallMode_ ? "true" : "false");
1873         }, "UIContentOnContainerModalEvent");
1874     }
1875 }
1876 
HideTitleButton(bool & hideSplitButton,bool & hideMaximizeButton,bool & hideMinimizeButton,bool & hideCloseButton)1877 void WindowSessionImpl::HideTitleButton(bool& hideSplitButton, bool& hideMaximizeButton,
1878     bool& hideMinimizeButton, bool& hideCloseButton)
1879 {
1880     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1881     if (uiContent == nullptr || !IsDecorEnable()) {
1882         return;
1883     }
1884     hideMaximizeButton = hideMaximizeButton || property_->IsFullScreenDisabled();
1885     bool isLayoutFullScreen = property_->IsLayoutFullScreen();
1886     bool hideSplitBtn = hideSplitButton || property_->IsSplitDisabled();
1887     if (property_->IsAdaptToImmersive() && !property_->GetIsAtomicService()) {
1888         uiContent->HideWindowTitleButton(hideSplitBtn, !isLayoutFullScreen && hideMaximizeButton,
1889             hideMinimizeButton, hideCloseButton);
1890     } else {
1891         uiContent->HideWindowTitleButton(hideSplitBtn, hideMaximizeButton, hideMinimizeButton, hideCloseButton);
1892     }
1893     // compatible mode adapt to proportional scale, will show its button
1894     bool showScaleBtn = property_->IsAdaptToProportionalScale() && !property_->GetIsAtomicService();
1895     uiContent->OnContainerModalEvent(SCB_COMPATIBLE_MAXIMIZE_VISIBILITY,
1896         !isLayoutFullScreen && showScaleBtn  ? "true" : "false");
1897     // compatible mode adapt to back, will show its button
1898     bool isAdaptToBackButton = property_->IsAdaptToBackButton();
1899     uiContent->OnContainerModalEvent(SCB_BACK_VISIBILITY, isAdaptToBackButton ? "true" : "false");
1900 }
1901 
NapiSetUIContent(const std::string & contentInfo,ani_env * env,ani_object storage,BackupAndRestoreType type,sptr<IRemoteObject> token,AppExecFwk::Ability * ability)1902 WMError WindowSessionImpl::NapiSetUIContent(const std::string& contentInfo, ani_env* env, ani_object storage,
1903     BackupAndRestoreType type, sptr<IRemoteObject> token, AppExecFwk::Ability* ability)
1904 {
1905     return SetUIContentInner(contentInfo, env, storage,
1906         type == BackupAndRestoreType::NONE ? WindowSetUIContentType::DEFAULT : WindowSetUIContentType::RESTORE,
1907         type, ability, 1u);
1908 }
1909 
NapiSetUIContent(const std::string & contentInfo,napi_env env,napi_value storage,BackupAndRestoreType type,sptr<IRemoteObject> token,AppExecFwk::Ability * ability)1910 WMError WindowSessionImpl::NapiSetUIContent(const std::string& contentInfo, napi_env env, napi_value storage,
1911     BackupAndRestoreType type, sptr<IRemoteObject> token, AppExecFwk::Ability* ability)
1912 {
1913     WindowSetUIContentType setUIContentType;
1914     if (!navDestinationInfo_.empty()) {
1915         setUIContentType = WindowSetUIContentType::BY_SHARED;
1916     } else {
1917         setUIContentType =
1918             type == BackupAndRestoreType::NONE ? WindowSetUIContentType::DEFAULT : WindowSetUIContentType::RESTORE;
1919     }
1920     return SetUIContentInner(contentInfo, env, storage, setUIContentType, type, ability);
1921 }
1922 
SetUIContentByName(const std::string & contentInfo,napi_env env,napi_value storage,AppExecFwk::Ability * ability)1923 WMError WindowSessionImpl::SetUIContentByName(
1924     const std::string& contentInfo, napi_env env, napi_value storage, AppExecFwk::Ability* ability)
1925 {
1926     return SetUIContentInner(contentInfo, env, storage, WindowSetUIContentType::BY_NAME,
1927         BackupAndRestoreType::NONE, ability);
1928 }
1929 
SetUIContentByAbc(const std::string & contentInfo,napi_env env,napi_value storage,AppExecFwk::Ability * ability)1930 WMError WindowSessionImpl::SetUIContentByAbc(
1931     const std::string& contentInfo, napi_env env, napi_value storage, AppExecFwk::Ability* ability)
1932 {
1933     return SetUIContentInner(contentInfo, env, storage, WindowSetUIContentType::BY_ABC,
1934         BackupAndRestoreType::NONE, ability);
1935 }
1936 
DestroyExistUIContent()1937 void WindowSessionImpl::DestroyExistUIContent()
1938 {
1939     if (auto uiContent = GetUIContentSharedPtr()) {
1940         uiContent->Destroy();
1941     }
1942 }
1943 
UIContentCreate(AppExecFwk::Ability * ability,void * env,int isAni)1944 std::unique_ptr<Ace::UIContent> WindowSessionImpl::UIContentCreate(AppExecFwk::Ability* ability, void* env, int isAni)
1945 {
1946     if (isAni) {
1947         return  ability != nullptr ? Ace::UIContent::Create(ability) :
1948             Ace::UIContent::CreateWithAniEnv(GetContext().get(), reinterpret_cast<ani_env*>(env));
1949     } else {
1950         return  ability != nullptr ? Ace::UIContent::Create(ability) :
1951             Ace::UIContent::Create(GetContext().get(), reinterpret_cast<NativeEngine*>(env));
1952     }
1953 }
UIContentInitByName(Ace::UIContent * uiContent,const std::string & contentInfo,void * storage,int isAni)1954 Ace::UIContentErrorCode WindowSessionImpl::UIContentInitByName(Ace::UIContent* uiContent,
1955     const std::string& contentInfo, void* storage, int isAni)
1956 {
1957     if (isAni) {
1958         return uiContent->InitializeByNameWithAniStorage(this, contentInfo, (ani_object)storage);
1959     } else {
1960         return uiContent->InitializeByName(this, contentInfo, (napi_value)storage);
1961     }
1962 }
1963 
1964 template<typename T>
UIContentInit(Ace::UIContent * uiContent,T contentInfo,void * storage,int isAni)1965 Ace::UIContentErrorCode WindowSessionImpl::UIContentInit(Ace::UIContent* uiContent, T contentInfo,
1966     void* storage, int isAni)
1967 {
1968     if (isAni) {
1969         return uiContent->InitializeWithAniStorage(this, contentInfo, (ani_object)storage);
1970     } else {
1971         return uiContent->Initialize(this, contentInfo, (napi_value)storage);
1972     }
1973 }
1974 
UIContentRestore(Ace::UIContent * uiContent,const std::string & contentInfo,void * storage,Ace::ContentInfoType infoType,int isAni)1975 Ace::UIContentErrorCode WindowSessionImpl::UIContentRestore(Ace::UIContent* uiContent, const std::string& contentInfo,
1976     void* storage, Ace::ContentInfoType infoType, int isAni)
1977 {
1978     if (isAni) {
1979         return uiContent->Restore(this, contentInfo, (ani_object)storage, infoType);
1980     } else {
1981         return uiContent->Restore(this, contentInfo, (napi_value)storage, infoType);
1982     }
1983 }
1984 
InitUIContent(const std::string & contentInfo,void * env,void * storage,WindowSetUIContentType setUIContentType,BackupAndRestoreType restoreType,AppExecFwk::Ability * ability,OHOS::Ace::UIContentErrorCode & aceRet,int isAni)1985 WMError WindowSessionImpl::InitUIContent(const std::string& contentInfo, void* env, void* storage,
1986     WindowSetUIContentType setUIContentType, BackupAndRestoreType restoreType, AppExecFwk::Ability* ability,
1987     OHOS::Ace::UIContentErrorCode& aceRet, int isAni)
1988 {
1989     DestroyExistUIContent();
1990     std::unique_ptr<Ace::UIContent> uiContent = UIContentCreate(ability, (void*)env, isAni);
1991     if (uiContent == nullptr) {
1992         TLOGE(WmsLogTag::WMS_LIFE, "uiContent nullptr id: %{public}d", GetPersistentId());
1993         return WMError::WM_ERROR_NULLPTR;
1994     }
1995     switch (setUIContentType) {
1996         default:
1997         case WindowSetUIContentType::DEFAULT: {
1998             if (isUIExtensionAbilityProcess_ && property_->GetIsUIExtFirstSubWindow()) {
1999                 // subWindow created by UIExtensionAbility
2000                 uiContent->SetUIExtensionSubWindow(true);
2001                 uiContent->SetUIExtensionAbilityProcess(true);
2002             } else {
2003                 auto routerStack = GetRestoredRouterStack();
2004                 auto type = GetAceContentInfoType(BackupAndRestoreType::RESOURCESCHEDULE_RECOVERY);
2005                 if (!routerStack.empty() && UIContentRestore(uiContent.get(), routerStack, storage, type,
2006                     isAni) == Ace::UIContentErrorCode::NO_ERRORS) {
2007                     TLOGI(WmsLogTag::WMS_LIFE, "Restore router stack succeed.");
2008                     break;
2009                 }
2010             }
2011             if (!intentParam_.empty()) {
2012                 TLOGI(WmsLogTag::WMS_LIFE, "Default SetIntentParam, isColdStart:%{public}u", isIntentColdStart_);
2013                 uiContent->SetIntentParam(intentParam_, std::move(loadPageCallback_), isIntentColdStart_);
2014                 intentParam_ = "";
2015             }
2016             aceRet = UIContentInit(uiContent.get(), contentInfo, storage, isAni);
2017             break;
2018         }
2019         case WindowSetUIContentType::RESTORE:
2020             aceRet = UIContentRestore(uiContent.get(), contentInfo, storage, GetAceContentInfoType(restoreType), isAni);
2021             break;
2022         case WindowSetUIContentType::BY_NAME:
2023             if (!intentParam_.empty()) {
2024                 TLOGI(WmsLogTag::WMS_LIFE, "By name setIntentParam, isColdStart:%{public}u", isIntentColdStart_);
2025                 uiContent->SetIntentParam(intentParam_, std::move(loadPageCallback_), isIntentColdStart_);
2026                 intentParam_ = "";
2027             }
2028             aceRet = UIContentInitByName(uiContent.get(), contentInfo, storage, isAni);
2029             break;
2030         case WindowSetUIContentType::BY_SHARED:
2031             TLOGI(WmsLogTag::WMS_LIFE, "By shared, restoreNavDestinationInfo, id:%{public}d", GetPersistentId());
2032             uiContent->RestoreNavDestinationInfo(navDestinationInfo_, true);
2033             aceRet = UIContentInit(uiContent.get(), contentInfo, storage, isAni);
2034             navDestinationInfo_ = "";
2035             break;
2036         case WindowSetUIContentType::BY_ABC:
2037             aceRet = UIContentInit(uiContent.get(), GetAbcContent(contentInfo), storage, isAni);
2038             break;
2039     }
2040     // make uiContent available after Initialize/Restore
2041     {
2042         std::unique_lock<std::shared_mutex> lock(uiContentMutex_);
2043         uiContent_ = std::move(uiContent);
2044         // compatibleMode app in pc, need change decor title to float title bar
2045         if (property_->IsAdaptToImmersive()) {
2046             uiContent_->SetContainerModalTitleVisible(false, true);
2047             uiContent_->EnableContainerModalCustomGesture(true);
2048         }
2049         TLOGI(WmsLogTag::DEFAULT, "[%{public}d, %{public}d]",
2050             uiContent_->IsUIExtensionSubWindow(), uiContent_->IsUIExtensionAbilityProcess());
2051     }
2052     RegisterUIContenCallback();
2053     return WMError::WM_OK;
2054 }
2055 
RegisterUIContenCallback()2056 void WindowSessionImpl::RegisterUIContenCallback()
2057 {
2058     RegisterWatchFocusActiveChangeCallback();
2059     RegisterKeyFrameCallback();
2060 }
2061 
RegisterWatchFocusActiveChangeCallback()2062 void WindowSessionImpl::RegisterWatchFocusActiveChangeCallback()
2063 {
2064     if (auto uiContent = GetUIContentSharedPtr()) {
2065         uiContent->AddFocusActiveChangeCallback([this](bool isFocusActive) {
2066             NotifyWatchFocusActiveChange(isFocusActive);
2067         });
2068     } else {
2069         TLOGE(WmsLogTag::WMS_EVENT, "uiContent is nullptr");
2070     }
2071 }
2072 
RegisterKeyFrameCallback()2073 void WindowSessionImpl::RegisterKeyFrameCallback()
2074 {
2075     auto uiContent = GetUIContentSharedPtr();
2076     if (!uiContent) {
2077         TLOGE(WmsLogTag::WMS_EVENT, "uiContent is nullptr");
2078         return;
2079     }
2080     const char* const where = __func__;
2081     uiContent->AddKeyFrameCanvasNodeCallback([where, weakThis = wptr(this)](
2082         std::shared_ptr<RSCanvasNode>& rsCanvasNode, std::shared_ptr<RSTransaction>& rsTransaction) {
2083         auto window = weakThis.promote();
2084         if (!window) {
2085             TLOGNE(WmsLogTag::WMS_LAYOUT, "%{public}s window is null", where);
2086             return;
2087         }
2088         if (auto session = window->GetHostSession()) {
2089             session->UpdateKeyFrameCloneNode(rsCanvasNode, rsTransaction);
2090         } else {
2091             TLOGNE(WmsLogTag::WMS_LAYOUT, "%{public}s session is nullptr", where);
2092         }
2093     });
2094     uiContent->AddKeyFrameAnimateEndCallback([where, weakThis = wptr(this)]() {
2095         auto window = weakThis.promote();
2096         if (!window) {
2097             TLOGNE(WmsLogTag::WMS_LAYOUT, "%{public}s window is null", where);
2098             return;
2099         }
2100         if (auto session = window->GetHostSession()) {
2101             session->KeyFrameAnimateEnd();
2102         } else {
2103             TLOGNE(WmsLogTag::WMS_LAYOUT, "%{public}s session is nullptr", where);
2104         }
2105     });
2106 }
2107 
LinkKeyFrameCanvasNode(std::shared_ptr<RSCanvasNode> & rsCanvasNode)2108 WSError WindowSessionImpl::LinkKeyFrameCanvasNode(std::shared_ptr<RSCanvasNode>& rsCanvasNode)
2109 {
2110     TLOGD(WmsLogTag::WMS_LAYOUT, "in");
2111     auto uiContent = GetUIContentSharedPtr();
2112     auto session = GetHostSession();
2113     if (!uiContent || !session) {
2114         TLOGE(WmsLogTag::WMS_EVENT, "uiContent or session is nullptr");
2115         return WSError::WS_ERROR_NULLPTR;
2116     }
2117     RSAdapterUtil::SetRSUIContext(rsCanvasNode, GetRSUIContext(), true);
2118     uiContent->LinkKeyFrameCanvasNode(rsCanvasNode);
2119     return WSError::WS_OK;
2120 }
2121 
SetKeyFramePolicy(KeyFramePolicy & keyFramePolicy)2122 WSError WindowSessionImpl::SetKeyFramePolicy(KeyFramePolicy& keyFramePolicy)
2123 {
2124     TLOGD(WmsLogTag::WMS_LAYOUT, "in");
2125     keyFramePolicy_ = keyFramePolicy;
2126     return WSError::WS_OK;
2127 }
2128 
SetDragKeyFramePolicy(const KeyFramePolicy & keyFramePolicy)2129 WMError WindowSessionImpl::SetDragKeyFramePolicy(const KeyFramePolicy& keyFramePolicy)
2130 {
2131     TLOGD(WmsLogTag::WMS_LAYOUT, "in");
2132     auto session = GetHostSession();
2133     if (session == nullptr) {
2134         TLOGE(WmsLogTag::WMS_EVENT, "session is nullptr");
2135         return WMError::WM_ERROR_NULLPTR;
2136     }
2137     WSError errorCode = session->SetDragKeyFramePolicy(keyFramePolicy);
2138     TLOGI(WmsLogTag::WMS_LAYOUT, "Id: %{public}d, keyFramePolicy: %{public}s, errorCode: %{public}d",
2139         GetPersistentId(), keyFramePolicy.ToString().c_str(), static_cast<int32_t>(errorCode));
2140     return static_cast<WMError>(errorCode);
2141 }
2142 
NotifyWatchFocusActiveChange(bool isActive)2143 WMError WindowSessionImpl::NotifyWatchFocusActiveChange(bool isActive)
2144 {
2145     TLOGD(WmsLogTag::WMS_EVENT, "isActive:%{public}d", isActive);
2146     if (IsWindowSessionInvalid()) {
2147         return WMError::WM_ERROR_INVALID_WINDOW;
2148     }
2149     return SingletonContainer::Get<WindowAdapter>().NotifyWatchFocusActiveChange(isActive);
2150 }
2151 
SetForceSplitEnable(AppForceLandscapeConfig & config)2152 void WindowSessionImpl::SetForceSplitEnable(AppForceLandscapeConfig& config)
2153 {
2154     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
2155     if (uiContent == nullptr) {
2156         TLOGE(WmsLogTag::DEFAULT, "uiContent is null!");
2157         return;
2158     }
2159     bool isForceSplit = (config.mode_ == FORCE_SPLIT_MODE || config.mode_ == NAV_FORCE_SPLIT_MODE);
2160     bool isRouter = (config.supportSplit_ == FORCE_SPLIT_MODE);
2161     TLOGI(WmsLogTag::DEFAULT, "windowId: %{public}u, isForceSplit: %{public}u, homePage: %{public}s, "
2162         "supportSplit: %{public}d, isRouter: %{public}u, arkUIOptions: %{public}s",
2163         GetWindowId(), isForceSplit, config.homePage_.c_str(), config.supportSplit_, isRouter,
2164         config.arkUIOptions_.c_str());
2165     uiContent->SetForceSplitConfig(config.arkUIOptions_);
2166     uiContent->SetForceSplitEnable(isForceSplit, config.homePage_, isRouter);
2167 }
2168 
SetAppHookWindowInfo(const HookWindowInfo & hookWindowInfo)2169 void WindowSessionImpl::SetAppHookWindowInfo(const HookWindowInfo& hookWindowInfo)
2170 {
2171     std::unique_lock<std::shared_mutex> lock(hookWindowInfoMutex_);
2172     TLOGI(WmsLogTag::WMS_LAYOUT, "Id:%{public}u, preHookWindowInfo:[%{public}s], newHookWindowInfo:[%{public}s]",
2173         GetWindowId(), hookWindowInfo_.ToString().c_str(), hookWindowInfo.ToString().c_str());
2174     hookWindowInfo_ = hookWindowInfo;
2175 }
2176 
GetAppHookWindowInfo()2177 HookWindowInfo WindowSessionImpl::GetAppHookWindowInfo()
2178 {
2179     std::shared_lock<std::shared_mutex> lock(hookWindowInfoMutex_);
2180     return hookWindowInfo_;
2181 }
2182 
HookWindowSizeByHookWindowInfo(Rect & rect)2183 void WindowSessionImpl::HookWindowSizeByHookWindowInfo(Rect& rect)
2184 {
2185     auto hookWindowInfo = GetAppHookWindowInfo();
2186     if (!hookWindowInfo.enableHookWindow || !WindowHelper::IsMainWindow(GetType())) {
2187         TLOGD(WmsLogTag::WMS_LAYOUT, "Id:%{public}u, do not need hook window info.", GetWindowId());
2188         return;
2189     }
2190     if (!MathHelper::NearEqual(hookWindowInfo.widthHookRatio, HookWindowInfo::DEFAULT_WINDOW_SIZE_HOOK_RATIO)) {
2191         rect.width_ = static_cast<uint32_t>(rect.width_ * hookWindowInfo.widthHookRatio);
2192         TLOGD(WmsLogTag::WMS_LAYOUT, "Id:%{public}u, hook window width, hooked width:%{public}u, "
2193             "widthHookRatio:%{public}f.", GetWindowId(), rect.width_, hookWindowInfo.widthHookRatio);
2194     }
2195 }
2196 
SetUIContentInner(const std::string & contentInfo,void * env,void * storage,WindowSetUIContentType setUIContentType,BackupAndRestoreType restoreType,AppExecFwk::Ability * ability,int isAni)2197 WMError WindowSessionImpl::SetUIContentInner(const std::string& contentInfo, void* env, void* storage,
2198     WindowSetUIContentType setUIContentType, BackupAndRestoreType restoreType, AppExecFwk::Ability* ability,
2199     int isAni)
2200 {
2201     TLOGI(WmsLogTag::WMS_LIFE, "%{public}s, state:%{public}u, persistentId: %{public}d",
2202         contentInfo.c_str(), state_, GetPersistentId());
2203     if (IsWindowSessionInvalid()) {
2204         TLOGE(WmsLogTag::WMS_LIFE, "window is invalid! window state: %{public}d",
2205             state_);
2206         return WMError::WM_ERROR_INVALID_WINDOW;
2207     }
2208     if (GetUIContentSharedPtr() != nullptr) {
2209         shouldReNotifyHighlight_ = true;
2210     }
2211     NotifySetUIContentComplete();
2212     OHOS::Ace::UIContentErrorCode aceRet = OHOS::Ace::UIContentErrorCode::NO_ERRORS;
2213     WMError initUIContentRet = InitUIContent(contentInfo, env, storage, setUIContentType, restoreType, ability, aceRet,
2214         isAni);
2215     if (initUIContentRet != WMError::WM_OK) {
2216         TLOGE(WmsLogTag::WMS_LIFE, "Init UIContent fail, ret:%{public}u", initUIContentRet);
2217         return initUIContentRet;
2218     }
2219     if (auto uiContent = GetUIContentSharedPtr()) {
2220         TLOGI(WmsLogTag::WMS_LAYOUT, "id:%{public}d, posX:%{public}d, posY:%{public}d, "
2221               "scaleX:%{public}f, scaleY:%{public}f", GetPersistentId(),
2222               singleHandTransform_.posX, singleHandTransform_.posY,
2223               singleHandTransform_.scaleX, singleHandTransform_.scaleY);
2224         uiContent->UpdateSingleHandTransform(singleHandTransform_);
2225     }
2226     WindowType winType = GetType();
2227     bool isSubWindow = WindowHelper::IsSubWindow(winType);
2228     bool isDialogWindow = WindowHelper::IsDialogWindow(winType);
2229     if (IsDecorEnable()) {
2230         if (isSubWindow) {
2231             SetAPPWindowLabel(subWindowTitle_);
2232         } else if (isDialogWindow) {
2233             SetAPPWindowLabel(dialogTitle_);
2234         }
2235     }
2236 
2237     AppForceLandscapeConfig config = {};
2238     if (WindowHelper::IsMainWindow(winType) && GetAppForceLandscapeConfig(config) == WMError::WM_OK &&
2239         config.supportSplit_ > 0) {
2240         SetForceSplitEnable(config);
2241     }
2242 
2243     uint32_t version = 0;
2244     auto context = GetContext();
2245     if ((context != nullptr) && (context->GetApplicationInfo() != nullptr)) {
2246         version = context->GetApplicationInfo()->apiCompatibleVersion;
2247     }
2248     // 10 ArkUI new framework support after API10
2249     if (version < 10) {
2250         SetLayoutFullScreenByApiVersion(isIgnoreSafeArea_);
2251         if (!isSystembarPropertiesSet_) {
2252             SetSystemBarProperty(WindowType::WINDOW_TYPE_STATUS_BAR, SystemBarProperty());
2253         }
2254     } else if (isIgnoreSafeAreaNeedNotify_) {
2255         SetLayoutFullScreenByApiVersion(isIgnoreSafeArea_);
2256     } else if (isSubWindow) {
2257         SetLayoutFullScreenByApiVersion(isIgnoreSafeArea_);
2258         isIgnoreSafeAreaNeedNotify_ = false;
2259     }
2260 
2261     // UIContent may be nullptr on setting system bar properties, need to set menubar color on UIContent init.
2262     if (auto uiContent = GetUIContentSharedPtr()) {
2263         auto property = GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_STATUS_BAR);
2264         uiContent->SetStatusBarItemColor(property.contentColor_);
2265     }
2266 
2267     UpdateDecorEnable(true);
2268     if (state_ == WindowState::STATE_SHOWN) {
2269         // UIContent may be nullptr when show window, need to notify again when window is shown
2270         if (auto uiContent = GetUIContentSharedPtr()) {
2271             uiContent->Foreground();
2272         }
2273         UpdateTitleButtonVisibility();
2274     }
2275     UpdateViewportConfig(GetRect(), WindowSizeChangeReason::UNDEFINED);
2276     if (shouldReNotifyFocus_) {
2277         // uiContent may be nullptr when notify focus status, need to notify again when uiContent is not empty.
2278         NotifyUIContentFocusStatus();
2279         shouldReNotifyFocus_ = false;
2280     }
2281     if (shouldReNotifyHighlight_) {
2282         // uiContent may be nullptr when notify highlight status, need to notify again when uiContent is not empty.
2283         NotifyUIContentHighlightStatus(isHighlighted_);
2284         shouldReNotifyHighlight_ = false;
2285     }
2286     if (aceRet != OHOS::Ace::UIContentErrorCode::NO_ERRORS) {
2287         WLOGFE("failed to init or restore uicontent with file %{public}s. errorCode: %{public}d",
2288             contentInfo.c_str(), static_cast<uint16_t>(aceRet));
2289         return WMError::WM_ERROR_INVALID_PARAM;
2290     }
2291     NotifyAfterUIContentReady();
2292     TLOGD(WmsLogTag::WMS_LIFE, "end");
2293     return WMError::WM_OK;
2294 }
2295 
GetAbcContent(const std::string & abcPath)2296 std::shared_ptr<std::vector<uint8_t>> WindowSessionImpl::GetAbcContent(const std::string& abcPath)
2297 {
2298     std::filesystem::path abcFile { abcPath };
2299     if (abcFile.empty() || !abcFile.is_absolute() || !std::filesystem::exists(abcFile)) {
2300         WLOGFE("abc file path is not valid");
2301         return nullptr;
2302     }
2303     int begin, end;
2304     std::fstream file(abcFile, std::ios::in | std::ios::binary);
2305     if (!file) {
2306         WLOGFE("abc file is not valid");
2307         return nullptr;
2308     }
2309     begin = file.tellg();
2310     file.seekg(0, std::ios::end);
2311     end = file.tellg();
2312     int len = end - begin;
2313     WLOGFD("abc file: %{public}s, size: %{public}d", abcPath.c_str(), len);
2314 
2315     if (len <= 0) {
2316         WLOGFE("abc file size is 0");
2317         return nullptr;
2318     }
2319     std::vector<uint8_t> abcBytes(len);
2320     file.seekg(0, std::ios::beg);
2321     file.read(reinterpret_cast<char *>(abcBytes.data()), len);
2322     return std::make_shared<std::vector<uint8_t>>(abcBytes);
2323 }
2324 
UpdateDecorEnableToAce(bool isDecorEnable)2325 void WindowSessionImpl::UpdateDecorEnableToAce(bool isDecorEnable)
2326 {
2327     if (auto uiContent = GetUIContentSharedPtr()) {
2328         WindowMode mode = GetWindowMode();
2329         bool decorVisible = mode == WindowMode::WINDOW_MODE_FLOATING ||
2330             mode == WindowMode::WINDOW_MODE_SPLIT_PRIMARY || mode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY ||
2331             (mode == WindowMode::WINDOW_MODE_FULLSCREEN && !property_->IsLayoutFullScreen());
2332         TLOGD(WmsLogTag::WMS_DECOR, "decorVisible:%{public}d", decorVisible);
2333         if (windowSystemConfig_.freeMultiWindowSupport_) {
2334             auto isSubWindow = WindowHelper::IsSubWindow(GetType());
2335             decorVisible = decorVisible && (windowSystemConfig_.freeMultiWindowEnable_ ||
2336                 (property_->GetIsPcAppInPad() && isSubWindow));
2337         }
2338         if (GetWindowMode() == WindowMode::WINDOW_MODE_FULLSCREEN && property_->IsDecorFullscreenDisabled()) {
2339             decorVisible = false;
2340         }
2341         uiContent->UpdateDecorVisible(decorVisible, isDecorEnable);
2342         return;
2343     }
2344 
2345     std::lock_guard<std::recursive_mutex> lockListener(windowChangeListenerMutex_);
2346     auto windowChangeListeners = GetListeners<IWindowChangeListener>();
2347     for (auto& listener : windowChangeListeners) {
2348         if (listener.GetRefPtr() != nullptr) {
2349             listener.GetRefPtr()->OnModeChange(GetWindowMode(), isDecorEnable);
2350         }
2351     }
2352 }
2353 
UpdateDecorEnable(bool needNotify,WindowMode mode)2354 void WindowSessionImpl::UpdateDecorEnable(bool needNotify, WindowMode mode)
2355 {
2356     if (mode == WindowMode::WINDOW_MODE_UNDEFINED) {
2357         mode = GetWindowMode();
2358     }
2359     if (needNotify) {
2360         if (auto uiContent = GetUIContentSharedPtr()) {
2361             bool decorVisible = mode == WindowMode::WINDOW_MODE_FLOATING ||
2362                 mode == WindowMode::WINDOW_MODE_SPLIT_PRIMARY || mode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY ||
2363                 (mode == WindowMode::WINDOW_MODE_FULLSCREEN && !property_->IsLayoutFullScreen());
2364             if (windowSystemConfig_.freeMultiWindowSupport_) {
2365                 auto isSubWindow = WindowHelper::IsSubWindow(GetType());
2366                 decorVisible = decorVisible && (windowSystemConfig_.freeMultiWindowEnable_ ||
2367                     (property_->GetIsPcAppInPad() && isSubWindow));
2368             }
2369             TLOGI(WmsLogTag::WMS_DECOR, "decorVisible:%{public}d, id: %{public}d", decorVisible, GetPersistentId());
2370             uiContent->UpdateDecorVisible(decorVisible, IsDecorEnable());
2371             uiContent->NotifyWindowMode(mode);
2372         }
2373         NotifyModeChange(mode, IsDecorEnable());
2374     }
2375 }
2376 
2377 /** @note @window.layout */
NotifyModeChange(WindowMode mode,bool hasDeco)2378 void WindowSessionImpl::NotifyModeChange(WindowMode mode, bool hasDeco)
2379 {
2380     {
2381         std::lock_guard<std::recursive_mutex> lockListener(windowChangeListenerMutex_);
2382         auto windowChangeListeners = GetListeners<IWindowChangeListener>();
2383         for (auto& listener : windowChangeListeners) {
2384             if (listener.GetRefPtr() != nullptr) {
2385                 listener.GetRefPtr()->OnModeChange(mode, hasDeco);
2386             }
2387         }
2388     }
2389 
2390     if (GetHostSession()) {
2391         property_->SetWindowMode(mode);
2392         property_->SetDecorEnable(hasDeco);
2393     }
2394     UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_MODE);
2395     UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_DECOR_ENABLE);
2396 }
2397 
GetSurfaceNode() const2398 std::shared_ptr<RSSurfaceNode> WindowSessionImpl::GetSurfaceNode() const
2399 {
2400     TLOGI(WmsLogTag::DEFAULT, "name:%{public}s, id:%{public}d",
2401         property_->GetWindowName().c_str(), GetPersistentId());
2402     return surfaceNode_;
2403 }
2404 
GetContext() const2405 const std::shared_ptr<AbilityRuntime::Context> WindowSessionImpl::GetContext() const
2406 {
2407     TLOGD(WmsLogTag::DEFAULT, "name:%{public}s, id:%{public}d",
2408         property_->GetWindowName().c_str(), GetPersistentId());
2409     std::shared_lock<std::shared_mutex> lock(contextMutex_);
2410     return context_;
2411 }
2412 
SetContext(const std::shared_ptr<AbilityRuntime::Context> & context)2413 void WindowSessionImpl::SetContext(const std::shared_ptr<AbilityRuntime::Context>& context)
2414 {
2415     std::unique_lock<std::shared_mutex> lock(contextMutex_);
2416     context_ = context;
2417 }
2418 
GetRequestRect() const2419 Rect WindowSessionImpl::GetRequestRect() const
2420 {
2421     return property_->GetRequestRect();
2422 }
2423 
GetGlobalDisplayRect() const2424 Rect WindowSessionImpl::GetGlobalDisplayRect() const
2425 {
2426     return property_->GetGlobalDisplayRect();
2427 }
2428 
ClientToGlobalDisplay(const Position & inPosition,Position & outPosition) const2429 WMError WindowSessionImpl::ClientToGlobalDisplay(const Position& inPosition, Position& outPosition) const
2430 {
2431     const auto windowId = GetWindowId();
2432     const auto transform = GetCurrentTransform();
2433     if (WindowHelper::IsScaled(transform)) {
2434         TLOGW(WmsLogTag::WMS_LAYOUT,
2435             "Scaled window is not supported, windowId: %{public}u, scaleX: %{public}f, scaleY: %{public}f",
2436             windowId, transform.scaleX_, transform.scaleY_);
2437         return WMError::WM_ERROR_INVALID_OP_IN_CUR_STATUS;
2438     }
2439     const auto globalDisplayRect = GetGlobalDisplayRect();
2440     const Position& basePosition = {globalDisplayRect.posX_, globalDisplayRect.posY_};
2441     if (!inPosition.SafeAdd(basePosition, outPosition)) {
2442         TLOGW(WmsLogTag::WMS_LAYOUT,
2443             "Position overflow, windowId: %{public}u, inPosition: %{public}s, basePosition: %{public}s",
2444             windowId, inPosition.ToString().c_str(), basePosition.ToString().c_str());
2445         return WMError::WM_ERROR_ILLEGAL_PARAM;
2446     }
2447     TLOGD(WmsLogTag::WMS_LAYOUT,
2448         "windowId: %{public}u, globalDisplayRect: %{public}s, inPosition: %{public}s, outPosition: %{public}s",
2449         windowId, globalDisplayRect.ToString().c_str(),
2450         inPosition.ToString().c_str(), outPosition.ToString().c_str());
2451     return WMError::WM_OK;
2452 }
2453 
GlobalDisplayToClient(const Position & inPosition,Position & outPosition) const2454 WMError WindowSessionImpl::GlobalDisplayToClient(const Position& inPosition, Position& outPosition) const
2455 {
2456     const auto windowId = GetWindowId();
2457     const auto transform = GetCurrentTransform();
2458     if (WindowHelper::IsScaled(transform)) {
2459         TLOGW(WmsLogTag::WMS_LAYOUT,
2460             "Scaled window is not supported, windowId: %{public}u, scaleX: %{public}f, scaleY: %{public}f",
2461             windowId, transform.scaleX_, transform.scaleY_);
2462         return WMError::WM_ERROR_INVALID_OP_IN_CUR_STATUS;
2463     }
2464     const auto globalDisplayRect = GetGlobalDisplayRect();
2465     const Position& basePosition = {globalDisplayRect.posX_, globalDisplayRect.posY_};
2466     if (!inPosition.SafeSub(basePosition, outPosition)) {
2467         TLOGW(WmsLogTag::WMS_LAYOUT,
2468             "Position overflow, windowId: %{public}u, inPosition: %{public}s, basePosition: %{public}s",
2469             windowId, inPosition.ToString().c_str(), basePosition.ToString().c_str());
2470         return WMError::WM_ERROR_ILLEGAL_PARAM;
2471     }
2472     TLOGD(WmsLogTag::WMS_LAYOUT,
2473         "windowId: %{public}u, globalDisplayRect: %{public}s, inPosition: %{public}s, outPosition: %{public}s",
2474         windowId, globalDisplayRect.ToString().c_str(),
2475         inPosition.ToString().c_str(), outPosition.ToString().c_str());
2476     return WMError::WM_OK;
2477 }
2478 
UpdateGlobalDisplayRectFromServer(const WSRect & rect,SizeChangeReason reason)2479 WSError WindowSessionImpl::UpdateGlobalDisplayRectFromServer(const WSRect& rect, SizeChangeReason reason)
2480 {
2481     const uint32_t windowId = GetWindowId();
2482     TLOGD(WmsLogTag::WMS_LAYOUT, "windowId: %{public}u, rect: %{public}s, reason: %{public}u",
2483         windowId, rect.ToString().c_str(), reason);
2484 
2485     // According to the drag specification, in drag-move scenarios, if the final reason is DRAG_END
2486     // but the last recorded reason is neither DRAG_START nor DRAG, override it to DRAG_MOVE
2487     // to ensure consistent handling of drag operations (same as JsWindowListener::OnRectChange).
2488     if (reason == SizeChangeReason::DRAG_END &&
2489         globalDisplayRectSizeChangeReason_ != SizeChangeReason::DRAG_START &&
2490         globalDisplayRectSizeChangeReason_ != SizeChangeReason::DRAG) {
2491         TLOGD(WmsLogTag::WMS_LAYOUT, "Override DRAG_END to DRAG_MOVE, windowId: %{public}u", windowId);
2492         reason = SizeChangeReason::DRAG_MOVE;
2493     }
2494 
2495     Rect newRect = { rect.posX_, rect.posY_, rect.width_, rect.height_ };
2496     if (newRect == GetGlobalDisplayRect() && reason == globalDisplayRectSizeChangeReason_) {
2497         TLOGD(WmsLogTag::WMS_LAYOUT,
2498             "No change in rect or reason, windowId: %{public}d, rect: %{public}s, reason: %{public}u",
2499             windowId, rect.ToString().c_str(), reason);
2500         return WSError::WS_DO_NOTHING;
2501     }
2502     property_->SetGlobalDisplayRect(newRect);
2503     globalDisplayRectSizeChangeReason_ = reason;
2504     auto windowSizeChangeReason = static_cast<WindowSizeChangeReason>(reason);
2505     layoutCallback_->OnUpdateGlobalDisplayRect(newRect, windowSizeChangeReason, GetPersistentId());
2506     NotifyGlobalDisplayRectChange(newRect, windowSizeChangeReason);
2507     return WSError::WS_OK;
2508 }
2509 
GetType() const2510 WindowType WindowSessionImpl::GetType() const
2511 {
2512     return property_->GetWindowType();
2513 }
2514 
GetWindowName() const2515 const std::string& WindowSessionImpl::GetWindowName() const
2516 {
2517     return property_->GetWindowName();
2518 }
2519 
GetWindowState() const2520 WindowState WindowSessionImpl::GetWindowState() const
2521 {
2522     return state_;
2523 }
2524 
GetRequestWindowState() const2525 WindowState WindowSessionImpl::GetRequestWindowState() const
2526 {
2527     return requestState_;
2528 }
2529 
NotifyExtensionSecureLimitChange(bool isLimit)2530 WSError WindowSessionImpl::NotifyExtensionSecureLimitChange(bool isLimit)
2531 {
2532     TLOGI(WmsLogTag::WMS_UIEXT, "windowId: %{public}d, isLimite: %{public}u", GetPersistentId(), isLimit);
2533     std::vector<sptr<IExtensionSecureLimitChangeListener>> secureLimitChangeListeners;
2534     {
2535         std::lock_guard<std::mutex> lockListener(secureLimitChangeListenerMutex_);
2536         secureLimitChangeListeners = GetListeners<IExtensionSecureLimitChangeListener>();
2537     }
2538     for (const auto& listener : secureLimitChangeListeners) {
2539         if (listener != nullptr) {
2540             listener->OnSecureLimitChange(isLimit);
2541         }
2542     }
2543     if (auto uiContent = GetUIContentSharedPtr()) {
2544         AAFwk::Want want;
2545         want.SetParam(Extension::EXTENSION_SECURE_LIMIT_CHANGE, isLimit);
2546         uiContent->SendUIExtProprty(
2547             static_cast<uint32_t>(Extension::Businesscode::NOTIFY_EXTENSION_SECURE_LIMIT_CHANGE),
2548             want, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
2549     }
2550     return WSError::WS_OK;
2551 }
2552 
2553 /** @note @window.focus */
SetExclusivelyHighlighted(bool isExclusivelyHighlighted)2554 WMError WindowSessionImpl::SetExclusivelyHighlighted(bool isExclusivelyHighlighted)
2555 {
2556     if (IsWindowSessionInvalid()) {
2557         return WMError::WM_ERROR_INVALID_WINDOW;
2558     }
2559     TLOGI(WmsLogTag::WMS_FOCUS, "windowId: %{public}d, isExclusivelyHighlighted: %{public}d",
2560         property_->GetPersistentId(), isExclusivelyHighlighted);
2561     if (WindowHelper::IsMainWindow(GetType()) || WindowHelper::IsDialogWindow(GetType()) ||
2562         WindowHelper::IsModalWindow(property_->GetWindowFlags())) {
2563         TLOGE(WmsLogTag::WMS_FOCUS, "unsupport window, type: %{public}u, windowFlags: %{public}u ",
2564             GetType(), property_->GetWindowFlags());
2565         return WMError::WM_ERROR_INVALID_CALLING;
2566     }
2567     if (property_->GetExclusivelyHighlighted() == isExclusivelyHighlighted) {
2568         TLOGD(WmsLogTag::WMS_FOCUS, "already exclusivelyHighlighted");
2569         return WMError::WM_OK;
2570     }
2571     property_->SetExclusivelyHighlighted(isExclusivelyHighlighted);
2572     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_EXCLUSIVE_HIGHLIGHTED);
2573 }
2574 
2575 /** @note @window.focus */
GetExclusivelyHighlighted() const2576 bool WindowSessionImpl::GetExclusivelyHighlighted() const
2577 {
2578     bool isExclusivelyHighlighted = property_->GetExclusivelyHighlighted();
2579     TLOGD(WmsLogTag::WMS_FOCUS, "windowId: %{public}d, isExclusivelyHighlighted: %{public}d",
2580         property_->GetPersistentId(), isExclusivelyHighlighted);
2581     return isExclusivelyHighlighted;
2582 }
2583 
2584 /** @note @window.focus */
NotifyHighlightChange(bool isHighlight)2585 WSError WindowSessionImpl::NotifyHighlightChange(bool isHighlight)
2586 {
2587     TLOGI(WmsLogTag::WMS_FOCUS, "windowId: %{public}d, isHighlight: %{public}u,", GetPersistentId(), isHighlight);
2588     isHighlighted_ = isHighlight;
2589     if (GetUIContentSharedPtr() != nullptr) {
2590         NotifyUIContentHighlightStatus(isHighlighted_);
2591     } else {
2592         shouldReNotifyHighlight_ = true;
2593     }
2594     std::lock_guard<std::mutex> lockListener(highlightChangeListenerMutex_);
2595     auto highlightChangeListeners = GetListeners<IWindowHighlightChangeListener>();
2596     for (const auto& listener : highlightChangeListeners) {
2597         if (listener != nullptr) {
2598             listener->OnWindowHighlightChange(isHighlight);
2599         }
2600     }
2601     return WSError::WS_OK;
2602 }
2603 
2604 /** @note @window.focus */
IsWindowHighlighted(bool & highlighted) const2605 WMError WindowSessionImpl::IsWindowHighlighted(bool& highlighted) const
2606 {
2607     if (IsWindowSessionInvalid()) {
2608         TLOGE(WmsLogTag::WMS_FOCUS, "session is invalid");
2609         return WMError::WM_ERROR_INVALID_WINDOW;
2610     }
2611     auto hostSession = GetHostSession();
2612     hostSession->GetIsHighlighted(highlighted);
2613     TLOGD(WmsLogTag::WMS_FOCUS, "windowId: %{public}d, isWindowHighlighted: %{public}d",
2614         GetPersistentId(), highlighted);
2615     return WMError::WM_OK;
2616 }
2617 
SetFocusable(bool isFocusable)2618 WMError WindowSessionImpl::SetFocusable(bool isFocusable)
2619 {
2620     if (IsWindowSessionInvalid()) {
2621         return WMError::WM_ERROR_INVALID_WINDOW;
2622     }
2623     TLOGI(WmsLogTag::WMS_FOCUS, "set focusable: windowId=%{public}d, isFocusable=%{public}d",
2624         property_->GetPersistentId(), isFocusable);
2625     property_->SetFocusable(isFocusable);
2626     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_FOCUSABLE);
2627 }
2628 
GetFocusable() const2629 bool WindowSessionImpl::GetFocusable() const
2630 {
2631     bool isFocusable = property_->GetFocusable();
2632     TLOGD(WmsLogTag::WMS_FOCUS, "get focusable: windowId=%{public}d, isFocusable=%{public}d",
2633         property_->GetPersistentId(), isFocusable);
2634     return isFocusable;
2635 }
2636 
SetTouchable(bool isTouchable)2637 WMError WindowSessionImpl::SetTouchable(bool isTouchable)
2638 {
2639     WLOGFD("%{public}d", isTouchable);
2640     if (IsWindowSessionInvalid()) {
2641         return WMError::WM_ERROR_INVALID_WINDOW;
2642     }
2643     property_->SetTouchable(isTouchable);
2644     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_TOUCHABLE);
2645 }
2646 
2647 /** @note @window.hierarchy */
SetTopmost(bool topmost)2648 WMError WindowSessionImpl::SetTopmost(bool topmost)
2649 {
2650     TLOGD(WmsLogTag::WMS_HIERARCHY, "%{public}d", topmost);
2651     if (!windowSystemConfig_.IsPcWindow()) {
2652         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
2653     }
2654     if (IsWindowSessionInvalid()) {
2655         return WMError::WM_ERROR_INVALID_WINDOW;
2656     }
2657     property_->SetTopmost(topmost);
2658     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_TOPMOST);
2659 }
2660 
2661 /** @note @window.hierarchy */
IsTopmost() const2662 bool WindowSessionImpl::IsTopmost() const
2663 {
2664     return property_->IsTopmost();
2665 }
2666 
2667 /** @note @window.hierarchy */
SetMainWindowTopmost(bool isTopmost)2668 WMError WindowSessionImpl::SetMainWindowTopmost(bool isTopmost)
2669 {
2670     if (IsWindowSessionInvalid()) {
2671         TLOGE(WmsLogTag::WMS_HIERARCHY, "session is invalid");
2672         return WMError::WM_ERROR_INVALID_WINDOW;
2673     }
2674     if (!IsPcOrPadFreeMultiWindowMode()) {
2675         TLOGE(WmsLogTag::WMS_HIERARCHY, "device not support");
2676         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
2677     }
2678     if (!WindowHelper::IsMainWindow(GetType())) {
2679         TLOGE(WmsLogTag::WMS_HIERARCHY, "window type is not supported");
2680         return WMError::WM_ERROR_INVALID_CALLING;
2681     }
2682     property_->SetMainWindowTopmost(isTopmost);
2683     uint32_t accessTokenId = static_cast<uint32_t>(IPCSkeleton::GetCallingTokenID());
2684     property_->SetAccessTokenId(accessTokenId);
2685     TLOGD(WmsLogTag::WMS_HIERARCHY, "tokenId=%{private}u, isTopmost=%{public}d", accessTokenId, isTopmost);
2686     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_MAIN_WINDOW_TOPMOST);
2687 }
2688 
2689 /** @note @window.hierarchy */
RaiseToAppTopOnDrag()2690 WMError WindowSessionImpl::RaiseToAppTopOnDrag()
2691 {
2692     TLOGI(WmsLogTag::WMS_HIERARCHY, "id: %{public}d", GetPersistentId());
2693     if (IsWindowSessionInvalid()) {
2694         TLOGE(WmsLogTag::WMS_HIERARCHY, "session is nullptr");
2695         return WMError::WM_ERROR_INVALID_WINDOW;
2696     }
2697     if (!WindowHelper::IsAppWindow(GetType())) {
2698         TLOGE(WmsLogTag::WMS_HIERARCHY, "must be app window");
2699         return WMError::WM_ERROR_INVALID_CALLING;
2700     }
2701     auto hostSession = GetHostSession();
2702     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_NULLPTR);
2703     if (WindowHelper::IsSubWindow(GetType())) {
2704         return static_cast<WMError>(hostSession->RaiseToAppTop());
2705     }
2706     return static_cast<WMError>(hostSession->RaiseAppMainWindowToTop());
2707 }
2708 
IsMainWindowTopmost() const2709 bool WindowSessionImpl::IsMainWindowTopmost() const
2710 {
2711     return property_->IsMainWindowTopmost();
2712 }
2713 
SetWindowDelayRaiseEnabled(bool isEnabled)2714 WMError WindowSessionImpl::SetWindowDelayRaiseEnabled(bool isEnabled)
2715 {
2716     if (IsWindowSessionInvalid()) {
2717         return WMError::WM_ERROR_INVALID_WINDOW;
2718     }
2719     if (IsPadAndNotFreeMutiWindowCompatibleMode()) {
2720         TLOGE(WmsLogTag::WMS_FOCUS, "The is PcAppInPad, not supported");
2721         return WMError::WM_OK;
2722     }
2723     if (!IsPcOrPadFreeMultiWindowMode()) {
2724         TLOGE(WmsLogTag::WMS_FOCUS, "The device is not supported");
2725         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
2726     }
2727     if (!WindowHelper::IsAppWindow(GetType())) {
2728         TLOGE(WmsLogTag::WMS_FOCUS, "window type is not supported");
2729         return WMError::WM_ERROR_INVALID_TYPE;
2730     }
2731     property_->SetWindowDelayRaiseEnabled(isEnabled);
2732     TLOGI(WmsLogTag::WMS_FOCUS, "isEnabled: %{public}d", isEnabled);
2733     AAFwk::Want want;
2734     want.SetParam(Extension::HOST_WINDOW_DELAY_RAISE_STATE_FIELD, isEnabled);
2735     if (auto uiContent = GetUIContentSharedPtr()) {
2736         uiContent->SendUIExtProprty(static_cast<uint32_t>(Extension::Businesscode::SYNC_HOST_WINDOW_DELAY_RAISE_STATE),
2737             want, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
2738     }
2739     return WMError::WM_OK;
2740 }
2741 
IsWindowDelayRaiseEnabled() const2742 bool WindowSessionImpl::IsWindowDelayRaiseEnabled() const
2743 {
2744     return property_->IsWindowDelayRaiseEnabled();
2745 }
2746 
SetResizeByDragEnabled(bool dragEnabled)2747 WMError WindowSessionImpl::SetResizeByDragEnabled(bool dragEnabled)
2748 {
2749     TLOGD(WmsLogTag::WMS_LAYOUT, "%{public}d", dragEnabled);
2750     if (IsWindowSessionInvalid()) {
2751         TLOGE(WmsLogTag::WMS_LAYOUT, "Session is invalid");
2752         return WMError::WM_ERROR_INVALID_WINDOW;
2753     }
2754     if (WindowHelper::IsMainWindow(GetType()) ||
2755         (WindowHelper::IsSubWindow(GetType()) && windowOption_->GetSubWindowDecorEnable())) {
2756         property_->SetDragEnabled(dragEnabled);
2757         hasSetEnableDrag_.store(true);
2758     } else {
2759         TLOGE(WmsLogTag::WMS_LAYOUT, "This is not main window or decor enabled sub window.");
2760         return WMError::WM_ERROR_INVALID_TYPE;
2761     }
2762     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_DRAGENABLED);
2763 }
2764 
2765 /** @note @window.hierarchy */
SetRaiseByClickEnabled(bool raiseEnabled)2766 WMError WindowSessionImpl::SetRaiseByClickEnabled(bool raiseEnabled)
2767 {
2768     WLOGFD("%{public}d", raiseEnabled);
2769     auto parentId = GetParentId();
2770     if (parentId == INVALID_SESSION_ID) {
2771         TLOGE(WmsLogTag::WMS_HIERARCHY, "Window id: %{public}d Parent id is invalid!",
2772               GetPersistentId());
2773         return WMError::WM_ERROR_INVALID_PARENT;
2774     }
2775 
2776     if (!WindowHelper::IsSubWindow(GetType())) {
2777         TLOGE(WmsLogTag::WMS_HIERARCHY, "Window id: %{public}d Must be app sub window!",
2778               GetPersistentId());
2779         return WMError::WM_ERROR_INVALID_CALLING;
2780     }
2781 
2782     if (state_ != WindowState::STATE_SHOWN) {
2783         TLOGE(WmsLogTag::WMS_HIERARCHY, "Window id: %{public}d The sub window must be shown!",
2784               GetPersistentId());
2785         return WMError::WM_DO_NOTHING;
2786     }
2787     if (IsWindowSessionInvalid()) {
2788         return WMError::WM_ERROR_INVALID_WINDOW;
2789     }
2790 
2791     property_->SetRaiseEnabled(raiseEnabled);
2792     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_RAISEENABLED);
2793 }
2794 
2795 /** @note @window.immersive */
SetAvoidAreaOption(uint32_t avoidAreaOption)2796 WMError WindowSessionImpl::SetAvoidAreaOption(uint32_t avoidAreaOption)
2797 {
2798     if (IsWindowSessionInvalid()) {
2799         TLOGE(WmsLogTag::WMS_IMMS, "Session is invalid");
2800         return WMError::WM_ERROR_INVALID_WINDOW;
2801     }
2802     property_->SetAvoidAreaOption(avoidAreaOption);
2803     TLOGI(WmsLogTag::WMS_IMMS, "win %{public}d, set option %{public}d",
2804         GetPersistentId(), avoidAreaOption);
2805     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_AVOID_AREA_OPTION);
2806 }
2807 
2808 /** @note @window.immersive */
GetAvoidAreaOption(uint32_t & avoidAreaOption)2809 WMError WindowSessionImpl::GetAvoidAreaOption(uint32_t& avoidAreaOption)
2810 {
2811     if (IsWindowSessionInvalid()) {
2812         TLOGE(WmsLogTag::WMS_IMMS, "Session is invalid");
2813         return WMError::WM_ERROR_INVALID_WINDOW;
2814     }
2815     avoidAreaOption = property_->GetAvoidAreaOption();
2816     return WMError::WM_OK;
2817 }
2818 
HideNonSystemFloatingWindows(bool shouldHide)2819 WMError WindowSessionImpl::HideNonSystemFloatingWindows(bool shouldHide)
2820 {
2821     WLOGFD("%{public}d", shouldHide);
2822     if (IsWindowSessionInvalid()) {
2823         return WMError::WM_ERROR_INVALID_WINDOW;
2824     }
2825     property_->SetHideNonSystemFloatingWindows(shouldHide);
2826     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_HIDE_NON_SYSTEM_FLOATING_WINDOWS);
2827 }
2828 
SetLandscapeMultiWindow(bool isLandscapeMultiWindow)2829 WMError WindowSessionImpl::SetLandscapeMultiWindow(bool isLandscapeMultiWindow)
2830 {
2831     TLOGI(WmsLogTag::WMS_MULTI_WINDOW, "isLandscapeMultiWindow:%{public}d",
2832         isLandscapeMultiWindow);
2833     if (IsWindowSessionInvalid()) {
2834         TLOGE(WmsLogTag::WMS_MULTI_WINDOW, "Session is invalid");
2835         return WMError::WM_ERROR_INVALID_WINDOW;
2836     }
2837     auto hostSession = GetHostSession();
2838     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
2839     hostSession->SetLandscapeMultiWindow(isLandscapeMultiWindow);
2840     return WMError::WM_OK;
2841 }
2842 
SetSingleFrameComposerEnabled(bool enable)2843 WMError WindowSessionImpl::SetSingleFrameComposerEnabled(bool enable)
2844 {
2845     WLOGFD("enable %{public}d", enable);
2846     if (IsWindowSessionInvalid()) {
2847         WLOGE("The window state is invalid ");
2848         return WMError::WM_ERROR_INVALID_WINDOW;
2849     }
2850 
2851     if (surfaceNode_ == nullptr) {
2852         WLOGE("The surface node is nullptr");
2853         return WMError::WM_ERROR_INVALID_WINDOW;
2854     }
2855 
2856     surfaceNode_->MarkNodeSingleFrameComposer(enable);
2857     RSTransactionAdapter::FlushImplicitTransaction(surfaceNode_);
2858     return WMError::WM_OK;
2859 }
2860 
IsFloatingWindowAppType() const2861 bool WindowSessionImpl::IsFloatingWindowAppType() const
2862 {
2863     if (IsWindowSessionInvalid()) {
2864         return false;
2865     }
2866     return property_->IsFloatingWindowAppType();
2867 }
2868 
GetTouchable() const2869 bool WindowSessionImpl::GetTouchable() const
2870 {
2871     return property_->GetTouchable();
2872 }
2873 
SetWindowType(WindowType type)2874 WMError WindowSessionImpl::SetWindowType(WindowType type)
2875 {
2876     TLOGD(WmsLogTag::DEFAULT, "%{public}u type %{public}u", GetWindowId(), static_cast<uint32_t>(type));
2877     if (type != WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW && !SessionPermission::IsSystemCalling()) {
2878         TLOGE(WmsLogTag::DEFAULT, "permission denied!");
2879         return WMError::WM_ERROR_NOT_SYSTEM_APP;
2880     }
2881     if (IsWindowSessionInvalid()) {
2882         TLOGE(WmsLogTag::DEFAULT, "Session is invalid");
2883         return WMError::WM_ERROR_INVALID_WINDOW;
2884     }
2885     property_->SetWindowType(type);
2886     UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_OTHER_PROPS);
2887     return WMError::WM_OK;
2888 }
2889 
SetBrightness(float brightness)2890 WMError WindowSessionImpl::SetBrightness(float brightness)
2891 {
2892     if ((brightness < MINIMUM_BRIGHTNESS &&
2893          std::fabs(brightness - UNDEFINED_BRIGHTNESS) >= std::numeric_limits<float>::min()) ||
2894         brightness > MAXIMUM_BRIGHTNESS) {
2895         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "invalid brightness value: %{public}f", brightness);
2896         return WMError::WM_ERROR_INVALID_PARAM;
2897     }
2898     if (!(WindowHelper::IsAppWindow(GetType()) || GetType() == WindowType::WINDOW_TYPE_WALLET_SWIPE_CARD)) {
2899         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "non app window does not support set brightness, type: %{public}u", GetType());
2900         return WMError::WM_ERROR_INVALID_TYPE;
2901     }
2902     property_->SetBrightness(brightness);
2903     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_SET_BRIGHTNESS);
2904 }
2905 
GetBrightness() const2906 float WindowSessionImpl::GetBrightness() const
2907 {
2908     return property_->GetBrightness();
2909 }
2910 
SetRequestedOrientation(Orientation orientation,bool needAnimation)2911 void WindowSessionImpl::SetRequestedOrientation(Orientation orientation, bool needAnimation)
2912 {
2913     if (IsWindowSessionInvalid()) {
2914         TLOGE(WmsLogTag::DEFAULT, "windowSession is invalid");
2915         return;
2916     }
2917     TLOGI(WmsLogTag::WMS_MAIN, "id:%{public}u lastReqOrientation:%{public}u target:%{public}u state:%{public}u",
2918         GetPersistentId(), property_->GetRequestedOrientation(), orientation, state_);
2919     if (!isNeededForciblySetOrientation(orientation)) {
2920         return;
2921     }
2922     if (needAnimation) {
2923         NotifyPreferredOrientationChange(orientation);
2924         SetUserRequestedOrientation(orientation);
2925     }
2926     // when compatible mode disable fullscreen and request orientation, will enter into immersive mode
2927     if (property_->IsFullScreenDisabled() && IsHorizontalOrientation(orientation)) {
2928         TLOGI(WmsLogTag::WMS_COMPAT, "compatible request horizontal orientation %{public}u", orientation);
2929         property_->SetIsLayoutFullScreen(true);
2930     }
2931     // the orientation of the invalid type is only applied to pageRotation.
2932     if (orientation == Orientation::INVALID) {
2933         Orientation requestedOrientation = ConvertInvalidOrientation();
2934         property_->SetRequestedOrientation(requestedOrientation, needAnimation);
2935     } else {
2936         property_->SetRequestedOrientation(orientation, needAnimation);
2937     }
2938     UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_ORIENTATION);
2939 }
2940 
GetRequestedOrientation()2941 Orientation WindowSessionImpl::GetRequestedOrientation()
2942 {
2943     if (IsWindowSessionInvalid()) {
2944         TLOGE(WmsLogTag::DEFAULT, "windowSession is invalid");
2945         return Orientation::UNSPECIFIED;
2946     }
2947     TLOGI(WmsLogTag::WMS_ROTATION, "userRequestedOrientation:%{public}u", property_->GetUserRequestedOrientation());
2948     return property_->GetUserRequestedOrientation();
2949 }
2950 
ConvertUserOrientationToUserPageOrientation(Orientation Orientation) const2951 Orientation WindowSessionImpl::ConvertUserOrientationToUserPageOrientation(Orientation Orientation) const
2952 {
2953     switch (Orientation) {
2954         case Orientation::USER_ROTATION_LANDSCAPE:
2955             return Orientation::USER_PAGE_ROTATION_LANDSCAPE;
2956         case Orientation::USER_ROTATION_LANDSCAPE_INVERTED:
2957             return Orientation::USER_PAGE_ROTATION_LANDSCAPE_INVERTED;
2958         case Orientation::USER_ROTATION_PORTRAIT:
2959             return Orientation::USER_PAGE_ROTATION_PORTRAIT;
2960         case Orientation::USER_ROTATION_PORTRAIT_INVERTED:
2961             return Orientation::USER_PAGE_ROTATION_PORTRAIT_INVERTED;
2962         default:
2963             break;
2964     }
2965     return Orientation::UNSPECIFIED;
2966 }
2967 
ConvertInvalidOrientation()2968 Orientation WindowSessionImpl::ConvertInvalidOrientation()
2969 {
2970     Orientation requestedOrientation = GetRequestedOrientation();
2971     if (IsUserOrientation(requestedOrientation)) {
2972         requestedOrientation = ConvertUserOrientationToUserPageOrientation(requestedOrientation);
2973     }
2974     TLOGI(WmsLogTag::WMS_ROTATION, "convertInvalidOrientation:%{public}u", requestedOrientation);
2975     return requestedOrientation;
2976 }
2977 
SetUserRequestedOrientation(Orientation orientation)2978 void WindowSessionImpl::SetUserRequestedOrientation(Orientation orientation)
2979 {
2980     if (IsWindowSessionInvalid()) {
2981         TLOGE(WmsLogTag::DEFAULT, "windowSession is invalid");
2982         return;
2983     }
2984     TLOGI(WmsLogTag::WMS_ROTATION,
2985         "id:%{public}u userRequestedOrientation:%{public}u state:%{public}u",
2986         GetPersistentId(), orientation, state_);
2987     property_->SetUserRequestedOrientation(orientation);
2988 }
2989 
isNeededForciblySetOrientation(Orientation orientation)2990 bool WindowSessionImpl::isNeededForciblySetOrientation(Orientation orientation)
2991 {
2992     TLOGI(WmsLogTag::WMS_ROTATION, "orientation:%{public}u", orientation);
2993     if (IsUserOrientation(orientation)) {
2994         return true;
2995     }
2996     Orientation lastOrientation = property_->GetRequestedOrientation();
2997     TLOGI(WmsLogTag::WMS_ROTATION, "lastOrientation:%{public}u", lastOrientation);
2998     if (orientation == Orientation::INVALID) {
2999         orientation = ConvertInvalidOrientation();
3000         if (IsUserPageOrientation(orientation) && IsUserOrientation(lastOrientation)) {
3001             lastOrientation = ConvertUserOrientationToUserPageOrientation(lastOrientation);
3002         }
3003     }
3004     return lastOrientation != orientation;
3005 }
3006 
GetContentInfo(BackupAndRestoreType type)3007 std::string WindowSessionImpl::GetContentInfo(BackupAndRestoreType type)
3008 {
3009     WLOGFD("in");
3010     if (type == BackupAndRestoreType::NONE) {
3011         return "";
3012     }
3013     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3014     if (uiContent == nullptr) {
3015         WLOGFE("fail to GetContentInfo id: %{public}d", GetPersistentId());
3016         return "";
3017     }
3018     return uiContent->GetContentInfo(GetAceContentInfoType(type));
3019 }
3020 
SetRestoredRouterStack(const std::string & routerStack)3021 WMError WindowSessionImpl::SetRestoredRouterStack(const std::string& routerStack)
3022 {
3023     TLOGD(WmsLogTag::WMS_LIFE, "in");
3024     restoredRouterStack_ = routerStack;
3025     return WMError::WM_OK;
3026 }
3027 
GetRestoredRouterStack()3028 std::string WindowSessionImpl::GetRestoredRouterStack()
3029 {
3030     TLOGD(WmsLogTag::WMS_LIFE, "in");
3031     return std::move(restoredRouterStack_);
3032 }
3033 
GetUIContent() const3034 Ace::UIContent* WindowSessionImpl::GetUIContent() const
3035 {
3036     std::shared_lock<std::shared_mutex> lock(uiContentMutex_);
3037     return uiContent_.get();
3038 }
3039 
GetUIContentSharedPtr() const3040 std::shared_ptr<Ace::UIContent> WindowSessionImpl::GetUIContentSharedPtr() const
3041 {
3042     std::shared_lock<std::shared_mutex> lock(uiContentMutex_);
3043     return uiContent_;
3044 }
3045 
GetUIContentWithId(uint32_t winId) const3046 Ace::UIContent* WindowSessionImpl::GetUIContentWithId(uint32_t winId) const
3047 {
3048     sptr<Window> targetWindow = FindWindowById(winId);
3049     if (targetWindow == nullptr) {
3050         WLOGE("target window is null");
3051         return nullptr;
3052     }
3053     return targetWindow->GetUIContent();
3054 }
3055 
OnNewWant(const AAFwk::Want & want)3056 void WindowSessionImpl::OnNewWant(const AAFwk::Want& want)
3057 {
3058     WLOGFI("[name:%{public}s, id:%{public}d]",
3059         property_->GetWindowName().c_str(), GetPersistentId());
3060     navDestinationInfo_ = want.GetStringParam(AAFwk::Want::ATOMIC_SERVICE_SHARE_ROUTER);
3061     if (!navDestinationInfo_.empty()) {
3062         auto uiContent = GetUIContentSharedPtr();
3063         if (uiContent != nullptr) {
3064             TLOGI(WmsLogTag::WMS_LIFE, "call uiContent RestoreNavDestinationInfo.");
3065             uiContent->RestoreNavDestinationInfo(navDestinationInfo_, false);
3066             navDestinationInfo_ = "";
3067         } else {
3068             TLOGE(WmsLogTag::WMS_LIFE, "uiContent is nullptr.");
3069         }
3070     }
3071     if (auto uiContent = GetUIContentSharedPtr()) {
3072         uiContent->OnNewWant(want);
3073     }
3074 }
3075 
SetAPPWindowLabel(const std::string & label)3076 WMError WindowSessionImpl::SetAPPWindowLabel(const std::string& label)
3077 {
3078     TLOGI(WmsLogTag::WMS_DECOR, "Enter");
3079     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3080     if (uiContent == nullptr) {
3081         TLOGI(WmsLogTag::WMS_DECOR, "uicontent is empty");
3082         return WMError::WM_ERROR_NULLPTR;
3083     }
3084     uiContent->SetAppWindowTitle(label);
3085     return WMError::WM_OK;
3086 }
3087 
SetAPPWindowIcon(const std::shared_ptr<Media::PixelMap> & icon)3088 WMError WindowSessionImpl::SetAPPWindowIcon(const std::shared_ptr<Media::PixelMap>& icon)
3089 {
3090     if (icon == nullptr) {
3091         TLOGE(WmsLogTag::WMS_DECOR, "icon is empty");
3092         return WMError::WM_ERROR_NULLPTR;
3093     }
3094     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3095     if (uiContent == nullptr) {
3096         TLOGE(WmsLogTag::WMS_DECOR, "uicontent is empty");
3097         return WMError::WM_ERROR_NULLPTR;
3098     }
3099     uiContent->SetAppWindowIcon(icon);
3100     TLOGD(WmsLogTag::WMS_DECOR, "end");
3101     return WMError::WM_OK;
3102 }
3103 
RegisterLifeCycleListener(const sptr<IWindowLifeCycle> & listener)3104 WMError WindowSessionImpl::RegisterLifeCycleListener(const sptr<IWindowLifeCycle>& listener)
3105 {
3106     WLOGFD("in");
3107     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
3108     return RegisterListener(lifecycleListeners_[GetPersistentId()], listener);
3109 }
3110 
RegisterWindowStageLifeCycleListener(const sptr<IWindowStageLifeCycle> & listener)3111 WMError WindowSessionImpl::RegisterWindowStageLifeCycleListener(const sptr<IWindowStageLifeCycle>& listener)
3112 {
3113     TLOGD(WmsLogTag::WMS_LIFE, "in");
3114     std::lock_guard<std::recursive_mutex> lockListener(windowStageLifeCycleListenerMutex_);
3115     return RegisterListener(windowStageLifecycleListeners_[GetPersistentId()], listener);
3116 }
3117 
UnregisterWindowStageLifeCycleListener(const sptr<IWindowStageLifeCycle> & listener)3118 WMError WindowSessionImpl::UnregisterWindowStageLifeCycleListener(const sptr<IWindowStageLifeCycle>& listener)
3119 {
3120     TLOGD(WmsLogTag::WMS_LIFE, "in");
3121     std::lock_guard<std::recursive_mutex> lockListener(windowStageLifeCycleListenerMutex_);
3122     return UnregisterListener(windowStageLifecycleListeners_[GetPersistentId()], listener);
3123 }
3124 
RegisterDisplayMoveListener(sptr<IDisplayMoveListener> & listener)3125 WMError WindowSessionImpl::RegisterDisplayMoveListener(sptr<IDisplayMoveListener>& listener)
3126 {
3127     WLOGFD("in");
3128     std::lock_guard<std::mutex> lockListener(displayMoveListenerMutex_);
3129     return RegisterListener(displayMoveListeners_[GetPersistentId()], listener);
3130 }
3131 
UnregisterDisplayMoveListener(sptr<IDisplayMoveListener> & listener)3132 WMError WindowSessionImpl::UnregisterDisplayMoveListener(sptr<IDisplayMoveListener>& listener)
3133 {
3134     WLOGFD("in");
3135     std::lock_guard<std::mutex> lockListener(displayMoveListenerMutex_);
3136     return UnregisterListener(displayMoveListeners_[GetPersistentId()], listener);
3137 }
3138 
IsWindowShouldDrag()3139 bool WindowSessionImpl::IsWindowShouldDrag()
3140 {
3141     if (!windowSystemConfig_.IsPcWindow() && !windowSystemConfig_.IsPadWindow() &&
3142         !windowSystemConfig_.IsPhoneWindow()) {
3143         return false;
3144     }
3145     return true;
3146 }
3147 
CheckCanDragWindowType()3148 bool WindowSessionImpl::CheckCanDragWindowType()
3149 {
3150     WindowType windowType = GetType();
3151     if (WindowHelper::IsSystemWindow(windowType) || WindowHelper::IsSubWindow(windowType)) {
3152         return true;
3153     }
3154     return false;
3155 }
3156 
3157 /**
3158  * Currently only supports system windows.
3159  */
EnableDrag(bool enableDrag)3160 WMError WindowSessionImpl::EnableDrag(bool enableDrag)
3161 {
3162     if (!IsWindowShouldDrag()) {
3163         TLOGE(WmsLogTag::WMS_LAYOUT, "The device is not supported");
3164         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
3165     }
3166     if (!CheckCanDragWindowType()) {
3167         TLOGI(WmsLogTag::WMS_LAYOUT, "Id:%{public}d, invalid window type:%{public}u",
3168             GetPersistentId(), GetType());
3169         return WMError::WM_ERROR_INVALID_CALLING;
3170     }
3171     property_->SetDragEnabled(enableDrag);
3172     hasSetEnableDrag_.store(true);
3173     auto hostSession = GetHostSession();
3174     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
3175     WMError errorCode = hostSession->SetSystemWindowEnableDrag(enableDrag);
3176     TLOGI(WmsLogTag::WMS_LAYOUT, "Id:%{public}d, enableDrag:%{public}d, errcode:%{public}d",
3177         GetPersistentId(), enableDrag, static_cast<int>(errorCode));
3178     return static_cast<WMError>(errorCode);
3179 }
3180 
RegisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener> & listener)3181 WMError WindowSessionImpl::RegisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener>& listener)
3182 {
3183     WLOGFD("in");
3184     std::lock_guard<std::recursive_mutex> lockListener(occupiedAreaChangeListenerMutex_);
3185     return RegisterListener(occupiedAreaChangeListeners_[GetPersistentId()], listener);
3186 }
3187 
UnregisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener> & listener)3188 WMError WindowSessionImpl::UnregisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener>& listener)
3189 {
3190     WLOGFD("in");
3191     std::lock_guard<std::recursive_mutex> lockListener(occupiedAreaChangeListenerMutex_);
3192     return UnregisterListener(occupiedAreaChangeListeners_[GetPersistentId()], listener);
3193 }
3194 
RegisterKeyboardWillShowListener(const sptr<IKBWillShowListener> & listener)3195 WMError WindowSessionImpl::RegisterKeyboardWillShowListener(const sptr<IKBWillShowListener>& listener)
3196 {
3197     TLOGD(WmsLogTag::WMS_KEYBOARD, "in");
3198     if (!(windowSystemConfig_.supportFunctionType_ & ALLOW_KEYBOARD_WILL_ANIMATION_NOTIFICATION)) {
3199         TLOGE(WmsLogTag::WMS_KEYBOARD, "Keyboard will animtion notification is not allowed");
3200         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
3201     }
3202     std::lock_guard<std::recursive_mutex> lockListener(keyboardWillShowListenerMutex_);
3203     WMError ret = RegisterListener(keyboardWillShowListeners_[GetPersistentId()], listener);
3204     if (ret == WMError::WM_OK && property_->EditSessionInfo().isKeyboardWillShowRegistered_ == false) {
3205         auto hostSession = GetHostSession();
3206         CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
3207         hostSession->NotifyKeyboardWillShowRegistered(true);
3208         property_->EditSessionInfo().isKeyboardWillShowRegistered_ = true;
3209     }
3210     return ret;
3211 }
3212 
UnregisterKeyboardWillShowListener(const sptr<IKBWillShowListener> & listener)3213 WMError WindowSessionImpl::UnregisterKeyboardWillShowListener(const sptr<IKBWillShowListener>& listener)
3214 {
3215     TLOGD(WmsLogTag::WMS_KEYBOARD, "in");
3216     std::lock_guard<std::recursive_mutex> lockListener(keyboardWillShowListenerMutex_);
3217     WMError ret = UnregisterListener(keyboardWillShowListeners_[GetPersistentId()], listener);
3218     if (keyboardWillShowListeners_[GetPersistentId()].empty()) {
3219         auto hostSession = GetHostSession();
3220         CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
3221         hostSession->NotifyKeyboardWillShowRegistered(false);
3222         property_->EditSessionInfo().isKeyboardWillShowRegistered_ = false;
3223     }
3224     return ret;
3225 }
3226 
RegisterKeyboardWillHideListener(const sptr<IKBWillHideListener> & listener)3227 WMError WindowSessionImpl::RegisterKeyboardWillHideListener(const sptr<IKBWillHideListener>& listener)
3228 {
3229     TLOGD(WmsLogTag::WMS_KEYBOARD, "in");
3230     if (!(windowSystemConfig_.supportFunctionType_ & ALLOW_KEYBOARD_WILL_ANIMATION_NOTIFICATION)) {
3231         TLOGE(WmsLogTag::WMS_KEYBOARD, "Keyboard will animtion notification is not allowed");
3232         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
3233     }
3234     std::lock_guard<std::recursive_mutex> lockListener(keyboardWillHideListenerMutex_);
3235     WMError ret = RegisterListener(keyboardWillHideListeners_[GetPersistentId()], listener);
3236     if (ret == WMError::WM_OK && property_->EditSessionInfo().isKeyboardWillHideRegistered_ == false) {
3237         auto hostSession = GetHostSession();
3238         CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
3239         hostSession->NotifyKeyboardWillHideRegistered(true);
3240         property_->EditSessionInfo().isKeyboardWillHideRegistered_ = true;
3241     }
3242     return ret;
3243 }
3244 
UnregisterKeyboardWillHideListener(const sptr<IKBWillHideListener> & listener)3245 WMError WindowSessionImpl::UnregisterKeyboardWillHideListener(const sptr<IKBWillHideListener>& listener)
3246 {
3247     TLOGD(WmsLogTag::WMS_KEYBOARD, "in");
3248     std::lock_guard<std::recursive_mutex> lockListener(keyboardWillHideListenerMutex_);
3249     WMError ret = UnregisterListener(keyboardWillHideListeners_[GetPersistentId()], listener);
3250     if (keyboardWillHideListeners_[GetPersistentId()].empty()) {
3251         auto hostSession = GetHostSession();
3252         CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
3253         hostSession->NotifyKeyboardWillHideRegistered(false);
3254         property_->EditSessionInfo().isKeyboardWillHideRegistered_ = false;
3255     }
3256     return ret;
3257 }
3258 
RegisterKeyboardDidShowListener(const sptr<IKeyboardDidShowListener> & listener)3259 WMError WindowSessionImpl::RegisterKeyboardDidShowListener(const sptr<IKeyboardDidShowListener>& listener)
3260 {
3261     TLOGD(WmsLogTag::WMS_KEYBOARD, "in");
3262     std::lock_guard<std::recursive_mutex> lockListener(keyboardDidShowListenerMutex_);
3263     WMError ret = RegisterListener(keyboardDidShowListeners_[GetPersistentId()], listener);
3264     if (ret == WMError::WM_OK && property_->EditSessionInfo().isKeyboardDidShowRegistered_ == false) {
3265         auto hostSession = GetHostSession();
3266         CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
3267         hostSession->NotifyKeyboardDidShowRegistered(true);
3268         property_->EditSessionInfo().isKeyboardDidShowRegistered_ = true;
3269     }
3270     return ret;
3271 }
3272 
UnregisterKeyboardDidShowListener(const sptr<IKeyboardDidShowListener> & listener)3273 WMError WindowSessionImpl::UnregisterKeyboardDidShowListener(const sptr<IKeyboardDidShowListener>& listener)
3274 {
3275     TLOGD(WmsLogTag::WMS_KEYBOARD, "in");
3276     std::lock_guard<std::recursive_mutex> lockListener(keyboardDidShowListenerMutex_);
3277     WMError ret = UnregisterListener(keyboardDidShowListeners_[GetPersistentId()], listener);
3278     if (keyboardDidShowListeners_[GetPersistentId()].empty()) {
3279         auto hostSession = GetHostSession();
3280         CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
3281         hostSession->NotifyKeyboardDidShowRegistered(false);
3282         property_->EditSessionInfo().isKeyboardDidShowRegistered_ = false;
3283     }
3284     return ret;
3285 }
3286 
RegisterKeyboardDidHideListener(const sptr<IKeyboardDidHideListener> & listener)3287 WMError WindowSessionImpl::RegisterKeyboardDidHideListener(const sptr<IKeyboardDidHideListener>& listener)
3288 {
3289     TLOGD(WmsLogTag::WMS_KEYBOARD, "in");
3290     std::lock_guard<std::recursive_mutex> lockListener(keyboardDidHideListenerMutex_);
3291     WMError ret = RegisterListener(keyboardDidHideListeners_[GetPersistentId()], listener);
3292     if (ret == WMError::WM_OK && property_->EditSessionInfo().isKeyboardDidHideRegistered_ == false) {
3293         auto hostSession = GetHostSession();
3294         CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
3295         hostSession->NotifyKeyboardDidHideRegistered(true);
3296         property_->EditSessionInfo().isKeyboardDidHideRegistered_ = true;
3297     }
3298     return ret;
3299 }
3300 
UnregisterKeyboardDidHideListener(const sptr<IKeyboardDidHideListener> & listener)3301 WMError WindowSessionImpl::UnregisterKeyboardDidHideListener(const sptr<IKeyboardDidHideListener>& listener)
3302 {
3303     TLOGD(WmsLogTag::WMS_KEYBOARD, "in");
3304     std::lock_guard<std::recursive_mutex> lockListener(keyboardDidHideListenerMutex_);
3305     WMError ret = UnregisterListener(keyboardDidHideListeners_[GetPersistentId()], listener);
3306     if (keyboardDidHideListeners_[GetPersistentId()].empty()) {
3307         auto hostSession = GetHostSession();
3308         CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
3309         hostSession->NotifyKeyboardDidHideRegistered(false);
3310         property_->EditSessionInfo().isKeyboardDidHideRegistered_ = false;
3311     }
3312     return ret;
3313 }
3314 
UnregisterLifeCycleListener(const sptr<IWindowLifeCycle> & listener)3315 WMError WindowSessionImpl::UnregisterLifeCycleListener(const sptr<IWindowLifeCycle>& listener)
3316 {
3317     WLOGFD("in");
3318     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
3319     return UnregisterListener(lifecycleListeners_[GetPersistentId()], listener);
3320 }
3321 
RegisterWindowChangeListener(const sptr<IWindowChangeListener> & listener)3322 WMError WindowSessionImpl::RegisterWindowChangeListener(const sptr<IWindowChangeListener>& listener)
3323 {
3324     WLOGFD("in");
3325     std::lock_guard<std::recursive_mutex> lockListener(windowChangeListenerMutex_);
3326     return RegisterListener(windowChangeListeners_[GetPersistentId()], listener);
3327 }
3328 
UnregisterWindowChangeListener(const sptr<IWindowChangeListener> & listener)3329 WMError WindowSessionImpl::UnregisterWindowChangeListener(const sptr<IWindowChangeListener>& listener)
3330 {
3331     WLOGFD("in");
3332     std::lock_guard<std::recursive_mutex> lockListener(windowChangeListenerMutex_);
3333     return UnregisterListener(windowChangeListeners_[GetPersistentId()], listener);
3334 }
3335 
RegisterWindowCrossAxisListener(const sptr<IWindowCrossAxisListener> & listener)3336 WMError WindowSessionImpl::RegisterWindowCrossAxisListener(const sptr<IWindowCrossAxisListener>& listener)
3337 {
3338     WLOGFD("in");
3339     std::lock_guard<std::recursive_mutex> lockListener(windowCrossAxisListenerMutex_);
3340     return RegisterListener(windowCrossAxisListeners_[GetPersistentId()], listener);
3341 }
3342 
UnregisterWindowCrossAxisListener(const sptr<IWindowCrossAxisListener> & listener)3343 WMError WindowSessionImpl::UnregisterWindowCrossAxisListener(const sptr<IWindowCrossAxisListener>& listener)
3344 {
3345     WLOGFD("in");
3346     std::lock_guard<std::recursive_mutex> lockListener(windowCrossAxisListenerMutex_);
3347     return UnregisterListener(windowCrossAxisListeners_[GetPersistentId()], listener);
3348 }
3349 
RegisterWindowStatusChangeListener(const sptr<IWindowStatusChangeListener> & listener)3350 WMError WindowSessionImpl::RegisterWindowStatusChangeListener(const sptr<IWindowStatusChangeListener>& listener)
3351 {
3352     WLOGFD("in");
3353     std::lock_guard<std::recursive_mutex> lockListener(windowStatusChangeListenerMutex_);
3354     return RegisterListener(windowStatusChangeListeners_[GetPersistentId()], listener);
3355 }
3356 
UnregisterWindowStatusChangeListener(const sptr<IWindowStatusChangeListener> & listener)3357 WMError WindowSessionImpl::UnregisterWindowStatusChangeListener(const sptr<IWindowStatusChangeListener>& listener)
3358 {
3359     WLOGFD("in");
3360     std::lock_guard<std::recursive_mutex> lockListener(windowStatusChangeListenerMutex_);
3361     return UnregisterListener(windowStatusChangeListeners_[GetPersistentId()], listener);
3362 }
3363 
RegisterWindowStatusDidChangeListener(const sptr<IWindowStatusDidChangeListener> & listener)3364 WMError WindowSessionImpl::RegisterWindowStatusDidChangeListener(const sptr<IWindowStatusDidChangeListener>& listener)
3365 {
3366     TLOGD(WmsLogTag::WMS_LAYOUT, "in");
3367     std::lock_guard<std::recursive_mutex> lockListener(windowStatusDidChangeListenerMutex_);
3368     return RegisterListener(windowStatusDidChangeListeners_[GetPersistentId()], listener);
3369 }
3370 
UnregisterWindowStatusDidChangeListener(const sptr<IWindowStatusDidChangeListener> & listener)3371 WMError WindowSessionImpl::UnregisterWindowStatusDidChangeListener(const sptr<IWindowStatusDidChangeListener>& listener)
3372 {
3373     TLOGD(WmsLogTag::WMS_LAYOUT, "in");
3374     std::lock_guard<std::recursive_mutex> lockListener(windowStatusDidChangeListenerMutex_);
3375     return UnregisterListener(windowStatusDidChangeListeners_[GetPersistentId()], listener);
3376 }
3377 
SetDecorVisible(bool isVisible)3378 WMError WindowSessionImpl::SetDecorVisible(bool isVisible)
3379 {
3380     if (IsWindowSessionInvalid()) {
3381         return WMError::WM_ERROR_INVALID_WINDOW;
3382     }
3383     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3384     if (uiContent == nullptr) {
3385         TLOGE(WmsLogTag::WMS_DECOR, "uicontent is null");
3386         return WMError::WM_ERROR_NULLPTR;
3387     }
3388     uiContent->SetContainerModalTitleVisible(isVisible, true);
3389     TLOGD(WmsLogTag::WMS_DECOR, "end");
3390     return WMError::WM_OK;
3391 }
3392 
GetDecorVisible(bool & isVisible)3393 WMError WindowSessionImpl::GetDecorVisible(bool& isVisible)
3394 {
3395     TLOGD(WmsLogTag::WMS_DECOR, "%{public}u in", GetWindowId());
3396     if (IsWindowSessionInvalid()) {
3397         return WMError::WM_ERROR_INVALID_WINDOW;
3398     }
3399     if (!IsPcOrFreeMultiWindowCapabilityEnabled()) {
3400         TLOGE(WmsLogTag::WMS_DECOR, "device not support");
3401         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
3402     }
3403     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3404     if (uiContent == nullptr) {
3405         TLOGE(WmsLogTag::WMS_DECOR, "uicontent is null");
3406         return WMError::WM_ERROR_NULLPTR;
3407     }
3408     isVisible = uiContent->GetContainerModalTitleVisible(GetImmersiveModeEnabledState());
3409     return WMError::WM_OK;
3410 }
3411 
SetWindowTitleMoveEnabled(bool enable)3412 WMError WindowSessionImpl::SetWindowTitleMoveEnabled(bool enable)
3413 {
3414     if (IsWindowSessionInvalid()) {
3415         return WMError::WM_ERROR_INVALID_WINDOW;
3416     }
3417     if (IsPadAndNotFreeMutiWindowCompatibleMode()) {
3418         TLOGE(WmsLogTag::WMS_DECOR, "The is PcAppInPad, not supported");
3419         return WMError::WM_OK;
3420     }
3421     if (!IsPcOrPadFreeMultiWindowMode()) {
3422         TLOGE(WmsLogTag::WMS_DECOR, "The device is not supported");
3423         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
3424     }
3425     if (!WindowHelper::IsMainWindow(GetType()) && !WindowHelper::IsSubWindow(GetType())) {
3426         TLOGE(WmsLogTag::WMS_DECOR, "called by invalid window type, type:%{public}d", GetType());
3427         return WMError::WM_ERROR_INVALID_CALLING;
3428     }
3429     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3430     if (uiContent == nullptr) {
3431         TLOGE(WmsLogTag::WMS_DECOR, "uicontent is null");
3432         return WMError::WM_ERROR_NULLPTR;
3433     }
3434     uiContent->EnableContainerModalGesture(enable);
3435     TLOGI(WmsLogTag::WMS_DECOR, "enable:%{public}d end", enable);
3436     return WMError::WM_OK;
3437 }
3438 
SetSubWindowModal(bool isModal,ModalityType modalityType)3439 WMError WindowSessionImpl::SetSubWindowModal(bool isModal, ModalityType modalityType)
3440 {
3441     if (IsWindowSessionInvalid()) {
3442         return WMError::WM_ERROR_INVALID_WINDOW;
3443     }
3444     if (!WindowHelper::IsSubWindow(GetType())) {
3445         TLOGE(WmsLogTag::WMS_SUB, "called by invalid window type, type:%{public}d", GetType());
3446         return WMError::WM_ERROR_INVALID_CALLING;
3447     }
3448     if (modalityType == ModalityType::APPLICATION_MODALITY && IsPadAndNotFreeMutiWindowCompatibleMode()) {
3449         TLOGE(WmsLogTag::WMS_SUB, "This is PcAppInPad, not support");
3450         return WMError::WM_OK;
3451     }
3452     if (modalityType == ModalityType::APPLICATION_MODALITY && !IsPcOrPadFreeMultiWindowMode()) {
3453         TLOGE(WmsLogTag::WMS_SUB, "device not support");
3454         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
3455     }
3456 
3457     WMError modalRet = isModal ?
3458         AddWindowFlag(WindowFlag::WINDOW_FLAG_IS_MODAL) :
3459         RemoveWindowFlag(WindowFlag::WINDOW_FLAG_IS_MODAL);
3460     if (modalRet != WMError::WM_OK) {
3461         return modalRet;
3462     }
3463     modalRet = isModal && modalityType == ModalityType::APPLICATION_MODALITY ?
3464         AddWindowFlag(WindowFlag::WINDOW_FLAG_IS_APPLICATION_MODAL) :
3465         RemoveWindowFlag(WindowFlag::WINDOW_FLAG_IS_APPLICATION_MODAL);
3466     auto hostSession = GetHostSession();
3467     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
3468     SubWindowModalType subWindowModalType = SubWindowModalType::TYPE_NORMAL;
3469     if (isModal) {
3470         subWindowModalType = modalityType == ModalityType::WINDOW_MODALITY ?
3471             SubWindowModalType::TYPE_WINDOW_MODALITY :
3472             SubWindowModalType::TYPE_APPLICATION_MODALITY;
3473     }
3474     if (!(property_->GetSubWindowZLevel() <= MAXIMUM_Z_LEVEL && !isModal)) {
3475         int32_t zLevel = GetSubWindowZLevelByFlags(GetType(), GetWindowFlags(), IsTopmost());
3476         property_->SetSubWindowZLevel(zLevel);
3477         UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_SUB_WINDOW_Z_LEVEL);
3478     }
3479     hostSession->NotifySubModalTypeChange(subWindowModalType);
3480     return modalRet;
3481 }
3482 
SetWindowModal(bool isModal)3483 WMError WindowSessionImpl::SetWindowModal(bool isModal)
3484 {
3485     if (IsWindowSessionInvalid()) {
3486         return WMError::WM_ERROR_INVALID_WINDOW;
3487     }
3488     if (!IsPcOrPadFreeMultiWindowMode()) {
3489         TLOGE(WmsLogTag::WMS_MAIN, "device not support");
3490         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
3491     }
3492     if (!WindowHelper::IsMainWindow(GetType())) {
3493         TLOGE(WmsLogTag::WMS_MAIN, "called by invalid window type, type:%{public}d", GetType());
3494         return WMError::WM_ERROR_INVALID_CALLING;
3495     }
3496     WMError modalRet = isModal ?
3497         AddWindowFlag(WindowFlag::WINDOW_FLAG_IS_MODAL) :
3498         RemoveWindowFlag(WindowFlag::WINDOW_FLAG_IS_MODAL);
3499     if (modalRet != WMError::WM_OK) {
3500         return modalRet;
3501     }
3502     auto hostSession = GetHostSession();
3503     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_SYSTEM_ABNORMALLY);
3504     hostSession->NotifyMainModalTypeChange(isModal);
3505     return modalRet;
3506 }
3507 
SetDecorHeight(int32_t decorHeight)3508 WMError WindowSessionImpl::SetDecorHeight(int32_t decorHeight)
3509 {
3510     if (IsWindowSessionInvalid()) {
3511         return WMError::WM_ERROR_INVALID_WINDOW;
3512     }
3513     float vpr = 0.f;
3514     auto err = GetVirtualPixelRatio(vpr);
3515     if (err != WMError::WM_OK) {
3516         return err;
3517     }
3518     int32_t decorHeightWithPx = static_cast<int32_t>(decorHeight * vpr);
3519     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3520     if (uiContent == nullptr) {
3521         TLOGE(WmsLogTag::WMS_DECOR, "uicontent is empty");
3522         return WMError::WM_ERROR_NULLPTR;
3523     }
3524     uiContent->SetContainerModalTitleHeight(decorHeightWithPx);
3525 
3526     if (auto hostSession = GetHostSession()) {
3527         hostSession->SetCustomDecorHeight(decorHeight);
3528     }
3529     decorHeight_ = decorHeight;
3530     TLOGD(WmsLogTag::WMS_DECOR, "end, height: %{public}d", decorHeight);
3531     return WMError::WM_OK;
3532 }
3533 
GetDecorHeight(int32_t & height)3534 WMError WindowSessionImpl::GetDecorHeight(int32_t& height)
3535 {
3536     if (IsWindowSessionInvalid()) {
3537         return WMError::WM_ERROR_INVALID_WINDOW;
3538     }
3539     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3540     if (uiContent == nullptr) {
3541         TLOGE(WmsLogTag::WMS_DECOR, "uiContent is null, windowId: %{public}u", GetWindowId());
3542         return WMError::WM_ERROR_NULLPTR;
3543     }
3544     height = uiContent->GetContainerModalTitleHeight();
3545     if (height == -1) {
3546         height = 0;
3547         TLOGD(WmsLogTag::WMS_DECOR, "Get app window decor height failed");
3548         return WMError::WM_OK;
3549     }
3550     float vpr = 0.f;
3551     auto err = GetVirtualPixelRatio(vpr);
3552     if (err != WMError::WM_OK) {
3553         return err;
3554     }
3555     height = static_cast<int32_t>(height / vpr);
3556     TLOGD(WmsLogTag::WMS_DECOR, "end, height: %{public}d", height);
3557     return WMError::WM_OK;
3558 }
3559 
SetDecorButtonStyle(const DecorButtonStyle & decorButtonStyle)3560 WMError WindowSessionImpl::SetDecorButtonStyle(const DecorButtonStyle& decorButtonStyle)
3561 {
3562     if (IsWindowSessionInvalid()) {
3563         return WMError::WM_ERROR_INVALID_WINDOW;
3564     }
3565 
3566     if (!WindowHelper::CheckButtonStyleValid(decorButtonStyle)) {
3567         TLOGE(WmsLogTag::WMS_DECOR, "set decor button style param invalid");
3568         return WMError::WM_ERROR_INVALID_PARAM;
3569     }
3570 
3571     if (!WindowHelper::IsMainWindow(GetType()) && !WindowHelper::IsSubWindow(GetType())) {
3572         TLOGE(WmsLogTag::WMS_DECOR, "called by invalid window type, type:%{public}d", GetType());
3573         return WMError::WM_ERROR_INVALID_CALLING;
3574     }
3575 
3576     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3577     if (uiContent == nullptr) {
3578         TLOGE(WmsLogTag::WMS_DECOR, "uiContent is null, windowId: %{public}u", GetWindowId());
3579         return WMError::WM_ERROR_NULLPTR;
3580     }
3581     nlohmann::json decorJson = WindowSessionImpl::SetContainerButtonStyle(decorButtonStyle);
3582     auto decorJsonStr =  decorJson.dump();
3583     TLOGI(WmsLogTag::WMS_DECOR, "decorJsonStr: %{public}s", decorJsonStr.c_str());
3584     uiContent->OnContainerModalEvent(DECOR_BUTTON_STYLE_CHANGE, decorJsonStr);
3585     decorButtonStyle_ = decorButtonStyle;
3586     return WMError::WM_OK;
3587 }
3588 
GetDecorButtonStyle(DecorButtonStyle & decorButtonStyle)3589 WMError WindowSessionImpl::GetDecorButtonStyle(DecorButtonStyle& decorButtonStyle)
3590 {
3591     if (IsWindowSessionInvalid()) {
3592         return WMError::WM_ERROR_INVALID_WINDOW;
3593     }
3594 
3595     if (!WindowHelper::IsMainWindow(GetType()) && !WindowHelper::IsSubWindow(GetType())) {
3596         TLOGE(WmsLogTag::WMS_DECOR, "called by invalid window type, type:%{public}d", GetType());
3597         return WMError::WM_ERROR_INVALID_CALLING;
3598     }
3599     decorButtonStyle = decorButtonStyle_;
3600     return WMError::WM_OK;
3601 }
3602 
GetTitleButtonArea(TitleButtonRect & titleButtonRect)3603 WMError WindowSessionImpl::GetTitleButtonArea(TitleButtonRect& titleButtonRect)
3604 {
3605     if (IsWindowSessionInvalid()) {
3606         return WMError::WM_ERROR_INVALID_WINDOW;
3607     }
3608     Rect decorRect;
3609     Rect titleButtonLeftRect;
3610     bool res = false;
3611     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3612     if (uiContent == nullptr) {
3613         TLOGE(WmsLogTag::WMS_DECOR, "uicontent is empty");
3614         return WMError::WM_ERROR_NULLPTR;
3615     }
3616     res = uiContent->GetContainerModalButtonsRect(decorRect, titleButtonLeftRect);
3617     if (!res) {
3618         TLOGE(WmsLogTag::WMS_DECOR, "GetContainerModalButtonsRect failed");
3619         return WMError::WM_OK;
3620     }
3621     float vpr = 0.f;
3622     auto err = GetVirtualPixelRatio(vpr);
3623     if (err != WMError::WM_OK) {
3624         return err;
3625     }
3626     titleButtonRect.posX_ = static_cast<int32_t>(decorRect.width_) -
3627         static_cast<int32_t>(titleButtonLeftRect.width_) - titleButtonLeftRect.posX_;
3628     titleButtonRect.posX_ = static_cast<int32_t>(titleButtonRect.posX_ / vpr);
3629     titleButtonRect.posY_ = static_cast<int32_t>(titleButtonLeftRect.posY_ / vpr);
3630     titleButtonRect.width_ = static_cast<uint32_t>(titleButtonLeftRect.width_ / vpr);
3631     titleButtonRect.height_ = static_cast<uint32_t>(titleButtonLeftRect.height_ / vpr);
3632     return WMError::WM_OK;
3633 }
3634 
GetUIContentRemoteObj(sptr<IRemoteObject> & uiContentRemoteObj)3635 WSError WindowSessionImpl::GetUIContentRemoteObj(sptr<IRemoteObject>& uiContentRemoteObj)
3636 {
3637     if (!SessionPermission::IsSystemCalling()) {
3638         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "Permission denied!");
3639         return WSError::WS_ERROR_NOT_SYSTEM_APP;
3640     }
3641     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3642     if (uiContent == nullptr) {
3643         TLOGE(WmsLogTag::DEFAULT, "uiContent is nullptr");
3644         return WSError::WS_ERROR_NULLPTR;
3645     }
3646     uiContentRemoteObj = uiContent->GetRemoteObj();
3647     return WSError::WS_OK;
3648 }
3649 
RegisterWindowTitleButtonRectChangeListener(const sptr<IWindowTitleButtonRectChangedListener> & listener)3650 WMError WindowSessionImpl::RegisterWindowTitleButtonRectChangeListener(
3651     const sptr<IWindowTitleButtonRectChangedListener>& listener)
3652 {
3653     if (IsWindowSessionInvalid()) {
3654         return WMError::WM_ERROR_INVALID_WINDOW;
3655     }
3656     auto persistentId = GetPersistentId();
3657     TLOGD(WmsLogTag::WMS_DECOR, "Start, id:%{public}d", persistentId);
3658     if (listener == nullptr) {
3659         TLOGE(WmsLogTag::WMS_DECOR, "listener is null");
3660         return WMError::WM_ERROR_NULLPTR;
3661     }
3662 
3663     {
3664         std::lock_guard<std::recursive_mutex> lockListener(windowTitleButtonRectChangeListenerMutex_);
3665         WMError ret = RegisterListener(windowTitleButtonRectChangeListeners_[persistentId], listener);
3666         if (ret != WMError::WM_OK) {
3667             TLOGE(WmsLogTag::WMS_DECOR, "register failed");
3668             return ret;
3669         }
3670     }
3671     if (auto uiContent = GetUIContentSharedPtr()) {
3672         const char* const where = __func__;
3673         uiContent->SubscribeContainerModalButtonsRectChange(
3674             [where, weakThis = wptr(this)](Rect& decorRect, Rect& titleButtonLeftRect) {
3675             auto window = weakThis.promote();
3676             if (!window) {
3677                 TLOGNE(WmsLogTag::WMS_DECOR, "%{public}s window is null", where);
3678                 return;
3679             }
3680             float vpr = 0.f;
3681             auto err = window->GetVirtualPixelRatio(vpr);
3682             if (err != WMError::WM_OK) {
3683                 return;
3684             }
3685             TitleButtonRect titleButtonRect;
3686             titleButtonRect.posX_ = static_cast<int32_t>(decorRect.width_) -
3687                 static_cast<int32_t>(titleButtonLeftRect.width_) - titleButtonLeftRect.posX_;
3688             titleButtonRect.posX_ = static_cast<int32_t>(titleButtonRect.posX_ / vpr);
3689             titleButtonRect.posY_ = static_cast<int32_t>(titleButtonLeftRect.posY_ / vpr);
3690             titleButtonRect.width_ = static_cast<uint32_t>(titleButtonLeftRect.width_ / vpr);
3691             titleButtonRect.height_ = static_cast<uint32_t>(titleButtonLeftRect.height_ / vpr);
3692             window->NotifyWindowTitleButtonRectChange(titleButtonRect);
3693         });
3694     }
3695     return WMError::WM_OK;
3696 }
3697 
UnregisterWindowTitleButtonRectChangeListener(const sptr<IWindowTitleButtonRectChangedListener> & listener)3698 WMError WindowSessionImpl::UnregisterWindowTitleButtonRectChangeListener(
3699     const sptr<IWindowTitleButtonRectChangedListener>& listener)
3700 {
3701     if (IsWindowSessionInvalid()) {
3702         return WMError::WM_ERROR_INVALID_WINDOW;
3703     }
3704     WMError ret = WMError::WM_OK;
3705     auto persistentId = GetPersistentId();
3706     TLOGD(WmsLogTag::WMS_DECOR, "Start, id:%{public}d", persistentId);
3707     if (listener == nullptr) {
3708         TLOGE(WmsLogTag::WMS_DECOR, "listener is nullptr");
3709         return WMError::WM_ERROR_NULLPTR;
3710     }
3711     {
3712         std::lock_guard<std::recursive_mutex> lockListener(windowTitleButtonRectChangeListenerMutex_);
3713         ret = UnregisterListener(windowTitleButtonRectChangeListeners_[persistentId], listener);
3714         if (ret != WMError::WM_OK) {
3715             TLOGE(WmsLogTag::WMS_DECOR, "failed");
3716             return ret;
3717         }
3718     }
3719     if (auto uiContent = GetUIContentSharedPtr()) {
3720         uiContent->SubscribeContainerModalButtonsRectChange(nullptr);
3721     }
3722     return ret;
3723 }
3724 
3725 template<typename T>
3726 EnableIfSame<T, IWindowTitleButtonRectChangedListener,
GetListeners()3727     std::vector<sptr<IWindowTitleButtonRectChangedListener>>> WindowSessionImpl::GetListeners()
3728 {
3729     std::vector<sptr<IWindowTitleButtonRectChangedListener>> windowTitleButtonRectListeners;
3730         for (auto& listener : windowTitleButtonRectChangeListeners_[GetPersistentId()]) {
3731             windowTitleButtonRectListeners.push_back(listener);
3732         }
3733     return windowTitleButtonRectListeners;
3734 }
3735 
NotifyWindowTitleButtonRectChange(TitleButtonRect titleButtonRect)3736 void WindowSessionImpl::NotifyWindowTitleButtonRectChange(TitleButtonRect titleButtonRect)
3737 {
3738     std::lock_guard<std::recursive_mutex> lockListener(windowTitleButtonRectChangeListenerMutex_);
3739     auto windowTitleButtonRectListeners = GetListeners<IWindowTitleButtonRectChangedListener>();
3740     for (auto& listener : windowTitleButtonRectListeners) {
3741         if (listener != nullptr) {
3742             listener->OnWindowTitleButtonRectChanged(titleButtonRect);
3743         }
3744     }
3745 }
3746 
3747 template<typename T>
3748 EnableIfSame<T, IWindowRectChangeListener,
GetListeners()3749     std::vector<sptr<IWindowRectChangeListener>>> WindowSessionImpl::GetListeners()
3750 {
3751     std::vector<sptr<IWindowRectChangeListener>> windowRectChangeListeners;
3752     for (auto& listener : windowRectChangeListeners_[GetPersistentId()]) {
3753         windowRectChangeListeners.push_back(listener);
3754     }
3755     return windowRectChangeListeners;
3756 }
3757 
RegisterWindowRectChangeListener(const sptr<IWindowRectChangeListener> & listener)3758 WMError WindowSessionImpl::RegisterWindowRectChangeListener(const sptr<IWindowRectChangeListener>& listener)
3759 {
3760     WMError ret = WMError::WM_OK;
3761     {
3762         std::lock_guard<std::mutex> lockListener(windowRectChangeListenerMutex_);
3763         ret = RegisterListener(windowRectChangeListeners_[GetPersistentId()], listener);
3764     }
3765     auto hostSession = GetHostSession();
3766     if (hostSession != nullptr && ret == WMError::WM_OK) {
3767         hostSession->UpdateRectChangeListenerRegistered(true);
3768     }
3769     return ret;
3770 }
3771 
UnregisterWindowRectChangeListener(const sptr<IWindowRectChangeListener> & listener)3772 WMError WindowSessionImpl::UnregisterWindowRectChangeListener(const sptr<IWindowRectChangeListener>& listener)
3773 {
3774     WMError ret = WMError::WM_OK;
3775     bool windowRectChangeListenersEmpty = false;
3776     {
3777         std::lock_guard<std::mutex> lockListener(windowRectChangeListenerMutex_);
3778         ret = UnregisterListener(windowRectChangeListeners_[GetPersistentId()], listener);
3779         windowRectChangeListenersEmpty = windowRectChangeListeners_.count(GetPersistentId()) == 0 ||
3780                                          windowRectChangeListeners_[GetPersistentId()].empty();
3781     }
3782     auto hostSession = GetHostSession();
3783     if (hostSession != nullptr && windowRectChangeListenersEmpty) {
3784         hostSession->UpdateRectChangeListenerRegistered(false);
3785     }
3786     return ret;
3787 }
3788 
3789 template<typename T>
3790 EnableIfSame<T, IRectChangeInGlobalDisplayListener,
GetListeners()3791     std::vector<sptr<IRectChangeInGlobalDisplayListener>>> WindowSessionImpl::GetListeners()
3792 {
3793     std::lock_guard<std::mutex> lock(rectChangeInGlobalDisplayListenerMutex_);
3794     auto it = rectChangeInGlobalDisplayListeners_.find(GetPersistentId());
3795     if (it != rectChangeInGlobalDisplayListeners_.end()) {
3796         return it->second;
3797     }
3798     return {};
3799 }
3800 
RegisterRectChangeInGlobalDisplayListener(const sptr<IRectChangeInGlobalDisplayListener> & listener)3801 WMError WindowSessionImpl::RegisterRectChangeInGlobalDisplayListener(
3802     const sptr<IRectChangeInGlobalDisplayListener>& listener)
3803 {
3804     std::lock_guard<std::mutex> lock(rectChangeInGlobalDisplayListenerMutex_);
3805     return RegisterListener(rectChangeInGlobalDisplayListeners_[GetPersistentId()], listener);
3806 }
3807 
UnregisterRectChangeInGlobalDisplayListener(const sptr<IRectChangeInGlobalDisplayListener> & listener)3808 WMError WindowSessionImpl::UnregisterRectChangeInGlobalDisplayListener(
3809     const sptr<IRectChangeInGlobalDisplayListener>& listener)
3810 {
3811     std::lock_guard<std::mutex> lock(rectChangeInGlobalDisplayListenerMutex_);
3812     return UnregisterListener(rectChangeInGlobalDisplayListeners_[GetPersistentId()], listener);
3813 }
3814 
3815 template<typename T>
3816 EnableIfSame<T, IExtensionSecureLimitChangeListener,
GetListeners()3817     std::vector<sptr<IExtensionSecureLimitChangeListener>>> WindowSessionImpl::GetListeners()
3818 {
3819     std::vector<sptr<IExtensionSecureLimitChangeListener>> secureLimitChangeListeners;
3820     for (auto& listener : secureLimitChangeListeners_[GetPersistentId()]) {
3821         secureLimitChangeListeners.push_back(listener);
3822     }
3823     return secureLimitChangeListeners;
3824 }
3825 
RegisterExtensionSecureLimitChangeListener(const sptr<IExtensionSecureLimitChangeListener> & listener)3826 WMError WindowSessionImpl::RegisterExtensionSecureLimitChangeListener(
3827     const sptr<IExtensionSecureLimitChangeListener>& listener)
3828 {
3829     TLOGD(WmsLogTag::WMS_UIEXT, "name=%{public}s, id=%{public}u", GetWindowName().c_str(), GetPersistentId());
3830     std::lock_guard<std::mutex> lockListener(secureLimitChangeListenerMutex_);
3831     return RegisterListener(secureLimitChangeListeners_[GetPersistentId()], listener);
3832 }
3833 
UnregisterExtensionSecureLimitChangeListener(const sptr<IExtensionSecureLimitChangeListener> & listener)3834 WMError WindowSessionImpl::UnregisterExtensionSecureLimitChangeListener(
3835     const sptr<IExtensionSecureLimitChangeListener>& listener)
3836 {
3837     TLOGD(WmsLogTag::WMS_UIEXT, "name=%{public}s, id=%{public}u", GetWindowName().c_str(), GetPersistentId());
3838     std::lock_guard<std::mutex> lockListener(secureLimitChangeListenerMutex_);
3839     return UnregisterListener(secureLimitChangeListeners_[GetPersistentId()], listener);
3840 }
3841 
3842 template<typename T>
GetListeners()3843 EnableIfSame<T, ISubWindowCloseListener, sptr<ISubWindowCloseListener>> WindowSessionImpl::GetListeners()
3844 {
3845     sptr<ISubWindowCloseListener> subWindowCloseListeners;
3846     subWindowCloseListeners = subWindowCloseListeners_[GetPersistentId()];
3847     return subWindowCloseListeners;
3848 }
3849 
RegisterSubWindowCloseListeners(const sptr<ISubWindowCloseListener> & listener)3850 WMError WindowSessionImpl::RegisterSubWindowCloseListeners(const sptr<ISubWindowCloseListener>& listener)
3851 {
3852     if (listener == nullptr) {
3853         WLOGFE("listener is null");
3854         return WMError::WM_ERROR_NULLPTR;
3855     }
3856     if (!WindowHelper::IsSubWindow(GetType()) && !WindowHelper::IsSystemSubWindow(GetType())) {
3857         WLOGFE("window type is not supported");
3858         return WMError::WM_ERROR_INVALID_CALLING;
3859     }
3860     std::lock_guard<std::mutex> lockListener(subWindowCloseListenersMutex_);
3861     subWindowCloseListeners_[GetPersistentId()] = listener;
3862     return WMError::WM_OK;
3863 }
3864 
UnregisterSubWindowCloseListeners(const sptr<ISubWindowCloseListener> & listener)3865 WMError WindowSessionImpl::UnregisterSubWindowCloseListeners(const sptr<ISubWindowCloseListener>& listener)
3866 {
3867     if (listener == nullptr) {
3868         WLOGFE("listener could not be null");
3869         return WMError::WM_ERROR_NULLPTR;
3870     }
3871     if (!WindowHelper::IsSubWindow(GetType()) && !WindowHelper::IsSystemSubWindow(GetType())) {
3872         WLOGFE("window type is not supported");
3873         return WMError::WM_ERROR_INVALID_CALLING;
3874     }
3875     std::lock_guard<std::mutex> lockListener(subWindowCloseListenersMutex_);
3876     subWindowCloseListeners_[GetPersistentId()] = nullptr;
3877     return WMError::WM_OK;
3878 }
3879 
3880 template<typename T>
3881 EnableIfSame<T, IWindowHighlightChangeListener, std::vector<sptr<IWindowHighlightChangeListener>>>
GetListeners()3882     WindowSessionImpl::GetListeners()
3883 {
3884     std::vector<sptr<IWindowHighlightChangeListener>> highlightChangeListeners;
3885     for (auto& listener : highlightChangeListeners_[GetPersistentId()]) {
3886         highlightChangeListeners.push_back(listener);
3887     }
3888     return highlightChangeListeners;
3889 }
3890 
RegisterWindowHighlightChangeListeners(const sptr<IWindowHighlightChangeListener> & listener)3891 WMError WindowSessionImpl::RegisterWindowHighlightChangeListeners(const sptr<IWindowHighlightChangeListener>& listener)
3892 {
3893     TLOGD(WmsLogTag::WMS_FOCUS, "name=%{public}s, id=%{public}u", GetWindowName().c_str(), GetPersistentId());
3894     std::lock_guard<std::mutex> lockListener(highlightChangeListenerMutex_);
3895     return RegisterListener(highlightChangeListeners_[GetPersistentId()], listener);
3896 }
3897 
UnregisterWindowHighlightChangeListeners(const sptr<IWindowHighlightChangeListener> & listener)3898 WMError WindowSessionImpl::UnregisterWindowHighlightChangeListeners(
3899     const sptr<IWindowHighlightChangeListener>& listener)
3900 {
3901     TLOGD(WmsLogTag::WMS_FOCUS, "name=%{public}s, id=%{public}u", GetWindowName().c_str(), GetPersistentId());
3902     std::lock_guard<std::mutex> lockListener(highlightChangeListenerMutex_);
3903     return UnregisterListener(highlightChangeListeners_[GetPersistentId()], listener);
3904 }
3905 
3906 template<typename T>
GetListeners()3907 EnableIfSame<T, IMainWindowCloseListener, sptr<IMainWindowCloseListener>> WindowSessionImpl::GetListeners()
3908 {
3909     return mainWindowCloseListeners_[GetPersistentId()];
3910 }
3911 
3912 template<typename T>
3913 EnableIfSame<T, ISystemBarPropertyListener,
GetListeners()3914     std::vector<sptr<ISystemBarPropertyListener>>> WindowSessionImpl::GetListeners()
3915 {
3916     std::vector<sptr<ISystemBarPropertyListener>> listeners;
3917     for (auto& listener : systemBarPropertyListeners_[GetPersistentId()]) {
3918         listeners.push_back(listener);
3919     }
3920     return listeners;
3921 }
3922 
RegisterSystemBarPropertyListener(const sptr<ISystemBarPropertyListener> & listener)3923 WMError WindowSessionImpl::RegisterSystemBarPropertyListener(const sptr<ISystemBarPropertyListener>& listener)
3924 {
3925     std::lock_guard<std::mutex> lockListener(systemBarPropertyListenerMutex_);
3926     return RegisterListener(systemBarPropertyListeners_[GetPersistentId()], listener);
3927 }
3928 
UnregisterSystemBarPropertyListener(const sptr<ISystemBarPropertyListener> & listener)3929 WMError WindowSessionImpl::UnregisterSystemBarPropertyListener(const sptr<ISystemBarPropertyListener>& listener)
3930 {
3931     std::lock_guard<std::mutex> lockListener(systemBarPropertyListenerMutex_);
3932     return UnregisterListener(systemBarPropertyListeners_[GetPersistentId()], listener);
3933 }
3934 
NotifySystemBarPropertyUpdate(WindowType type,const SystemBarProperty & property)3935 void WindowSessionImpl::NotifySystemBarPropertyUpdate(WindowType type, const SystemBarProperty& property)
3936 {
3937     std::lock_guard<std::mutex> lockListener(systemBarPropertyListenerMutex_);
3938     auto listeners = GetListeners<ISystemBarPropertyListener>();
3939     for (auto& listener : listeners) {
3940         if (listener != nullptr) {
3941             listener->OnSystemBarPropertyUpdate(type, property);
3942         }
3943     }
3944 }
3945 
RegisterMainWindowCloseListeners(const sptr<IMainWindowCloseListener> & listener)3946 WMError WindowSessionImpl::RegisterMainWindowCloseListeners(const sptr<IMainWindowCloseListener>& listener)
3947 {
3948     if (IsWindowSessionInvalid()) {
3949         return WMError::WM_ERROR_INVALID_WINDOW;
3950     }
3951     if (listener == nullptr) {
3952         TLOGE(WmsLogTag::WMS_PC, "listener is null");
3953         return WMError::WM_ERROR_NULLPTR;
3954     }
3955     if (!WindowHelper::IsMainWindow(GetType())) {
3956         TLOGE(WmsLogTag::WMS_PC, "window type is not supported");
3957         return WMError::WM_ERROR_INVALID_CALLING;
3958     }
3959     if (!IsPcOrFreeMultiWindowCapabilityEnabled()) {
3960         TLOGE(WmsLogTag::WMS_PC, "The device is not supported");
3961         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
3962     }
3963     std::lock_guard<std::mutex> lockListener(mainWindowCloseListenersMutex_);
3964     mainWindowCloseListeners_[GetPersistentId()] = listener;
3965     return WMError::WM_OK;
3966 }
3967 
UnregisterMainWindowCloseListeners(const sptr<IMainWindowCloseListener> & listener)3968 WMError WindowSessionImpl::UnregisterMainWindowCloseListeners(const sptr<IMainWindowCloseListener>& listener)
3969 {
3970     if (IsWindowSessionInvalid()) {
3971         return WMError::WM_ERROR_INVALID_WINDOW;
3972     }
3973     if (listener == nullptr) {
3974         TLOGE(WmsLogTag::WMS_PC, "listener could not be null");
3975         return WMError::WM_ERROR_NULLPTR;
3976     }
3977     if (!IsPcOrFreeMultiWindowCapabilityEnabled()) {
3978         TLOGE(WmsLogTag::WMS_PC, "The device is not supported");
3979         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
3980     }
3981     if (!WindowHelper::IsMainWindow(GetType())) {
3982         TLOGE(WmsLogTag::WMS_PC, "window type is not supported");
3983         return WMError::WM_ERROR_INVALID_CALLING;
3984     }
3985     std::lock_guard<std::mutex> lockListener(mainWindowCloseListenersMutex_);
3986     mainWindowCloseListeners_[GetPersistentId()] = nullptr;
3987     return WMError::WM_OK;
3988 }
3989 
3990 template<typename T>
GetListeners()3991 EnableIfSame<T, IWindowWillCloseListener, std::vector<sptr<IWindowWillCloseListener>>> WindowSessionImpl::GetListeners()
3992 {
3993     return windowWillCloseListeners_[GetPersistentId()];
3994 }
3995 
RegisterWindowWillCloseListeners(const sptr<IWindowWillCloseListener> & listener)3996 WMError WindowSessionImpl::RegisterWindowWillCloseListeners(const sptr<IWindowWillCloseListener>& listener)
3997 {
3998     if (IsWindowSessionInvalid()) {
3999         return WMError::WM_ERROR_INVALID_WINDOW;
4000     }
4001     if (listener == nullptr) {
4002         TLOGE(WmsLogTag::WMS_DECOR, "listener is null");
4003         return WMError::WM_ERROR_NULLPTR;
4004     }
4005     if (!IsPcOrFreeMultiWindowCapabilityEnabled()) {
4006         TLOGE(WmsLogTag::WMS_DECOR, "The device is not supported");
4007         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
4008     }
4009     if (!WindowHelper::IsAppWindow(GetType())) {
4010         TLOGE(WmsLogTag::WMS_DECOR, "window type is not supported");
4011         return WMError::WM_ERROR_INVALID_CALLING;
4012     }
4013     std::lock_guard<std::recursive_mutex> lockListener(windowWillCloseListenersMutex_);
4014     return RegisterListener(windowWillCloseListeners_[GetPersistentId()], listener);
4015 }
4016 
UnRegisterWindowWillCloseListeners(const sptr<IWindowWillCloseListener> & listener)4017 WMError WindowSessionImpl::UnRegisterWindowWillCloseListeners(const sptr<IWindowWillCloseListener>& listener)
4018 {
4019     if (IsWindowSessionInvalid()) {
4020         return WMError::WM_ERROR_INVALID_WINDOW;
4021     }
4022     if (listener == nullptr) {
4023         TLOGE(WmsLogTag::WMS_DECOR, "listener could not be null");
4024         return WMError::WM_ERROR_NULLPTR;
4025     }
4026     if (!IsPcOrFreeMultiWindowCapabilityEnabled()) {
4027         TLOGE(WmsLogTag::WMS_DECOR, "The device is not supported");
4028         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
4029     }
4030     if (!WindowHelper::IsAppWindow(GetType())) {
4031         TLOGE(WmsLogTag::WMS_DECOR, "window type is not supported");
4032         return WMError::WM_ERROR_INVALID_CALLING;
4033     }
4034     std::lock_guard<std::recursive_mutex> lockListener(windowWillCloseListenersMutex_);
4035     return UnregisterListener(windowWillCloseListeners_[GetPersistentId()], listener);
4036 }
4037 
4038 template<typename T>
4039 EnableIfSame<T, ISwitchFreeMultiWindowListener,
GetListeners()4040     std::vector<sptr<ISwitchFreeMultiWindowListener>>> WindowSessionImpl::GetListeners()
4041 {
4042     std::vector<sptr<ISwitchFreeMultiWindowListener>> switchFreeMultiWindowListeners;
4043     for (auto& listener : switchFreeMultiWindowListeners_[GetPersistentId()]) {
4044         switchFreeMultiWindowListeners.push_back(listener);
4045     }
4046     return switchFreeMultiWindowListeners;
4047 }
4048 
RegisterSwitchFreeMultiWindowListener(const sptr<ISwitchFreeMultiWindowListener> & listener)4049 WMError WindowSessionImpl::RegisterSwitchFreeMultiWindowListener(const sptr<ISwitchFreeMultiWindowListener>& listener)
4050 {
4051     if (listener == nullptr) {
4052         TLOGE(WmsLogTag::WMS_LAYOUT_PC, "listener is nullptr");
4053         return WMError::WM_ERROR_NULLPTR;
4054     }
4055     if (!WindowHelper::IsMainWindow(GetType()) && !WindowHelper::IsSubWindow(GetType())) {
4056         TLOGE(WmsLogTag::WMS_LAYOUT_PC, "window type is not supported");
4057         return WMError::WM_ERROR_INVALID_CALLING;
4058     }
4059     TLOGD(WmsLogTag::WMS_LAYOUT_PC, "Start register");
4060     std::lock_guard<std::mutex> lockListener(switchFreeMultiWindowListenerMutex_);
4061     return RegisterListener(switchFreeMultiWindowListeners_[GetPersistentId()], listener);
4062 }
4063 
UnregisterSwitchFreeMultiWindowListener(const sptr<ISwitchFreeMultiWindowListener> & listener)4064 WMError WindowSessionImpl::UnregisterSwitchFreeMultiWindowListener(const sptr<ISwitchFreeMultiWindowListener>& listener)
4065 {
4066     if (listener == nullptr) {
4067         TLOGE(WmsLogTag::WMS_LAYOUT_PC, "listener could not be null");
4068         return WMError::WM_ERROR_NULLPTR;
4069     }
4070     if (!WindowHelper::IsMainWindow(GetType()) && !WindowHelper::IsSubWindow(GetType())) {
4071         TLOGE(WmsLogTag::WMS_LAYOUT_PC, "window type is not supported");
4072         return WMError::WM_ERROR_INVALID_CALLING;
4073     }
4074     TLOGD(WmsLogTag::WMS_LAYOUT_PC, "Start unregister");
4075     std::lock_guard<std::mutex> lockListener(switchFreeMultiWindowListenerMutex_);
4076     return UnregisterListener(switchFreeMultiWindowListeners_[GetPersistentId()], listener);
4077 }
4078 
RecoverSessionListener()4079 void WindowSessionImpl::RecoverSessionListener()
4080 {
4081     auto persistentId = GetPersistentId();
4082     TLOGI(WmsLogTag::WMS_RECOVER, "with persistentId=%{public}d", persistentId);
4083     {
4084         std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
4085         if (avoidAreaChangeListeners_.find(persistentId) != avoidAreaChangeListeners_.end() &&
4086             !avoidAreaChangeListeners_[persistentId].empty()) {
4087             SingletonContainer::Get<WindowAdapter>().UpdateSessionAvoidAreaListener(persistentId, true);
4088         }
4089     }
4090     {
4091         std::lock_guard<std::recursive_mutex> lockListener(touchOutsideListenerMutex_);
4092         if (touchOutsideListeners_.find(persistentId) != touchOutsideListeners_.end() &&
4093             !touchOutsideListeners_[persistentId].empty()) {
4094             SingletonContainer::Get<WindowAdapter>().UpdateSessionTouchOutsideListener(persistentId, true);
4095         }
4096     }
4097     {
4098         std::lock_guard<std::recursive_mutex> lockListener(windowVisibilityChangeListenerMutex_);
4099         if (windowVisibilityChangeListeners_.find(persistentId) != windowVisibilityChangeListeners_.end() &&
4100             !windowVisibilityChangeListeners_[persistentId].empty()) {
4101             SingletonContainer::Get<WindowAdapter>().UpdateSessionWindowVisibilityListener(persistentId, true);
4102         }
4103     }
4104     {
4105         std::lock_guard<std::mutex> lockListener(windowRectChangeListenerMutex_);
4106         if (windowRectChangeListeners_.find(persistentId) != windowRectChangeListeners_.end() &&
4107             !windowRectChangeListeners_[persistentId].empty()) {
4108             if (auto hostSession = GetHostSession()) {
4109                 hostSession->UpdateRectChangeListenerRegistered(true);
4110             }
4111         }
4112     }
4113     {
4114         std::lock_guard<std::mutex> lockListener(windowRotationChangeListenerMutex_);
4115         if (windowRotationChangeListeners_.find(persistentId) != windowRotationChangeListeners_.end() &&
4116             !windowRotationChangeListeners_[persistentId].empty()) {
4117             if (auto hostSession = GetHostSession()) {
4118                 hostSession->UpdateRotationChangeRegistered(persistentId, true);
4119             }
4120         }
4121     }
4122     {
4123         std::lock_guard<std::recursive_mutex> lockListener(screenshotAppEventListenerMutex_);
4124         if (screenshotAppEventListeners_.find(persistentId) != screenshotAppEventListeners_.end() &&
4125             !screenshotAppEventListeners_[persistentId].empty()) {
4126             if (auto hostSession = GetHostSession()) {
4127                 hostSession->UpdateScreenshotAppEventRegistered(persistentId, true);
4128             }
4129         }
4130     }
4131     {
4132         std::lock_guard<std::recursive_mutex> lockListener(acrossDisplaysChangeListenerMutex_);
4133         if (acrossDisplaysChangeListeners_.find(persistentId) != acrossDisplaysChangeListeners_.end() &&
4134             !acrossDisplaysChangeListeners_[persistentId].empty()) {
4135             if (auto hostSession = GetHostSession()) {
4136                 hostSession->UpdateAcrossDisplaysChangeRegistered(true);
4137             }
4138         }
4139     }
4140 }
4141 
4142 template<typename T>
GetListeners()4143 EnableIfSame<T, IWindowLifeCycle, std::vector<sptr<IWindowLifeCycle>>> WindowSessionImpl::GetListeners()
4144 {
4145     std::vector<sptr<IWindowLifeCycle>> lifecycleListeners;
4146     for (auto& listener : lifecycleListeners_[GetPersistentId()]) {
4147         lifecycleListeners.push_back(listener);
4148     }
4149     return lifecycleListeners;
4150 }
4151 
4152 template<typename T>
GetListeners()4153 EnableIfSame<T, IWindowStageLifeCycle, std::vector<sptr<IWindowStageLifeCycle>>> WindowSessionImpl::GetListeners()
4154 {
4155     std::vector<sptr<IWindowStageLifeCycle>> windowStageLifecycleListeners;
4156     for (auto& listener : windowStageLifecycleListeners_[GetPersistentId()]) {
4157         windowStageLifecycleListeners.push_back(listener);
4158     }
4159     return windowStageLifecycleListeners;
4160 }
4161 
4162 template<typename T>
GetListeners()4163 EnableIfSame<T, IWindowChangeListener, std::vector<sptr<IWindowChangeListener>>> WindowSessionImpl::GetListeners()
4164 {
4165     std::vector<sptr<IWindowChangeListener>> windowChangeListeners;
4166     for (auto& listener : windowChangeListeners_[GetPersistentId()]) {
4167         windowChangeListeners.push_back(listener);
4168     }
4169     return windowChangeListeners;
4170 }
4171 
4172 template<typename T>
GetListeners()4173 EnableIfSame<T, IWindowCrossAxisListener, std::vector<sptr<IWindowCrossAxisListener>>> WindowSessionImpl::GetListeners()
4174 {
4175     std::vector<sptr<IWindowCrossAxisListener>> windowCrossAxisListeners;
4176     for (const auto& listener : windowCrossAxisListeners_[GetPersistentId()]) {
4177         windowCrossAxisListeners.push_back(listener);
4178     }
4179     return windowCrossAxisListeners;
4180 }
4181 
NotifyWindowCrossAxisChange(CrossAxisState state)4182 void WindowSessionImpl::NotifyWindowCrossAxisChange(CrossAxisState state)
4183 {
4184     TLOGI(WmsLogTag::WMS_LAYOUT, "id: %{public}d, cross axis state %{public}d", GetPersistentId(),
4185         static_cast<uint32_t>(state));
4186     crossAxisState_ = state;
4187     AAFwk::Want want;
4188     want.SetParam(Extension::CROSS_AXIS_FIELD, static_cast<int32_t>(state));
4189     if (auto uiContent = GetUIContentSharedPtr()) {
4190         uiContent->SendUIExtProprty(static_cast<uint32_t>(Extension::Businesscode::SYNC_CROSS_AXIS_STATE),
4191             want, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
4192     }
4193     std::lock_guard<std::recursive_mutex> lockListener(windowCrossAxisListenerMutex_);
4194     auto windowCrossAxisListeners = GetListeners<IWindowCrossAxisListener>();
4195     for (const auto& listener : windowCrossAxisListeners) {
4196         if (listener != nullptr) {
4197             listener->OnCrossAxisChange(state);
4198         }
4199     }
4200 }
4201 
IsWaterfallModeEnabled()4202 bool WindowSessionImpl::IsWaterfallModeEnabled()
4203 {
4204     if (!isValidWaterfallMode_.load() && InitWaterfallMode()) {
4205         isValidWaterfallMode_.store(true);
4206     }
4207     bool isWaterfallMode = isFullScreenWaterfallMode_.load();
4208     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "waterfall: %{public}d, winId: %{public}u", isWaterfallMode, GetWindowId());
4209     return isWaterfallMode;
4210 }
4211 
InitWaterfallMode()4212 bool WindowSessionImpl::InitWaterfallMode()
4213 {
4214     if (IsWindowSessionInvalid()) {
4215         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "session is invalid");
4216         return false;
4217     }
4218     auto hostSession = GetHostSession();
4219     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, false);
4220     bool isWaterfallMode = false;
4221     if (hostSession->GetWaterfallMode(isWaterfallMode) != WSError::WS_OK) {
4222         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "failed winId: %{public}u", GetWindowId());
4223         return false;
4224     }
4225     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "winId: %{public}u", GetWindowId());
4226     isFullScreenWaterfallMode_.store(isWaterfallMode);
4227     NotifyWaterfallModeChange(isWaterfallMode);
4228     return true;
4229 }
4230 
RegisterWaterfallModeChangeListener(const sptr<IWaterfallModeChangeListener> & listener)4231 WMError WindowSessionImpl::RegisterWaterfallModeChangeListener(const sptr<IWaterfallModeChangeListener>& listener)
4232 {
4233     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "winId: %{public}u", GetWindowId());
4234     std::lock_guard<std::mutex> lockListener(waterfallModeChangeListenerMutex_);
4235     return RegisterListener(waterfallModeChangeListeners_[GetPersistentId()], listener);
4236 }
4237 
UnregisterWaterfallModeChangeListener(const sptr<IWaterfallModeChangeListener> & listener)4238 WMError WindowSessionImpl::UnregisterWaterfallModeChangeListener(const sptr<IWaterfallModeChangeListener>& listener)
4239 {
4240     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "winId: %{public}u", GetWindowId());
4241     std::lock_guard<std::mutex> lockListener(waterfallModeChangeListenerMutex_);
4242     return UnregisterListener(waterfallModeChangeListeners_[GetPersistentId()], listener);
4243 }
4244 
GetWaterfallModeChangeListeners()4245 std::vector<sptr<IWaterfallModeChangeListener>> WindowSessionImpl::GetWaterfallModeChangeListeners()
4246 {
4247     std::vector<sptr<IWaterfallModeChangeListener>> listeners;
4248     std::lock_guard<std::mutex> lockListener(waterfallModeChangeListenerMutex_);
4249     for (auto& listener : waterfallModeChangeListeners_[GetPersistentId()]) {
4250         listeners.push_back(listener);
4251     }
4252     return listeners;
4253 }
4254 
NotifyAcrossDisplaysChange(bool isAcrossDisplays)4255 WMError WindowSessionImpl::NotifyAcrossDisplaysChange(bool isAcrossDisplays)
4256 {
4257     static bool isFirstNotify = true;
4258     if (!isFirstNotify && isAcrossDisplays_ == isAcrossDisplays) {
4259         return WMError::WM_DO_NOTHING;
4260     }
4261     std::lock_guard<std::recursive_mutex> lock(acrossDisplaysChangeListenerMutex_);
4262     const auto& acrossMultiDisplayChangeListeners = GetListeners<IAcrossDisplaysChangeListener>();
4263     for (const auto& listener : acrossMultiDisplayChangeListeners) {
4264         if (listener != nullptr) {
4265             listener->OnAcrossDisplaysChanged(isAcrossDisplays);
4266         }
4267     }
4268     isFirstNotify = false;
4269     isAcrossDisplays_ = isAcrossDisplays;
4270     return WMError::WM_OK;
4271 }
4272 
NotifyWaterfallModeChange(bool isWaterfallMode)4273 void WindowSessionImpl::NotifyWaterfallModeChange(bool isWaterfallMode)
4274 {
4275     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "winId: %{public}u, waterfall: %{public}d, stat: %{public}u",
4276         GetWindowId(), isWaterfallMode, static_cast<uint32_t>(state_));
4277     if (state_ != WindowState::STATE_SHOWN) {
4278         return;
4279     }
4280     AAFwk::Want want;
4281     want.SetParam(Extension::WATERFALL_MODE_FIELD, isWaterfallMode);
4282     if (auto uiContent = GetUIContentSharedPtr()) {
4283         TLOGI(WmsLogTag::WMS_ATTRIBUTE, "send uiext winId: %{public}u", GetWindowId());
4284         uiContent->SendUIExtProprty(static_cast<uint32_t>(Extension::Businesscode::SYNC_HOST_WATERFALL_MODE),
4285             want, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
4286     }
4287     auto waterfallModeChangeListeners = GetWaterfallModeChangeListeners();
4288     for (const auto& listener : waterfallModeChangeListeners) {
4289         if (listener != nullptr) {
4290             listener->OnWaterfallModeChange(isWaterfallMode);
4291         }
4292     }
4293 }
4294 
4295 template<typename T>
4296 EnableIfSame<T, IOccupiedAreaChangeListener,
GetListeners()4297     std::vector<sptr<IOccupiedAreaChangeListener>>> WindowSessionImpl::GetListeners()
4298 {
4299     std::vector<sptr<IOccupiedAreaChangeListener>> occupiedAreaChangeListeners;
4300     for (auto& listener : occupiedAreaChangeListeners_[GetPersistentId()]) {
4301         occupiedAreaChangeListeners.push_back(listener);
4302     }
4303     return occupiedAreaChangeListeners;
4304 }
4305 
4306 template<typename T>
GetListeners()4307 EnableIfSame<T, IKBWillShowListener, std::vector<sptr<IKBWillShowListener>>> WindowSessionImpl::GetListeners()
4308 {
4309     std::vector<sptr<IKBWillShowListener>> keyboardWillShowListeners;
4310     for (auto& listener : keyboardWillShowListeners_[GetPersistentId()]) {
4311         keyboardWillShowListeners.push_back(listener);
4312     }
4313     return keyboardWillShowListeners;
4314 }
4315 
4316 template<typename T>
GetListeners()4317 EnableIfSame<T, IKBWillHideListener, std::vector<sptr<IKBWillHideListener>>> WindowSessionImpl::GetListeners()
4318 {
4319     std::vector<sptr<IKBWillHideListener>> keyboardWillHideListeners;
4320     for (auto& listener : keyboardWillHideListeners_[GetPersistentId()]) {
4321         keyboardWillHideListeners.push_back(listener);
4322     }
4323     return keyboardWillHideListeners;
4324 }
4325 
4326 template<typename T>
GetListeners()4327 EnableIfSame<T, IKeyboardDidShowListener, std::vector<sptr<IKeyboardDidShowListener>>> WindowSessionImpl::GetListeners()
4328 {
4329     std::vector<sptr<IKeyboardDidShowListener>> keyboardDidShowListeners;
4330     for (auto& listener : keyboardDidShowListeners_[GetPersistentId()]) {
4331         keyboardDidShowListeners.push_back(listener);
4332     }
4333     return keyboardDidShowListeners;
4334 }
4335 
4336 template<typename T>
GetListeners()4337 EnableIfSame<T, IKeyboardDidHideListener, std::vector<sptr<IKeyboardDidHideListener>>> WindowSessionImpl::GetListeners()
4338 {
4339     std::vector<sptr<IKeyboardDidHideListener>> keyboardDidHideListeners;
4340     for (auto& listener : keyboardDidHideListeners_[GetPersistentId()]) {
4341         keyboardDidHideListeners.push_back(listener);
4342     }
4343     return keyboardDidHideListeners;
4344 }
4345 
4346 template<typename T>
RegisterListener(std::vector<sptr<T>> & holder,const sptr<T> & listener)4347 WMError WindowSessionImpl::RegisterListener(std::vector<sptr<T>>& holder, const sptr<T>& listener)
4348 {
4349     if (listener == nullptr) {
4350         WLOGFE("listener is null");
4351         return WMError::WM_ERROR_NULLPTR;
4352     }
4353     if (std::find(holder.begin(), holder.end(), listener) != holder.end()) {
4354         WLOGFE("already registered");
4355         return WMError::WM_OK;
4356     }
4357     holder.emplace_back(listener);
4358     return WMError::WM_OK;
4359 }
4360 
4361 template<typename T>
UnregisterListener(std::vector<sptr<T>> & holder,const sptr<T> & listener)4362 WMError WindowSessionImpl::UnregisterListener(std::vector<sptr<T>>& holder, const sptr<T>& listener)
4363 {
4364     if (listener == nullptr) {
4365         WLOGFE("listener could not be null");
4366         return WMError::WM_ERROR_NULLPTR;
4367     }
4368     holder.erase(std::remove_if(holder.begin(), holder.end(),
4369         [listener](sptr<T> registeredListener) {
4370             return registeredListener == listener;
4371         }), holder.end());
4372     return WMError::WM_OK;
4373 }
4374 
4375 template<typename T>
ClearUselessListeners(std::map<int32_t,T> & listeners,int32_t persistentId)4376 void WindowSessionImpl::ClearUselessListeners(std::map<int32_t, T>& listeners, int32_t persistentId)
4377 {
4378     listeners.erase(persistentId);
4379 }
4380 
4381 template<typename T>
ClearUselessListeners(std::unordered_map<int32_t,T> & listeners,int32_t persistentId)4382 void WindowSessionImpl::ClearUselessListeners(std::unordered_map<int32_t, T>& listeners, int32_t persistentId)
4383 {
4384     listeners.erase(persistentId);
4385 }
4386 
4387 template<typename T>
GetListeners()4388 EnableIfSame<T, IWindowStatusChangeListener, std::vector<sptr<IWindowStatusChangeListener>>> WindowSessionImpl::GetListeners()
4389 {
4390     std::vector<sptr<IWindowStatusChangeListener>> windowStatusChangeListeners;
4391     for (auto& listener : windowStatusChangeListeners_[GetPersistentId()]) {
4392         windowStatusChangeListeners.push_back(listener);
4393     }
4394     return windowStatusChangeListeners;
4395 }
4396 
4397 template<typename T>
GetListeners()4398 EnableIfSame<T, IWindowStatusDidChangeListener, std::vector<sptr<IWindowStatusDidChangeListener>>> WindowSessionImpl::GetListeners()
4399 {
4400     std::vector<sptr<IWindowStatusDidChangeListener>> windowStatusDidChangeListeners;
4401     for (auto& listener : windowStatusDidChangeListeners_[GetPersistentId()]) {
4402         windowStatusDidChangeListeners.push_back(listener);
4403     }
4404     return windowStatusDidChangeListeners;
4405 }
4406 
ClearListenersById(int32_t persistentId)4407 void WindowSessionImpl::ClearListenersById(int32_t persistentId)
4408 {
4409     TLOGI(WmsLogTag::WMS_LIFE, "Called id: %{public}d.", GetPersistentId());
4410     {
4411         std::lock_guard<std::mutex> lockListener(displayMoveListenerMutex_);
4412         ClearUselessListeners(displayMoveListeners_, persistentId);
4413     }
4414     {
4415         std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
4416         ClearUselessListeners(lifecycleListeners_, persistentId);
4417     }
4418     {
4419         std::lock_guard<std::recursive_mutex> lockListener(windowChangeListenerMutex_);
4420         ClearUselessListeners(windowChangeListeners_, persistentId);
4421     }
4422     {
4423         std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
4424         ClearUselessListeners(avoidAreaChangeListeners_, persistentId);
4425     }
4426     {
4427         std::lock_guard<std::recursive_mutex> lockListener(dialogDeathRecipientListenerMutex_);
4428         ClearUselessListeners(dialogDeathRecipientListeners_, persistentId);
4429     }
4430     {
4431         std::lock_guard<std::recursive_mutex> lockListener(dialogTargetTouchListenerMutex_);
4432         ClearUselessListeners(dialogTargetTouchListener_, persistentId);
4433     }
4434     {
4435         std::lock_guard<std::recursive_mutex> lockListener(screenshotListenerMutex_);
4436         ClearUselessListeners(screenshotListeners_, persistentId);
4437     }
4438     {
4439         std::lock_guard<std::recursive_mutex> lockListener(screenshotAppEventListenerMutex_);
4440         ClearUselessListeners(screenshotAppEventListeners_, persistentId);
4441     }
4442     {
4443         std::lock_guard<std::recursive_mutex> lockListener(windowStatusChangeListenerMutex_);
4444         ClearUselessListeners(windowStatusChangeListeners_, persistentId);
4445     }
4446     {
4447         std::lock_guard<std::recursive_mutex> lockListener(windowStatusDidChangeListenerMutex_);
4448         ClearUselessListeners(windowStatusDidChangeListeners_, persistentId);
4449     }
4450     {
4451         std::lock_guard<std::recursive_mutex> lockListener(windowTitleButtonRectChangeListenerMutex_);
4452         ClearUselessListeners(windowTitleButtonRectChangeListeners_, persistentId);
4453     }
4454     {
4455         std::lock_guard<std::mutex> lockListener(displayIdChangeListenerMutex_);
4456         ClearUselessListeners(displayIdChangeListeners_, persistentId);
4457     }
4458     {
4459         std::lock_guard<std::mutex> lockListener(systemDensityChangeListenerMutex_);
4460         ClearUselessListeners(systemDensityChangeListeners_, persistentId);
4461     }
4462     {
4463         std::lock_guard<std::recursive_mutex> lockListener(acrossDisplaysChangeListenerMutex_);
4464         ClearUselessListeners(acrossDisplaysChangeListeners_, persistentId);
4465     }
4466     {
4467         std::lock_guard<std::recursive_mutex> lockListener(windowNoInteractionListenerMutex_);
4468         ClearUselessListeners(windowNoInteractionListeners_, persistentId);
4469     }
4470     {
4471         std::lock_guard<std::mutex> lockListener(windowRectChangeListenerMutex_);
4472         ClearUselessListeners(windowRectChangeListeners_, persistentId);
4473     }
4474     {
4475         std::lock_guard<std::mutex> lockListener(rectChangeInGlobalDisplayListenerMutex_);
4476         ClearUselessListeners(rectChangeInGlobalDisplayListeners_, persistentId);
4477     }
4478     {
4479         std::lock_guard<std::mutex> lockListener(secureLimitChangeListenerMutex_);
4480         ClearUselessListeners(secureLimitChangeListeners_, persistentId);
4481     }
4482     {
4483         std::lock_guard<std::mutex> lockListener(subWindowCloseListenersMutex_);
4484         ClearUselessListeners(subWindowCloseListeners_, persistentId);
4485     }
4486     {
4487         std::lock_guard<std::mutex> lockListener(mainWindowCloseListenersMutex_);
4488         ClearUselessListeners(mainWindowCloseListeners_, persistentId);
4489     }
4490     {
4491         std::lock_guard<std::recursive_mutex> lockListener(windowWillCloseListenersMutex_);
4492         ClearUselessListeners(windowWillCloseListeners_, persistentId);
4493     }
4494     {
4495         std::lock_guard<std::recursive_mutex> lockListener(occupiedAreaChangeListenerMutex_);
4496         ClearUselessListeners(occupiedAreaChangeListeners_, persistentId);
4497     }
4498     {
4499         std::lock_guard<std::recursive_mutex> lockListener(keyboardWillShowListenerMutex_);
4500         ClearUselessListeners(keyboardWillShowListeners_, persistentId);
4501     }
4502     {
4503         std::lock_guard<std::recursive_mutex> lockListener(keyboardWillHideListenerMutex_);
4504         ClearUselessListeners(keyboardWillHideListeners_, persistentId);
4505     }
4506     {
4507         std::lock_guard<std::recursive_mutex> lockListener(keyboardDidShowListenerMutex_);
4508         ClearUselessListeners(keyboardDidShowListeners_, persistentId);
4509     }
4510     {
4511         std::lock_guard<std::recursive_mutex> lockListener(keyboardDidHideListenerMutex_);
4512         ClearUselessListeners(keyboardDidHideListeners_, persistentId);
4513     }
4514     {
4515         std::lock_guard<std::mutex> lockListener(highlightChangeListenerMutex_);
4516         ClearUselessListeners(highlightChangeListeners_, persistentId);
4517     }
4518     {
4519         std::lock_guard<std::recursive_mutex> lockListener(windowCrossAxisListenerMutex_);
4520         ClearUselessListeners(windowCrossAxisListeners_, persistentId);
4521     }
4522     {
4523         std::lock_guard<std::mutex> lockListener(waterfallModeChangeListenerMutex_);
4524         ClearUselessListeners(waterfallModeChangeListeners_, persistentId);
4525     }
4526     {
4527         std::lock_guard<std::mutex> lockListener(preferredOrientationChangeListenerMutex_);
4528         ClearUselessListeners(preferredOrientationChangeListener_, persistentId);
4529     }
4530     {
4531         std::lock_guard<std::mutex> lockListener(windowOrientationChangeListenerMutex_);
4532         ClearUselessListeners(windowOrientationChangeListener_, persistentId);
4533     }
4534     {
4535         std::lock_guard<std::mutex> lockListener(windowRotationChangeListenerMutex_);
4536         ClearUselessListeners(windowRotationChangeListeners_, persistentId);
4537     }
4538     {
4539         std::lock_guard<std::recursive_mutex> lockListener(windowStageLifeCycleListenerMutex_);
4540         ClearUselessListeners(windowStageLifecycleListeners_, persistentId);
4541     }
4542     ClearSwitchFreeMultiWindowListenersById(persistentId);
4543     TLOGI(WmsLogTag::WMS_LIFE, "Clear success, id: %{public}d.", GetPersistentId());
4544 }
4545 
ClearSwitchFreeMultiWindowListenersById(int32_t persistentId)4546 void WindowSessionImpl::ClearSwitchFreeMultiWindowListenersById(int32_t persistentId)
4547 {
4548     std::lock_guard<std::mutex> lockListener(switchFreeMultiWindowListenerMutex_);
4549     ClearUselessListeners(switchFreeMultiWindowListeners_, persistentId);
4550 }
4551 
RegisterWindowDestroyedListener(const NotifyNativeWinDestroyFunc & func)4552 void WindowSessionImpl::RegisterWindowDestroyedListener(const NotifyNativeWinDestroyFunc& func)
4553 {
4554     notifyNativeFunc_ = std::move(func);
4555 }
4556 
ClearVsyncStation()4557 void WindowSessionImpl::ClearVsyncStation()
4558 {
4559     if (vsyncStation_ != nullptr) {
4560         vsyncStation_->Destroy();
4561     }
4562 }
4563 
SetInputEventConsumer(const std::shared_ptr<IInputEventConsumer> & inputEventConsumer)4564 void WindowSessionImpl::SetInputEventConsumer(const std::shared_ptr<IInputEventConsumer>& inputEventConsumer)
4565 {
4566     TLOGI(WmsLogTag::WMS_EVENT, "in");
4567     std::lock_guard<std::recursive_mutex> lock(mutex_);
4568     inputEventConsumer_ = inputEventConsumer;
4569 }
4570 
SetTitleButtonVisible(bool isMaximizeVisible,bool isMinimizeVisible,bool isSplitVisible,bool isCloseVisible)4571 WMError WindowSessionImpl::SetTitleButtonVisible(bool isMaximizeVisible, bool isMinimizeVisible, bool isSplitVisible,
4572     bool isCloseVisible)
4573 {
4574     if (IsWindowSessionInvalid()) {
4575         return WMError::WM_ERROR_INVALID_WINDOW;
4576     }
4577     if (!WindowHelper::IsMainWindow(GetType())) {
4578         return WMError::WM_ERROR_INVALID_CALLING;
4579     }
4580     if (property_->GetPcAppInpadCompatibleMode() && !IsDecorEnable()) {
4581         TLOGE(WmsLogTag::WMS_DECOR, "The is PcAppInPad, not supported");
4582         return WMError::WM_OK;
4583     }
4584     if (!IsPcOrFreeMultiWindowCapabilityEnabled()) {
4585         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
4586     }
4587     if (GetUIContentSharedPtr() == nullptr || !IsDecorEnable()) {
4588         return WMError::WM_ERROR_INVALID_WINDOW;
4589     }
4590     windowTitleVisibleFlags_ = { isMaximizeVisible, isMinimizeVisible, isSplitVisible, isCloseVisible };
4591     UpdateTitleButtonVisibility();
4592     return WMError::WM_OK;
4593 }
4594 
SetSplitButtonVisible(bool isVisible)4595 WSError WindowSessionImpl::SetSplitButtonVisible(bool isVisible)
4596 {
4597     TLOGI(WmsLogTag::WMS_DECOR, "isVisible: %{public}d", isVisible);
4598     auto task = [weakThis = wptr(this), isVisible] {
4599         auto window = weakThis.promote();
4600         if (!window) {
4601             return;
4602         }
4603         window->isSplitButtonVisible_ = isVisible;
4604         window->UpdateTitleButtonVisibility();
4605     };
4606     handler_->PostTask(task, "WMS_WindowSessionImpl_SetSplitButtonVisible");
4607     return WSError::WS_OK;
4608 }
4609 
SetFollowScreenChange(bool isFollowScreenChange)4610 WMError WindowSessionImpl::SetFollowScreenChange(bool isFollowScreenChange)
4611 {
4612     TLOGI(WmsLogTag::DEFAULT, "window %{public}u set follow screen change: %{public}d",
4613         GetWindowId(), isFollowScreenChange);
4614     if (IsWindowSessionInvalid()) {
4615         return WMError::WM_ERROR_INVALID_WINDOW;
4616     }
4617 
4618     if (!WindowHelper::IsSystemWindow(property_->GetWindowType())) {
4619         TLOGE(WmsLogTag::DEFAULT, "window %{public}u type not support", GetWindowId());
4620         return WMError::WM_ERROR_INVALID_WINDOW_MODE_OR_SIZE;
4621     }
4622     property_->SetFollowScreenChange(isFollowScreenChange);
4623     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_FOLLOW_SCREEN_CHANGE);
4624 }
4625 
GetIsMidScene(bool & isMidScene)4626 WMError WindowSessionImpl::GetIsMidScene(bool& isMidScene)
4627 {
4628     if (IsWindowSessionInvalid()) {
4629         return WMError::WM_ERROR_INVALID_WINDOW;
4630     }
4631     auto hostSession = GetHostSession();
4632     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
4633     hostSession->GetIsMidScene(isMidScene);
4634     return WMError::WM_OK;
4635 }
4636 
GetCrossAxisState()4637 CrossAxisState WindowSessionImpl::GetCrossAxisState()
4638 {
4639     if (crossAxisState_ != CrossAxisState::STATE_INVALID) {
4640         return crossAxisState_;
4641     }
4642     if (IsWindowSessionInvalid()) {
4643         return CrossAxisState::STATE_INVALID;
4644     }
4645     auto hostSession = GetHostSession();
4646     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, CrossAxisState::STATE_INVALID);
4647     CrossAxisState state = CrossAxisState::STATE_INVALID;
4648     if (hostSession->GetCrossAxisState(state) != WSError::WS_OK) {
4649         return CrossAxisState::STATE_INVALID;
4650     }
4651     TLOGI(WmsLogTag::WMS_LAYOUT, "window id is %{public}d, state is %{public}d", GetPersistentId(),
4652         static_cast<uint32_t>(state));
4653     return state;
4654 }
4655 
SendContainerModalEvent(const std::string & eventName,const std::string & eventValue)4656 WSError WindowSessionImpl::SendContainerModalEvent(const std::string& eventName, const std::string& eventValue)
4657 {
4658     TLOGI(WmsLogTag::WMS_EVENT, "in");
4659     auto task = [weakThis = wptr(this), eventName, eventValue] {
4660         auto window = weakThis.promote();
4661         if (!window) {
4662             return;
4663         }
4664         std::shared_ptr<Ace::UIContent> uiContent = window->GetUIContentSharedPtr();
4665         if (uiContent == nullptr) {
4666             TLOGNE(WmsLogTag::WMS_EVENT, "uiContent is null!");
4667             return;
4668         }
4669         TLOGNI(WmsLogTag::WMS_EVENT, "name: %{public}s, value: %{public}s", eventName.c_str(), eventValue.c_str());
4670         uiContent->OnContainerModalEvent(eventName, eventValue);
4671     };
4672     handler_->PostTask(task, "WMS_WindowSessionImpl_SendContainerModalEvent");
4673     return WSError::WS_OK;
4674 }
4675 
SetWindowContainerColor(const std::string & activeColor,const std::string & inactiveColor)4676 WMError WindowSessionImpl::SetWindowContainerColor(const std::string& activeColor, const std::string& inactiveColor)
4677 {
4678     if (!windowSystemConfig_.IsPcWindow()) {
4679         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
4680     }
4681     if (!SessionPermission::VerifyCallingPermission(PermissionConstants::PERMISSION_WINDOW_TRANSPARENT) &&
4682         !SessionPermission::IsSystemCalling() &&
4683         containerColorList_.count(property_->GetSessionInfo().bundleName_) == 0) {
4684         TLOGE(WmsLogTag::WMS_DECOR, "winId: %{public}d, permission denied", GetPersistentId());
4685         return WMError::WM_ERROR_INVALID_PERMISSION;
4686     }
4687     if (IsWindowSessionInvalid()) {
4688         return WMError::WM_ERROR_INVALID_WINDOW;
4689     }
4690     if (!WindowHelper::IsMainWindow(GetType())) {
4691         TLOGE(WmsLogTag::WMS_DECOR, "winId: %{public}d, type: %{public}u not supported",
4692             GetPersistentId(), GetType());
4693         return WMError::WM_ERROR_INVALID_CALLING;
4694     }
4695     if (!IsDecorEnable()) {
4696         return WMError::WM_ERROR_INVALID_WINDOW;
4697     }
4698     uint32_t activeColorValue;
4699     if (!ColorParser::Parse(activeColor, activeColorValue)) {
4700         TLOGW(WmsLogTag::WMS_DECOR, "window: %{public}s, value: [%{public}s, %{public}u]",
4701             GetWindowName().c_str(), activeColor.c_str(), activeColorValue);
4702         return WMError::WM_ERROR_INVALID_PARAM;
4703     }
4704     uint32_t inactiveColorValue;
4705     if (!ColorParser::Parse(inactiveColor, inactiveColorValue)) {
4706         TLOGW(WmsLogTag::WMS_DECOR, "window: %{public}s, value: [%{public}s, %{public}u]",
4707             GetWindowName().c_str(), inactiveColor.c_str(), inactiveColorValue);
4708         return WMError::WM_ERROR_INVALID_PARAM;
4709     }
4710     if (!SessionPermission::IsSystemCalling() && (inactiveColorValue & OPAQUE) != OPAQUE) {
4711         TLOGE(WmsLogTag::WMS_DECOR, "winId: %{public}d, inactive alpha value error", GetPersistentId());
4712         return WMError::WM_ERROR_INVALID_PARAM;
4713     }
4714     if (auto uiContent = GetUIContentSharedPtr()) {
4715         uiContent->SetWindowContainerColor(activeColorValue, inactiveColorValue);
4716     } else {
4717         TLOGE(WmsLogTag::WMS_DECOR, "winId: %{public}d, uicontent is null", GetPersistentId());
4718         return WMError::WM_ERROR_NULLPTR;
4719     }
4720     return WMError::WM_OK;
4721 }
4722 
SetWindowContainerModalColor(const std::string & activeColor,const std::string & inactiveColor)4723 WMError WindowSessionImpl::SetWindowContainerModalColor(const std::string& activeColor,
4724                                                         const std::string& inactiveColor)
4725 {
4726     if (!windowSystemConfig_.IsPcWindow()) {
4727         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
4728     }
4729     if (!SessionPermission::IsSystemCalling()) {
4730         return WMError::WM_ERROR_NOT_SYSTEM_APP;
4731     }
4732     if (!WindowHelper::IsMainWindow(GetType())) {
4733         return WMError::WM_ERROR_INVALID_CALLING;
4734     }
4735     if (!IsDecorEnable()) {
4736         return WMError::WM_ERROR_INVALID_WINDOW;
4737     }
4738     uint32_t activeColorValue;
4739     if (!ColorParser::Parse(activeColor, activeColorValue)) {
4740         TLOGE(WmsLogTag::WMS_DECOR, "winId: %{public}d, active value: [%{public}s, %{public}u]",
4741             GetPersistentId(), activeColor.c_str(), activeColorValue);
4742         return WMError::WM_ERROR_INVALID_PARAM;
4743     }
4744     uint32_t inactiveColorValue;
4745     if (!ColorParser::Parse(inactiveColor, inactiveColorValue)) {
4746         TLOGE(WmsLogTag::WMS_DECOR, "winId: %{public}d, inactive value: [%{public}s, %{public}u]",
4747             GetPersistentId(), inactiveColor.c_str(), inactiveColorValue);
4748         return WMError::WM_ERROR_INVALID_PARAM;
4749     }
4750     if (auto uiContent = GetUIContentSharedPtr()) {
4751         uiContent->SetWindowContainerColor(activeColorValue, inactiveColorValue);
4752     } else {
4753         TLOGE(WmsLogTag::WMS_DECOR, "uiContent is null!");
4754         return WMError::WM_ERROR_NULLPTR;
4755     }
4756     return WMError::WM_OK;
4757 }
4758 
NotifyAfterForeground(bool needNotifyListeners,bool needNotifyUiContent,bool waitAttach)4759 void WindowSessionImpl::NotifyAfterForeground(bool needNotifyListeners, bool needNotifyUiContent, bool waitAttach)
4760 {
4761     if (needNotifyListeners) {
4762         NotifyAfterLifecycleForeground();
4763         {
4764             std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
4765             auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4766             CALL_LIFECYCLE_LISTENER(AfterForeground, lifecycleListeners);
4767         }
4768     }
4769     GetAttachStateSyncResult(waitAttach, true);
4770     if (needNotifyUiContent) {
4771         CALL_UI_CONTENT(Foreground);
4772     }
4773 
4774     if (vsyncStation_ != nullptr) {
4775         TLOGD(WmsLogTag::WMS_MAIN, "enable FrameRateLinker, linkerId=%{public}" PRIu64,
4776             vsyncStation_->GetFrameRateLinkerId());
4777         vsyncStation_->SetFrameRateLinkerEnable(GetRSUIContext(), true);
4778         if (WindowHelper::IsMainWindow(GetType())) {
4779             TLOGD(WmsLogTag::WMS_MAIN, "IsMainWindow: enable soloist linker");
4780             vsyncStation_->SetDisplaySoloistFrameRateLinkerEnable(true);
4781         }
4782     } else {
4783         TLOGW(WmsLogTag::WMS_MAIN, "vsyncStation is null");
4784     }
4785 
4786     if (!isValidWaterfallMode_.load()) {
4787         if (InitWaterfallMode()) {
4788             isValidWaterfallMode_.store(true);
4789         }
4790     } else if (isFullScreenWaterfallMode_.load() != waterfallModeWhenEnterBackground_) {
4791         NotifyWaterfallModeChange(isFullScreenWaterfallMode_.load());
4792     }
4793     if (!intentParam_.empty()) {
4794         std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
4795         if (uiContent != nullptr) {
4796             TLOGI(WmsLogTag::WMS_LIFE, "SetIntentParam, isColdStart:%{public}u", isIntentColdStart_);
4797             uiContent->SetIntentParam(intentParam_, std::move(loadPageCallback_), isIntentColdStart_);
4798             intentParam_ = "";
4799         } else {
4800             TLOGE(WmsLogTag::WMS_LIFE, "uiContent is nullptr.");
4801         }
4802     }
4803 }
4804 
GetAttachStateSyncResult(bool waitAttachState,bool afterForeground) const4805 void WindowSessionImpl::GetAttachStateSyncResult(bool waitAttachState, bool afterForeground) const
4806 {
4807     if (!lifecycleCallback_) {
4808         TLOGW(WmsLogTag::WMS_LIFE, "lifecycleCallback is null");
4809         return;
4810     }
4811     if (waitAttachState && WindowHelper::IsNeedWaitAttachStateWindow(GetType()) &&
4812         SysCapUtil::GetBundleName() != AppExecFwk::Constants::SCENE_BOARD_BUNDLE_NAME) {
4813         auto startTime = std::chrono::duration_cast<std::chrono::milliseconds>(
4814             std::chrono::system_clock::now().time_since_epoch()).count();
4815         if (afterForeground) {
4816             lifecycleCallback_->GetAttachSyncResult(WINDOW_LIFECYCLE_TIMEOUT);
4817         } else {
4818             lifecycleCallback_->GetDetachSyncResult(WINDOW_LIFECYCLE_TIMEOUT);
4819         }
4820         auto endTime = std::chrono::duration_cast<std::chrono::milliseconds>(
4821             std::chrono::system_clock::now().time_since_epoch()).count();
4822         auto waitTime = endTime - startTime;
4823         if (waitTime >= WINDOW_LIFECYCLE_TIMEOUT) {
4824             TLOGW(WmsLogTag::WMS_LIFE, "window attach state timeout, persistentId:%{public}d, "
4825                 "afterForeground:%{public}d", GetPersistentId(), afterForeground);
4826         }
4827         TLOGI(WmsLogTag::WMS_LIFE, "get attach state sync result, id:%{public}d, afterForeground:%{public}d",
4828             GetPersistentId(), afterForeground);
4829     }
4830 }
4831 
NotifyAfterDidForeground(uint32_t reason)4832 void WindowSessionImpl::NotifyAfterDidForeground(uint32_t reason)
4833 {
4834     TLOGI(WmsLogTag::WMS_LIFE, "reason: %{public}d", reason);
4835     if (reason != static_cast<uint32_t>(WindowStateChangeReason::USER_SWITCH) &&
4836         reason != static_cast<uint32_t>(WindowStateChangeReason::ABILITY_CALL)) {
4837         TLOGI(WmsLogTag::WMS_LIFE, "reason: %{public}d no need notify did foreground", reason);
4838         return;
4839     }
4840     if (handler_ == nullptr) {
4841         TLOGE(WmsLogTag::WMS_LIFE, "handler is nullptr");
4842         return;
4843     }
4844     const char* const where = __func__;
4845     handler_->PostTask([weak = wptr(this), where] {
4846         auto window = weak.promote();
4847         if (window == nullptr) {
4848             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s window is nullptr", where);
4849             return;
4850         }
4851         TLOGNI(WmsLogTag::WMS_LIFE, "%{public}s execute", where);
4852         auto lifecycleListeners = window->GetListeners<IWindowLifeCycle>();
4853         CALL_LIFECYCLE_LISTENER(AfterDidForeground, lifecycleListeners);
4854     }, where, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
4855 }
4856 
NotifyAfterBackground(bool needNotifyListeners,bool needNotifyUiContent,bool waitDetach)4857 void WindowSessionImpl::NotifyAfterBackground(bool needNotifyListeners, bool needNotifyUiContent, bool waitDetach)
4858 {
4859     if (needNotifyListeners) {
4860         {
4861             std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
4862             auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4863             CALL_LIFECYCLE_LISTENER(AfterBackground, lifecycleListeners);
4864         }
4865         NotifyAfterLifecycleBackground();
4866     }
4867     GetAttachStateSyncResult(waitDetach, false);
4868     if (needNotifyUiContent) {
4869         CALL_UI_CONTENT(Background);
4870     }
4871 
4872     if (vsyncStation_ != nullptr) {
4873         TLOGD(WmsLogTag::WMS_MAIN, "disable FrameRateLinker, linkerId=%{public}" PRIu64,
4874             vsyncStation_->GetFrameRateLinkerId());
4875         vsyncStation_->SetFrameRateLinkerEnable(GetRSUIContext(), false);
4876         if (WindowHelper::IsMainWindow(GetType())) {
4877             TLOGD(WmsLogTag::WMS_MAIN, "IsMainWindow: disable soloist linker");
4878             vsyncStation_->SetDisplaySoloistFrameRateLinkerEnable(false);
4879         }
4880     } else {
4881         TLOGW(WmsLogTag::WMS_MAIN, "vsyncStation is null");
4882     }
4883 
4884     waterfallModeWhenEnterBackground_ = isFullScreenWaterfallMode_.load();
4885 }
4886 
NotifyAfterDidBackground(uint32_t reason)4887 void WindowSessionImpl::NotifyAfterDidBackground(uint32_t reason)
4888 {
4889     TLOGI(WmsLogTag::WMS_LIFE, "reason: %{public}d", reason);
4890     if (reason != static_cast<uint32_t>(WindowStateChangeReason::USER_SWITCH) &&
4891         reason != static_cast<uint32_t>(WindowStateChangeReason::ABILITY_CALL)) {
4892         TLOGI(WmsLogTag::WMS_LIFE, "reason: %{public}d no need notify did background", reason);
4893         return;
4894     }
4895     if (handler_ == nullptr) {
4896         TLOGE(WmsLogTag::WMS_LIFE, "handler is nullptr");
4897         return;
4898     }
4899     const char* const where = __func__;
4900     handler_->PostTask([weak = wptr(this), where] {
4901         auto window = weak.promote();
4902         if (window == nullptr) {
4903             TLOGNI(WmsLogTag::WMS_LIFE, "%{public}s window is nullptr", where);
4904             return;
4905         }
4906         TLOGNI(WmsLogTag::WMS_LIFE, "%{public}s execute", where);
4907         auto lifecycleListeners = window->GetListeners<IWindowLifeCycle>();
4908         CALL_LIFECYCLE_LISTENER(AfterDidBackground, lifecycleListeners);
4909     }, where, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
4910 }
4911 
RequestInputMethodCloseKeyboard(bool isNeedKeyboard,bool keepKeyboardFlag)4912 static void RequestInputMethodCloseKeyboard(bool isNeedKeyboard, bool keepKeyboardFlag)
4913 {
4914     if (!isNeedKeyboard && !keepKeyboardFlag) {
4915 #ifdef IMF_ENABLE
4916         if (MiscServices::InputMethodController::GetInstance()) {
4917             MiscServices::InputMethodController::GetInstance()->RequestHideInput();
4918             TLOGD(WmsLogTag::WMS_KEYBOARD, "Notify InputMethod framework close keyboard end.");
4919         }
4920 #endif
4921     }
4922 }
4923 
NotifyUIContentFocusStatus()4924 void WindowSessionImpl::NotifyUIContentFocusStatus()
4925 {
4926     if (!isFocused_) {
4927         CALL_UI_CONTENT(UnFocus);
4928         return;
4929     }
4930     CALL_UI_CONTENT(Focus);
4931     auto task = [weak = wptr(this)]() {
4932         auto window = weak.promote();
4933         if (!window) {
4934             return;
4935         }
4936         bool isNeedKeyboard = false;
4937         if (auto uiContent = window->GetUIContentSharedPtr()) {
4938             // isNeedKeyboard is set by arkui and indicates whether the window needs a keyboard or not.
4939             isNeedKeyboard = uiContent->NeedSoftKeyboard();
4940         }
4941         // whether keep the keyboard created by other windows, support system window and app subwindow.
4942         bool keepKeyboardFlag = window->property_->GetKeepKeyboardFlag();
4943         TLOGNI(WmsLogTag::WMS_KEYBOARD, "id: %{public}d, isNeedKeyboard: %{public}d, keepKeyboardFlag: %{public}d",
4944             window->GetPersistentId(), isNeedKeyboard, keepKeyboardFlag);
4945         RequestInputMethodCloseKeyboard(isNeedKeyboard, keepKeyboardFlag);
4946     };
4947     if (auto uiContent = GetUIContentSharedPtr()) {
4948         uiContent->SetOnWindowFocused(task);
4949     }
4950 }
4951 
NotifyAfterFocused()4952 void WindowSessionImpl::NotifyAfterFocused()
4953 {
4954     NotifyWindowAfterFocused();
4955     if (GetUIContentSharedPtr() != nullptr) {
4956         NotifyUIContentFocusStatus();
4957     } else {
4958         shouldReNotifyFocus_ = true;
4959     }
4960 }
4961 
NotifyAfterUnfocused(bool needNotifyUiContent)4962 void WindowSessionImpl::NotifyAfterUnfocused(bool needNotifyUiContent)
4963 {
4964     NotifyWindowAfterUnfocused();
4965     if (needNotifyUiContent) {
4966         if (GetUIContentSharedPtr() == nullptr) {
4967             shouldReNotifyFocus_ = true;
4968         } else {
4969             CALL_UI_CONTENT(UnFocus);
4970         }
4971     }
4972 }
4973 
NotifyWindowAfterFocused()4974 void WindowSessionImpl::NotifyWindowAfterFocused()
4975 {
4976     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
4977     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4978     CALL_LIFECYCLE_LISTENER(AfterFocused, lifecycleListeners);
4979 }
4980 
NotifyWindowAfterUnfocused()4981 void WindowSessionImpl::NotifyWindowAfterUnfocused()
4982 {
4983     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
4984     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4985     // use needNotifyUinContent to separate ui content callbacks
4986     CALL_LIFECYCLE_LISTENER(AfterUnfocused, lifecycleListeners);
4987 }
4988 
NotifyUIContentHighlightStatus(bool isHighlighted)4989 void WindowSessionImpl::NotifyUIContentHighlightStatus(bool isHighlighted)
4990 {
4991     if (isHighlighted) {
4992         CALL_UI_CONTENT(ActiveWindow);
4993     } else {
4994         CALL_UI_CONTENT(UnActiveWindow);
4995     }
4996 }
4997 
NotifyBeforeDestroy(std::string windowName)4998 void WindowSessionImpl::NotifyBeforeDestroy(std::string windowName)
4999 {
5000     auto task = [this]() {
5001         if (auto uiContent = GetUIContentSharedPtr()) {
5002             uiContent->Destroy();
5003         }
5004         {
5005             std::unique_lock<std::shared_mutex> lock(uiContentMutex_);
5006             if (uiContent_ != nullptr) {
5007                 uiContent_ = nullptr;
5008                 TLOGND(WmsLogTag::WMS_LIFE, "NotifyBeforeDestroy: uiContent destroy success, persistentId:%{public}d",
5009                     GetPersistentId());
5010             }
5011         }
5012     };
5013     if (handler_) {
5014         handler_->PostSyncTask(task, "wms:NotifyBeforeDestroy");
5015     } else {
5016         task();
5017     }
5018     TLOGI(WmsLogTag::WMS_LIFE, "Release uicontent successfully, id: %{public}d.", GetPersistentId());
5019     if (notifyNativeFunc_) {
5020         notifyNativeFunc_(windowName);
5021     }
5022     TLOGI(WmsLogTag::WMS_LIFE, "successed with id: %{public}d.", GetPersistentId());
5023 }
5024 
NotifyAfterDestroy()5025 void WindowSessionImpl::NotifyAfterDestroy()
5026 {
5027     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
5028     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
5029     CALL_LIFECYCLE_LISTENER(AfterDestroyed, lifecycleListeners);
5030 }
5031 
NotifyAfterActive()5032 void WindowSessionImpl::NotifyAfterActive()
5033 {
5034     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
5035     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
5036     CALL_LIFECYCLE_LISTENER(AfterActive, lifecycleListeners);
5037 }
5038 
NotifyAfterInactive()5039 void WindowSessionImpl::NotifyAfterInactive()
5040 {
5041     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
5042     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
5043     CALL_LIFECYCLE_LISTENER(AfterInactive, lifecycleListeners);
5044 }
5045 
NotifyForegroundFailed(WMError ret)5046 void WindowSessionImpl::NotifyForegroundFailed(WMError ret)
5047 {
5048     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
5049     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
5050     CALL_LIFECYCLE_LISTENER_WITH_PARAM(ForegroundFailed, lifecycleListeners, static_cast<int32_t>(ret));
5051 }
5052 
NotifyBackgroundFailed(WMError ret)5053 void WindowSessionImpl::NotifyBackgroundFailed(WMError ret)
5054 {
5055     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
5056     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
5057     CALL_LIFECYCLE_LISTENER_WITH_PARAM(BackgroundFailed, lifecycleListeners, static_cast<int32_t>(ret));
5058 }
5059 
NotifyAfterResumed()5060 void WindowSessionImpl::NotifyAfterResumed()
5061 {
5062     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
5063     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
5064     CALL_LIFECYCLE_LISTENER(AfterResumed, lifecycleListeners);
5065 }
5066 
NotifyAfterPaused()5067 void WindowSessionImpl::NotifyAfterPaused()
5068 {
5069     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
5070     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
5071     CALL_LIFECYCLE_LISTENER(AfterPaused, lifecycleListeners);
5072 }
5073 
NotifyAfterLifecycleForeground()5074 void WindowSessionImpl::NotifyAfterLifecycleForeground()
5075 {
5076     std::lock_guard<std::recursive_mutex> lockListener(windowStageLifeCycleListenerMutex_);
5077     auto lifecycleListeners = GetListeners<IWindowStageLifeCycle>();
5078     CALL_LIFECYCLE_LISTENER(AfterLifecycleForeground, lifecycleListeners);
5079 }
5080 
NotifyAfterLifecycleBackground()5081 void WindowSessionImpl::NotifyAfterLifecycleBackground()
5082 {
5083     std::lock_guard<std::recursive_mutex> lockListener(windowStageLifeCycleListenerMutex_);
5084     auto lifecycleListeners = GetListeners<IWindowStageLifeCycle>();
5085     CALL_LIFECYCLE_LISTENER(AfterLifecycleBackground, lifecycleListeners);
5086 }
5087 
NotifyAfterLifecycleResumed()5088 void WindowSessionImpl::NotifyAfterLifecycleResumed()
5089 {
5090     TLOGI(WmsLogTag::WMS_LIFE, "in");
5091     std::lock_guard<std::recursive_mutex> lockListener(windowStageLifeCycleListenerMutex_);
5092     bool useControlState = property_->GetUseControlState();
5093     if (useControlState) {
5094         auto lifecycleListeners = GetListeners<IWindowStageLifeCycle>();
5095         CALL_LIFECYCLE_LISTENER(AfterLifecyclePaused, lifecycleListeners);
5096         isInteractiveStateFlag_ = false;
5097         return;
5098     }
5099 
5100     if (isInteractiveStateFlag_) {
5101         TLOGI(WmsLogTag::WMS_LIFE, "window has been in interactive status");
5102         return;
5103     }
5104     if (state_ != WindowState::STATE_SHOWN || !isDidForeground_) {
5105         TLOGI(WmsLogTag::WMS_LIFE, "state: %{public}d, isDidForeground: %{public}d", state_, isDidForeground_);
5106         return;
5107     }
5108     isInteractiveStateFlag_ = true;
5109     auto lifecycleListeners = GetListeners<IWindowStageLifeCycle>();
5110     CALL_LIFECYCLE_LISTENER(AfterLifecycleResumed, lifecycleListeners);
5111 }
5112 
NotifyAfterLifecyclePaused()5113 void WindowSessionImpl::NotifyAfterLifecyclePaused()
5114 {
5115     TLOGI(WmsLogTag::WMS_LIFE, "in");
5116     std::lock_guard<std::recursive_mutex> lockListener(windowStageLifeCycleListenerMutex_);
5117     if (!isInteractiveStateFlag_) {
5118         TLOGI(WmsLogTag::WMS_LIFE, "window has been in noninteractive status");
5119         return;
5120     }
5121     isInteractiveStateFlag_ = false;
5122     auto lifecycleListeners = GetListeners<IWindowStageLifeCycle>();
5123     CALL_LIFECYCLE_LISTENER(AfterLifecyclePaused, lifecycleListeners);
5124 }
5125 
MarkProcessed(int32_t eventId)5126 WSError WindowSessionImpl::MarkProcessed(int32_t eventId)
5127 {
5128     if (IsWindowSessionInvalid()) {
5129         WLOGFE("session is invalid");
5130         return WSError::WS_DO_NOTHING;
5131     }
5132     auto hostSession = GetHostSession();
5133     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WSError::WS_DO_NOTHING);
5134     return hostSession->MarkProcessed(eventId);
5135 }
5136 
RegisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener> & listener)5137 void WindowSessionImpl::RegisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener>& listener)
5138 {
5139     TLOGI(WmsLogTag::WMS_DIALOG, "window %{public}s id %{public}d register DialogDeathRecipientListener",
5140         GetWindowName().c_str(), GetPersistentId());
5141     if (listener == nullptr) {
5142         WLOGFE("listener is null");
5143         return;
5144     }
5145     std::lock_guard<std::recursive_mutex> lockListener(dialogDeathRecipientListenerMutex_);
5146     RegisterListener(dialogDeathRecipientListeners_[GetPersistentId()], listener);
5147 }
5148 
UnregisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener> & listener)5149 void WindowSessionImpl::UnregisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener>& listener)
5150 {
5151     TLOGI(WmsLogTag::WMS_DIALOG, "window %{public}s id %{public}d",
5152         GetWindowName().c_str(), GetPersistentId());
5153     std::lock_guard<std::recursive_mutex> lockListener(dialogDeathRecipientListenerMutex_);
5154     UnregisterListener(dialogDeathRecipientListeners_[GetPersistentId()], listener);
5155 }
5156 
RegisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener> & listener)5157 WMError WindowSessionImpl::RegisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener>& listener)
5158 {
5159     TLOGI(WmsLogTag::WMS_DIALOG, "window %{public}s id %{public}d",
5160         GetWindowName().c_str(), GetPersistentId());
5161     if (listener == nullptr) {
5162         WLOGFE("listener is nullptr");
5163         return WMError::WM_ERROR_NULLPTR;
5164     }
5165     std::lock_guard<std::recursive_mutex> lockListener(dialogTargetTouchListenerMutex_);
5166     return RegisterListener(dialogTargetTouchListener_[GetPersistentId()], listener);
5167 }
5168 
UnregisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener> & listener)5169 WMError WindowSessionImpl::UnregisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener>& listener)
5170 {
5171     TLOGI(WmsLogTag::WMS_DIALOG, "window %{public}s id %{public}d",
5172         GetWindowName().c_str(), GetPersistentId());
5173     std::lock_guard<std::recursive_mutex> lockListener(dialogTargetTouchListenerMutex_);
5174     return UnregisterListener(dialogTargetTouchListener_[GetPersistentId()], listener);
5175 }
5176 
RegisterScreenshotListener(const sptr<IScreenshotListener> & listener)5177 WMError WindowSessionImpl::RegisterScreenshotListener(const sptr<IScreenshotListener>& listener)
5178 {
5179     WLOGFD("in");
5180     std::lock_guard<std::recursive_mutex> lockListener(screenshotListenerMutex_);
5181     return RegisterListener(screenshotListeners_[GetPersistentId()], listener);
5182 }
5183 
UnregisterScreenshotListener(const sptr<IScreenshotListener> & listener)5184 WMError WindowSessionImpl::UnregisterScreenshotListener(const sptr<IScreenshotListener>& listener)
5185 {
5186     WLOGFD("in");
5187     std::lock_guard<std::recursive_mutex> lockListener(screenshotListenerMutex_);
5188     return UnregisterListener(screenshotListeners_[GetPersistentId()], listener);
5189 }
5190 
RegisterScreenshotAppEventListener(const IScreenshotAppEventListenerSptr & listener)5191 WMError WindowSessionImpl::RegisterScreenshotAppEventListener(const IScreenshotAppEventListenerSptr& listener)
5192 {
5193     if (IsWindowSessionInvalid()) {
5194         return WMError::WM_ERROR_INVALID_WINDOW;
5195     }
5196     auto persistentId = GetPersistentId();
5197     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "winId: %{public}d", persistentId);
5198     if (listener == nullptr) {
5199         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "listener is null");
5200         return WMError::WM_ERROR_NULLPTR;
5201     }
5202 
5203     WMError ret = WMError::WM_OK;
5204     bool isUpdate = false;
5205     {
5206         std::lock_guard<std::recursive_mutex> lockListener(screenshotAppEventListenerMutex_);
5207         ret = RegisterListener(screenshotAppEventListeners_[persistentId], listener);
5208         if (ret != WMError::WM_OK) {
5209             return ret;
5210         }
5211         if (screenshotAppEventListeners_[persistentId].size() == 1) {
5212             isUpdate = true;
5213         }
5214     }
5215     auto hostSession = GetHostSession();
5216     if (isUpdate && hostSession != nullptr) {
5217         ret = hostSession->UpdateScreenshotAppEventRegistered(persistentId, true);
5218     }
5219     return ret;
5220 }
5221 
UnregisterScreenshotAppEventListener(const IScreenshotAppEventListenerSptr & listener)5222 WMError WindowSessionImpl::UnregisterScreenshotAppEventListener(const IScreenshotAppEventListenerSptr& listener)
5223 {
5224     if (IsWindowSessionInvalid()) {
5225         return WMError::WM_ERROR_INVALID_WINDOW;
5226     }
5227     auto persistentId = GetPersistentId();
5228     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "winId: %{public}d", persistentId);
5229     if (listener == nullptr) {
5230         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "listener is null");
5231         return WMError::WM_ERROR_NULLPTR;
5232     }
5233 
5234     WMError ret = WMError::WM_OK;
5235     bool isUpdate = false;
5236     {
5237         std::lock_guard<std::recursive_mutex> lockListener(screenshotAppEventListenerMutex_);
5238         ret = UnregisterListener(screenshotAppEventListeners_[persistentId], listener);
5239         if (ret != WMError::WM_OK) {
5240             return ret;
5241         }
5242         if (screenshotAppEventListeners_[persistentId].empty()) {
5243             isUpdate = true;
5244         }
5245     }
5246     auto hostSession = GetHostSession();
5247     if (isUpdate && hostSession != nullptr) {
5248         ret = hostSession->UpdateScreenshotAppEventRegistered(persistentId, false);
5249     }
5250     return ret;
5251 }
5252 
5253 template<typename T>
5254 EnableIfSame<T, IDialogDeathRecipientListener, std::vector<sptr<IDialogDeathRecipientListener>>> WindowSessionImpl::
GetListeners()5255     GetListeners()
5256 {
5257     std::vector<sptr<IDialogDeathRecipientListener>> dialogDeathRecipientListener;
5258     for (auto& listener : dialogDeathRecipientListeners_[GetPersistentId()]) {
5259         dialogDeathRecipientListener.push_back(listener);
5260     }
5261     return dialogDeathRecipientListener;
5262 }
5263 
5264 template<typename T>
5265 EnableIfSame<T, IDialogTargetTouchListener,
GetListeners()5266     std::vector<sptr<IDialogTargetTouchListener>>> WindowSessionImpl::GetListeners()
5267 {
5268     std::vector<sptr<IDialogTargetTouchListener>> dialogTargetTouchListener;
5269     for (auto& listener : dialogTargetTouchListener_[GetPersistentId()]) {
5270         dialogTargetTouchListener.push_back(listener);
5271     }
5272     return dialogTargetTouchListener;
5273 }
5274 
5275 template<typename T>
GetListeners()5276 EnableIfSame<T, IScreenshotListener, std::vector<sptr<IScreenshotListener>>> WindowSessionImpl::GetListeners()
5277 {
5278     std::vector<sptr<IScreenshotListener>> screenshotListeners;
5279     for (auto& listener : screenshotListeners_[GetPersistentId()]) {
5280         screenshotListeners.push_back(listener);
5281     }
5282     return screenshotListeners;
5283 }
5284 
5285 template<typename T>
GetListeners()5286 EnableIfSame<T, IScreenshotAppEventListener, std::vector<IScreenshotAppEventListenerSptr>> WindowSessionImpl::GetListeners()
5287 {
5288     return screenshotAppEventListeners_[GetPersistentId()];
5289 }
5290 
5291 
NotifyDestroy()5292 WSError WindowSessionImpl::NotifyDestroy()
5293 {
5294     if (WindowHelper::IsDialogWindow(property_->GetWindowType())) {
5295         std::lock_guard<std::recursive_mutex> lockListener(dialogDeathRecipientListenerMutex_);
5296         auto dialogDeathRecipientListener = GetListeners<IDialogDeathRecipientListener>();
5297         for (auto& listener : dialogDeathRecipientListener) {
5298             if (listener != nullptr) {
5299                 listener->OnDialogDeathRecipient();
5300             }
5301         }
5302     } else if (WindowHelper::IsSubWindow(property_->GetWindowType())) {
5303         if (property_->GetIsUIExtFirstSubWindow() && !isUIExtensionAbilityProcess_) {
5304             Destroy();
5305         }
5306     }
5307     return WSError::WS_OK;
5308 }
5309 
5310 template<typename T>
GetListeners()5311 EnableIfSame<T, IDisplayMoveListener, std::vector<sptr<IDisplayMoveListener>>> WindowSessionImpl::GetListeners()
5312 {
5313     std::vector<sptr<IDisplayMoveListener>> displayMoveListeners;
5314     for (auto& listener : displayMoveListeners_[GetPersistentId()]) {
5315         displayMoveListeners.push_back(listener);
5316     }
5317     return displayMoveListeners;
5318 }
5319 
NotifyDisplayMove(DisplayId from,DisplayId to)5320 void WindowSessionImpl::NotifyDisplayMove(DisplayId from, DisplayId to)
5321 {
5322     WLOGFD("from %{public}" PRIu64 " to %{public}" PRIu64, from, to);
5323     std::lock_guard<std::mutex> lockListener(displayMoveListenerMutex_);
5324     auto displayMoveListeners = GetListeners<IDisplayMoveListener>();
5325     for (auto& listener : displayMoveListeners) {
5326         if (listener != nullptr) {
5327             listener->OnDisplayMove(from, to);
5328         }
5329     }
5330 }
5331 
NotifyCloseExistPipWindow()5332 WSError WindowSessionImpl::NotifyCloseExistPipWindow()
5333 {
5334     TLOGI(WmsLogTag::WMS_PIP, "in");
5335     auto task = []() {
5336         PictureInPictureManager::DoClose(true, true);
5337     };
5338     handler_->PostTask(task, "WMS_WindowSessionImpl_NotifyCloseExistPipWindow");
5339     return WSError::WS_OK;
5340 }
5341 
NotifyTouchDialogTarget(int32_t posX,int32_t posY)5342 void WindowSessionImpl::NotifyTouchDialogTarget(int32_t posX, int32_t posY)
5343 {
5344     TLOGI(WmsLogTag::WMS_DIALOG, "window %{public}s id %{public}d", GetWindowName().c_str(), GetPersistentId());
5345     if (auto hostSession = GetHostSession()) {
5346         hostSession->ProcessPointDownSession(posX, posY);
5347     }
5348     std::lock_guard<std::recursive_mutex> lockListener(dialogTargetTouchListenerMutex_);
5349     auto dialogTargetTouchListener = GetListeners<IDialogTargetTouchListener>();
5350     for (auto& listener : dialogTargetTouchListener) {
5351         if (listener != nullptr) {
5352             listener->OnDialogTargetTouch();
5353         }
5354     }
5355 }
5356 
NotifyScreenshot()5357 void WindowSessionImpl::NotifyScreenshot()
5358 {
5359     std::lock_guard<std::recursive_mutex> lockListener(screenshotListenerMutex_);
5360     auto screenshotListeners = GetListeners<IScreenshotListener>();
5361     for (auto& listener : screenshotListeners) {
5362         if (listener != nullptr) {
5363             listener->OnScreenshot();
5364         }
5365     }
5366     if (auto uiContent = GetUIContentSharedPtr()) {
5367         AAFwk::Want want;
5368         uiContent->SendUIExtProprty(static_cast<uint32_t>(Extension::Businesscode::NOTIFY_SCREENSHOT),
5369             want, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
5370     }
5371 }
5372 
NotifyScreenshotAppEvent(ScreenshotEventType type)5373 WSError WindowSessionImpl::NotifyScreenshotAppEvent(ScreenshotEventType type)
5374 {
5375     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "winId: %{public}d, screenshotEvent: %{public}d",
5376         GetPersistentId(), type);
5377     std::lock_guard<std::recursive_mutex> lockListener(screenshotAppEventListenerMutex_);
5378     auto screenshotAppEventListeners = GetListeners<IScreenshotAppEventListener>();
5379     for (auto& listener : screenshotAppEventListeners) {
5380         if (listener != nullptr) {
5381             listener->OnScreenshotAppEvent(type);
5382         }
5383     }
5384     return WSError::WS_OK;
5385 }
5386 
5387 /** @note @window.layout */
NotifySizeChange(Rect rect,WindowSizeChangeReason reason)5388 void WindowSessionImpl::NotifySizeChange(Rect rect, WindowSizeChangeReason reason)
5389 {
5390     HookWindowSizeByHookWindowInfo(rect);
5391     {
5392         std::lock_guard<std::recursive_mutex> lockListener(windowChangeListenerMutex_);
5393         auto windowChangeListeners = GetListeners<IWindowChangeListener>();
5394         TLOGD(WmsLogTag::WMS_LAYOUT, "Id:%{public}d, sizeChange listenerSize:%{public}zu",
5395             GetPersistentId(), windowChangeListeners.size());
5396         for (auto& listener : windowChangeListeners) {
5397             if (listener != nullptr) {
5398                 listener->OnSizeChange(rect, reason);
5399             }
5400         }
5401     }
5402     {
5403         std::lock_guard<std::mutex> lockRectListener(windowRectChangeListenerMutex_);
5404         auto windowRectChangeListeners = GetListeners<IWindowRectChangeListener>();
5405         TLOGD(WmsLogTag::WMS_LAYOUT, "Id:%{public}d, rectChange listenerSize:%{public}zu",
5406             GetPersistentId(), windowRectChangeListeners.size());
5407         for (auto& listener : windowRectChangeListeners) {
5408             if (listener != nullptr) {
5409                 listener->OnRectChange(rect, reason);
5410             }
5411         }
5412     }
5413     NotifyUIExtHostWindowRectChangeListeners(rect, reason);
5414 }
5415 
NotifyGlobalDisplayRectChange(const Rect & rect,WindowSizeChangeReason reason)5416 void WindowSessionImpl::NotifyGlobalDisplayRectChange(const Rect& rect, WindowSizeChangeReason reason)
5417 {
5418     auto listeners = GetListeners<IRectChangeInGlobalDisplayListener>();
5419     TLOGD(WmsLogTag::WMS_LAYOUT,
5420         "windowId: %{public}d, rect: %{public}s, reason: %{public}d, listenerSize: %{public}zu",
5421         GetPersistentId(), rect.ToString().c_str(), static_cast<int32_t>(reason), listeners.size());
5422     Rect hookedRect = rect;
5423     HookWindowSizeByHookWindowInfo(hookedRect);
5424     for (const auto& listener : listeners) {
5425         if (listener) {
5426             listener->OnRectChangeInGlobalDisplay(hookedRect, reason);
5427         }
5428     }
5429 }
5430 
NotifyUIExtHostWindowRectChangeListeners(const Rect rect,const WindowSizeChangeReason reason)5431 void WindowSessionImpl::NotifyUIExtHostWindowRectChangeListeners(const Rect rect, const WindowSizeChangeReason reason)
5432 {
5433     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
5434     CHECK_UI_CONTENT_RETURN_IF_NULL(uiContent);
5435     bool isUIExtensionWindow = WindowHelper::IsUIExtensionWindow(GetType());
5436     if (!isUIExtensionWindow && !rectChangeUIExtListenerIds_.empty()) {
5437         TLOGI(WmsLogTag::WMS_UIEXT, "rectChangeUIExtListenerIds_ size: %{public}zu",
5438             rectChangeUIExtListenerIds_.size());
5439         AAFwk::Want rectWant;
5440         rectWant.SetParam(Extension::RECT_X, rect.posX_);
5441         rectWant.SetParam(Extension::RECT_Y, rect.posY_);
5442         rectWant.SetParam(Extension::RECT_WIDTH, static_cast<int32_t>(rect.width_));
5443         rectWant.SetParam(Extension::RECT_HEIGHT, static_cast<int32_t>(rect.height_));
5444         rectWant.SetParam(Extension::RECT_CHANGE_REASON, static_cast<int32_t>(reason));
5445         uiContent->SendUIExtProprtyByPersistentId(
5446             static_cast<uint32_t>(Extension::Businesscode::NOTIFY_HOST_WINDOW_RECT_CHANGE), rectWant,
5447             rectChangeUIExtListenerIds_, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
5448     }
5449 }
5450 
NotifySubWindowClose(bool & terminateCloseProcess)5451 void WindowSessionImpl::NotifySubWindowClose(bool& terminateCloseProcess)
5452 {
5453     WLOGFD("in");
5454     std::lock_guard<std::mutex> lockListener(subWindowCloseListenersMutex_);
5455     auto subWindowCloseListeners = GetListeners<ISubWindowCloseListener>();
5456     if (subWindowCloseListeners != nullptr) {
5457         subWindowCloseListeners->OnSubWindowClose(terminateCloseProcess);
5458     }
5459 }
5460 
NotifyMainWindowClose(bool & terminateCloseProcess)5461 WMError WindowSessionImpl::NotifyMainWindowClose(bool& terminateCloseProcess)
5462 {
5463     std::lock_guard<std::mutex> lockListener(mainWindowCloseListenersMutex_);
5464     auto mainWindowCloseListener = GetListeners<IMainWindowCloseListener>();
5465     if (mainWindowCloseListener != nullptr) {
5466         mainWindowCloseListener->OnMainWindowClose(terminateCloseProcess);
5467         return WMError::WM_OK;
5468     }
5469     return WMError::WM_ERROR_NULLPTR;
5470 }
5471 
NotifyWindowWillClose(sptr<Window> window)5472 WMError WindowSessionImpl::NotifyWindowWillClose(sptr<Window> window)
5473 {
5474     std::lock_guard<std::recursive_mutex> lockListener(windowWillCloseListenersMutex_);
5475     const auto& windowWillCloseListeners = GetListeners<IWindowWillCloseListener>();
5476     auto res = WMError::WM_ERROR_NULLPTR;
5477     for (const auto& listener : windowWillCloseListeners) {
5478         if (listener != nullptr) {
5479             listener->OnWindowWillClose(window);
5480             res = WMError::WM_OK;
5481         }
5482     }
5483     return res;
5484 }
5485 
NotifySwitchFreeMultiWindow(bool enable)5486 void WindowSessionImpl::NotifySwitchFreeMultiWindow(bool enable)
5487 {
5488     std::lock_guard<std::mutex> lockListener(switchFreeMultiWindowListenerMutex_);
5489     auto switchFreeMultiWindowListeners = GetListeners<ISwitchFreeMultiWindowListener>();
5490     for (auto& listener : switchFreeMultiWindowListeners) {
5491         if (listener != nullptr) {
5492             listener->OnSwitchFreeMultiWindow(enable);
5493         }
5494     }
5495 }
5496 
RegisterAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener> & listener)5497 WMError WindowSessionImpl::RegisterAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener>& listener)
5498 {
5499     auto persistentId = GetPersistentId();
5500     TLOGI(WmsLogTag::WMS_IMMS, "win %{public}d", persistentId);
5501     if (listener == nullptr) {
5502         TLOGE(WmsLogTag::WMS_IMMS, "listener is null");
5503         return WMError::WM_ERROR_NULLPTR;
5504     }
5505 
5506     WMError ret = WMError::WM_OK;
5507     bool isUpdate = false;
5508     {
5509         std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
5510         ret = RegisterListener(avoidAreaChangeListeners_[persistentId], listener);
5511         if (ret != WMError::WM_OK) {
5512             return ret;
5513         }
5514         if (avoidAreaChangeListeners_[persistentId].size() == 1) {
5515             isUpdate = true;
5516         }
5517     }
5518     if (isUpdate) {
5519         ret = SingletonContainer::Get<WindowAdapter>().UpdateSessionAvoidAreaListener(persistentId, true);
5520     }
5521     return ret;
5522 }
5523 
UnregisterAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener> & listener)5524 WMError WindowSessionImpl::UnregisterAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener>& listener)
5525 {
5526     auto persistentId = GetPersistentId();
5527     TLOGI(WmsLogTag::WMS_IMMS, "win %{public}d", persistentId);
5528     if (listener == nullptr) {
5529         WLOGFE("listener is null");
5530         return WMError::WM_ERROR_NULLPTR;
5531     }
5532 
5533     WMError ret = WMError::WM_OK;
5534     bool isUpdate = false;
5535     {
5536         std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
5537         ret = UnregisterListener(avoidAreaChangeListeners_[persistentId], listener);
5538         if (ret != WMError::WM_OK) {
5539             return ret;
5540         }
5541         if (avoidAreaChangeListeners_[persistentId].empty()) {
5542             isUpdate = true;
5543         }
5544     }
5545     if (isUpdate) {
5546         ret = SingletonContainer::Get<WindowAdapter>().UpdateSessionAvoidAreaListener(persistentId, false);
5547     }
5548     return ret;
5549 }
5550 
RegisterExtensionAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener> & listener)5551 WMError WindowSessionImpl::RegisterExtensionAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener>& listener)
5552 {
5553     auto persistentId = GetPersistentId();
5554     WLOGFI("Start, id:%{public}d", persistentId);
5555     std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
5556     return RegisterListener(avoidAreaChangeListeners_[persistentId], listener);
5557 }
5558 
UnregisterExtensionAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener> & listener)5559 WMError WindowSessionImpl::UnregisterExtensionAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener>& listener)
5560 {
5561     auto persistentId = GetPersistentId();
5562     WLOGFI("Start, id:%{public}d", persistentId);
5563     std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
5564     return UnregisterListener(avoidAreaChangeListeners_[persistentId], listener);
5565 }
5566 
5567 template<typename T>
5568 EnableIfSame<T, IAvoidAreaChangedListener,
GetListeners()5569     std::vector<sptr<IAvoidAreaChangedListener>>> WindowSessionImpl::GetListeners()
5570 {
5571     std::vector<sptr<IAvoidAreaChangedListener>> windowChangeListeners;
5572     for (auto& listener : avoidAreaChangeListeners_[GetPersistentId()]) {
5573         windowChangeListeners.push_back(listener);
5574     }
5575     return windowChangeListeners;
5576 }
5577 
NotifyAvoidAreaChange(const sptr<AvoidArea> & avoidArea,AvoidAreaType type)5578 void WindowSessionImpl::NotifyAvoidAreaChange(const sptr<AvoidArea>& avoidArea, AvoidAreaType type)
5579 {
5580     std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
5581     auto avoidAreaChangeListeners = GetListeners<IAvoidAreaChangedListener>();
5582     bool isUIExtensionWithSystemHost =
5583         WindowHelper::IsUIExtensionWindow(GetType()) && WindowHelper::IsSystemWindow(GetRootHostWindowType());
5584     bool isSystemWindow = WindowHelper::IsSystemWindow(GetType());
5585     uint32_t currentApiVersion = GetTargetAPIVersionByApplicationInfo();
5586     AvoidArea newAvoidArea;
5587     // api 18 isolation for UEC with system host window
5588     if ((isUIExtensionWithSystemHost || isSystemWindow) && currentApiVersion < static_cast<uint32_t>(API_VERSION_18)) {
5589         TLOGI(WmsLogTag::WMS_IMMS, "win %{public}d api %{public}u type %{public}d not supported",
5590             GetPersistentId(), currentApiVersion, type);
5591     } else {
5592         newAvoidArea = *avoidArea;
5593         TLOGI(WmsLogTag::WMS_IMMS, "win %{public}d api %{public}u type %{public}d area %{public}s",
5594             GetPersistentId(), currentApiVersion, type, newAvoidArea.ToString().c_str());
5595     }
5596 
5597     for (auto& listener : avoidAreaChangeListeners) {
5598         if (listener != nullptr) {
5599             listener->OnAvoidAreaChanged(newAvoidArea, type);
5600         }
5601     }
5602 }
5603 
NotifyTransferComponentData(const AAFwk::WantParams & wantParams)5604 WSError WindowSessionImpl::NotifyTransferComponentData(const AAFwk::WantParams& wantParams)
5605 {
5606     return WSError::WS_OK;
5607 }
5608 
NotifyTransferComponentDataSync(const AAFwk::WantParams & wantParams,AAFwk::WantParams & reWantParams)5609 WSErrorCode WindowSessionImpl::NotifyTransferComponentDataSync(const AAFwk::WantParams& wantParams,
5610     AAFwk::WantParams& reWantParams)
5611 {
5612     return WSErrorCode::WS_OK;
5613 }
5614 
UpdateAvoidArea(const sptr<AvoidArea> & avoidArea,AvoidAreaType type)5615 WSError WindowSessionImpl::UpdateAvoidArea(const sptr<AvoidArea>& avoidArea, AvoidAreaType type)
5616 {
5617     auto task = [weak = wptr(this), avoidArea, type] {
5618         auto window = weak.promote();
5619         if (!window) {
5620             return;
5621         }
5622         if ((window->lastAvoidAreaMap_.find(type) == window->lastAvoidAreaMap_.end() &&
5623              type != AvoidAreaType::TYPE_CUTOUT) ||
5624             window->lastAvoidAreaMap_[type] != *avoidArea) {
5625             window->lastAvoidAreaMap_[type] = *avoidArea;
5626             window->NotifyAvoidAreaChange(avoidArea, type);
5627             window->UpdateViewportConfig(window->GetRect(), WindowSizeChangeReason::AVOID_AREA_CHANGE);
5628         }
5629     };
5630     handler_->PostTask(std::move(task), __func__);
5631     return WSError::WS_OK;
5632 }
5633 
SetPipActionEvent(const std::string & action,int32_t status)5634 WSError WindowSessionImpl::SetPipActionEvent(const std::string& action, int32_t status)
5635 {
5636     TLOGI(WmsLogTag::WMS_PIP, "action: %{public}s, status: %{public}d", action.c_str(), status);
5637     auto task = [action, status]() {
5638         PictureInPictureManager::DoActionEvent(action, status);
5639     };
5640     handler_->PostTask(task, "WMS_WindowSessionImpl_SetPipActionEvent");
5641     return WSError::WS_OK;
5642 }
5643 
SetPiPControlEvent(WsPiPControlType controlType,WsPiPControlStatus status)5644 WSError WindowSessionImpl::SetPiPControlEvent(WsPiPControlType controlType, WsPiPControlStatus status)
5645 {
5646     TLOGI(WmsLogTag::WMS_PIP, "controlType:%{public}u, enabled:%{public}d", controlType, status);
5647     auto task = [controlType, status]() {
5648         PictureInPictureManager::DoControlEvent(static_cast<PiPControlType>(controlType),
5649             static_cast<PiPControlStatus>(status));
5650     };
5651     handler_->PostTask(task, "WMS_WindowSessionImpl_SetPiPControlEvent");
5652     return WSError::WS_OK;
5653 }
5654 
NotifyPipWindowSizeChange(double width,double height,double scale)5655 WSError WindowSessionImpl::NotifyPipWindowSizeChange(double width, double height, double scale)
5656 {
5657     TLOGI(WmsLogTag::WMS_PIP, "width: %{public}f, height: %{public}f scale: %{public}f", width, height, scale);
5658     auto task = [width, height, scale]() {
5659         PictureInPictureManager::PipSizeChange(width, height, scale);
5660     };
5661     handler_->PostTask(task, "WMS_WindowSessionImpl_NotifyPipWindowSizeChange");
5662     return WSError::WS_OK;
5663 }
5664 
SendFbActionEvent(const std::string & action)5665 WSError WindowSessionImpl::SendFbActionEvent(const std::string& action)
5666 {
5667     TLOGI(WmsLogTag::WMS_SYSTEM, "action: %{public}s", action.c_str());
5668     auto task = [action]() {
5669         FloatingBallManager::DoFbActionEvent(action);
5670     };
5671     handler_->PostTask(task, "WMS_WindowSessionImpl_SendFbActionEvent");
5672     return WSError::WS_OK;
5673 }
5674 
GetFloatingBallWindowId(uint32_t & windowId)5675 WMError WindowSessionImpl::GetFloatingBallWindowId(uint32_t& windowId)
5676 {
5677     if (IsWindowSessionInvalid()) {
5678         return WMError::WM_ERROR_INVALID_WINDOW;
5679     }
5680 
5681     auto hostSession = GetHostSession();
5682     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
5683     WMError ret = hostSession->GetFloatingBallWindowId(windowId);
5684     return ret;
5685 }
5686 
RegisterTouchOutsideListener(const sptr<ITouchOutsideListener> & listener)5687 WMError WindowSessionImpl::RegisterTouchOutsideListener(const sptr<ITouchOutsideListener>& listener)
5688 {
5689     bool isUpdate = false;
5690     WMError ret = WMError::WM_OK;
5691     auto persistentId = GetPersistentId();
5692     TLOGI(WmsLogTag::WMS_EVENT, "name=%{public}s, id=%{public}u",
5693         GetWindowName().c_str(), GetPersistentId());
5694     if (listener == nullptr) {
5695         TLOGE(WmsLogTag::WMS_EVENT, "listener is null");
5696         return WMError::WM_ERROR_NULLPTR;
5697     }
5698 
5699     {
5700         std::lock_guard<std::recursive_mutex> lockListener(touchOutsideListenerMutex_);
5701         ret = RegisterListener(touchOutsideListeners_[persistentId], listener);
5702         if (ret != WMError::WM_OK) {
5703             TLOGE(WmsLogTag::WMS_EVENT, "fail, ret:%{public}u", ret);
5704             return ret;
5705         }
5706         if (touchOutsideListeners_[persistentId].size() == 1) {
5707             isUpdate = true;
5708         }
5709     }
5710     if (isUpdate) {
5711         ret = SingletonContainer::Get<WindowAdapter>().UpdateSessionTouchOutsideListener(persistentId, true);
5712     }
5713     return ret;
5714 }
5715 
UnregisterTouchOutsideListener(const sptr<ITouchOutsideListener> & listener)5716 WMError WindowSessionImpl::UnregisterTouchOutsideListener(const sptr<ITouchOutsideListener>& listener)
5717 {
5718     bool isUpdate = false;
5719     WMError ret = WMError::WM_OK;
5720     auto persistentId = GetPersistentId();
5721     TLOGI(WmsLogTag::WMS_EVENT, "name=%{public}s, id=%{public}u",
5722         GetWindowName().c_str(), GetPersistentId());
5723     if (listener == nullptr) {
5724         TLOGE(WmsLogTag::WMS_EVENT, "listener is null");
5725         return WMError::WM_ERROR_NULLPTR;
5726     }
5727 
5728     {
5729         std::lock_guard<std::recursive_mutex> lockListener(touchOutsideListenerMutex_);
5730         ret = UnregisterListener(touchOutsideListeners_[persistentId], listener);
5731         if (ret != WMError::WM_OK) {
5732             TLOGE(WmsLogTag::WMS_EVENT, "fail, ret:%{public}u", ret);
5733             return ret;
5734         }
5735         if (touchOutsideListeners_[persistentId].empty()) {
5736             isUpdate = true;
5737         }
5738     }
5739     if (isUpdate) {
5740         ret = SingletonContainer::Get<WindowAdapter>().UpdateSessionTouchOutsideListener(persistentId, false);
5741     }
5742     return ret;
5743 }
5744 
5745 template<typename T>
GetListeners()5746 EnableIfSame<T, ITouchOutsideListener, std::vector<sptr<ITouchOutsideListener>>> WindowSessionImpl::GetListeners()
5747 {
5748     std::vector<sptr<ITouchOutsideListener>> windowChangeListeners;
5749     for (auto& listener : touchOutsideListeners_[GetPersistentId()]) {
5750         windowChangeListeners.push_back(listener);
5751     }
5752     return windowChangeListeners;
5753 }
5754 
NotifyTouchOutside()5755 WSError WindowSessionImpl::NotifyTouchOutside()
5756 {
5757     TLOGD(WmsLogTag::WMS_EVENT, "window: name=%{public}s, id=%{public}u",
5758         GetWindowName().c_str(), GetPersistentId());
5759     std::lock_guard<std::recursive_mutex> lockListener(touchOutsideListenerMutex_);
5760     auto touchOutsideListeners = GetListeners<ITouchOutsideListener>();
5761     for (auto& listener : touchOutsideListeners) {
5762         if (listener != nullptr) {
5763             listener->OnTouchOutside();
5764         }
5765     }
5766     return WSError::WS_OK;
5767 }
5768 
RegisterWindowVisibilityChangeListener(const IWindowVisibilityListenerSptr & listener)5769 WMError WindowSessionImpl::RegisterWindowVisibilityChangeListener(const IWindowVisibilityListenerSptr& listener)
5770 {
5771     auto persistentId = GetPersistentId();
5772     WLOGFD("Start, persistentId=%{public}d.", persistentId);
5773     WMError ret = WMError::WM_OK;
5774     bool isFirstRegister = false;
5775     {
5776         std::lock_guard<std::recursive_mutex> lockListener(windowVisibilityChangeListenerMutex_);
5777         ret = RegisterListener(windowVisibilityChangeListeners_[persistentId], listener);
5778         if (ret != WMError::WM_OK) {
5779             return ret;
5780         }
5781         isFirstRegister = windowVisibilityChangeListeners_[persistentId].size() == 1;
5782     }
5783 
5784     if (isFirstRegister) {
5785         ret = SingletonContainer::Get<WindowAdapter>().UpdateSessionWindowVisibilityListener(persistentId, true);
5786     }
5787     return ret;
5788 }
5789 
UnregisterWindowVisibilityChangeListener(const IWindowVisibilityListenerSptr & listener)5790 WMError WindowSessionImpl::UnregisterWindowVisibilityChangeListener(const IWindowVisibilityListenerSptr& listener)
5791 {
5792     auto persistentId = GetPersistentId();
5793     WLOGFD("Start, persistentId=%{public}d.", persistentId);
5794     WMError ret = WMError::WM_OK;
5795     bool isLastUnregister = false;
5796     {
5797         std::lock_guard<std::recursive_mutex> lockListener(windowVisibilityChangeListenerMutex_);
5798         ret = UnregisterListener(windowVisibilityChangeListeners_[persistentId], listener);
5799         if (ret != WMError::WM_OK) {
5800             return ret;
5801         }
5802         isLastUnregister = windowVisibilityChangeListeners_[persistentId].empty();
5803     }
5804 
5805     if (isLastUnregister) {
5806         ret = SingletonContainer::Get<WindowAdapter>().UpdateSessionWindowVisibilityListener(persistentId, false);
5807     }
5808     return ret;
5809 }
5810 
RegisterDisplayIdChangeListener(const IDisplayIdChangeListenerSptr & listener)5811 WMError WindowSessionImpl::RegisterDisplayIdChangeListener(const IDisplayIdChangeListenerSptr& listener)
5812 {
5813     TLOGD(WmsLogTag::WMS_ATTRIBUTE, "name=%{public}s, id=%{public}u", GetWindowName().c_str(), GetPersistentId());
5814     std::lock_guard<std::mutex> lockListener(displayIdChangeListenerMutex_);
5815     return RegisterListener(displayIdChangeListeners_[GetPersistentId()], listener);
5816 }
5817 
UnregisterDisplayIdChangeListener(const IDisplayIdChangeListenerSptr & listener)5818 WMError WindowSessionImpl::UnregisterDisplayIdChangeListener(const IDisplayIdChangeListenerSptr& listener)
5819 {
5820     TLOGD(WmsLogTag::WMS_ATTRIBUTE, "name=%{public}s, id=%{public}u", GetWindowName().c_str(), GetPersistentId());
5821     std::lock_guard<std::mutex> lockListener(displayIdChangeListenerMutex_);
5822     return UnregisterListener(displayIdChangeListeners_[GetPersistentId()], listener);
5823 }
5824 
RegisterSystemDensityChangeListener(const ISystemDensityChangeListenerSptr & listener)5825 WMError WindowSessionImpl::RegisterSystemDensityChangeListener(const ISystemDensityChangeListenerSptr& listener)
5826 {
5827     TLOGD(WmsLogTag::WMS_ATTRIBUTE, "name=%{public}s, id=%{public}d", GetWindowName().c_str(), GetPersistentId());
5828     std::lock_guard<std::mutex> lockListener(systemDensityChangeListenerMutex_);
5829     return RegisterListener(systemDensityChangeListeners_[GetPersistentId()], listener);
5830 }
5831 
UnregisterSystemDensityChangeListener(const ISystemDensityChangeListenerSptr & listener)5832 WMError WindowSessionImpl::UnregisterSystemDensityChangeListener(const ISystemDensityChangeListenerSptr& listener)
5833 {
5834     TLOGD(WmsLogTag::WMS_ATTRIBUTE, "name=%{public}s, id=%{public}d", GetWindowName().c_str(), GetPersistentId());
5835     std::lock_guard<std::mutex> lockListener(systemDensityChangeListenerMutex_);
5836     return UnregisterListener(systemDensityChangeListeners_[GetPersistentId()], listener);
5837 }
5838 
RegisterAcrossDisplaysChangeListener(const IAcrossDisplaysChangeListenerSptr & listener)5839 WMError WindowSessionImpl::RegisterAcrossDisplaysChangeListener(
5840     const IAcrossDisplaysChangeListenerSptr& listener)
5841 {
5842     if (IsWindowSessionInvalid()) {
5843         return WMError::WM_ERROR_INVALID_WINDOW;
5844     }
5845     auto persistentId = GetPersistentId();
5846     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "winId: %{public}d", persistentId);
5847     if (listener == nullptr) {
5848         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "listener is null");
5849         return WMError::WM_ERROR_NULLPTR;
5850     }
5851 
5852     WMError ret = WMError::WM_OK;
5853     bool isUpdate = false;
5854     {
5855         std::lock_guard<std::recursive_mutex> lockListener(acrossDisplaysChangeListenerMutex_);
5856         ret = RegisterListener(acrossDisplaysChangeListeners_[persistentId], listener);
5857         if (ret != WMError::WM_OK) {
5858             return ret;
5859         }
5860         if (acrossDisplaysChangeListeners_[persistentId].size() == 1) {
5861             isUpdate = true;
5862         }
5863     }
5864     auto hostSession = GetHostSession();
5865     if (isUpdate && hostSession != nullptr) {
5866         ret = hostSession->UpdateAcrossDisplaysChangeRegistered(true);
5867     }
5868     if (ret != WMError::WM_OK) {
5869         std::lock_guard<std::recursive_mutex> lockListener(acrossDisplaysChangeListenerMutex_);
5870         UnregisterListener(acrossDisplaysChangeListeners_[persistentId], listener);
5871     }
5872     return ret;
5873 }
5874 
UnRegisterAcrossDisplaysChangeListener(const IAcrossDisplaysChangeListenerSptr & listener)5875 WMError WindowSessionImpl::UnRegisterAcrossDisplaysChangeListener(
5876     const IAcrossDisplaysChangeListenerSptr& listener)
5877 {
5878     if (IsWindowSessionInvalid()) {
5879         return WMError::WM_ERROR_INVALID_WINDOW;
5880     }
5881     auto persistentId = GetPersistentId();
5882     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "winId: %{public}d", persistentId);
5883     if (listener == nullptr) {
5884         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "listener is null");
5885         return WMError::WM_ERROR_NULLPTR;
5886     }
5887 
5888     WMError ret = WMError::WM_OK;
5889     bool isUpdate = false;
5890     {
5891         std::lock_guard<std::recursive_mutex> lockListener(acrossDisplaysChangeListenerMutex_);
5892         ret = UnregisterListener(acrossDisplaysChangeListeners_[persistentId], listener);
5893         if (ret != WMError::WM_OK) {
5894             return ret;
5895         }
5896         if (acrossDisplaysChangeListeners_[persistentId].empty()) {
5897             isUpdate = true;
5898         }
5899     }
5900     auto hostSession = GetHostSession();
5901     if (isUpdate && hostSession != nullptr) {
5902         ret = hostSession->UpdateAcrossDisplaysChangeRegistered(false);
5903     }
5904     if (ret != WMError::WM_OK) {
5905         std::lock_guard<std::recursive_mutex> lockListener(acrossDisplaysChangeListenerMutex_);
5906         RegisterListener(acrossDisplaysChangeListeners_[persistentId], listener);
5907     }
5908     return ret;
5909 }
5910 
RegisterWindowNoInteractionListener(const IWindowNoInteractionListenerSptr & listener)5911 WMError WindowSessionImpl::RegisterWindowNoInteractionListener(const IWindowNoInteractionListenerSptr& listener)
5912 {
5913     WLOGFD("in");
5914     std::lock_guard<std::recursive_mutex> lockListener(windowNoInteractionListenerMutex_);
5915     WMError ret = RegisterListener(windowNoInteractionListeners_[GetPersistentId()], listener);
5916     if (ret != WMError::WM_OK) {
5917         WLOGFE("register failed.");
5918     } else {
5919         SubmitNoInteractionMonitorTask(this->lastInteractionEventId_.load(), listener);
5920     }
5921     return ret;
5922 }
5923 
UnregisterWindowNoInteractionListener(const IWindowNoInteractionListenerSptr & listener)5924 WMError WindowSessionImpl::UnregisterWindowNoInteractionListener(const IWindowNoInteractionListenerSptr& listener)
5925 {
5926     WLOGFD("in");
5927     std::lock_guard<std::recursive_mutex> lockListener(windowNoInteractionListenerMutex_);
5928     WMError ret = UnregisterListener(windowNoInteractionListeners_[GetPersistentId()], listener);
5929     if (windowNoInteractionListeners_[GetPersistentId()].empty()) {
5930         lastInteractionEventId_.store(-1);
5931     }
5932     return ret;
5933 }
5934 
5935 template<typename T>
GetListeners()5936 EnableIfSame<T, IWindowRotationChangeListener, std::vector<sptr<IWindowRotationChangeListener>>> WindowSessionImpl::GetListeners()
5937 {
5938     std::vector<sptr<IWindowRotationChangeListener>> windowRotationChangeListener;
5939     for (auto& listener : windowRotationChangeListeners_[GetPersistentId()]) {
5940         windowRotationChangeListener.push_back(listener);
5941     }
5942     return windowRotationChangeListener;
5943 }
5944 
RegisterWindowRotationChangeListener(const sptr<IWindowRotationChangeListener> & listener)5945 WMError WindowSessionImpl::RegisterWindowRotationChangeListener(const sptr<IWindowRotationChangeListener>& listener)
5946 {
5947     if (listener == nullptr) {
5948         TLOGE(WmsLogTag::WMS_ROTATION, "listener is null");
5949         return WMError::WM_ERROR_NULLPTR;
5950     }
5951     auto persistentId = GetPersistentId();
5952     WMError ret = WMError::WM_OK;
5953     {
5954         std::lock_guard<std::mutex> lockListener(windowRotationChangeListenerMutex_);
5955         ret = RegisterListener(windowRotationChangeListeners_[persistentId], listener);
5956     }
5957     auto hostSession = GetHostSession();
5958     if (hostSession != nullptr && ret == WMError::WM_OK) {
5959         hostSession->UpdateRotationChangeRegistered(persistentId, true);
5960     }
5961     return ret;
5962 }
5963 
UnregisterWindowRotationChangeListener(const sptr<IWindowRotationChangeListener> & listener)5964 WMError WindowSessionImpl::UnregisterWindowRotationChangeListener(const sptr<IWindowRotationChangeListener>& listener)
5965 {
5966     WMError ret = WMError::WM_OK;
5967     auto persistentId = GetPersistentId();
5968     bool windowRotationChangeListenerEmpty = false;
5969     {
5970         std::lock_guard<std::mutex> lockListener(windowRotationChangeListenerMutex_);
5971         ret = UnregisterListener(windowRotationChangeListeners_[persistentId], listener);
5972         windowRotationChangeListenerEmpty = windowRotationChangeListeners_.count(persistentId) == 0 ||
5973                                             windowRotationChangeListeners_[persistentId].empty();
5974     }
5975     auto hostSession = GetHostSession();
5976     if (hostSession != nullptr && windowRotationChangeListenerEmpty) {
5977         hostSession->UpdateRotationChangeRegistered(persistentId, false);
5978     }
5979     return ret;
5980 }
5981 
5982 template<typename T>
GetListeners()5983 EnableIfSame<T, IWindowVisibilityChangedListener, std::vector<IWindowVisibilityListenerSptr>> WindowSessionImpl::GetListeners()
5984 {
5985     std::vector<IWindowVisibilityListenerSptr> windowVisibilityChangeListeners;
5986     for (auto& listener : windowVisibilityChangeListeners_[GetPersistentId()]) {
5987         windowVisibilityChangeListeners.push_back(listener);
5988     }
5989     return windowVisibilityChangeListeners;
5990 }
5991 
5992 template<typename T>
5993 EnableIfSame<T, IDisplayIdChangeListener,
GetListeners()5994     std::vector<IDisplayIdChangeListenerSptr>> WindowSessionImpl::GetListeners()
5995 {
5996     return displayIdChangeListeners_[GetPersistentId()];
5997 }
5998 
5999 template<typename T>
6000 EnableIfSame<T, ISystemDensityChangeListener,
GetListeners()6001     std::vector<ISystemDensityChangeListenerSptr>> WindowSessionImpl::GetListeners()
6002 {
6003     return systemDensityChangeListeners_[GetPersistentId()];
6004 }
6005 
6006 template<typename T>
GetListeners()6007 EnableIfSame<T, IAcrossDisplaysChangeListener, std::vector<IAcrossDisplaysChangeListenerSptr>> WindowSessionImpl::GetListeners()
6008 {
6009     return acrossDisplaysChangeListeners_[GetPersistentId()];
6010 }
6011 
6012 template<typename T>
GetListeners()6013 EnableIfSame<T, IWindowNoInteractionListener, std::vector<IWindowNoInteractionListenerSptr>> WindowSessionImpl::GetListeners()
6014 {
6015     std::vector<IWindowNoInteractionListenerSptr> noInteractionListeners;
6016     for (auto& listener : windowNoInteractionListeners_[GetPersistentId()]) {
6017         noInteractionListeners.push_back(listener);
6018     }
6019     return noInteractionListeners;
6020 }
6021 
NotifyDisplayIdChange(DisplayId displayId)6022 WSError WindowSessionImpl::NotifyDisplayIdChange(DisplayId displayId)
6023 {
6024     TLOGD(WmsLogTag::WMS_ATTRIBUTE, "id=%{public}u, displayId=%{public}" PRIu64, GetPersistentId(), displayId);
6025     std::lock_guard<std::mutex> lock(displayIdChangeListenerMutex_);
6026     auto displayIdChangeListeners = GetListeners<IDisplayIdChangeListener>();
6027     for (auto& listener : displayIdChangeListeners) {
6028         if (listener != nullptr) {
6029             listener->OnDisplayIdChanged(displayId);
6030         }
6031     }
6032     return WSError::WS_OK;
6033 }
6034 
NotifyWatchGestureConsumeResult(int32_t keyCode,bool isConsumed)6035 WMError WindowSessionImpl::NotifyWatchGestureConsumeResult(int32_t keyCode, bool isConsumed)
6036 {
6037     TLOGD(WmsLogTag::WMS_EVENT, "keyCode:%{public}d, isConsumed:%{public}d", keyCode, isConsumed);
6038     if (IsWindowSessionInvalid()) {
6039         return WMError::WM_ERROR_INVALID_WINDOW;
6040     }
6041     return SingletonContainer::Get<WindowAdapter>().NotifyWatchGestureConsumeResult(keyCode, isConsumed);
6042 }
6043 
GetWatchGestureConsumed() const6044 bool WindowSessionImpl::GetWatchGestureConsumed() const
6045 {
6046     return isWatchGestureConsumed_;
6047 }
6048 
SetWatchGestureConsumed(bool isWatchGestureConsumed)6049 void WindowSessionImpl::SetWatchGestureConsumed(bool isWatchGestureConsumed)
6050 {
6051     TLOGD(WmsLogTag::WMS_EVENT, "wid:%{public}d, isWatchGestureConsumed:%{public}d",
6052         GetPersistentId(), isWatchGestureConsumed);
6053     isWatchGestureConsumed_ = isWatchGestureConsumed;
6054 }
6055 
NotifySystemDensityChange(float density)6056 WSError WindowSessionImpl::NotifySystemDensityChange(float density)
6057 {
6058     std::lock_guard<std::mutex> lock(systemDensityChangeListenerMutex_);
6059     const auto& systemDensityChangeListeners = GetListeners<ISystemDensityChangeListener>();
6060     for (const auto& listener : systemDensityChangeListeners) {
6061         if (listener != nullptr) {
6062             listener->OnSystemDensityChanged(density);
6063         }
6064     }
6065     return WSError::WS_OK;
6066 }
6067 
SetWindowDefaultDensityEnabled(bool enabled)6068 WMError WindowSessionImpl::SetWindowDefaultDensityEnabled(bool enabled)
6069 {
6070     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "WinId: %{public}d, enabled: %{public}u", GetPersistentId(), enabled);
6071     if (!SessionPermission::IsSystemCalling()) {
6072         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "WinId: %{public}d permission denied!", GetPersistentId());
6073         return WMError::WM_ERROR_NOT_SYSTEM_APP;
6074     }
6075     if (IsWindowSessionInvalid()) {
6076         return WMError::WM_ERROR_INVALID_WINDOW;
6077     }
6078     SetDefaultDensityEnabledValue(enabled);
6079     UpdateDensity();
6080     return WMError::WM_OK;
6081 }
6082 
SetDefaultDensityEnabledValue(bool enabled)6083 void WindowSessionImpl::SetDefaultDensityEnabledValue(bool enabled)
6084 {
6085     isDefaultDensityEnabled_.store(enabled);
6086 }
6087 
NotifyWindowVisibility(bool isVisible)6088 WSError WindowSessionImpl::NotifyWindowVisibility(bool isVisible)
6089 {
6090     TLOGD(WmsLogTag::WMS_ATTRIBUTE, "window: name=%{public}s, id=%{public}u, isVisible=%{public}d",
6091         GetWindowName().c_str(), GetPersistentId(), isVisible);
6092     std::lock_guard<std::recursive_mutex> lockListener(windowVisibilityChangeListenerMutex_);
6093     auto windowVisibilityListeners = GetListeners<IWindowVisibilityChangedListener>();
6094     for (auto& listener : windowVisibilityListeners) {
6095         if (listener != nullptr) {
6096             listener->OnWindowVisibilityChangedCallback(isVisible);
6097         }
6098     }
6099     return WSError::WS_OK;
6100 }
6101 
NotifyNoInteractionTimeout(const IWindowNoInteractionListenerSptr & listener)6102 WSError WindowSessionImpl::NotifyNoInteractionTimeout(const IWindowNoInteractionListenerSptr& listener)
6103 {
6104     if (listener == nullptr) {
6105         WLOGFE("invalid listener");
6106         return WSError::WS_ERROR_NULLPTR;
6107     }
6108     WLOGFD("name=%{public}s, id=%{public}u, timeout=%{public}" PRId64,
6109         GetWindowName().c_str(), GetPersistentId(), listener->GetTimeout());
6110 
6111     listener->OnWindowNoInteractionCallback();
6112     return WSError::WS_OK;
6113 }
6114 
NotifyPointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)6115 void WindowSessionImpl::NotifyPointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
6116 {
6117     if (!pointerEvent) {
6118         TLOGE(WmsLogTag::WMS_INPUT_KEY_FLOW, "Pointer event is nullptr");
6119         return;
6120     }
6121 
6122     std::shared_ptr<IInputEventConsumer> inputEventConsumer;
6123     {
6124         std::lock_guard<std::recursive_mutex> lock(mutex_);
6125         inputEventConsumer = inputEventConsumer_;
6126     }
6127     if (inputEventConsumer != nullptr) {
6128         WLOGFD("Transfer pointer event to inputEventConsumer");
6129         if (pointerEvent->GetPointerAction() != MMI::PointerEvent::POINTER_ACTION_MOVE) {
6130             TLOGI(WmsLogTag::WMS_INPUT_KEY_FLOW,
6131                 "Transfer to inputEventConsumer InputTracking id:%{public}d",
6132                 pointerEvent->GetId());
6133         }
6134         if (!(inputEventConsumer->OnInputEvent(pointerEvent))) {
6135             pointerEvent->MarkProcessed();
6136         }
6137         return;
6138     }
6139     if (FilterPointerEvent(pointerEvent)) {
6140         return;
6141     }
6142     if (auto uiContent = GetUIContentSharedPtr()) {
6143         if (pointerEvent->GetPointerAction() != MMI::PointerEvent::POINTER_ACTION_MOVE) {
6144             TLOGD(WmsLogTag::WMS_EVENT, "eid:%{public}d", pointerEvent->GetId());
6145         }
6146         if (IsWindowDelayRaiseEnabled()) {
6147             if (pointerEvent->GetPointerAction() == MMI::PointerEvent::POINTER_ACTION_DOWN ||
6148                 pointerEvent->GetPointerAction() == MMI::PointerEvent::POINTER_ACTION_UP ||
6149                 pointerEvent->GetPointerAction() == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN ||
6150                 pointerEvent->GetPointerAction() == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP) {
6151                 TLOGI(WmsLogTag::WMS_EVENT, "Delay,id:%{public}d", pointerEvent->GetId());
6152             }
6153             pointerEvent->MarkProcessed();
6154             return;
6155         }
6156         TLOGD(WmsLogTag::WMS_EVENT, "Start to process pointerEvent, id: %{public}d", pointerEvent->GetId());
6157         if (!uiContent->ProcessPointerEvent(pointerEvent)) {
6158             TLOGI(WmsLogTag::WMS_INPUT_KEY_FLOW, "UI content does not consume");
6159             pointerEvent->MarkProcessed();
6160         }
6161     } else {
6162         if (pointerEvent->GetPointerAction() != MMI::PointerEvent::POINTER_ACTION_MOVE) {
6163             TLOGW(WmsLogTag::WMS_INPUT_KEY_FLOW, "not consume, wid:%{public}u", GetWindowId());
6164         }
6165         pointerEvent->MarkProcessed();
6166     }
6167 }
6168 
InjectTouchEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)6169 WMError WindowSessionImpl::InjectTouchEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
6170 {
6171     if (!pointerEvent) {
6172         TLOGE(WmsLogTag::WMS_INPUT_KEY_FLOW, "Pointer event is nullptr");
6173         return WMError::WM_ERROR_INVALID_PARAM;
6174     }
6175     if (pointerEvent->GetPointerAction() != MMI::PointerEvent::POINTER_ACTION_MOVE) {
6176         TLOGI(WmsLogTag::WMS_EVENT, "eid:%{public}d, ac:%{public}d", pointerEvent->GetId(),
6177             pointerEvent->GetPointerAction());
6178     }
6179     if (auto uiContent = GetUIContentSharedPtr()) {
6180         TLOGD(WmsLogTag::WMS_EVENT, "Start to process pointerEvent, id: %{public}d", pointerEvent->GetId());
6181         if (!uiContent->ProcessPointerEvent(pointerEvent)) {
6182             TLOGI(WmsLogTag::WMS_INPUT_KEY_FLOW, "UI content does not consume");
6183             pointerEvent->MarkProcessed();
6184         }
6185     } else {
6186         if (pointerEvent->GetPointerAction() != MMI::PointerEvent::POINTER_ACTION_MOVE) {
6187             TLOGW(WmsLogTag::WMS_INPUT_KEY_FLOW, "pointerEvent not consumed, windowId:%{public}u", GetWindowId());
6188         }
6189         pointerEvent->MarkProcessed();
6190         return WMError::WM_ERROR_SYSTEM_ABNORMALLY;
6191     }
6192     return WMError::WM_OK;
6193 }
6194 
SetKeyEventFilter(KeyEventFilterFunc filter)6195 WMError WindowSessionImpl::SetKeyEventFilter(KeyEventFilterFunc filter)
6196 {
6197     std::unique_lock<std::mutex> lock(keyEventFilterMutex_);
6198     keyEventFilter_ = std::move(filter);
6199     return WMError::WM_OK;
6200 }
6201 
ClearKeyEventFilter()6202 WMError WindowSessionImpl::ClearKeyEventFilter()
6203 {
6204     std::unique_lock<std::mutex> lock(keyEventFilterMutex_);
6205     keyEventFilter_ = nullptr;
6206     return WMError::WM_OK;
6207 }
6208 
SetMouseEventFilter(MouseEventFilterFunc filter)6209 WMError WindowSessionImpl::SetMouseEventFilter(MouseEventFilterFunc filter)
6210 {
6211     std::unique_lock<std::mutex> lock(mouseEventFilterMutex_);
6212     mouseEventFilter_ = std::move(filter);
6213     return WMError::WM_OK;
6214 }
6215 
ClearMouseEventFilter()6216 WMError WindowSessionImpl::ClearMouseEventFilter()
6217 {
6218     std::unique_lock<std::mutex> lock(mouseEventFilterMutex_);
6219     mouseEventFilter_ = nullptr;
6220     return WMError::WM_OK;
6221 }
6222 
SetTouchEventFilter(TouchEventFilterFunc filter)6223 WMError WindowSessionImpl::SetTouchEventFilter(TouchEventFilterFunc filter)
6224 {
6225     std::unique_lock<std::mutex> lock(touchEventFilterMutex_);
6226     touchEventFilter_ = std::move(filter);
6227     return WMError::WM_OK;
6228 }
6229 
ClearTouchEventFilter()6230 WMError WindowSessionImpl::ClearTouchEventFilter()
6231 {
6232     std::unique_lock<std::mutex> lock(touchEventFilterMutex_);
6233     touchEventFilter_ = nullptr;
6234     return WMError::WM_OK;
6235 }
6236 
FilterKeyEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent)6237 bool WindowSessionImpl::FilterKeyEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
6238 {
6239     std::lock_guard<std::mutex> lock(keyEventFilterMutex_);
6240     if (keyEventFilter_ != nullptr) {
6241         bool isFilter = keyEventFilter_(*keyEvent.get());
6242         TLOGE(WmsLogTag::WMS_SYSTEM, "keyCode:%{public}d isFilter:%{public}d",
6243             keyEvent->GetKeyCode(), isFilter);
6244         if (isFilter) {
6245             keyEvent->MarkProcessed();
6246             return true;
6247         }
6248     }
6249     return false;
6250 }
6251 
NotifyConsumeResultToFloatWindow(const std::shared_ptr<MMI::KeyEvent> & keyEvent,bool isConsumed)6252 void WindowSessionImpl::NotifyConsumeResultToFloatWindow
6253     (const std::shared_ptr<MMI::KeyEvent>& keyEvent, bool isConsumed)
6254 {
6255     if ((keyEvent->GetKeyCode() == MMI::KeyEvent::KEYCODE_TAB ||
6256          keyEvent->GetKeyCode() == MMI::KeyEvent::KEYCODE_ENTER) && !GetWatchGestureConsumed() &&
6257         keyEvent->GetKeyAction() == MMI::KeyEvent::KEY_ACTION_DOWN) {
6258         TLOGD(WmsLogTag::WMS_EVENT, "wid:%{public}d, keyCode:%{public}d, isConsumed:%{public}d",
6259             GetWindowId(), keyEvent->GetKeyCode(), isConsumed);
6260         NotifyWatchGestureConsumeResult(keyEvent->GetKeyCode(), isConsumed);
6261     }
6262 }
6263 
FilterPointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)6264 bool WindowSessionImpl::FilterPointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
6265 {
6266     bool isFiltered = false;
6267     auto sourceType = pointerEvent->GetSourceType();
6268     auto action = pointerEvent->GetPointerAction();
6269     if (sourceType == OHOS::MMI::PointerEvent::SOURCE_TYPE_TOUCHSCREEN) {
6270         std::lock_guard<std::mutex> lock(touchEventFilterMutex_);
6271         if (touchEventFilter_ == nullptr) {
6272             TLOGD(WmsLogTag::WMS_INPUT_KEY_FLOW, "touch event filter null");
6273             return false;
6274         }
6275         isFiltered = touchEventFilter_(*pointerEvent.get());
6276     } else if (sourceType == OHOS::MMI::PointerEvent::SOURCE_TYPE_MOUSE &&
6277                (action != OHOS::MMI::PointerEvent::POINTER_ACTION_AXIS_BEGIN &&
6278                 action != OHOS::MMI::PointerEvent::POINTER_ACTION_AXIS_UPDATE &&
6279                 action != OHOS::MMI::PointerEvent::POINTER_ACTION_AXIS_END)) {
6280         std::lock_guard<std::mutex> lock(mouseEventFilterMutex_);
6281         if (mouseEventFilter_ == nullptr) {
6282             TLOGD(WmsLogTag::WMS_INPUT_KEY_FLOW, "mouse event filter null");
6283             return false;
6284         }
6285         isFiltered = mouseEventFilter_(*pointerEvent.get());
6286     }
6287     if (isFiltered) {
6288         if (action == MMI::PointerEvent::POINTER_ACTION_DOWN ||
6289             action == MMI::PointerEvent::POINTER_ACTION_UP ||
6290             action == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN ||
6291             action == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP) {
6292             TLOGI(WmsLogTag::WMS_EVENT, "id:%{public}d", pointerEvent->GetId());
6293         }
6294         pointerEvent->MarkProcessed();
6295     }
6296     TLOGD(WmsLogTag::WMS_INPUT_KEY_FLOW, "event consumed:%{public}d", isFiltered);
6297     return isFiltered;
6298 }
6299 
HandleEscKeyEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent,bool & isConsumed)6300 WMError WindowSessionImpl::HandleEscKeyEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent, bool& isConsumed)
6301 {
6302     if (keyEvent == nullptr) {
6303         TLOGE(WmsLogTag::WMS_EVENT, "keyevent is nullptr");
6304         return WMError::WM_ERROR_NULLPTR;
6305     }
6306 
6307     if (!isConsumed && keyEvent->GetKeyCode() == MMI::KeyEvent::KEYCODE_ESCAPE &&
6308         IsPcOrPadFreeMultiWindowMode() &&
6309         property_->GetWindowMode() == WindowMode::WINDOW_MODE_FULLSCREEN &&
6310         GetImmersiveModeEnabledState() &&
6311         keyEvent->GetKeyAction() == MMI::KeyEvent::KEY_ACTION_DOWN && !escKeyEventTriggered_) {
6312         if (Recover() == WMError::WM_OK) {
6313             isConsumed = true;
6314             keyEvent->MarkProcessed();
6315         }
6316         TLOGI(WmsLogTag::WMS_EVENT, "recover from fullscreen, consumed: %{public}d", isConsumed);
6317     }
6318 
6319     if (!isConsumed && !escKeyEventTriggered_ && escKeyHasDown_) {
6320         bool escToBackFlag = keyEvent->HasFlag(MMI::InputEvent::EVENT_FLAG_KEYBOARD_ESCAPE);
6321         if (!escToBackFlag) {
6322             TLOGE(WmsLogTag::WMS_EVENT, "ESC no flag");
6323             return WMError::WM_DO_NOTHING;
6324         }
6325 
6326         TLOGI(WmsLogTag::WMS_EVENT, "normal mode, handlebackevent");
6327         HandleBackEvent();
6328     }
6329 
6330     return WMError::WM_OK;
6331 }
6332 
DispatchKeyEventCallback(const std::shared_ptr<MMI::KeyEvent> & keyEvent,bool & isConsumed)6333 void WindowSessionImpl::DispatchKeyEventCallback(const std::shared_ptr<MMI::KeyEvent>& keyEvent, bool& isConsumed)
6334 {
6335     std::shared_ptr<IInputEventConsumer> inputEventConsumer;
6336     {
6337         std::lock_guard<std::recursive_mutex> lock(mutex_);
6338         inputEventConsumer = inputEventConsumer_;
6339     }
6340     int32_t keyCode = keyEvent->GetKeyCode();
6341     int32_t keyAction = keyEvent->GetKeyAction();
6342     if (keyCode == MMI::KeyEvent::KEYCODE_BACK && keyAction == MMI::KeyEvent::KEY_ACTION_UP) {
6343         TLOGI(WmsLogTag::DEFAULT, "In");
6344         if (inputEventConsumer != nullptr) {
6345             WLOGFD("Transfer key event to inputEventConsumer");
6346             if (inputEventConsumer->OnInputEvent(keyEvent)) {
6347                 return;
6348             }
6349             PerformBack();
6350             keyEvent->MarkProcessed();
6351             return;
6352         }
6353         HandleBackEvent();
6354         keyEvent->MarkProcessed();
6355         return;
6356     }
6357 
6358     if (inputEventConsumer != nullptr) {
6359         WLOGD("Transfer key event to inputEventConsumer");
6360         if (!(inputEventConsumer->OnInputEvent(keyEvent))) {
6361             keyEvent->MarkProcessed();
6362         }
6363         return;
6364     }
6365 
6366     if (auto uiContent = GetUIContentSharedPtr()) {
6367         if (FilterKeyEvent(keyEvent)) return;
6368         isConsumed = uiContent->ProcessKeyEvent(keyEvent);
6369         TLOGI(WmsLogTag::WMS_EVENT, "id: %{public}d, consumed: %{public}d,"
6370             "escTrigger: %{public}d, escDown: %{public}d",
6371             keyEvent->GetId(), isConsumed, escKeyEventTriggered_, escKeyHasDown_);
6372         HandleEscKeyEvent(keyEvent, isConsumed);
6373         NotifyConsumeResultToFloatWindow(keyEvent, isConsumed);
6374         if (!isConsumed) {
6375             keyEvent->MarkProcessed();
6376         }
6377         if (keyEvent->GetKeyCode() == MMI::KeyEvent::KEYCODE_ESCAPE) {
6378             escKeyHasDown_ = (keyAction == MMI::KeyEvent::KEY_ACTION_DOWN);
6379             escKeyEventTriggered_ = isConsumed;
6380         }
6381     }
6382 }
6383 
HandleBackEvent()6384 WSError WindowSessionImpl::HandleBackEvent()
6385 {
6386     TLOGI(WmsLogTag::WMS_EVENT, "in");
6387     bool isConsumed = false;
6388     std::shared_ptr<IInputEventConsumer> inputEventConsumer;
6389     {
6390         std::lock_guard<std::recursive_mutex> lock(mutex_);
6391         inputEventConsumer = inputEventConsumer_;
6392     }
6393     if (inputEventConsumer != nullptr) {
6394         WLOGFD("Transfer back event to inputEventConsumer");
6395         std::shared_ptr<MMI::KeyEvent> backKeyEvent = MMI::KeyEvent::Create();
6396         if (backKeyEvent == nullptr) {
6397             WLOGFE("backKeyEvent is null");
6398             return WSError::WS_ERROR_NULLPTR;
6399         }
6400         backKeyEvent->SetKeyCode(MMI::KeyEvent::KEYCODE_BACK);
6401         backKeyEvent->SetKeyAction(MMI::KeyEvent::KEY_ACTION_UP);
6402         isConsumed = inputEventConsumer->OnInputEvent(backKeyEvent);
6403     } else {
6404         if (auto uiContent = GetUIContentSharedPtr()) {
6405             WLOGFD("Transfer back event to uiContent");
6406             isConsumed = uiContent->ProcessBackPressed();
6407         } else {
6408             WLOGFE("There is no back event consumer");
6409         }
6410     }
6411 
6412     if (isConsumed) {
6413         WLOGD("Back key event is consumed");
6414         return WSError::WS_OK;
6415     }
6416     WLOGFD("report Back");
6417     SingletonContainer::Get<WindowInfoReporter>().ReportBackButtonInfoImmediately();
6418     if (handler_ == nullptr) {
6419         WLOGFE("HandleBackEvent handler_ is nullptr!");
6420         return WSError::WS_ERROR_INVALID_PARAM;
6421     }
6422     // notify back event to host session
6423     wptr<WindowSessionImpl> weak = this;
6424     auto task = [weak]() {
6425         auto weakSession = weak.promote();
6426         if (weakSession == nullptr) {
6427             WLOGFE("HandleBackEvent session wptr is nullptr");
6428             return;
6429         }
6430         weakSession->PerformBack();
6431     };
6432     if (!handler_->PostTask(task, "wms:PerformBack")) {
6433         WLOGFE("Failed to post PerformBack");
6434         return WSError::WS_ERROR_INVALID_OPERATION;
6435     }
6436     return WSError::WS_OK;
6437 }
6438 
NotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent,bool & isConsumed,bool notifyInputMethod)6439 void WindowSessionImpl::NotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent, bool& isConsumed,
6440     bool notifyInputMethod)
6441 {
6442     if (keyEvent == nullptr) {
6443         WLOGFE("keyEvent is nullptr");
6444         return;
6445     }
6446 
6447 #ifdef IMF_ENABLE
6448     bool isKeyboardEvent = IsKeyboardEvent(keyEvent);
6449     if (isKeyboardEvent && notifyInputMethod) {
6450         WLOGD("Async dispatch keyEvent to input method");
6451         auto callback = [weakThis = wptr(this)] (std::shared_ptr<MMI::KeyEvent>& keyEvent, bool consumed) {
6452             if (keyEvent == nullptr) {
6453                 WLOGFW("keyEvent is null, consumed:%{public}" PRId32, consumed);
6454                 return;
6455             }
6456 
6457             if (consumed) {
6458                 WLOGD("Input method has processed key event, id:%{public}" PRId32, keyEvent->GetId());
6459                 return;
6460             }
6461 
6462             auto promoteThis = weakThis.promote();
6463             if (promoteThis == nullptr) {
6464                 WLOGFW("promoteThis is nullptr");
6465                 keyEvent->MarkProcessed();
6466                 return;
6467             }
6468             bool isConsumed = false;
6469             promoteThis->DispatchKeyEventCallback(keyEvent, isConsumed);
6470         };
6471         auto ret = MiscServices::InputMethodController::GetInstance()->DispatchKeyEvent(
6472             const_cast<std::shared_ptr<MMI::KeyEvent>&>(keyEvent), callback);
6473         if (ret != 0) {
6474             WLOGFE("DispatchKeyEvent failed, ret:%{public}" PRId32 ", id:%{public}" PRId32, ret, keyEvent->GetId());
6475             DispatchKeyEventCallback(keyEvent, isConsumed);
6476         }
6477         return;
6478     }
6479 #endif // IMF_ENABLE
6480     DispatchKeyEventCallback(keyEvent, isConsumed);
6481 }
6482 
IsKeyboardEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent) const6483 bool WindowSessionImpl::IsKeyboardEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent) const
6484 {
6485     int32_t keyCode = keyEvent->GetKeyCode();
6486     bool isKeyFN = (keyCode == MMI::KeyEvent::KEYCODE_FN);
6487     bool isKeyBack = (keyCode == MMI::KeyEvent::KEYCODE_BACK);
6488     bool isKeyboard = (keyCode >= MMI::KeyEvent::KEYCODE_0 && keyCode <= MMI::KeyEvent::KEYCODE_NUMPAD_RIGHT_PAREN);
6489     bool isKeySound = (keyCode == MMI::KeyEvent::KEYCODE_SOUND);
6490     TLOGD(WmsLogTag::WMS_EVENT, "isKeyFN:%{public}d, isKeyboard:%{public}d", isKeyFN, isKeyboard);
6491     return (isKeyFN || isKeyboard || isKeyBack || isKeySound);
6492 }
6493 
RequestVsync(const std::shared_ptr<VsyncCallback> & vsyncCallback)6494 void WindowSessionImpl::RequestVsync(const std::shared_ptr<VsyncCallback>& vsyncCallback)
6495 {
6496     if (vsyncStation_ == nullptr) {
6497         TLOGW(WmsLogTag::WMS_MAIN, "vsyncStation is null");
6498         return;
6499     }
6500     vsyncStation_->RequestVsync(vsyncCallback);
6501 }
6502 
GetVSyncPeriod()6503 int64_t WindowSessionImpl::GetVSyncPeriod()
6504 {
6505     if (vsyncStation_ == nullptr) {
6506         TLOGW(WmsLogTag::WMS_MAIN, "vsyncStation is null");
6507         return 0;
6508     }
6509     return vsyncStation_->GetVSyncPeriod();
6510 }
6511 
FlushFrameRate(uint32_t rate,int32_t animatorExpectedFrameRate,uint32_t rateType)6512 void WindowSessionImpl::FlushFrameRate(uint32_t rate, int32_t animatorExpectedFrameRate, uint32_t rateType)
6513 {
6514     if (vsyncStation_ == nullptr) {
6515         TLOGW(WmsLogTag::WMS_MAIN, "vsyncStation is null");
6516         return;
6517     }
6518     vsyncStation_->FlushFrameRate(GetRSUIContext(), rate, animatorExpectedFrameRate, rateType);
6519 }
6520 
UpdateProperty(WSPropertyChangeAction action)6521 WMError WindowSessionImpl::UpdateProperty(WSPropertyChangeAction action)
6522 {
6523     TLOGD(WmsLogTag::DEFAULT, "action:%{public}" PRIu64, action);
6524     if (IsWindowSessionInvalid()) {
6525         TLOGE(WmsLogTag::DEFAULT, "session is invalid");
6526         return WMError::WM_ERROR_INVALID_WINDOW;
6527     }
6528     auto hostSession = GetHostSession();
6529     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
6530     return hostSession->UpdateSessionPropertyByAction(property_, action);
6531 }
6532 
Find(const std::string & name)6533 sptr<Window> WindowSessionImpl::Find(const std::string& name)
6534 {
6535     std::shared_lock<std::shared_mutex> lock(windowSessionMutex_);
6536     auto iter = windowSessionMap_.find(name);
6537     if (iter == windowSessionMap_.end()) {
6538         TLOGD(WmsLogTag::DEFAULT, "Can not find window %{public}s", name.c_str());
6539         return nullptr;
6540     }
6541     return iter->second.second;
6542 }
6543 
SetAceAbilityHandler(const sptr<IAceAbilityHandler> & handler)6544 void WindowSessionImpl::SetAceAbilityHandler(const sptr<IAceAbilityHandler>& handler)
6545 {
6546     if (handler == nullptr) {
6547         WLOGE("ace ability handler is nullptr");
6548     }
6549     std::lock_guard<std::recursive_mutex> lock(mutex_);
6550     aceAbilityHandler_ = handler;
6551 }
6552 
SetBackgroundColor(const std::string & color)6553 WMError WindowSessionImpl::SetBackgroundColor(const std::string& color)
6554 {
6555     if (IsWindowSessionInvalid()) {
6556         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "session is invalid");
6557         return WMError::WM_ERROR_INVALID_WINDOW;
6558     }
6559     uint32_t colorValue;
6560     if (ColorParser::Parse(color, colorValue)) {
6561         TLOGD(WmsLogTag::WMS_ATTRIBUTE, "window: %{public}s, value: [%{public}s, %{public}u]",
6562             GetWindowName().c_str(), color.c_str(), colorValue);
6563         return SetBackgroundColor(colorValue);
6564     }
6565     TLOGE(WmsLogTag::WMS_ATTRIBUTE, "invalid color string: %{public}s", color.c_str());
6566     return WMError::WM_ERROR_INVALID_PARAM;
6567 }
6568 
SetBackgroundColor(uint32_t color)6569 WMError WindowSessionImpl::SetBackgroundColor(uint32_t color)
6570 {
6571     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "window: %{public}s, value:%{public}u", GetWindowName().c_str(), color);
6572 
6573     // 0xff000000: ARGB style, means Opaque color.
6574     const bool isAlphaZero = !(color & 0xff000000);
6575     std::string bundleName;
6576     std::string abilityName;
6577     auto context = GetContext();
6578     if ((context != nullptr) && (context->GetApplicationInfo() != nullptr)) {
6579         bundleName = context->GetBundleName();
6580         abilityName = context->GetApplicationInfo()->name;
6581     }
6582 
6583     if (isAlphaZero && WindowHelper::IsMainWindow(GetType())) {
6584         auto& reportInstance = SingletonContainer::Get<WindowInfoReporter>();
6585         reportInstance.ReportZeroOpacityInfoImmediately(bundleName, abilityName);
6586     }
6587 
6588     if (auto uiContent = GetUIContentSharedPtr()) {
6589         uiContent->SetBackgroundColor(color);
6590         // 24: Shift right by 24 bits to move the alpha channel to the lowest 8 bits.
6591         uint8_t alpha = static_cast<uint8_t>((color >> 24) & 0xff);
6592         property_->SetBackgroundAlpha(alpha);
6593         UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_BACKGROUND_ALPHA);
6594         return WMError::WM_OK;
6595     } else {
6596         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "uiContent is null, win=%{public}u, value=%{public}u",
6597             GetWindowId(), color);
6598     }
6599 
6600     if (aceAbilityHandler_ != nullptr) {
6601         TLOGI(WmsLogTag::WMS_ATTRIBUTE, "set ability background color, win=%{public}u, value=%{public}u",
6602             GetWindowId(), color);
6603         aceAbilityHandler_->SetBackgroundColor(color);
6604         return WMError::WM_OK;
6605     }
6606     TLOGW(WmsLogTag::WMS_ATTRIBUTE, "FA mode could not set bg color: %{public}u", GetWindowId());
6607     return WMError::WM_ERROR_INVALID_OPERATION;
6608 }
6609 
FindWindowById(uint32_t winId)6610 sptr<Window> WindowSessionImpl::FindWindowById(uint32_t winId)
6611 {
6612     std::shared_lock<std::shared_mutex> lock(windowSessionMutex_);
6613     if (windowSessionMap_.empty()) {
6614         WLOGFE("Please create mainWindow First!");
6615         return nullptr;
6616     }
6617     for (auto iter = windowSessionMap_.begin(); iter != windowSessionMap_.end(); iter++) {
6618         if (static_cast<int32_t>(winId) == iter->second.first) {
6619             WLOGD("FindWindow id: %{public}u", winId);
6620             return iter->second.second;
6621         }
6622     }
6623     WLOGFE("Cannot find Window, id: %{public}d", winId);
6624     return nullptr;
6625 }
6626 
GetSubWindow(int parentId)6627 std::vector<sptr<Window>> WindowSessionImpl::GetSubWindow(int parentId)
6628 {
6629     std::lock_guard<std::recursive_mutex> lock(subWindowSessionMutex_);
6630     auto iter = subWindowSessionMap_.find(parentId);
6631     if (iter == subWindowSessionMap_.end()) {
6632         return std::vector<sptr<Window>>();
6633     }
6634     return std::vector<sptr<Window>>(subWindowSessionMap_[parentId].begin(), subWindowSessionMap_[parentId].end());
6635 }
6636 
IsApplicationModalSubWindowShowing(int32_t parentId)6637 bool WindowSessionImpl::IsApplicationModalSubWindowShowing(int32_t parentId)
6638 {
6639     auto subMap = GetSubWindow(parentId);
6640     auto applicationModalIndex = std::find_if(subMap.begin(), subMap.end(),
6641         [](const auto& subWindow) {
6642             return WindowHelper::IsApplicationModalSubWindow(subWindow->GetType(), subWindow->GetWindowFlags()) &&
6643                    subWindow->GetWindowState() != WindowState::STATE_SHOWN;
6644         });
6645     return applicationModalIndex != subMap.end();
6646 }
6647 
GetBackgroundColor() const6648 uint32_t WindowSessionImpl::GetBackgroundColor() const
6649 {
6650     if (auto uiContent = GetUIContentSharedPtr()) {
6651         return uiContent->GetBackgroundColor();
6652     }
6653     WLOGD("uiContent is null, windowId: %{public}u, use FA mode", GetWindowId());
6654     if (aceAbilityHandler_ != nullptr) {
6655         return aceAbilityHandler_->GetBackgroundColor();
6656     }
6657     WLOGFD("FA mode does not get bg color: %{public}u", GetWindowId());
6658     return 0xffffffff; // means no background color been set, default color is white
6659 }
6660 
SetLayoutFullScreenByApiVersion(bool status)6661 WMError WindowSessionImpl::SetLayoutFullScreenByApiVersion(bool status)
6662 {
6663     return WMError::WM_OK;
6664 }
6665 
UpdateSystemBarProperties(const std::unordered_map<WindowType,SystemBarProperty> & systemBarProperties,const std::unordered_map<WindowType,SystemBarPropertyFlag> & systemBarPropertyFlags)6666 WMError WindowSessionImpl::UpdateSystemBarProperties(
6667     const std::unordered_map<WindowType, SystemBarProperty>& systemBarProperties,
6668     const std::unordered_map<WindowType, SystemBarPropertyFlag>& systemBarPropertyFlags)
6669 {
6670     return WMError::WM_OK;
6671 }
6672 
SetSystemBarProperty(WindowType type,const SystemBarProperty & property)6673 WMError WindowSessionImpl::SetSystemBarProperty(WindowType type, const SystemBarProperty& property)
6674 {
6675     return WMError::WM_OK;
6676 }
6677 
HookCompatibleModeAvoidAreaNotify()6678 void WindowSessionImpl::HookCompatibleModeAvoidAreaNotify()
6679 {
6680     AvoidArea avoidArea;
6681     Rect rect = GetRect();
6682     GetAvoidAreaByType(AvoidAreaType::TYPE_SYSTEM, avoidArea, rect);
6683     auto avoidSptr = sptr<AvoidArea>::MakeSptr(avoidArea);
6684     NotifyAvoidAreaChange(avoidSptr, AvoidAreaType::TYPE_SYSTEM);
6685 }
6686 
UpdateSpecificSystemBarEnabled(bool systemBarEnable,bool systemBarEnableAnimation,SystemBarProperty & property)6687 void WindowSessionImpl::UpdateSpecificSystemBarEnabled(bool systemBarEnable, bool systemBarEnableAnimation,
6688     SystemBarProperty& property)
6689 {
6690     property.enable_ = systemBarEnable;
6691     property.enableAnimation_ = systemBarEnableAnimation;
6692     // isolate on api 18
6693     if (GetTargetAPIVersion() >= API_VERSION_18) {
6694         property.settingFlag_ |= SystemBarSettingFlag::ENABLE_SETTING;
6695     }
6696 }
6697 
SetSpecificBarProperty(WindowType type,const SystemBarProperty & property)6698 WMError WindowSessionImpl::SetSpecificBarProperty(WindowType type, const SystemBarProperty& property)
6699 {
6700     return WMError::WM_OK;
6701 }
6702 
NotifyOccupiedAreaChangeInfoInner(sptr<OccupiedAreaChangeInfo> info)6703 void WindowSessionImpl::NotifyOccupiedAreaChangeInfoInner(sptr<OccupiedAreaChangeInfo> info)
6704 {
6705     std::lock_guard<std::recursive_mutex> lockListener(occupiedAreaChangeListenerMutex_);
6706     auto occupiedAreaChangeListeners = GetListeners<IOccupiedAreaChangeListener>();
6707     for (auto& listener : occupiedAreaChangeListeners) {
6708         if (listener != nullptr) {
6709             listener->OnSizeChange(info);
6710         }
6711     }
6712 }
6713 
NotifyOccupiedAreaChangeInfo(sptr<OccupiedAreaChangeInfo> info,const std::shared_ptr<RSTransaction> & rsTransaction,const Rect & callingWindowRect,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)6714 void WindowSessionImpl::NotifyOccupiedAreaChangeInfo(sptr<OccupiedAreaChangeInfo> info,
6715     const std::shared_ptr<RSTransaction>& rsTransaction, const Rect& callingWindowRect,
6716     const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
6717 {
6718     if (handler_ == nullptr) {
6719         TLOGE(WmsLogTag::WMS_KEYBOARD, "handler is nullptr");
6720         return;
6721     }
6722     auto task = [weak = wptr(this), info, rsTransaction, callingWindowRect, avoidAreas]() {
6723         if (info != nullptr) {
6724             TLOGNI(WmsLogTag::WMS_KEYBOARD, "transaction: %{public}d, safeHeight: %{public}u"
6725                 ", occupied rect: x %{public}d, y %{public}d, w %{public}u, h %{public}u, "
6726                 "callingWindowRect: %{public}s", rsTransaction != nullptr, info->safeHeight_, info->rect_.posX_,
6727                 info->rect_.posY_, info->rect_.width_, info->rect_.height_, callingWindowRect.ToString().c_str());
6728         }
6729         auto window = weak.promote();
6730         if (!window) {
6731             TLOGNE(WmsLogTag::WMS_KEYBOARD, "window is nullptr, notify occupied area change info failed");
6732             return;
6733         }
6734         if (rsTransaction) {
6735             RSTransactionAdapter::FlushImplicitTransaction(window->GetRSUIContext());
6736             rsTransaction->Begin();
6737         }
6738         window->NotifyOccupiedAreaChangeInfoInner(info);
6739         window->occupiedAreaInfo_ = info;
6740         window->UpdateViewportConfig(callingWindowRect, WindowSizeChangeReason::OCCUPIED_AREA_CHANGE,
6741             nullptr, nullptr, avoidAreas);
6742         if (rsTransaction) {
6743             rsTransaction->Commit();
6744         }
6745     };
6746     handler_->PostTask(task, "WMS_WindowSessionImpl_NotifyOccupiedAreaChangeInfo");
6747 }
6748 
NotifyKeyboardWillShow(const KeyboardAnimationInfo & keyboardAnimationInfo)6749 void WindowSessionImpl::NotifyKeyboardWillShow(const KeyboardAnimationInfo& keyboardAnimationInfo)
6750 {
6751     std::lock_guard<std::recursive_mutex> lockListener(keyboardWillShowListenerMutex_);
6752     auto keyboardWillShowListeners = GetListeners<IKBWillShowListener>();
6753     for (const auto& listener : keyboardWillShowListeners) {
6754         if (listener != nullptr) {
6755             auto config = GetKeyboardAnimationConfig();
6756             auto animation = keyboardAnimationInfo.isShow ? config.curveIn : config.curveOut;
6757             listener->OnKeyboardWillShow(keyboardAnimationInfo, animation);
6758         }
6759     }
6760 }
6761 
NotifyKeyboardWillHide(const KeyboardAnimationInfo & keyboardAnimationInfo)6762 void WindowSessionImpl::NotifyKeyboardWillHide(const KeyboardAnimationInfo& keyboardAnimationInfo)
6763 {
6764     std::lock_guard<std::recursive_mutex> lockListener(keyboardWillHideListenerMutex_);
6765     auto keyboardWillHideListeners = GetListeners<IKBWillHideListener>();
6766     for (const auto& listener : keyboardWillHideListeners) {
6767         if (listener != nullptr) {
6768             auto config = GetKeyboardAnimationConfig();
6769             auto animation = keyboardAnimationInfo.isShow ? config.curveIn : config.curveOut;
6770             listener->OnKeyboardWillHide(keyboardAnimationInfo, animation);
6771         }
6772     }
6773 }
6774 
NotifyKeyboardDidShow(const KeyboardPanelInfo & keyboardPanelInfo)6775 void WindowSessionImpl::NotifyKeyboardDidShow(const KeyboardPanelInfo& keyboardPanelInfo)
6776 {
6777     std::lock_guard<std::recursive_mutex> lockListener(keyboardDidShowListenerMutex_);
6778     auto keyboardDidShowListeners = GetListeners<IKeyboardDidShowListener>();
6779     for (const auto& listener : keyboardDidShowListeners) {
6780         if (listener != nullptr) {
6781             listener->OnKeyboardDidShow(keyboardPanelInfo);
6782         }
6783     }
6784     if (auto uiContent = GetUIContentSharedPtr()) {
6785         AAFwk::Want want;
6786         WriteKeyboardInfoToWant(want, keyboardPanelInfo);
6787         uiContent->SendUIExtProprtyByPersistentId(
6788             static_cast<uint32_t>(Extension::Businesscode::NOTIFY_KEYBOARD_DID_SHOW), want,
6789             keyboardDidShowUIExtListenerIds_, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
6790     }
6791 }
6792 
NotifyKeyboardDidHide(const KeyboardPanelInfo & keyboardPanelInfo)6793 void WindowSessionImpl::NotifyKeyboardDidHide(const KeyboardPanelInfo& keyboardPanelInfo)
6794 {
6795     std::lock_guard<std::recursive_mutex> lockListener(keyboardDidHideListenerMutex_);
6796     auto keyboardDidHideListeners = GetListeners<IKeyboardDidHideListener>();
6797     for (const auto& listener : keyboardDidHideListeners) {
6798         if (listener != nullptr) {
6799             listener->OnKeyboardDidHide(keyboardPanelInfo);
6800         }
6801     }
6802     if (auto uiContent = GetUIContentSharedPtr()) {
6803         AAFwk::Want want;
6804         WriteKeyboardInfoToWant(want, keyboardPanelInfo);
6805         uiContent->SendUIExtProprtyByPersistentId(
6806             static_cast<uint32_t>(Extension::Businesscode::NOTIFY_KEYBOARD_DID_HIDE), want,
6807             keyboardDidHideUIExtListenerIds_, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
6808     }
6809 }
6810 
WriteKeyboardInfoToWant(AAFwk::Want & want,const KeyboardPanelInfo & keyboardPanelInfo) const6811 void WindowSessionImpl::WriteKeyboardInfoToWant(AAFwk::Want& want, const KeyboardPanelInfo& keyboardPanelInfo) const
6812 {
6813     want.SetParam(Extension::RECT_X, static_cast<int>(keyboardPanelInfo.rect_.posX_));
6814     want.SetParam(Extension::RECT_Y, static_cast<int>(keyboardPanelInfo.rect_.posY_));
6815     want.SetParam(Extension::RECT_WIDTH, static_cast<int>(keyboardPanelInfo.rect_.width_));
6816     want.SetParam(Extension::RECT_HEIGHT, static_cast<int>(keyboardPanelInfo.rect_.height_));
6817     want.SetParam(Extension::BEGIN_X, static_cast<int>(keyboardPanelInfo.beginRect_.posX_));
6818     want.SetParam(Extension::BEGIN_Y, static_cast<int>(keyboardPanelInfo.beginRect_.posY_));
6819     want.SetParam(Extension::BEGIN_WIDTH, static_cast<int>(keyboardPanelInfo.beginRect_.width_));
6820     want.SetParam(Extension::BEGIN_HEIGHT, static_cast<int>(keyboardPanelInfo.beginRect_.height_));
6821     want.SetParam(Extension::END_X, static_cast<int>(keyboardPanelInfo.endRect_.posX_));
6822     want.SetParam(Extension::END_Y, static_cast<int>(keyboardPanelInfo.endRect_.posY_));
6823     want.SetParam(Extension::END_WIDTH, static_cast<int>(keyboardPanelInfo.endRect_.width_));
6824     want.SetParam(Extension::END_HEIGHT, static_cast<int>(keyboardPanelInfo.endRect_.height_));
6825     want.SetParam(Extension::GRAVITY, static_cast<int>(keyboardPanelInfo.gravity_));
6826     want.SetParam(Extension::ISSHOWING, keyboardPanelInfo.isShowing_);
6827 }
6828 
ReadKeyboardInfoFromWant(const AAFwk::Want & want,KeyboardPanelInfo & keyboardPanelInfo) const6829 void WindowSessionImpl::ReadKeyboardInfoFromWant(const AAFwk::Want& want, KeyboardPanelInfo& keyboardPanelInfo) const
6830 {
6831     keyboardPanelInfo.rect_ = {
6832         want.GetIntParam(Extension::RECT_X, 0),
6833         want.GetIntParam(Extension::RECT_Y, 0),
6834         want.GetIntParam(Extension::RECT_WIDTH, 0),
6835         want.GetIntParam(Extension::RECT_HEIGHT, 0)
6836     };
6837     keyboardPanelInfo.beginRect_ = {
6838         want.GetIntParam(Extension::BEGIN_X, 0),
6839         want.GetIntParam(Extension::BEGIN_Y, 0),
6840         want.GetIntParam(Extension::BEGIN_WIDTH, 0),
6841         want.GetIntParam(Extension::BEGIN_HEIGHT, 0)
6842     };
6843     keyboardPanelInfo.endRect_ = {
6844         want.GetIntParam(Extension::END_X, 0),
6845         want.GetIntParam(Extension::END_Y, 0),
6846         want.GetIntParam(Extension::END_WIDTH, 0),
6847         want.GetIntParam(Extension::END_HEIGHT, 0)
6848     };
6849     keyboardPanelInfo.gravity_ = static_cast<WindowGravity>(want.GetIntParam(Extension::GRAVITY, 0));
6850     keyboardPanelInfo.isShowing_ = want.GetBoolParam(Extension::ISSHOWING, false);
6851 }
6852 
GetWindowExtensionSessionSet()6853 std::set<sptr<WindowSessionImpl>>& WindowSessionImpl::GetWindowExtensionSessionSet()
6854 {
6855     return g_windowExtensionSessionSet_;
6856 }
6857 
NotifyKeyboardAnimationCompleted(const KeyboardPanelInfo & keyboardPanelInfo)6858 void WindowSessionImpl::NotifyKeyboardAnimationCompleted(const KeyboardPanelInfo& keyboardPanelInfo)
6859 {
6860     TLOGI(WmsLogTag::WMS_KEYBOARD, "isShowAnimation: %{public}d, beginRect: %{public}s, endRect: %{public}s",
6861         keyboardPanelInfo.isShowing_, keyboardPanelInfo.beginRect_.ToString().c_str(),
6862         keyboardPanelInfo.endRect_.ToString().c_str());
6863     if (handler_ == nullptr) {
6864         TLOGE(WmsLogTag::WMS_KEYBOARD, "handler is nullptr");
6865         return;
6866     }
6867     auto task = [weak = wptr(this), keyboardPanelInfo]() {
6868         auto window = weak.promote();
6869         if (!window) {
6870             TLOGNE(WmsLogTag::WMS_KEYBOARD, "window is nullptr, notify keyboard animation completed failed");
6871             return;
6872         }
6873         if (keyboardPanelInfo.isShowing_) {
6874             window->NotifyKeyboardDidShow(keyboardPanelInfo);
6875         } else {
6876             window->NotifyKeyboardDidHide(keyboardPanelInfo);
6877         }
6878     };
6879     handler_->PostTask(task, __func__);
6880 }
6881 
NotifyKeyboardAnimationWillBegin(const KeyboardAnimationInfo & keyboardAnimationInfo,const std::shared_ptr<RSTransaction> & rsTransaction)6882 void WindowSessionImpl::NotifyKeyboardAnimationWillBegin(const KeyboardAnimationInfo& keyboardAnimationInfo,
6883     const std::shared_ptr<RSTransaction>& rsTransaction)
6884 {
6885     TLOGI(WmsLogTag::WMS_KEYBOARD, "isShowAnimation: %{public}d, beginRect: %{public}s, endRect: %{public}s \
6886         rsTransaction is empty:%{public}d",
6887         keyboardAnimationInfo.isShow, keyboardAnimationInfo.beginRect.ToString().c_str(),
6888         keyboardAnimationInfo.endRect.ToString().c_str(), (rsTransaction == nullptr));
6889     if (handler_ == nullptr) {
6890         TLOGE(WmsLogTag::WMS_KEYBOARD, "handler is nullptr");
6891         return;
6892     }
6893     auto task = [weak = wptr(this), keyboardAnimationInfo, rsTransaction]() {
6894         auto window = weak.promote();
6895         if (!window) {
6896             TLOGNE(WmsLogTag::WMS_KEYBOARD, "window is nullptr, notify keyboard animation completed failed");
6897             return;
6898         }
6899 
6900         if (rsTransaction != nullptr) {
6901             RSTransaction::FlushImplicitTransaction();
6902             rsTransaction->Begin();
6903         }
6904         if (keyboardAnimationInfo.isShow) {
6905             window->NotifyKeyboardWillShow(keyboardAnimationInfo);
6906         } else {
6907             window->NotifyKeyboardWillHide(keyboardAnimationInfo);
6908         }
6909         if (rsTransaction != nullptr) {
6910             rsTransaction->Commit();
6911         }
6912     };
6913     handler_->PostTask(task, __func__);
6914 }
6915 
GetKeyboardAnimationConfig()6916 KeyboardAnimationConfig WindowSessionImpl::GetKeyboardAnimationConfig()
6917 {
6918     return { windowSystemConfig_.animationIn_, windowSystemConfig_.animationOut_ };
6919 }
6920 
DumpSessionElementInfo(const std::vector<std::string> & params)6921 void WindowSessionImpl::DumpSessionElementInfo(const std::vector<std::string>& params)
6922 {
6923     WLOGFD("in");
6924 }
6925 
UpdateMaximizeMode(MaximizeMode mode)6926 WSError WindowSessionImpl::UpdateMaximizeMode(MaximizeMode mode)
6927 {
6928     return WSError::WS_OK;
6929 }
6930 
TransferAccessibilityEvent(const Accessibility::AccessibilityEventInfo & info,int64_t uiExtensionIdLevel)6931 WMError WindowSessionImpl::TransferAccessibilityEvent(const Accessibility::AccessibilityEventInfo& info,
6932     int64_t uiExtensionIdLevel)
6933 {
6934     return WMError::WM_OK;
6935 }
6936 
NotifySessionForeground(uint32_t reason,bool withAnimation)6937 void WindowSessionImpl::NotifySessionForeground(uint32_t reason, bool withAnimation)
6938 {
6939     WLOGFD("in");
6940 }
6941 
NotifySessionBackground(uint32_t reason,bool withAnimation,bool isFromInnerkits)6942 void WindowSessionImpl::NotifySessionBackground(uint32_t reason, bool withAnimation, bool isFromInnerkits)
6943 {
6944     WLOGFD("in");
6945 }
6946 
UpdateTitleInTargetPos(bool isShow,int32_t height)6947 WSError WindowSessionImpl::UpdateTitleInTargetPos(bool isShow, int32_t height)
6948 {
6949     return WSError::WS_OK;
6950 }
6951 
SwitchFreeMultiWindow(bool enable)6952 WSError WindowSessionImpl::SwitchFreeMultiWindow(bool enable)
6953 {
6954     return WSError::WS_OK;
6955 }
6956 
NotifyDialogStateChange(bool isForeground)6957 WSError WindowSessionImpl::NotifyDialogStateChange(bool isForeground)
6958 {
6959     return WSError::WS_OK;
6960 }
6961 
UpdatePiPRect(const Rect & rect,WindowSizeChangeReason reason)6962 void WindowSessionImpl::UpdatePiPRect(const Rect& rect, WindowSizeChangeReason reason)
6963 {
6964     if (IsWindowSessionInvalid()) {
6965         WLOGFE("session is invalid");
6966         return;
6967     }
6968     auto hostSession = GetHostSession();
6969     CHECK_HOST_SESSION_RETURN_IF_NULL(hostSession);
6970     hostSession->UpdatePiPRect(rect, static_cast<SizeChangeReason>(reason));
6971 }
6972 
UpdatePiPControlStatus(PiPControlType controlType,PiPControlStatus status)6973 void WindowSessionImpl::UpdatePiPControlStatus(PiPControlType controlType, PiPControlStatus status)
6974 {
6975     TLOGI(WmsLogTag::WMS_PIP, "controlType:%{public}u, status:%{public}d", controlType, status);
6976     if (IsWindowSessionInvalid()) {
6977         TLOGE(WmsLogTag::WMS_PIP, "HostSession is invalid");
6978         return;
6979     }
6980     auto hostSession = GetHostSession();
6981     CHECK_HOST_SESSION_RETURN_IF_NULL(hostSession);
6982     hostSession->UpdatePiPControlStatus(static_cast<WsPiPControlType>(controlType),
6983         static_cast<WsPiPControlStatus>(status));
6984 }
6985 
SetAutoStartPiP(bool isAutoStart,uint32_t priority,uint32_t width,uint32_t height)6986 void WindowSessionImpl::SetAutoStartPiP(bool isAutoStart, uint32_t priority, uint32_t width, uint32_t height)
6987 {
6988     if (IsWindowSessionInvalid()) {
6989         TLOGE(WmsLogTag::WMS_PIP, "session is invalid");
6990         return;
6991     }
6992     if (auto hostSession = GetHostSession()) {
6993         hostSession->SetAutoStartPiP(isAutoStart, priority, width, height);
6994     }
6995 }
6996 
UpdatePiPTemplateInfo(PiPTemplateInfo & pipTemplateInfo)6997 void WindowSessionImpl::UpdatePiPTemplateInfo(PiPTemplateInfo& pipTemplateInfo)
6998 {
6999     if (IsWindowSessionInvalid()) {
7000         TLOGE(WmsLogTag::WMS_PIP, "session is invalid");
7001         return;
7002     }
7003     TLOGI(WmsLogTag::WMS_PIP, "UpdatePiPTemplateInfo, pipTemplateType: %{public}u, priority: %{public}d, "
7004         "defaultWindowSizeType: %{public}d", pipTemplateInfo.pipTemplateType, pipTemplateInfo.priority,
7005         pipTemplateInfo.defaultWindowSizeType);
7006     if (auto hostSession = GetHostSession()) {
7007         hostSession->UpdatePiPTemplateInfo(pipTemplateInfo);
7008     }
7009 }
7010 
UpdateFloatingBall(const FloatingBallTemplateBaseInfo & fbTemplateBaseInfo,const std::shared_ptr<Media::PixelMap> & icon)7011 WMError WindowSessionImpl::UpdateFloatingBall(const FloatingBallTemplateBaseInfo& fbTemplateBaseInfo,
7012     const std::shared_ptr<Media::PixelMap>& icon)
7013 {
7014     if (IsWindowSessionInvalid()) {
7015         TLOGE(WmsLogTag::WMS_SYSTEM, "session is invalid");
7016         return WMError::WM_ERROR_FB_STATE_ABNORMALLY;
7017     }
7018 
7019     if (GetProperty()->GetFbTemplateInfo().template_ == static_cast<uint32_t>(FloatingBallTemplate::STATIC)) {
7020         TLOGE(WmsLogTag::WMS_SYSTEM, "Fb static template can't update");
7021         return WMError::WM_ERROR_FB_UPDATE_STATIC_TEMPLATE_DENIED;
7022     }
7023 
7024     if (GetProperty()->GetFbTemplateInfo().template_ != fbTemplateBaseInfo.template_) {
7025         TLOGE(WmsLogTag::WMS_SYSTEM, "Fb template type can't update");
7026         return WMError::WM_ERROR_FB_UPDATE_TEMPLATE_TYPE_DENIED;
7027     }
7028     FloatingBallTemplateInfo fbTemplateInfo = FloatingBallTemplateInfo(fbTemplateBaseInfo, icon);
7029     auto hostSession = GetHostSession();
7030     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_FB_STATE_ABNORMALLY);
7031     return hostSession->UpdateFloatingBall(fbTemplateInfo);
7032 }
7033 
RestoreFbMainWindow(const std::shared_ptr<AAFwk::Want> & want)7034 WMError WindowSessionImpl::RestoreFbMainWindow(const std::shared_ptr<AAFwk::Want>& want)
7035 {
7036     if (IsWindowSessionInvalid()) {
7037         TLOGE(WmsLogTag::WMS_SYSTEM, "session is invalid");
7038         return WMError::WM_ERROR_FB_STATE_ABNORMALLY;
7039     }
7040     auto hostSession = GetHostSession();
7041     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_FB_STATE_ABNORMALLY);
7042     return hostSession->RestoreFbMainWindow(want);
7043 }
7044 
NotifyPrepareCloseFloatingBall()7045 void WindowSessionImpl::NotifyPrepareCloseFloatingBall()
7046 {
7047     TLOGI(WmsLogTag::WMS_SYSTEM, "NotifyPrepareCloseFloatingBall");
7048     if (IsWindowSessionInvalid()) {
7049         TLOGE(WmsLogTag::WMS_SYSTEM, "session is invalid");
7050         return;
7051     }
7052     auto hostSession = GetHostSession();
7053     CHECK_HOST_SESSION_RETURN_IF_NULL(hostSession);
7054     hostSession->NotifyFloatingBallPrepareClose();
7055 }
7056 
GetWindowStatusInner(WindowMode mode)7057 WindowStatus WindowSessionImpl::GetWindowStatusInner(WindowMode mode)
7058 {
7059     auto windowStatus = WindowStatus::WINDOW_STATUS_UNDEFINED;
7060     if (mode == WindowMode::WINDOW_MODE_FLOATING) {
7061         windowStatus = WindowStatus::WINDOW_STATUS_FLOATING;
7062         if (property_->GetMaximizeMode() == MaximizeMode::MODE_AVOID_SYSTEM_BAR) {
7063             windowStatus = WindowStatus::WINDOW_STATUS_MAXIMIZE;
7064         }
7065     } else if (mode == WindowMode::WINDOW_MODE_SPLIT_PRIMARY || mode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY) {
7066         windowStatus = WindowStatus::WINDOW_STATUS_SPLITSCREEN;
7067     }
7068     if (mode == WindowMode::WINDOW_MODE_FULLSCREEN) {
7069         if (IsPcOrPadFreeMultiWindowMode() && GetTargetAPIVersion() >= 14) { // 14: isolated version
7070             windowStatus = GetImmersiveModeEnabledState() ? WindowStatus::WINDOW_STATUS_FULLSCREEN :
7071                 WindowStatus::WINDOW_STATUS_MAXIMIZE;
7072         } else {
7073             windowStatus = WindowStatus::WINDOW_STATUS_FULLSCREEN;
7074         }
7075     }
7076     if (state_ == WindowState::STATE_HIDDEN) {
7077         windowStatus = WindowStatus::WINDOW_STATUS_MINIMIZE;
7078     }
7079     return windowStatus;
7080 }
7081 
GetStatusBarHeight() const7082 uint32_t WindowSessionImpl::GetStatusBarHeight() const
7083 {
7084     uint32_t height = 0;
7085     auto hostSession = GetHostSession();
7086     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, height);
7087     height = static_cast<uint32_t>(hostSession->GetStatusBarHeight());
7088     TLOGD(WmsLogTag::WMS_IMMS, "win %{public}u height %{public}u", GetPersistentId(), height);
7089     return height;
7090 }
7091 
7092 /** @note @window.layout */
NotifyWindowStatusChange(WindowMode mode)7093 void WindowSessionImpl::NotifyWindowStatusChange(WindowMode mode)
7094 {
7095     auto windowStatus = GetWindowStatusInner(mode);
7096     if (windowSystemConfig_.skipRedundantWindowStatusNotifications_ && lastWindowStatus_.load() == windowStatus) {
7097         TLOGD(WmsLogTag::WMS_LAYOUT, "Duplicate windowStatus:%{public}d, id:%{public}d, WindowMode:%{public}d",
7098             windowStatus, GetPersistentId(), mode);
7099         return;
7100     }
7101     TLOGI(WmsLogTag::WMS_LAYOUT, "id:%{public}d, windowMode:%{public}d, windowStatus:%{public}d, "
7102         "lastWindowStatus:%{public}d, skipRedundantWindowStatusNotifications:%{public}d", GetPersistentId(), mode,
7103         windowStatus, lastWindowStatus_.load(), windowSystemConfig_.skipRedundantWindowStatusNotifications_);
7104     lastWindowStatus_.store(windowStatus);
7105     std::lock_guard<std::recursive_mutex> lockListener(windowStatusChangeListenerMutex_);
7106     auto windowStatusChangeListeners = GetListeners<IWindowStatusChangeListener>();
7107     for (auto& listener : windowStatusChangeListeners) {
7108         if (listener != nullptr) {
7109             listener->OnWindowStatusChange(windowStatus);
7110         }
7111     }
7112     if (state_ != WindowState::STATE_HIDDEN) {
7113         auto ret = HiSysEventWrite(
7114             HiviewDFX::HiSysEvent::Domain::WINDOW_MANAGER,
7115             "WINDOW_STATUS_CHANGE",
7116             HiviewDFX::HiSysEvent::EventType::BEHAVIOR,
7117             "BUNDLE_NAME", property_->GetSessionInfo().bundleName_,
7118             "WINDOW_MODE", static_cast<int32_t>(mode));
7119         if (ret) {
7120             TLOGW(WmsLogTag::WMS_FOCUS, "write event fail, WINDOW_STATUS_CHANGE, ret=%{public}d", ret);
7121         }
7122     }
7123 }
7124 
7125 /** @note @window.layout */
NotifyWindowStatusDidChange(WindowMode mode)7126 void WindowSessionImpl::NotifyWindowStatusDidChange(WindowMode mode)
7127 {
7128     auto windowStatus = GetWindowStatusInner(mode);
7129     auto lastStatus = lastStatusWhenNotifyWindowStatusDidChange_.load();
7130     if (lastStatus == windowStatus) {
7131         TLOGI(WmsLogTag::WMS_LAYOUT, "Duplicate windowStatus:%{public}u, id:%{public}d, windowMode:%{public}u",
7132             windowStatus, GetPersistentId(), mode);
7133         return;
7134     }
7135     lastStatusWhenNotifyWindowStatusDidChange_.store(windowStatus);
7136     std::vector<sptr<IWindowStatusDidChangeListener>> windowStatusDidChangeListeners;
7137     {
7138         std::lock_guard<std::recursive_mutex> lockListener(windowStatusDidChangeListenerMutex_);
7139         windowStatusDidChangeListeners = GetListeners<IWindowStatusDidChangeListener>();
7140     }
7141     const auto& windowRect = GetRect();
7142     TLOGI(WmsLogTag::WMS_LAYOUT, "Id:%{public}d, WindowMode:%{public}u, windowStatus:%{public}u, "
7143         "lastWindowStatus:%{public}u, listenerSize:%{public}zu, rect:%{public}s",
7144         GetPersistentId(), mode, windowStatus, lastStatus, windowStatusDidChangeListeners.size(),
7145         windowRect.ToString().c_str());
7146     for (auto& listener : windowStatusDidChangeListeners) {
7147         if (listener != nullptr) {
7148             listener->OnWindowStatusDidChange(windowStatus);
7149         }
7150     }
7151 }
7152 
NotifyFirstValidLayoutUpdate(const Rect & preRect,const Rect & newRect)7153 void WindowSessionImpl::NotifyFirstValidLayoutUpdate(const Rect& preRect, const Rect& newRect)
7154 {
7155     bool isFirstValidLayoutUpdate = true;
7156     if (preRect.IsUninitializedSize() && !newRect.IsUninitializedSize() &&
7157         isFirstValidLayoutUpdate_.compare_exchange_strong(isFirstValidLayoutUpdate, false)) {
7158         updateRectCallback_->OnFirstValidRectUpdate(GetPersistentId());
7159         TLOGI(WmsLogTag::WMS_LAYOUT, "Id:%{public}d, rect:%{public}s", GetPersistentId(), newRect.ToString().c_str());
7160     }
7161 }
7162 
7163 template <typename T>
GetListeners()7164 EnableIfSame<T, IPreferredOrientationChangeListener, sptr<IPreferredOrientationChangeListener>> WindowSessionImpl::GetListeners()
7165 {
7166     sptr<IPreferredOrientationChangeListener> preferredOrientationChangeListener;
7167     preferredOrientationChangeListener = preferredOrientationChangeListener_[GetPersistentId()];
7168     return preferredOrientationChangeListener;
7169 }
7170 
RegisterPreferredOrientationChangeListener(const sptr<IPreferredOrientationChangeListener> & listener)7171 WMError WindowSessionImpl::RegisterPreferredOrientationChangeListener(
7172     const sptr<IPreferredOrientationChangeListener>& listener)
7173 {
7174     if (listener == nullptr) {
7175         TLOGE(WmsLogTag::WMS_ROTATION, "listener is null.");
7176         return WMError::WM_ERROR_NULLPTR;
7177     }
7178     std::lock_guard<std::mutex> lockListener(preferredOrientationChangeListenerMutex_);
7179     preferredOrientationChangeListener_[GetPersistentId()] = listener;
7180     return WMError::WM_OK;
7181 }
7182 
UnregisterPreferredOrientationChangeListener(const sptr<IPreferredOrientationChangeListener> & listener)7183 WMError WindowSessionImpl::UnregisterPreferredOrientationChangeListener(
7184     const sptr<IPreferredOrientationChangeListener>& listener)
7185 {
7186     if (listener == nullptr) {
7187         TLOGE(WmsLogTag::WMS_ROTATION, "listener is null.");
7188         return WMError::WM_ERROR_NULLPTR;
7189     }
7190     std::lock_guard<std::mutex> lockListener(preferredOrientationChangeListenerMutex_);
7191     preferredOrientationChangeListener_[GetPersistentId()] = nullptr;
7192     return WMError::WM_OK;
7193 }
7194 
NotifyPreferredOrientationChange(Orientation orientation)7195 void WindowSessionImpl::NotifyPreferredOrientationChange(Orientation orientation)
7196 {
7197     TLOGD(WmsLogTag::WMS_ROTATION, "in");
7198     std::lock_guard<std::mutex> lockListener(preferredOrientationChangeListenerMutex_);
7199     auto preferredOrientationChangeListener = GetListeners<IPreferredOrientationChangeListener>();
7200     if (preferredOrientationChangeListener != nullptr) {
7201         preferredOrientationChangeListener->OnPreferredOrientationChange(orientation);
7202         TLOGI(WmsLogTag::WMS_ROTATION, "OnPreferredOrientationChange is success.");
7203     }
7204 }
7205 
NotifyClientOrientationChange()7206 void WindowSessionImpl::NotifyClientOrientationChange()
7207 {
7208     TLOGD(WmsLogTag::WMS_ROTATION, "in");
7209     std::lock_guard<std::mutex> lockListener(windowOrientationChangeListenerMutex_);
7210     auto windowOrientationChangeListener = GetListeners<IWindowOrientationChangeListener>();
7211     if (windowOrientationChangeListener != nullptr) {
7212         windowOrientationChangeListener->OnOrientationChange();
7213         TLOGI(WmsLogTag::WMS_ROTATION, "OnOrientationChange is success.");
7214     }
7215 }
7216 
7217 template<typename T>
GetListeners()7218 EnableIfSame<T, IWindowOrientationChangeListener, sptr<IWindowOrientationChangeListener>> WindowSessionImpl::GetListeners()
7219 {
7220     TLOGD(WmsLogTag::WMS_ROTATION, "in");
7221     sptr<IWindowOrientationChangeListener> windowOrientationChangeListener;
7222     windowOrientationChangeListener = windowOrientationChangeListener_[GetPersistentId()];
7223     return windowOrientationChangeListener;
7224 }
7225 
RegisterOrientationChangeListener(const sptr<IWindowOrientationChangeListener> & listener)7226 WMError WindowSessionImpl::RegisterOrientationChangeListener(
7227     const sptr<IWindowOrientationChangeListener>& listener)
7228 {
7229     TLOGI(WmsLogTag::WMS_ROTATION, "in");
7230     if (listener == nullptr) {
7231         TLOGE(WmsLogTag::WMS_ROTATION, "listener is null.");
7232         return WMError::WM_ERROR_NULLPTR;
7233     }
7234     std::lock_guard<std::mutex> lockListener(windowOrientationChangeListenerMutex_);
7235     windowOrientationChangeListener_[GetPersistentId()] = listener;
7236     return WMError::WM_OK;
7237 }
7238 
UnregisterOrientationChangeListener(const sptr<IWindowOrientationChangeListener> & listener)7239 WMError WindowSessionImpl::UnregisterOrientationChangeListener(
7240     const sptr<IWindowOrientationChangeListener>& listener)
7241 {
7242     TLOGI(WmsLogTag::WMS_ROTATION, "in");
7243     if (listener == nullptr) {
7244         TLOGE(WmsLogTag::WMS_ROTATION, "listener is null.");
7245         return WMError::WM_ERROR_NULLPTR;
7246     }
7247     std::lock_guard<std::mutex> lockListener(windowOrientationChangeListenerMutex_);
7248     windowOrientationChangeListener_[GetPersistentId()] = nullptr;
7249     return WMError::WM_OK;
7250 }
7251 
NotifyTransformChange(const Transform & transform)7252 void WindowSessionImpl::NotifyTransformChange(const Transform& transform)
7253 {
7254     WLOGFI("in");
7255     SetCurrentTransform(transform);
7256     if (auto uiContent = GetUIContentSharedPtr()) {
7257         uiContent->UpdateTransform(transform);
7258         SetLayoutTransform(transform);
7259         SetNeedRenotifyTransform(false);
7260     } else {
7261         SetNeedRenotifyTransform(true);
7262     }
7263 }
7264 
NotifySingleHandTransformChange(const SingleHandTransform & singleHandTransform)7265 void WindowSessionImpl::NotifySingleHandTransformChange(const SingleHandTransform& singleHandTransform)
7266 {
7267     singleHandTransform_ = singleHandTransform;
7268     if (auto uiContent = GetUIContentSharedPtr()) {
7269         TLOGI(WmsLogTag::WMS_LAYOUT, "id:%{public}d, posX:%{public}d, posY:%{public}d, "
7270               "scaleX:%{public}f, scaleY:%{public}f", GetPersistentId(),
7271               singleHandTransform.posX, singleHandTransform.posY,
7272               singleHandTransform.scaleX, singleHandTransform.scaleY);
7273         uiContent->UpdateSingleHandTransform(singleHandTransform);
7274     } else {
7275         TLOGW(WmsLogTag::WMS_LAYOUT, "id:%{public}d, uiContent is nullptr", GetPersistentId());
7276     }
7277 }
7278 
SubmitNoInteractionMonitorTask(int32_t eventId,const IWindowNoInteractionListenerSptr & listener)7279 void WindowSessionImpl::SubmitNoInteractionMonitorTask(int32_t eventId,
7280     const IWindowNoInteractionListenerSptr& listener)
7281 {
7282     auto task = [sessionWptr = wptr(this), eventId, listenerWptr = wptr(listener)]() {
7283         auto session = sessionWptr.promote();
7284         if (session == nullptr) {
7285             WLOGFE("windowInteractionMonitor task running failed, window session is null");
7286             return;
7287         }
7288         if (eventId != session->lastInteractionEventId_.load()) {
7289             WLOGFD("event id of windowInteractionMonitor has been changed, need not notify!");
7290             return;
7291         }
7292         if (session->state_ != WindowState::STATE_SHOWN) {
7293             WLOGFD("window state is not show, need not notify!");
7294             return;
7295         }
7296         session->NotifyNoInteractionTimeout(listenerWptr.promote());
7297     };
7298     handler_->PostTask(task, listener->GetTimeout());
7299 }
7300 
RefreshNoInteractionTimeoutMonitor()7301 void WindowSessionImpl::RefreshNoInteractionTimeoutMonitor()
7302 {
7303     std::lock_guard<std::recursive_mutex> lockListener(windowNoInteractionListenerMutex_);
7304     if (windowNoInteractionListeners_[GetPersistentId()].empty()) {
7305         return;
7306     }
7307     this->lastInteractionEventId_.fetch_add(1);
7308     int32_t eventId = lastInteractionEventId_.load();
7309     auto noInteractionListeners = GetListeners<IWindowNoInteractionListener>();
7310     for (const auto& listenerItem : noInteractionListeners) {
7311         SubmitNoInteractionMonitorTask(eventId, listenerItem);
7312     }
7313 }
7314 
IsUserOrientation(Orientation orientation) const7315 bool WindowSessionImpl::IsUserOrientation(Orientation orientation) const
7316 {
7317     if (orientation == Orientation::USER_ROTATION_PORTRAIT ||
7318         orientation == Orientation::USER_ROTATION_LANDSCAPE ||
7319         orientation == Orientation::USER_ROTATION_PORTRAIT_INVERTED ||
7320         orientation == Orientation::USER_ROTATION_LANDSCAPE_INVERTED) {
7321         return true;
7322     }
7323     return false;
7324 }
7325 
IsUserPageOrientation(Orientation orientation) const7326 bool WindowSessionImpl::IsUserPageOrientation(Orientation orientation) const
7327 {
7328     if (orientation == Orientation::USER_PAGE_ROTATION_PORTRAIT ||
7329         orientation == Orientation::USER_PAGE_ROTATION_LANDSCAPE ||
7330         orientation == Orientation::USER_PAGE_ROTATION_PORTRAIT_INVERTED ||
7331         orientation == Orientation::USER_PAGE_ROTATION_LANDSCAPE_INVERTED) {
7332         return true;
7333     }
7334     return false;
7335 }
7336 
IsVerticalOrientation(Orientation orientation) const7337 bool WindowSessionImpl::IsVerticalOrientation(Orientation orientation) const
7338 {
7339     if (orientation == Orientation::VERTICAL ||
7340         orientation == Orientation::REVERSE_VERTICAL ||
7341         orientation == Orientation::SENSOR_VERTICAL ||
7342         orientation == Orientation::AUTO_ROTATION_PORTRAIT_RESTRICTED ||
7343         orientation == Orientation::USER_ROTATION_PORTRAIT ||
7344         orientation == Orientation::USER_ROTATION_PORTRAIT_INVERTED) {
7345         return true;
7346     }
7347     return false;
7348 }
7349 
IsHorizontalOrientation(Orientation orientation) const7350 bool WindowSessionImpl::IsHorizontalOrientation(Orientation orientation) const
7351 {
7352     return orientation == Orientation::HORIZONTAL ||
7353            orientation == Orientation::REVERSE_HORIZONTAL ||
7354            orientation == Orientation::SENSOR_HORIZONTAL ||
7355            orientation == Orientation::AUTO_ROTATION_LANDSCAPE_RESTRICTED ||
7356            orientation == Orientation::USER_ROTATION_LANDSCAPE ||
7357            orientation == Orientation::USER_ROTATION_LANDSCAPE_INVERTED;
7358 }
7359 
GetCallingWindowWindowStatus(WindowStatus & windowStatus) const7360 WMError WindowSessionImpl::GetCallingWindowWindowStatus(WindowStatus& windowStatus) const
7361 {
7362     TLOGD(WmsLogTag::WMS_KEYBOARD, "id: %{public}d", GetPersistentId());
7363     if (IsWindowSessionInvalid()) {
7364         TLOGE(WmsLogTag::WMS_KEYBOARD, "session is invalid");
7365         return WMError::WM_ERROR_INVALID_WINDOW;
7366     }
7367     return SingletonContainer::Get<WindowAdapter>().GetCallingWindowWindowStatus(GetPersistentId(), windowStatus);
7368 }
7369 
GetCallingWindowRect(Rect & rect) const7370 WMError WindowSessionImpl::GetCallingWindowRect(Rect& rect) const
7371 {
7372     if (IsWindowSessionInvalid()) {
7373         TLOGE(WmsLogTag::WMS_KEYBOARD, "session is invalid");
7374         return WMError::WM_ERROR_INVALID_WINDOW;
7375     }
7376     return SingletonContainer::Get<WindowAdapter>().GetCallingWindowRect(GetPersistentId(), rect);
7377 }
7378 
SetUiDvsyncSwitch(bool dvsyncSwitch)7379 void WindowSessionImpl::SetUiDvsyncSwitch(bool dvsyncSwitch)
7380 {
7381     if (vsyncStation_ == nullptr) {
7382         TLOGW(WmsLogTag::WMS_MAIN, "vsyncStation is null");
7383         return;
7384     }
7385     vsyncStation_->SetUiDvsyncSwitch(dvsyncSwitch);
7386 }
7387 
SetTouchEvent(int32_t touchType)7388 void WindowSessionImpl::SetTouchEvent(int32_t touchType)
7389 {
7390     if (vsyncStation_ == nullptr) {
7391         TLOGW(WmsLogTag::WMS_MAIN, "vsyncStation is null");
7392         return;
7393     }
7394     vsyncStation_->SetTouchEvent(touchType);
7395 }
7396 
NotifyAppForceLandscapeConfigUpdated()7397 WSError WindowSessionImpl::NotifyAppForceLandscapeConfigUpdated()
7398 {
7399     return WSError::WS_DO_NOTHING;
7400 }
7401 
SetFrameLayoutCallbackEnable(bool enable)7402 void WindowSessionImpl::SetFrameLayoutCallbackEnable(bool enable)
7403 {
7404     enableFrameLayoutFinishCb_ = enable;
7405 }
7406 
UpdateFrameLayoutCallbackIfNeeded(WindowSizeChangeReason wmReason)7407 void WindowSessionImpl::UpdateFrameLayoutCallbackIfNeeded(WindowSizeChangeReason wmReason)
7408 {
7409     bool isDragInPcmode = IsFreeMultiWindowMode() && (wmReason == WindowSizeChangeReason::DRAG_END);
7410     if (wmReason == WindowSizeChangeReason::FULL_TO_SPLIT || wmReason == WindowSizeChangeReason::SPLIT_TO_FULL ||
7411         wmReason == WindowSizeChangeReason::FULL_TO_FLOATING || wmReason == WindowSizeChangeReason::FLOATING_TO_FULL ||
7412         isDragInPcmode) {
7413         TLOGI(WmsLogTag::WMS_MULTI_WINDOW, "enable framelayoutfinish callback reason:%{public}u", wmReason);
7414         SetFrameLayoutCallbackEnable(true);
7415     }
7416 }
7417 
SetContinueState(int32_t continueState)7418 WMError WindowSessionImpl::SetContinueState(int32_t continueState)
7419 {
7420     if (continueState > ContinueState::CONTINUESTATE_MAX || continueState < ContinueState::CONTINUESTATE_UNKNOWN) {
7421         TLOGE(WmsLogTag::WMS_MAIN, "continueState is invalid: %{public}d", continueState);
7422         return WMError::WM_ERROR_INVALID_PARAM;
7423     }
7424     property_->EditSessionInfo().continueState = static_cast<ContinueState>(continueState);
7425     return WMError::WM_OK;
7426 }
7427 
SetUIContentComplete()7428 void WindowSessionImpl::SetUIContentComplete()
7429 {
7430     bool setUIContentCompleted = false;
7431     if (setUIContentCompleted_.compare_exchange_strong(setUIContentCompleted, true)) {
7432         TLOGI(WmsLogTag::WMS_LIFE, "persistentId=%{public}d", GetPersistentId());
7433         handler_->RemoveTask(SET_UICONTENT_TIMEOUT_LISTENER_TASK_NAME + std::to_string(GetPersistentId()));
7434     } else {
7435         TLOGI(WmsLogTag::WMS_LIFE, "already SetUIContent, persistentId=%{public}d", GetPersistentId());
7436     }
7437 }
7438 
AddSetUIContentTimeoutCheck()7439 void WindowSessionImpl::AddSetUIContentTimeoutCheck()
7440 {
7441     const auto checkBeginTime =
7442         std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now())
7443             .time_since_epoch().count();
7444     auto task = [weakThis = wptr(this), checkBeginTime] {
7445         auto window = weakThis.promote();
7446         if (window == nullptr) {
7447             TLOGNI(WmsLogTag::WMS_LIFE, "window is nullptr");
7448             return;
7449         }
7450         if (window->setUIContentCompleted_.load()) {
7451             TLOGNI(WmsLogTag::WMS_LIFE, "already SetUIContent, persistentId=%{public}d", window->GetPersistentId());
7452             return;
7453         }
7454 
7455         const auto checkEndTime =
7456             std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now())
7457                 .time_since_epoch().count();
7458         if (checkEndTime - checkBeginTime > SET_UICONTENT_TIMEOUT_TIME_AFTER_FREEZE_MS) {
7459             TLOGNI(WmsLogTag::WMS_LIFE, "will start re-check after freeze, persistentId=%{public}d",
7460                 window->GetPersistentId());
7461             window->AddSetUIContentTimeoutCheck();
7462             return;
7463         }
7464 
7465         TLOGNW(WmsLogTag::WMS_LIFE, "SetUIContent timeout, persistentId=%{public}d", window->GetPersistentId());
7466         std::ostringstream oss;
7467         oss << "SetUIContent timeout uid: " << getuid();
7468         oss << ", windowName: " << window->GetWindowName();
7469         auto context = window->GetContext();
7470         if (context) {
7471             oss << ", bundleName: " << context->GetBundleName();
7472             if (context->GetApplicationInfo()) {
7473                 oss << ", abilityName: " << context->GetApplicationInfo()->name;
7474             }
7475         }
7476         SingletonContainer::Get<WindowInfoReporter>().ReportWindowException(
7477             static_cast<int32_t>(WindowDFXHelperType::WINDOW_TRANSPARENT_CHECK), getpid(), oss.str());
7478 
7479         if (WindowHelper::IsUIExtensionWindow(window->GetType())) {
7480             window->NotifyExtensionTimeout(TimeoutErrorCode::SET_UICONTENT_TIMEOUT);
7481         }
7482     };
7483     handler_->PostTask(task, SET_UICONTENT_TIMEOUT_LISTENER_TASK_NAME + std::to_string(GetPersistentId()),
7484         SET_UICONTENT_TIMEOUT_TIME_MS, AppExecFwk::EventQueue::Priority::HIGH);
7485 }
7486 
NotifySetUIContentComplete()7487 void WindowSessionImpl::NotifySetUIContentComplete()
7488 {
7489     if (WindowHelper::IsSubWindow(GetType()) || WindowHelper::IsSystemWindow(GetType())) {
7490         // created by UIExtension
7491         auto extWindow = FindExtensionWindowWithContext();
7492         if (extWindow != nullptr) {
7493             extWindow->SetUIContentComplete();
7494         }
7495     }
7496     SetUIContentComplete();
7497 }
7498 
SetUIExtensionDestroyComplete()7499 void WindowSessionImpl::SetUIExtensionDestroyComplete()
7500 {
7501     bool setUIExtensionDestroyCompleted = false;
7502     if (setUIExtensionDestroyCompleted_.compare_exchange_strong(setUIExtensionDestroyCompleted, true)) {
7503         TLOGI(WmsLogTag::WMS_LIFE, "persistentId=%{public}d", GetPersistentId());
7504         handler_->RemoveTask(SET_UIEXTENSION_DESTROY_TIMEOUT_LISTENER_TASK_NAME + std::to_string(GetPersistentId()));
7505     } else {
7506         TLOGI(WmsLogTag::WMS_LIFE, "already, persistentId=%{public}d", GetPersistentId());
7507     }
7508 }
7509 
SetUIExtensionDestroyCompleteInSubWindow()7510 void WindowSessionImpl::SetUIExtensionDestroyCompleteInSubWindow()
7511 {
7512     if (WindowHelper::IsSubWindow(GetType()) || WindowHelper::IsSystemWindow(GetType())) {
7513         bool startUIExtensionDestroyTimer = true;
7514         auto extensionWindow = FindExtensionWindowWithContext();
7515         if (extensionWindow != nullptr && extensionWindow->startUIExtensionDestroyTimer_.compare_exchange_strong(
7516             startUIExtensionDestroyTimer, false)) {
7517             TLOGI(WmsLogTag::WMS_LIFE, "called");
7518             extensionWindow->SetUIExtensionDestroyComplete();
7519             extensionWindow->setUIExtensionDestroyCompleted_.store(false);
7520         }
7521     }
7522 }
7523 
AddSetUIExtensionDestroyTimeoutCheck()7524 void WindowSessionImpl::AddSetUIExtensionDestroyTimeoutCheck()
7525 {
7526     const char* const where = __func__;
7527     auto task = [weakThis = wptr(this), where] {
7528         auto window = weakThis.promote();
7529         if (window == nullptr) {
7530             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s: window is nullptr", where);
7531             return;
7532         }
7533         if (window->setUIExtensionDestroyCompleted_.load()) {
7534             TLOGNI(WmsLogTag::WMS_LIFE, "%{public}s: already, persistentId=%{public}d", where,
7535                 window->GetPersistentId());
7536             return;
7537         }
7538 
7539         TLOGNI(WmsLogTag::WMS_LIFE, "%{public}s: timeout, persistentId=%{public}d", where, window->GetPersistentId());
7540         std::ostringstream oss;
7541         oss << "SetUIExtDestroy timeout uid: " << getuid();
7542         oss << ", windowName: " << window->GetWindowName();
7543         auto context = window->GetContext();
7544         if (context) {
7545             oss << ", bundleName: " << context->GetBundleName();
7546             if (context->GetApplicationInfo()) {
7547                 oss << ", abilityName: " << context->GetApplicationInfo()->name;
7548             }
7549         }
7550         SingletonContainer::Get<WindowInfoReporter>().ReportWindowException(
7551             static_cast<int32_t>(WindowDFXHelperType::WINDOW_TRANSPARENT_CHECK), getpid(), oss.str());
7552 
7553         if (WindowHelper::IsUIExtensionWindow(window->GetType())) {
7554             window->NotifyExtensionTimeout(TimeoutErrorCode::SET_UIEXTENSION_DESTROY_TIMEOUT);
7555         }
7556     };
7557     handler_->PostTask(task, SET_UIEXTENSION_DESTROY_TIMEOUT_LISTENER_TASK_NAME + std::to_string(GetPersistentId()),
7558         SET_UIEXTENSION_DESTROY_TIMEOUT_TIME_MS, AppExecFwk::EventQueue::Priority::HIGH);
7559     startUIExtensionDestroyTimer_.store(true);
7560 }
7561 
SetEnableDragBySystem(bool enableDrag)7562 WSError WindowSessionImpl::SetEnableDragBySystem(bool enableDrag)
7563 {
7564     TLOGE(WmsLogTag::WMS_LAYOUT, "enableDrag: %{public}d", enableDrag);
7565     property_->SetDragEnabled(enableDrag);
7566     hasSetEnableDrag_.store(true);
7567     return WSError::WS_OK;
7568 }
7569 
SetDragActivated(bool dragActivated)7570 WSError WindowSessionImpl::SetDragActivated(bool dragActivated)
7571 {
7572     dragActivated_ = dragActivated;
7573     return WSError::WS_OK;
7574 }
7575 
IsWindowDraggable()7576 bool WindowSessionImpl::IsWindowDraggable()
7577 {
7578     bool isDragEnabled = GetProperty()->GetDragEnabled();
7579     TLOGD(WmsLogTag::WMS_LAYOUT, "PersistentId: %{public}d, dragEnabled: %{public}d, dragActivate: %{public}d",
7580         GetPersistentId(), isDragEnabled, dragActivated_.load());
7581     return isDragEnabled && dragActivated_.load();
7582 }
7583 
SetTargetAPIVersion(uint32_t targetAPIVersion)7584 void WindowSessionImpl::SetTargetAPIVersion(uint32_t targetAPIVersion)
7585 {
7586     targetAPIVersion_ = targetAPIVersion;
7587 }
7588 
GetTargetAPIVersion() const7589 uint32_t WindowSessionImpl::GetTargetAPIVersion() const
7590 {
7591     return targetAPIVersion_;
7592 }
7593 
GetTargetAPIVersionByApplicationInfo() const7594 uint32_t WindowSessionImpl::GetTargetAPIVersionByApplicationInfo() const
7595 {
7596     return (context_ != nullptr && context_->GetApplicationInfo() != nullptr) ?
7597         static_cast<uint32_t>(context_->GetApplicationInfo()->apiTargetVersion) % API_VERSION_MOD :
7598         INVALID_TARGET_API_VERSION;
7599 }
7600 
IsDeviceFeatureCapableFor(const std::string & feature) const7601 bool WindowSessionImpl::IsDeviceFeatureCapableFor(const std::string& feature) const
7602 {
7603     if (context_ == nullptr || context_->GetHapModuleInfo() == nullptr) {
7604         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "window [%{public}d] context is nullptr", GetPersistentId());
7605         return false;
7606     }
7607     std::string deviceType = system::GetParameter("const.product.devicetype", "");
7608     std::map<std::string, std::vector<std::string>>& requiredDeviceFeatures =
7609         context_->GetHapModuleInfo()->requiredDeviceFeatures;
7610     if (requiredDeviceFeatures.find(deviceType) == requiredDeviceFeatures.end()) {
7611         return false;
7612     }
7613     auto& features = requiredDeviceFeatures[deviceType];
7614     return std::find(features.begin(), features.end(), feature) != features.end();
7615 }
7616 
IsDeviceFeatureCapableForFreeMultiWindow() const7617 bool WindowSessionImpl::IsDeviceFeatureCapableForFreeMultiWindow() const
7618 {
7619     static const std::string DEVICE_FEATURE_LARGE_SCREEN = "large_screen";
7620     return IsDeviceFeatureCapableFor(DEVICE_FEATURE_LARGE_SCREEN)
7621         && system::GetParameter("const.window.device_feature_support_type", "0") == "1";
7622 }
7623 
SetLayoutTransform(const Transform & transform)7624 void WindowSessionImpl::SetLayoutTransform(const Transform& transform)
7625 {
7626     std::lock_guard<std::recursive_mutex> lock(transformMutex_);
7627     layoutTransform_ = transform;
7628 }
7629 
GetLayoutTransform() const7630 Transform WindowSessionImpl::GetLayoutTransform() const
7631 {
7632     std::lock_guard<std::recursive_mutex> lock(transformMutex_);
7633     return layoutTransform_;
7634 }
7635 
UpdateCompatScaleInfo(const Transform & transform)7636 WMError WindowSessionImpl::UpdateCompatScaleInfo(const Transform& transform)
7637 {
7638     if (!WindowHelper::IsMainWindow(GetType()) || !IsInCompatScaleMode()) {
7639         TLOGD(WmsLogTag::WMS_COMPAT, "id:%{public}d not scale mode", GetPersistentId());
7640         return WMError::WM_DO_NOTHING;
7641     }
7642     compatScaleX_ = transform.scaleX_;
7643     compatScaleY_ = transform.scaleY_;
7644     AAFwk::Want want;
7645     want.SetParam(Extension::COMPAT_IS_SIMULATION_SCALE_FIELD, IsAdaptToSimulationScale());
7646     want.SetParam(Extension::COMPAT_IS_PROPORTION_SCALE_FIELD, IsAdaptToProportionalScale());
7647     want.SetParam(Extension::COMPAT_SCALE_X_FIELD, compatScaleX_);
7648     want.SetParam(Extension::COMPAT_SCALE_Y_FIELD, compatScaleY_);
7649     if (auto uiContent = GetUIContentSharedPtr()) {
7650         uiContent->SendUIExtProprty(static_cast<uint32_t>(Extension::Businesscode::SYNC_COMPAT_INFO),
7651             want, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
7652     }
7653     return WMError::WM_OK;
7654 }
7655 
SetCurrentTransform(const Transform & transform)7656 void WindowSessionImpl::SetCurrentTransform(const Transform& transform)
7657 {
7658     {
7659         std::lock_guard<std::mutex> lock(currentTransformMutex_);
7660         currentTransform_ = transform;
7661     }
7662     handler_->PostTask([weakThis = wptr(this), transform, where = __func__] {
7663         auto window = weakThis.promote();
7664         if (window == nullptr) {
7665             TLOGNE(WmsLogTag::WMS_COMPAT, "%{public}s window is null", where);
7666             return;
7667         }
7668         window->UpdateCompatScaleInfo(transform);
7669     }, __func__);
7670 }
7671 
GetCurrentTransform() const7672 Transform WindowSessionImpl::GetCurrentTransform() const
7673 {
7674     std::lock_guard<std::mutex> lock(currentTransformMutex_);
7675     return currentTransform_;
7676 }
7677 
RegisterWindowInspectorCallback()7678 void WindowSessionImpl::RegisterWindowInspectorCallback()
7679 {
7680     auto getWMSWindowListCallback = [weakThis = wptr(this)]() -> std::optional<WindowListInfo> {
7681         if (auto window = weakThis.promote()) {
7682             return std::make_optional<WindowListInfo>({
7683                 window->GetWindowName(), window->GetWindowId(),
7684                 static_cast<uint32_t>(window->GetType()), window->GetRect()
7685             });
7686         } else {
7687             return std::nullopt;
7688         }
7689     };
7690     WindowInspector::GetInstance().RegisterGetWMSWindowListCallback(GetWindowId(), std::move(getWMSWindowListCallback));
7691 }
7692 
SetCompatInfoInExtensionConfig(AAFwk::WantParams & want) const7693 void WindowSessionImpl::SetCompatInfoInExtensionConfig(AAFwk::WantParams& want) const
7694 {
7695     if (!IsInCompatScaleMode()) {
7696         TLOGD(WmsLogTag::WMS_COMPAT, "id:%{public}d not scale mode", GetPersistentId());
7697         return;
7698     }
7699     want.SetParam(Extension::COMPAT_IS_SIMULATION_SCALE_FIELD,
7700         AAFwk::Integer::Box(static_cast<int32_t>(IsAdaptToSimulationScale())));
7701     want.SetParam(Extension::COMPAT_IS_PROPORTION_SCALE_FIELD,
7702         AAFwk::Integer::Box(static_cast<int32_t>(IsAdaptToProportionalScale())));
7703     want.SetParam(Extension::COMPAT_SCALE_X_FIELD, AAFwk::Float::Box(compatScaleX_));
7704     want.SetParam(Extension::COMPAT_SCALE_Y_FIELD, AAFwk::Float::Box(compatScaleY_));
7705 }
7706 
GetExtensionConfig(AAFwk::WantParams & want) const7707 void WindowSessionImpl::GetExtensionConfig(AAFwk::WantParams& want) const
7708 {
7709     want.SetParam(Extension::CROSS_AXIS_FIELD, AAFwk::Integer::Box(static_cast<int32_t>(crossAxisState_.load())));
7710     bool isWaterfallMode = isFullScreenWaterfallMode_.load();
7711     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "waterfall: %{public}d, winId: %{public}u", isWaterfallMode, GetWindowId());
7712     want.SetParam(Extension::WATERFALL_MODE_FIELD, AAFwk::Integer::Box(static_cast<int32_t>(isWaterfallMode)));
7713     WindowType rootHostWindowType = (GetType() == WindowType::WINDOW_TYPE_UI_EXTENSION) ?
7714                                     GetRootHostWindowType() : GetType();
7715     want.SetParam(Extension::ROOT_HOST_WINDOW_TYPE_FIELD,
7716                   AAFwk::Integer::Box(static_cast<int32_t>(rootHostWindowType)));
7717     bool gestureBackEnable = true;
7718     GetGestureBackEnabled(gestureBackEnable);
7719     want.SetParam(Extension::GESTURE_BACK_ENABLED, AAFwk::Integer::Box(static_cast<int32_t>(gestureBackEnable)));
7720     want.SetParam(Extension::IMMERSIVE_MODE_ENABLED,
7721         AAFwk::Integer::Box(static_cast<int32_t>(GetImmersiveModeEnabledState())));
7722     bool isHostWindowDelayRaiseEnabled = IsWindowDelayRaiseEnabled();
7723     want.SetParam(Extension::HOST_WINDOW_DELAY_RAISE_STATE_FIELD,
7724         AAFwk::Integer::Box(static_cast<int32_t>(isHostWindowDelayRaiseEnabled)));
7725     SetCompatInfoInExtensionConfig(want);
7726 }
7727 
OnExtensionMessage(uint32_t code,int32_t persistentId,const AAFwk::Want & data)7728 WMError WindowSessionImpl::OnExtensionMessage(uint32_t code, int32_t persistentId, const AAFwk::Want& data)
7729 {
7730     switch (code) {
7731         case static_cast<uint32_t>(Extension::Businesscode::NOTIFY_HOST_WINDOW_TO_RAISE): {
7732             return HandleHostWindowRaise(code, persistentId, data);
7733             break;
7734         }
7735         case static_cast<uint32_t>(Extension::Businesscode::REGISTER_HOST_WINDOW_RECT_CHANGE_LISTENER): {
7736             return HandleRegisterHostWindowRectChangeListener(code, persistentId, data);
7737             break;
7738         }
7739         case static_cast<uint32_t>(Extension::Businesscode::UNREGISTER_HOST_WINDOW_RECT_CHANGE_LISTENER): {
7740             return HandleUnregisterHostWindowRectChangeListener(code, persistentId, data);
7741             break;
7742         }
7743         case static_cast<uint32_t>(Extension::Businesscode::REGISTER_KEYBOARD_DID_SHOW_LISTENER): {
7744             return HandleUIExtRegisterKeyboardDidShowListener(code, persistentId, data);
7745             break;
7746         }
7747         case static_cast<uint32_t>(Extension::Businesscode::UNREGISTER_KEYBOARD_DID_SHOW_LISTENER): {
7748             return HandleUIExtUnregisterKeyboardDidShowListener(code, persistentId, data);
7749             break;
7750         }
7751         case static_cast<uint32_t>(Extension::Businesscode::REGISTER_KEYBOARD_DID_HIDE_LISTENER): {
7752             return HandleUIExtRegisterKeyboardDidHideListener(code, persistentId, data);
7753             break;
7754         }
7755         case static_cast<uint32_t>(Extension::Businesscode::UNREGISTER_KEYBOARD_DID_HIDE_LISTENER): {
7756             return HandleUIExtUnregisterKeyboardDidHideListener(code, persistentId, data);
7757             break;
7758         }
7759         default: {
7760             TLOGI(WmsLogTag::WMS_UIEXT, "Message was not processed, businessCode: %{public}u", code);
7761             break;
7762         }
7763     }
7764     return WMError::WM_OK;
7765 }
7766 
HandleHostWindowRaise(uint32_t code,int32_t persistentId,const AAFwk::Want & data)7767 WMError WindowSessionImpl::HandleHostWindowRaise(uint32_t code, int32_t persistentId, const AAFwk::Want& data)
7768 {
7769     TLOGI(WmsLogTag::WMS_UIEXT, "businessCode: %{public}u", code);
7770     auto ret = RaiseToAppTopOnDrag();
7771     if (ret != WMError::WM_OK) {
7772         TLOGE(WmsLogTag::WMS_HIERARCHY, "Raise host window failed, winId: %{public}u, errCode: %{public}d",
7773             GetWindowId(), ret);
7774         return ret;
7775     }
7776     TLOGI(WmsLogTag::WMS_HIERARCHY, "Raise host window successfully, winId: %{public}u", GetWindowId());
7777     return WMError::WM_OK;
7778 }
7779 
HandleRegisterHostWindowRectChangeListener(uint32_t code,int32_t persistentId,const AAFwk::Want & data)7780 WMError WindowSessionImpl::HandleRegisterHostWindowRectChangeListener(uint32_t code, int32_t persistentId,
7781     const AAFwk::Want& data)
7782 {
7783     TLOGI(WmsLogTag::WMS_UIEXT, "businessCode: %{public}u", code);
7784     rectChangeUIExtListenerIds_.emplace(persistentId);
7785     TLOGI(WmsLogTag::WMS_UIEXT, "persistentId: %{public}d register rect change listener", persistentId);
7786     return WMError::WM_OK;
7787 }
7788 
HandleUnregisterHostWindowRectChangeListener(uint32_t code,int32_t persistentId,const AAFwk::Want & data)7789 WMError WindowSessionImpl::HandleUnregisterHostWindowRectChangeListener(uint32_t code, int32_t persistentId,
7790     const AAFwk::Want& data)
7791 {
7792     TLOGI(WmsLogTag::WMS_UIEXT, "businessCode: %{public}u", code);
7793     rectChangeUIExtListenerIds_.erase(persistentId);
7794     TLOGI(WmsLogTag::WMS_UIEXT, "persistentId: %{public}d unregister rect change listener", persistentId);
7795     return WMError::WM_OK;
7796 }
7797 
HandleUIExtRegisterKeyboardDidShowListener(uint32_t code,int32_t persistentId,const AAFwk::Want & data)7798 WMError WindowSessionImpl::HandleUIExtRegisterKeyboardDidShowListener(uint32_t code, int32_t persistentId,
7799     const AAFwk::Want& data)
7800 {
7801     if (keyboardDidShowUIExtListeners_.find(persistentId) == keyboardDidShowUIExtListeners_.end()) {
7802         sptr<IKeyboardDidShowListener> listener = sptr<IKeyboardDidShowListener>::MakeSptr();
7803         keyboardDidShowUIExtListeners_[persistentId] = listener;
7804         keyboardDidShowUIExtListenerIds_.emplace(persistentId);
7805         RegisterKeyboardDidShowListener(listener);
7806     }
7807     return WMError::WM_OK;
7808 }
7809 
HandleUIExtUnregisterKeyboardDidShowListener(uint32_t code,int32_t persistentId,const AAFwk::Want & data)7810 WMError WindowSessionImpl::HandleUIExtUnregisterKeyboardDidShowListener(uint32_t code, int32_t persistentId,
7811     const AAFwk::Want& data)
7812 {
7813     if (keyboardDidShowUIExtListeners_.find(persistentId) != keyboardDidShowUIExtListeners_.end()) {
7814         sptr<IKeyboardDidShowListener> listener = keyboardDidShowUIExtListeners_[persistentId];
7815         keyboardDidShowUIExtListeners_.erase(persistentId);
7816         keyboardDidShowUIExtListenerIds_.erase(persistentId);
7817         UnregisterKeyboardDidShowListener(listener);
7818     }
7819     return WMError::WM_OK;
7820 }
7821 
HandleUIExtRegisterKeyboardDidHideListener(uint32_t code,int32_t persistentId,const AAFwk::Want & data)7822 WMError WindowSessionImpl::HandleUIExtRegisterKeyboardDidHideListener(uint32_t code, int32_t persistentId,
7823     const AAFwk::Want& data)
7824 {
7825     if (keyboardDidHideUIExtListeners_.find(persistentId) == keyboardDidHideUIExtListeners_.end()) {
7826         sptr<IKeyboardDidHideListener> listener = sptr<IKeyboardDidHideListener>::MakeSptr();
7827         keyboardDidHideUIExtListeners_[persistentId] = listener;
7828         keyboardDidHideUIExtListenerIds_.emplace(persistentId);
7829         RegisterKeyboardDidHideListener(listener);
7830     }
7831     return WMError::WM_OK;
7832 }
7833 
HandleUIExtUnregisterKeyboardDidHideListener(uint32_t code,int32_t persistentId,const AAFwk::Want & data)7834 WMError WindowSessionImpl::HandleUIExtUnregisterKeyboardDidHideListener(uint32_t code, int32_t persistentId,
7835     const AAFwk::Want& data)
7836 {
7837     if (keyboardDidHideUIExtListeners_.find(persistentId) != keyboardDidHideUIExtListeners_.end()) {
7838         sptr<IKeyboardDidHideListener> listener = keyboardDidHideUIExtListeners_[persistentId];
7839         keyboardDidHideUIExtListeners_.erase(persistentId);
7840         keyboardDidHideUIExtListenerIds_.erase(persistentId);
7841         UnregisterKeyboardDidHideListener(listener);
7842     }
7843     return WMError::WM_OK;
7844 }
7845 
IsValidCrossState(int32_t state) const7846 bool WindowSessionImpl::IsValidCrossState(int32_t state) const
7847 {
7848     return state >= static_cast<int32_t>(CrossAxisState::STATE_INVALID) &&
7849         state < static_cast<int32_t>(CrossAxisState::STATE_END);
7850 }
7851 
UpdateSubWindowInfo(uint32_t subWindowLevel,const std::shared_ptr<AbilityRuntime::Context> & context)7852 void WindowSessionImpl::UpdateSubWindowInfo(uint32_t subWindowLevel,
7853     const std::shared_ptr<AbilityRuntime::Context>& context)
7854 {
7855     property_->SetSubWindowLevel(subWindowLevel);
7856     SetContext(context);
7857     std::vector<sptr<WindowSessionImpl>> subWindows;
7858     GetSubWindows(GetPersistentId(), subWindows);
7859     for (auto& subWindow : subWindows) {
7860         if (subWindow != nullptr) {
7861             subWindow->UpdateSubWindowInfo(subWindowLevel + 1, context);
7862         }
7863     }
7864 }
7865 
IsSubWindowMaximizeSupported() const7866 bool WindowSessionImpl::IsSubWindowMaximizeSupported() const
7867 {
7868     if (!WindowHelper::IsSubWindow(GetType())) {
7869         return false;
7870     }
7871     if (windowOption_ != nullptr) {
7872         return windowOption_->GetSubWindowMaximizeSupported();
7873     }
7874     return false;
7875 }
7876 
IsFullScreenPcAppInPadMode() const7877 bool WindowSessionImpl::IsFullScreenPcAppInPadMode() const
7878 {
7879     return property_->GetIsPcAppInPad() && GetWindowMode() == WindowMode::WINDOW_MODE_FULLSCREEN
7880         && !IsFreeMultiWindowMode();
7881 }
7882 
NotifyClientWindowSize()7883 void WindowSessionImpl::NotifyClientWindowSize()
7884 {
7885     if (IsFullScreenPcAppInPadMode()) {
7886         const auto& windowRect = GetRect();
7887         NotifySizeChange(windowRect, WindowSizeChangeReason::MOVE);
7888         auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
7889         sptr<DisplayInfo> displayInfo = display ? display->GetDisplayInfo() : nullptr;
7890         UpdateViewportConfig(windowRect, WindowSizeChangeReason::UNDEFINED, nullptr, displayInfo);
7891     }
7892 }
7893 
CheckMultiWindowRect(uint32_t & width,uint32_t & height)7894 WMError WindowSessionImpl::CheckMultiWindowRect(uint32_t& width, uint32_t& height)
7895 {
7896     const auto& requestRect = GetRequestRect();
7897 
7898     if (WindowHelper::IsSubWindow(GetType())) {
7899         auto mainWindow = FindMainWindowWithContext();
7900         if (mainWindow != nullptr && (mainWindow->GetWindowMode() == WindowMode::WINDOW_MODE_SPLIT_SECONDARY ||
7901                                       mainWindow->GetWindowMode() == WindowMode::WINDOW_MODE_SPLIT_PRIMARY)) {
7902             if (width == requestRect.width_ && height == requestRect.height_) {
7903                 TLOGW(WmsLogTag::WMS_LAYOUT, "Request same size in multiWindow will not update, return");
7904                 return WMError::WM_ERROR_INVALID_WINDOW;
7905             }
7906         }
7907     }
7908     return WMError::WM_OK;
7909 }
7910 
GetRouterStackInfo(std::string & routerStackInfo)7911 WMError WindowSessionImpl::GetRouterStackInfo(std::string& routerStackInfo)
7912 {
7913     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
7914     if (uiContent == nullptr) {
7915         TLOGE(WmsLogTag::WMS_LIFE, "uiContent is nullptr.");
7916         return WMError::WM_ERROR_NULLPTR;
7917     }
7918     TLOGI(WmsLogTag::WMS_LIFE, "id:%{public}d", GetPersistentId());
7919     routerStackInfo = uiContent->GetTopNavDestinationInfo();
7920     return WMError::WM_OK;
7921 }
7922 
NotifyRotationChange(const RotationChangeInfo & rotationChangeInfo)7923 RotationChangeResult WindowSessionImpl::NotifyRotationChange(const RotationChangeInfo& rotationChangeInfo)
7924 {
7925     TLOGI(WmsLogTag::WMS_ROTATION, "info type: %{public}d, orientation: %{public}d, "
7926         "rect:[%{public}d, %{public}d, %{public}d, %{public}d]", rotationChangeInfo.type_,
7927         rotationChangeInfo.orientation_, rotationChangeInfo.displayRect_.posX_,
7928         rotationChangeInfo.displayRect_.posY_, rotationChangeInfo.displayRect_.width_,
7929         rotationChangeInfo.displayRect_.height_);
7930     NotifyRotationChangeResultInner(rotationChangeInfo);
7931     RotationChangeResult rotationChangeResult = { RectType::RELATIVE_TO_SCREEN, { 0, 0, 0, 0 } };
7932     getRotationResultFuture_->ResetRotationResultLock();
7933     rotationChangeResult = getRotationResultFuture_->GetRotationResult(WINDOW_ROTATION_CHANGE);
7934     Rect resultRect = rotationChangeResult.windowRect_;
7935     if (CheckAndModifyWindowRect(resultRect.width_, resultRect.height_) != WMError::WM_OK ||
7936         CheckMultiWindowRect(resultRect.width_, resultRect.height_) != WMError::WM_OK) {
7937         rotationChangeResult.windowRect_.width_ = 0;
7938         rotationChangeResult.windowRect_.height_ = 0;
7939     }
7940     TLOGI(WmsLogTag::WMS_ROTATION, "result rectType: %{public}d, rect:[%{public}d, %{public}d, %{public}d, %{public}d]",
7941         rotationChangeResult.rectType_, rotationChangeResult.windowRect_.posX_, rotationChangeResult.windowRect_.posY_,
7942         rotationChangeResult.windowRect_.width_, rotationChangeResult.windowRect_.height_);
7943     return rotationChangeResult;
7944 }
7945 
NotifyRotationChangeResult(RotationChangeResult rotationChangeResult)7946 void WindowSessionImpl::NotifyRotationChangeResult(RotationChangeResult rotationChangeResult)
7947 {
7948     TLOGI(WmsLogTag::WMS_ROTATION, "release rotation change lock.");
7949     if (getRotationResultFuture_) {
7950         getRotationResultFuture_->OnUpdateRotationResult(rotationChangeResult);
7951     }
7952 }
7953 
NotifyRotationChangeResultInner(const RotationChangeInfo & rotationChangeInfo)7954 void WindowSessionImpl::NotifyRotationChangeResultInner(const RotationChangeInfo& rotationChangeInfo)
7955 {
7956     std::vector<sptr<IWindowRotationChangeListener>> windowRotationChangeListeners;
7957     {
7958         std::lock_guard<std::mutex> lockListener(windowRotationChangeListenerMutex_);
7959         windowRotationChangeListeners = GetListeners<IWindowRotationChangeListener>();
7960     }
7961     handler_->PostTask(
7962         [weakThis = wptr(this), windowRotationChangeListeners, rotationChangeInfo] {
7963             TLOGI(WmsLogTag::WMS_ROTATION, "post task to notify listener.");
7964             auto window = weakThis.promote();
7965             if (window == nullptr) {
7966                 TLOGE(WmsLogTag::WMS_ROTATION, "window is null");
7967                 return;
7968             }
7969             RotationChangeResult rotationChangeResult = { RectType::RELATIVE_TO_SCREEN, { 0, 0, 0, 0 } };
7970             for (auto& listener : windowRotationChangeListeners) {
7971                 if (listener == nullptr) {
7972                     continue;
7973                 }
7974                 listener->OnRotationChange(rotationChangeInfo, rotationChangeResult);
7975                 if (rotationChangeInfo.type_ == RotationChangeType::WINDOW_DID_ROTATE) {
7976                     continue;
7977                 }
7978             }
7979             window->NotifyRotationChangeResult(rotationChangeResult);
7980         }, __func__);
7981 }
7982 
SetCurrentRotation(int32_t currentRotation)7983 WSError WindowSessionImpl::SetCurrentRotation(int32_t currentRotation)
7984 {
7985     TLOGI(WmsLogTag::WMS_ROTATION, "currentRotation: %{public}d", currentRotation);
7986     if (currentRotation > FULL_CIRCLE_DEGREE || currentRotation < ZERO_CIRCLE_DEGREE) {
7987         TLOGE(WmsLogTag::WMS_ROTATION, "currentRotation is invalid: %{public}d", currentRotation);
7988         return WSError::WS_ERROR_INVALID_PARAM;
7989     }
7990     property_->EditSessionInfo().currentRotation_ = currentRotation;
7991     return WSError::WS_OK;
7992 }
7993 
SetContainerButtonStyle(const DecorButtonStyle & decorButtonStyle)7994 nlohmann::json WindowSessionImpl::SetContainerButtonStyle(const DecorButtonStyle& decorButtonStyle)
7995 {
7996     nlohmann::json decorJson;
7997     decorJson.emplace(BUTTON_BACKGROUND_CORNER_RADIUS, decorButtonStyle.buttonBackgroundCornerRadius);
7998     decorJson.emplace(BUTTON_BACKGROUND_SIZE, decorButtonStyle.buttonBackgroundSize);
7999     decorJson.emplace(BUTTON_ICON_SIZE, decorButtonStyle.buttonIconSize);
8000     decorJson.emplace(CLOSE_BUTTON_RIGHT_MARGIN, decorButtonStyle.closeButtonRightMargin);
8001     decorJson.emplace(BUTTON_COLOR_MODE, decorButtonStyle.colorMode);
8002     decorJson.emplace(BUTTON_SPACING_BETWEEN, decorButtonStyle.spacingBetweenButtons);
8003     return decorJson;
8004 }
8005 
GetRSUIDirector() const8006 std::shared_ptr<RSUIDirector> WindowSessionImpl::GetRSUIDirector() const
8007 {
8008     RETURN_IF_RS_CLIENT_MULTI_INSTANCE_DISABLED(nullptr);
8009     TLOGD(WmsLogTag::WMS_SCB, "%{public}s, windowId: %{public}u",
8010           RSAdapterUtil::RSUIDirectorToStr(rsUIDirector_).c_str(), GetWindowId());
8011     return rsUIDirector_;
8012 }
8013 
GetRSUIContext() const8014 std::shared_ptr<RSUIContext> WindowSessionImpl::GetRSUIContext() const
8015 {
8016     RETURN_IF_RS_CLIENT_MULTI_INSTANCE_DISABLED(nullptr);
8017     auto rsUIContext = rsUIDirector_ ? rsUIDirector_->GetRSUIContext() : nullptr;
8018     TLOGD(WmsLogTag::WMS_SCB, "%{public}s, windowId: %{public}u",
8019           RSAdapterUtil::RSUIContextToStr(rsUIContext).c_str(), GetWindowId());
8020     return rsUIContext;
8021 }
8022 
IsAnco() const8023 bool WindowSessionImpl::IsAnco() const
8024 {
8025     return property_->GetCollaboratorType() == static_cast<int32_t>(CollaboratorType::RESERVE_TYPE);
8026 }
8027 
OnPointDown(int32_t eventId,int32_t posX,int32_t posY)8028 bool WindowSessionImpl::OnPointDown(int32_t eventId, int32_t posX, int32_t posY)
8029 {
8030     auto hostSession = GetHostSession();
8031     if (!hostSession) {
8032         TLOGE(WmsLogTag::WMS_EVENT, "windowId:%{public}u,%{public}d", GetWindowId(), eventId);
8033         return false;
8034     }
8035 
8036     auto ret = hostSession->ProcessPointDownSession(posX, posY);
8037     TLOGD(WmsLogTag::WMS_EVENT, "windowId:%{public}u,%{public}d,%{public}d", GetWindowId(), eventId, ret);
8038     return ret == WSError::WS_OK;
8039 }
8040 
SetNavDestinationInfo(const std::string & navDestinationInfo)8041 void WindowSessionImpl::SetNavDestinationInfo(const std::string& navDestinationInfo)
8042 {
8043     navDestinationInfo_ = navDestinationInfo;
8044 }
8045 
SetIntentParam(const std::string & intentParam,const std::function<void ()> & loadPageCallback,bool isColdStart)8046 WMError WindowSessionImpl::SetIntentParam(const std::string& intentParam,
8047     const std::function<void()>& loadPageCallback, bool isColdStart)
8048 {
8049     TLOGI(WmsLogTag::WMS_LIFE, "in");
8050     intentParam_ = intentParam;
8051     loadPageCallback_ = loadPageCallback;
8052     isIntentColdStart_ = isColdStart;
8053     return WMError::WM_OK;
8054 }
8055 
GetPiPSettingSwitchStatus(bool & switchStatus) const8056 WMError WindowSessionImpl::GetPiPSettingSwitchStatus(bool& switchStatus) const
8057 {
8058     if (IsWindowSessionInvalid()) {
8059         TLOGE(WmsLogTag::WMS_PIP, "session is invalid");
8060         return WMError::WM_ERROR_INVALID_WINDOW;
8061     }
8062     return SingletonContainer::Get<WindowAdapter>().GetPiPSettingSwitchStatus(switchStatus);
8063 }
8064 
SwitchSubWindow(bool freeMultiWindowEnable,int32_t parentId)8065 void WindowSessionImpl::SwitchSubWindow(bool freeMultiWindowEnable, int32_t parentId)
8066 {
8067     std::lock_guard<std::recursive_mutex> lock(subWindowSessionMutex_);
8068     if (subWindowSessionMap_.count(parentId) == 0) {
8069         TLOGD(WmsLogTag::WMS_LAYOUT, "subWindowSessionMap is empty");
8070         return;
8071     }
8072     for (auto& subWindowSession : subWindowSessionMap_.at(parentId)) {
8073         if (subWindowSession &&
8074             subWindowSession->windowSystemConfig_.freeMultiWindowEnable_ != freeMultiWindowEnable) {
8075             subWindowSession->SetFreeMultiWindowMode(freeMultiWindowEnable);
8076             subWindowSession->UpdateTitleButtonVisibility();
8077             subWindowSession->UpdateDecorEnable(true);
8078             subWindowSession->UpdateEnableDragWhenSwitchMultiWindow(freeMultiWindowEnable);
8079             subWindowSession->SwitchSubWindow(freeMultiWindowEnable, subWindowSession->GetPersistentId());
8080         }
8081     }
8082 }
8083 
UpdateEnableDragWhenSwitchMultiWindow(bool enable)8084 void WindowSessionImpl::UpdateEnableDragWhenSwitchMultiWindow(bool enable)
8085 {
8086     if (hasSetEnableDrag_.load() || property_->IsDragResizeDisabled()) {
8087         TLOGI(WmsLogTag::WMS_LAYOUT, "EnableDrag is already set, id: %{public}d", GetPersistentId());
8088         return;
8089     }
8090     auto isSystemWindow = WindowHelper::IsSystemWindow(property_->GetWindowType());
8091     bool isDialog = WindowHelper::IsDialogWindow(property_->GetWindowType());
8092     bool isSystemCalling = property_->GetSystemCalling();
8093     TLOGI(WmsLogTag::WMS_LAYOUT, "windId: %{public}d, isSystemWindow: %{public}d, isDialog: %{public}d, "
8094         "isSystemCalling: %{public}d", GetPersistentId(), isSystemWindow, isDialog, isSystemCalling);
8095     if (!enable || (isSystemWindow && !isDialog && !isSystemCalling)) {
8096         property_->SetDragEnabled(false);
8097     } else {
8098         property_->SetDragEnabled(true);
8099     }
8100     UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_DRAGENABLED);
8101 }
8102 
SetNotifySizeChangeFlag(bool flag)8103 void WindowSessionImpl::SetNotifySizeChangeFlag(bool flag)
8104 {
8105     if (flag) {
8106         if (GetType() != WindowType::WINDOW_TYPE_FLOAT_NAVIGATION) {
8107             return;
8108         }
8109         if (GetRect() == GetRequestRect()) {
8110             return;
8111         }
8112         notifySizeChangeFlag_ = true;
8113         TLOGD(WmsLogTag::WMS_LAYOUT, "Set notify size change flag is true");
8114         return;
8115     }
8116     notifySizeChangeFlag_ = false;
8117 }
8118 
8119 } // namespace Rosen
8120 } // namespace OHOS
8121