• 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 #include <optional>
20 
21 #include <common/rs_common_def.h>
22 #include <filesystem>
23 #include <fstream>
24 #include <ipc_skeleton.h>
25 #include <hisysevent.h>
26 #include <parameters.h>
27 #ifdef IMF_ENABLE
28 #include <input_method_controller.h>
29 #endif // IMF_ENABLE
30 #include <transaction/rs_interfaces.h>
31 #include <transaction/rs_transaction.h>
32 
33 #include "anr_handler.h"
34 #include "color_parser.h"
35 #include "display_info.h"
36 #include "display_manager.h"
37 #include "hitrace_meter.h"
38 #include "session_permission.h"
39 #include "key_event.h"
40 #include "session/container/include/window_event_channel.h"
41 #include "session_manager/include/session_manager.h"
42 #include "vsync_station.h"
43 #include "window_adapter.h"
44 #include "window_manager_hilog.h"
45 #include "window_helper.h"
46 #include "color_parser.h"
47 #include "singleton_container.h"
48 #include "perform_reporter.h"
49 #include "picture_in_picture_manager.h"
50 #include "parameters.h"
51 
52 namespace OHOS::Accessibility {
53 class AccessibilityEventInfo;
54 }
55 namespace OHOS {
56 namespace Rosen {
57 namespace {
58 constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, HILOG_DOMAIN_WINDOW, "WindowSessionImpl"};
59 constexpr int32_t FULL_CIRCLE_DEGREE = 360;
60 constexpr int32_t ONE_FOURTH_FULL_CIRCLE_DEGREE = 90;
61 constexpr int32_t FORCE_SPLIT_MODE = 5;
62 
CheckIfNeedCommitRsTransaction(WindowSizeChangeReason wmReason)63 bool CheckIfNeedCommitRsTransaction(WindowSizeChangeReason wmReason)
64 {
65     if (wmReason == WindowSizeChangeReason::FULL_TO_SPLIT ||
66         wmReason == WindowSizeChangeReason::FULL_TO_FLOATING || wmReason == WindowSizeChangeReason::RECOVER ||
67         wmReason == WindowSizeChangeReason::MAXIMIZE) {
68         return false;
69     }
70     return true;
71 }
72 
FillViewportConfig(Rect rect,float density,int32_t orientation,uint32_t transformHint)73 Ace::ViewportConfig FillViewportConfig(Rect rect, float density, int32_t orientation, uint32_t transformHint)
74 {
75     Ace::ViewportConfig config;
76     config.SetSize(rect.width_, rect.height_);
77     config.SetPosition(rect.posX_, rect.posY_);
78     config.SetDensity(density);
79     config.SetOrientation(orientation);
80     config.SetTransformHint(transformHint);
81     return config;
82 }
83 }
84 
85 std::map<int32_t, std::vector<sptr<IWindowLifeCycle>>> WindowSessionImpl::lifecycleListeners_;
86 std::map<int32_t, std::vector<sptr<IDisplayMoveListener>>> WindowSessionImpl::displayMoveListeners_;
87 std::map<int32_t, std::vector<sptr<IWindowChangeListener>>> WindowSessionImpl::windowChangeListeners_;
88 std::map<int32_t, std::vector<sptr<IAvoidAreaChangedListener>>> WindowSessionImpl::avoidAreaChangeListeners_;
89 std::map<int32_t, std::vector<sptr<IDialogDeathRecipientListener>>> WindowSessionImpl::dialogDeathRecipientListeners_;
90 std::map<int32_t, std::vector<sptr<IDialogTargetTouchListener>>> WindowSessionImpl::dialogTargetTouchListener_;
91 std::map<int32_t, std::vector<sptr<IOccupiedAreaChangeListener>>> WindowSessionImpl::occupiedAreaChangeListeners_;
92 std::map<int32_t, std::vector<sptr<IScreenshotListener>>> WindowSessionImpl::screenshotListeners_;
93 std::map<int32_t, std::vector<sptr<ITouchOutsideListener>>> WindowSessionImpl::touchOutsideListeners_;
94 std::map<int32_t, std::vector<IWindowVisibilityListenerSptr>> WindowSessionImpl::windowVisibilityChangeListeners_;
95 std::map<int32_t, std::vector<IWindowNoInteractionListenerSptr>> WindowSessionImpl::windowNoInteractionListeners_;
96 std::map<int32_t, std::vector<sptr<IWindowTitleButtonRectChangedListener>>>
97     WindowSessionImpl::windowTitleButtonRectChangeListeners_;
98 std::map<int32_t, std::vector<sptr<IWindowRectChangeListener>>> WindowSessionImpl::windowRectChangeListeners_;
99 std::map<int32_t, sptr<ISubWindowCloseListener>> WindowSessionImpl::subWindowCloseListeners_;
100 std::map<int32_t, std::vector<sptr<ISwitchFreeMultiWindowListener>>> WindowSessionImpl::switchFreeMultiWindowListeners_;
101 std::recursive_mutex WindowSessionImpl::lifeCycleListenerMutex_;
102 std::recursive_mutex WindowSessionImpl::windowChangeListenerMutex_;
103 std::recursive_mutex WindowSessionImpl::avoidAreaChangeListenerMutex_;
104 std::recursive_mutex WindowSessionImpl::dialogDeathRecipientListenerMutex_;
105 std::recursive_mutex WindowSessionImpl::dialogTargetTouchListenerMutex_;
106 std::recursive_mutex WindowSessionImpl::occupiedAreaChangeListenerMutex_;
107 std::recursive_mutex WindowSessionImpl::screenshotListenerMutex_;
108 std::recursive_mutex WindowSessionImpl::touchOutsideListenerMutex_;
109 std::recursive_mutex WindowSessionImpl::windowVisibilityChangeListenerMutex_;
110 std::recursive_mutex WindowSessionImpl::windowNoInteractionListenerMutex_;
111 std::recursive_mutex WindowSessionImpl::windowStatusChangeListenerMutex_;
112 std::recursive_mutex WindowSessionImpl::windowTitleButtonRectChangeListenerMutex_;
113 std::mutex WindowSessionImpl::displayMoveListenerMutex_;
114 std::mutex WindowSessionImpl::windowRectChangeListenerMutex_;
115 std::mutex WindowSessionImpl::subWindowCloseListenersMutex_;
116 std::mutex WindowSessionImpl::switchFreeMultiWindowListenerMutex_;
117 std::map<std::string, std::pair<int32_t, sptr<WindowSessionImpl>>> WindowSessionImpl::windowSessionMap_;
118 std::shared_mutex WindowSessionImpl::windowSessionMutex_;
119 std::set<sptr<WindowSessionImpl>> WindowSessionImpl::windowExtensionSessionSet_;
120 std::shared_mutex WindowSessionImpl::windowExtensionSessionMutex_;
121 std::map<int32_t, std::vector<sptr<WindowSessionImpl>>> WindowSessionImpl::subWindowSessionMap_;
122 std::map<int32_t, std::vector<sptr<IWindowStatusChangeListener>>> WindowSessionImpl::windowStatusChangeListeners_;
123 bool WindowSessionImpl::isUIExtensionAbilityProcess_ = false;
124 
125 #define CALL_LIFECYCLE_LISTENER(windowLifecycleCb, listeners) \
126     do {                                                      \
127         for (auto& listener : (listeners)) {                  \
128             if (listener != nullptr) {            \
129                 listener->windowLifecycleCb();    \
130             }                                                 \
131         }                                                     \
132     } while (0)
133 
134 #define CALL_LIFECYCLE_LISTENER_WITH_PARAM(windowLifecycleCb, listeners, param) \
135     do {                                                                        \
136         for (auto& listener : (listeners)) {                                    \
137             if (listener != nullptr) {                                         \
138                 listener->windowLifecycleCb(param);                 \
139             }                                                                   \
140         }                                                                       \
141     } while (0)
142 
143 #define CALL_UI_CONTENT(uiContentCb)                                           \
144     do {                                                                       \
145         std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();   \
146         if (uiContent != nullptr) {                                            \
147             uiContent->uiContentCb();                                          \
148         }                                                                      \
149     } while (0)
150 
151 #define CHECK_HOST_SESSION_RETURN_IF_NULL(hostSession)                         \
152     do {                                                                       \
153         if ((hostSession) == nullptr) {                                        \
154             TLOGE(WmsLogTag::DEFAULT, "hostSession is null");                  \
155             return;                                                            \
156         }                                                                      \
157     } while (false)
158 
159 #define CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, ret)              \
160     do {                                                                       \
161         if ((hostSession) == nullptr) {                                        \
162             TLOGE(WmsLogTag::DEFAULT, "hostSession is null");                  \
163             return ret;                                                        \
164         }                                                                      \
165     } while (false)
166 
WindowSessionImpl(const sptr<WindowOption> & option)167 WindowSessionImpl::WindowSessionImpl(const sptr<WindowOption>& option)
168 {
169     WLOGFD("[WMSCom]WindowSessionImpl");
170     property_ = new (std::nothrow) WindowSessionProperty();
171     if (property_ == nullptr) {
172         WLOGFE("[WMSCom]Property is null");
173         return;
174     }
175     WindowType optionWindowType = option->GetWindowType();
176     SessionInfo sessionInfo;
177     sessionInfo.bundleName_ = option->GetBundleName();
178     property_->SetSessionInfo(sessionInfo);
179     property_->SetWindowName(option->GetWindowName());
180     property_->SetRequestRect(option->GetWindowRect());
181     property_->SetWindowType(optionWindowType);
182     property_->SetFocusable(option->GetFocusable());
183     property_->SetTouchable(option->GetTouchable());
184     property_->SetDisplayId(option->GetDisplayId());
185     property_->SetParentId(option->GetParentId());
186     property_->SetTurnScreenOn(option->IsTurnScreenOn());
187     property_->SetKeepScreenOn(option->IsKeepScreenOn());
188     property_->SetWindowMode(option->GetWindowMode());
189     property_->SetWindowFlags(option->GetWindowFlags());
190     property_->SetCallingSessionId(option->GetCallingWindow());
191     property_->SetExtensionFlag(option->GetExtensionTag());
192     property_->SetTopmost(option->GetWindowTopmost());
193     property_->SetRealParentId(option->GetRealParentId());
194     property_->SetParentWindowType(option->GetParentWindowType());
195     property_->SetUIExtensionUsage(static_cast<UIExtensionUsage>(option->GetUIExtensionUsage()));
196     layoutCallback_ = sptr<FutureCallback>::MakeSptr();
197     property_->SetIsUIExtensionSubWindowFlag(option->GetIsUIExtensionSubWindowFlag());
198     isMainHandlerAvailable_ = option->GetMainHandlerAvailable();
199     isIgnoreSafeArea_ = WindowHelper::IsSubWindow(optionWindowType);
200     windowOption_ = option;
201     surfaceNode_ = CreateSurfaceNode(property_->GetWindowName(), optionWindowType);
202     handler_ = std::make_shared<AppExecFwk::EventHandler>(AppExecFwk::EventRunner::GetMainEventRunner());
203     if (surfaceNode_ != nullptr) {
204         vsyncStation_ = std::make_shared<VsyncStation>(surfaceNode_->GetId());
205         if (WindowHelper::IsSubWindow(GetType())) {
206             surfaceNode_->SetFrameGravity(Gravity::TOP_LEFT);
207         }
208     }
209 }
210 
IsPcOrPadCapabilityEnabled() const211 bool WindowSessionImpl::IsPcOrPadCapabilityEnabled() const
212 {
213     return windowSystemConfig_.uiType_ == UI_TYPE_PC ||
214            IsFreeMultiWindowMode() || property_->GetIsPcAppInPad();
215 }
216 
MakeSubOrDialogWindowDragableAndMoveble()217 void WindowSessionImpl::MakeSubOrDialogWindowDragableAndMoveble()
218 {
219     TLOGI(WmsLogTag::WMS_LIFE, "Called %{public}d.", GetPersistentId());
220     if (IsPcOrPadCapabilityEnabled() && windowOption_ != nullptr) {
221         if (WindowHelper::IsSubWindow(property_->GetWindowType())) {
222             TLOGI(WmsLogTag::WMS_LIFE, "create subwindow, title: %{public}s, decorEnable: %{public}d",
223                 windowOption_->GetSubWindowTitle().c_str(), windowOption_->GetSubWindowDecorEnable());
224             property_->SetDecorEnable(windowOption_->GetSubWindowDecorEnable());
225             property_->SetDragEnabled(windowOption_->GetSubWindowDecorEnable());
226             subWindowTitle_ = windowOption_->GetSubWindowTitle();
227         }
228         bool isDialog = WindowHelper::IsDialogWindow(property_->GetWindowType());
229         if (isDialog) {
230             bool dialogDecorEnable = windowOption_->GetDialogDecorEnable();
231             property_->SetDecorEnable(dialogDecorEnable);
232             property_->SetDragEnabled(dialogDecorEnable);
233             dialogTitle_ = windowOption_->GetDialogTitle();
234             TLOGI(WmsLogTag::WMS_LIFE, "create dialogWindow, title: %{public}s, decorEnable: %{public}d",
235                 dialogTitle_.c_str(), dialogDecorEnable);
236         }
237     }
238 }
239 
CreateSurfaceNode(std::string name,WindowType type)240 RSSurfaceNode::SharedPtr WindowSessionImpl::CreateSurfaceNode(std::string name, WindowType type)
241 {
242     struct RSSurfaceNodeConfig rsSurfaceNodeConfig;
243     rsSurfaceNodeConfig.SurfaceNodeName = name;
244     RSSurfaceNodeType rsSurfaceNodeType = RSSurfaceNodeType::DEFAULT;
245     switch (type) {
246         case WindowType::WINDOW_TYPE_BOOT_ANIMATION:
247         case WindowType::WINDOW_TYPE_POINTER:
248             rsSurfaceNodeType = RSSurfaceNodeType::SELF_DRAWING_WINDOW_NODE;
249             break;
250         case WindowType::WINDOW_TYPE_APP_MAIN_WINDOW:
251             rsSurfaceNodeType = RSSurfaceNodeType::APP_WINDOW_NODE;
252             break;
253         case WindowType::WINDOW_TYPE_UI_EXTENSION:
254             TLOGI(WmsLogTag::WMS_LIFE, "uiExtensionUsage = %{public}u", property_->GetUIExtensionUsage());
255             if (property_->GetUIExtensionUsage() == UIExtensionUsage::CONSTRAINED_EMBEDDED) {
256                 rsSurfaceNodeType = RSSurfaceNodeType::UI_EXTENSION_SECURE_NODE;
257             } else {
258                 rsSurfaceNodeType = RSSurfaceNodeType::UI_EXTENSION_COMMON_NODE;
259             }
260             break;
261         case WindowType::WINDOW_TYPE_PIP:
262             rsSurfaceNodeType = RSSurfaceNodeType::APP_WINDOW_NODE;
263             break;
264         default:
265             rsSurfaceNodeType = RSSurfaceNodeType::DEFAULT;
266             break;
267     }
268     return RSSurfaceNode::Create(rsSurfaceNodeConfig, rsSurfaceNodeType);
269 }
270 
~WindowSessionImpl()271 WindowSessionImpl::~WindowSessionImpl()
272 {
273     WLOGFD("[WMSCom]~WindowSessionImpl, id: %{public}d", GetPersistentId());
274     Destroy(true, false);
275 }
276 
GetWindowId() const277 uint32_t WindowSessionImpl::GetWindowId() const
278 {
279     return static_cast<uint32_t>(GetPersistentId()) & 0xffffffff; // 0xffffffff: to get low 32 bits
280 }
281 
GetDisplayId() const282 uint64_t WindowSessionImpl::GetDisplayId() const
283 {
284     return property_->GetDisplayId();
285 }
286 
GetParentId() const287 int32_t WindowSessionImpl::GetParentId() const
288 {
289     // 0xffffffff: to get low 32 bits
290     uint32_t parentID = static_cast<uint32_t>(property_->GetParentPersistentId()) & 0x7fffffff;
291     return static_cast<int32_t>(parentID);
292 }
293 
IsWindowSessionInvalid() const294 bool WindowSessionImpl::IsWindowSessionInvalid() const
295 {
296     bool res = ((GetHostSession() == nullptr) || (GetPersistentId() == INVALID_SESSION_ID) ||
297         (state_ == WindowState::STATE_DESTROYED));
298     if (res) {
299         TLOGW(WmsLogTag::WMS_LIFE, "already destroyed or not created! id: %{public}d state_: %{public}u",
300             GetPersistentId(), state_);
301     }
302     return res;
303 }
304 
IsMainHandlerAvailable() const305 bool WindowSessionImpl::IsMainHandlerAvailable() const
306 {
307     TLOGI(WmsLogTag::DEFAULT, "id:%{public}d, isAvailable:%{public}u",
308         GetPersistentId(), isMainHandlerAvailable_);
309     return isMainHandlerAvailable_;
310 }
311 
GetPersistentId() const312 int32_t WindowSessionImpl::GetPersistentId() const
313 {
314     if (property_) {
315         return property_->GetPersistentId();
316     }
317     return INVALID_SESSION_ID;
318 }
319 
GetProperty() const320 sptr<WindowSessionProperty> WindowSessionImpl::GetProperty() const
321 {
322     return property_;
323 }
324 
GetSystemSessionConfig() const325 SystemSessionConfig WindowSessionImpl::GetSystemSessionConfig() const
326 {
327     return windowSystemConfig_;
328 }
329 
GetHostSession() const330 sptr<ISession> WindowSessionImpl::GetHostSession() const
331 {
332     std::lock_guard<std::mutex> lock(hostSessionMutex_);
333     return hostSession_;
334 }
335 
GetColorSpaceFromSurfaceGamut(GraphicColorGamut colorGamut)336 ColorSpace WindowSessionImpl::GetColorSpaceFromSurfaceGamut(GraphicColorGamut colorGamut)
337 {
338     if (colorGamut == GraphicColorGamut::GRAPHIC_COLOR_GAMUT_SRGB) {
339         return ColorSpace::COLOR_SPACE_DEFAULT;
340     } else if (colorGamut == GraphicColorGamut::GRAPHIC_COLOR_GAMUT_DCI_P3) {
341         return ColorSpace::COLOR_SPACE_WIDE_GAMUT;
342     } else {
343         WLOGFE("try to get not exist ColorSpace");
344         return ColorSpace::COLOR_SPACE_DEFAULT;
345     }
346 }
347 
GetSurfaceGamutFromColorSpace(ColorSpace colorSpace)348 GraphicColorGamut WindowSessionImpl::GetSurfaceGamutFromColorSpace(ColorSpace colorSpace)
349 {
350     if (colorSpace == ColorSpace::COLOR_SPACE_DEFAULT) {
351         return GraphicColorGamut::GRAPHIC_COLOR_GAMUT_SRGB;
352     } else if (colorSpace == ColorSpace::COLOR_SPACE_WIDE_GAMUT) {
353         return GraphicColorGamut::GRAPHIC_COLOR_GAMUT_DCI_P3;
354     } else {
355         WLOGFE("try to get not exist colorGamut");
356         return GraphicColorGamut::GRAPHIC_COLOR_GAMUT_SRGB;
357     }
358 }
359 
IsSupportWideGamut()360 bool WindowSessionImpl::IsSupportWideGamut()
361 {
362     return true;
363 }
364 
SetColorSpace(ColorSpace colorSpace)365 void WindowSessionImpl::SetColorSpace(ColorSpace colorSpace)
366 {
367     if (IsWindowSessionInvalid() || surfaceNode_ == nullptr) {
368         TLOGE(WmsLogTag::DEFAULT, "session is invalid");
369         return;
370     }
371     auto colorGamut = GetSurfaceGamutFromColorSpace(colorSpace);
372     surfaceNode_->SetColorSpace(colorGamut);
373 }
374 
GetColorSpace()375 ColorSpace WindowSessionImpl::GetColorSpace()
376 {
377     if (IsWindowSessionInvalid() || surfaceNode_ == nullptr) {
378         TLOGE(WmsLogTag::DEFAULT, "session is invalid");
379         return ColorSpace::COLOR_SPACE_DEFAULT;
380     }
381     GraphicColorGamut colorGamut = surfaceNode_->GetColorSpace();
382     return GetColorSpaceFromSurfaceGamut(colorGamut);
383 }
384 
WindowSessionCreateCheck()385 WMError WindowSessionImpl::WindowSessionCreateCheck()
386 {
387     if (!property_ || vsyncStation_ == nullptr || !vsyncStation_->IsVsyncReceiverCreated()) {
388         return WMError::WM_ERROR_NULLPTR;
389     }
390     const auto& name = property_->GetWindowName();
391     std::shared_lock<std::shared_mutex> lock(windowSessionMutex_);
392     // check window name, same window names are forbidden
393     if (windowSessionMap_.find(name) != windowSessionMap_.end()) {
394         WLOGFE("WindowName(%{public}s) already exists.", name.c_str());
395         return WMError::WM_ERROR_REPEAT_OPERATION;
396     }
397 
398     // check if camera floating window is already exists
399     if (property_->GetWindowType() == WindowType::WINDOW_TYPE_FLOAT_CAMERA ||
400         property_->GetWindowType() == WindowType::WINDOW_TYPE_PIP) {
401         for (const auto& item : windowSessionMap_) {
402             if (item.second.second && item.second.second->property_ &&
403                 item.second.second->property_->GetWindowType() == WindowType::WINDOW_TYPE_FLOAT_CAMERA) {
404                     WLOGFE("Camera floating window is already exists.");
405                 return WMError::WM_ERROR_REPEAT_OPERATION;
406             }
407         }
408         uint32_t accessTokenId = static_cast<uint32_t>(IPCSkeleton::GetCallingTokenID());
409         property_->SetAccessTokenId(accessTokenId);
410         TLOGI(WmsLogTag::DEFAULT, "Create camera float window, TokenId = %{private}u", accessTokenId);
411     }
412     return WMError::WM_OK;
413 }
414 
SetDefaultDisplayIdIfNeed()415 void WindowSessionImpl::SetDefaultDisplayIdIfNeed()
416 {
417     TLOGI(WmsLogTag::WMS_LIFE, "Called");
418     auto displayId = property_->GetDisplayId();
419     if (displayId == DISPLAY_ID_INVALID) {
420         auto defaultDisplayId = SingletonContainer::IsDestroyed() ? DISPLAY_ID_INVALID :
421             SingletonContainer::Get<DisplayManager>().GetDefaultDisplayId();
422         defaultDisplayId = (defaultDisplayId == DISPLAY_ID_INVALID) ? 0 : defaultDisplayId;
423         property_->SetDisplayId(defaultDisplayId);
424         TLOGI(WmsLogTag::WMS_LIFE, "Reset displayId to %{public}" PRIu64, defaultDisplayId);
425     }
426 }
427 
Create(const std::shared_ptr<AbilityRuntime::Context> & context,const sptr<Rosen::ISession> & iSession,const std::string & identityToken)428 WMError WindowSessionImpl::Create(const std::shared_ptr<AbilityRuntime::Context>& context,
429     const sptr<Rosen::ISession>& iSession, const std::string& identityToken)
430 {
431     return WMError::WM_OK;
432 }
433 
Connect()434 WMError WindowSessionImpl::Connect()
435 {
436     TLOGI(WmsLogTag::WMS_LIFE, "Called");
437     auto hostSession = GetHostSession();
438     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_NULLPTR);
439     sptr<ISessionStage> iSessionStage(this);
440     auto windowEventChannel = new (std::nothrow) WindowEventChannel(iSessionStage);
441     if (windowEventChannel && property_) {
442         windowEventChannel->SetIsUIExtension(property_->GetWindowType() == WindowType::WINDOW_TYPE_UI_EXTENSION);
443         windowEventChannel->SetUIExtensionUsage(property_->GetUIExtensionUsage());
444     }
445     sptr<IWindowEventChannel> iWindowEventChannel(windowEventChannel);
446     sptr<IRemoteObject> token = context_ ? context_->GetToken() : nullptr;
447     if (token) {
448         property_->SetTokenState(true);
449     }
450     auto ret = hostSession->Connect(
451         iSessionStage, iWindowEventChannel, surfaceNode_, windowSystemConfig_, property_,
452         token, identityToken_);
453     TLOGI(WmsLogTag::WMS_LIFE, "Window Connect [name:%{public}s, id:%{public}d, type:%{public}u], ret:%{public}u",
454         property_->GetWindowName().c_str(), GetPersistentId(), property_->GetWindowType(), ret);
455     return static_cast<WMError>(ret);
456 }
457 
ConsumePointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)458 void WindowSessionImpl::ConsumePointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
459 {
460     NotifyPointerEvent(pointerEvent);
461 }
462 
ConsumeKeyEvent(std::shared_ptr<MMI::KeyEvent> & keyEvent)463 void WindowSessionImpl::ConsumeKeyEvent(std::shared_ptr<MMI::KeyEvent>& keyEvent)
464 {
465     bool isConsumed = false;
466     NotifyKeyEvent(keyEvent, isConsumed, false);
467 }
468 
PreNotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent)469 bool WindowSessionImpl::PreNotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
470 {
471     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
472     if (uiContent != nullptr) {
473         return uiContent->ProcessKeyEvent(keyEvent, true);
474     }
475     return false;
476 }
477 
NotifyOnKeyPreImeEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent)478 bool WindowSessionImpl::NotifyOnKeyPreImeEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
479 {
480     return PreNotifyKeyEvent(keyEvent);
481 }
482 
UpdateSubWindowStateAndNotify(int32_t parentPersistentId,const WindowState newState)483 void WindowSessionImpl::UpdateSubWindowStateAndNotify(int32_t parentPersistentId, const WindowState newState)
484 {
485     auto iter = subWindowSessionMap_.find(parentPersistentId);
486     if (iter == subWindowSessionMap_.end()) {
487         TLOGD(WmsLogTag::WMS_SUB, "parent window: %{public}d has no child node", parentPersistentId);
488         return;
489     }
490     const auto& subWindows = iter->second;
491     if (subWindows.empty()) {
492         TLOGD(WmsLogTag::WMS_SUB, "parent window: %{public}d, its subWindowMap is empty", parentPersistentId);
493         return;
494     }
495 
496     // when parent window hide and subwindow whose state is shown should hide and notify user
497     if (newState == WindowState::STATE_HIDDEN) {
498         for (auto subwindow : subWindows) {
499             if (subwindow != nullptr && subwindow->GetWindowState() == WindowState::STATE_SHOWN) {
500                 subwindow->state_ = WindowState::STATE_HIDDEN;
501                 subwindow->NotifyAfterBackground();
502                 TLOGD(WmsLogTag::WMS_SUB, "Notify subWindow background, id:%{public}d", subwindow->GetPersistentId());
503                 UpdateSubWindowStateAndNotify(subwindow->GetPersistentId(), newState);
504             }
505         }
506     // when parent window show and subwindow whose state is shown should show and notify user
507     } else if (newState == WindowState::STATE_SHOWN) {
508         for (auto subwindow : subWindows) {
509             if (subwindow != nullptr && subwindow->GetWindowState() == WindowState::STATE_HIDDEN &&
510                 subwindow->GetRequestWindowState() == WindowState::STATE_SHOWN) {
511                 subwindow->state_ = WindowState::STATE_SHOWN;
512                 subwindow->NotifyAfterForeground();
513                 TLOGD(WmsLogTag::WMS_SUB, "Notify subWindow foreground, id:%{public}d", subwindow->GetPersistentId());
514                 UpdateSubWindowStateAndNotify(subwindow->GetPersistentId(), newState);
515             }
516         }
517     }
518 }
519 
Show(uint32_t reason,bool withAnimation,bool withFocus)520 WMError WindowSessionImpl::Show(uint32_t reason, bool withAnimation, bool withFocus)
521 {
522     TLOGI(WmsLogTag::WMS_LIFE, "name:%{public}s, id:%{public}d, type:%{public}u, reason:%{public}u, state:%{public}u",
523         property_->GetWindowName().c_str(), property_->GetPersistentId(), GetType(), reason, state_);
524     if (IsWindowSessionInvalid()) {
525         WLOGFE("session is invalid");
526         return WMError::WM_ERROR_INVALID_WINDOW;
527     }
528     if (state_ == WindowState::STATE_SHOWN) {
529         TLOGD(WmsLogTag::WMS_LIFE, "window session is alreay shown [name:%{public}s, id:%{public}d, type: %{public}u]",
530             property_->GetWindowName().c_str(), GetPersistentId(), property_->GetWindowType());
531         NotifyAfterForeground(true, false);
532         return WMError::WM_OK;
533     }
534 
535     auto hostSession = GetHostSession();
536     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
537     WSError ret = hostSession->Foreground(property_);
538     // delete after replace WSError with WMError
539     WMError res = static_cast<WMError>(ret);
540     if (res == WMError::WM_OK) {
541         UpdateSubWindowStateAndNotify(GetPersistentId(), WindowState::STATE_SHOWN);
542         state_ = WindowState::STATE_SHOWN;
543         requestState_ = WindowState::STATE_SHOWN;
544         NotifyAfterForeground();
545     } else {
546         NotifyForegroundFailed(res);
547     }
548     return res;
549 }
550 
Hide(uint32_t reason,bool withAnimation,bool isFromInnerkits)551 WMError WindowSessionImpl::Hide(uint32_t reason, bool withAnimation, bool isFromInnerkits)
552 {
553     TLOGI(WmsLogTag::WMS_LIFE, "id:%{public}d Hide, reason:%{public}u, state:%{public}u",
554         GetPersistentId(), reason, state_);
555     if (IsWindowSessionInvalid()) {
556         WLOGFE("session is invalid");
557         return WMError::WM_ERROR_INVALID_WINDOW;
558     }
559     if (state_ == WindowState::STATE_HIDDEN || state_ == WindowState::STATE_CREATED) {
560         TLOGD(WmsLogTag::WMS_LIFE, "window session is alreay hidden [name:%{public}s, id:%{public}d, type: %{public}u]",
561             property_->GetWindowName().c_str(), GetPersistentId(), property_->GetWindowType());
562         NotifyBackgroundFailed(WMError::WM_DO_NOTHING);
563         return WMError::WM_OK;
564     }
565     UpdateSubWindowStateAndNotify(GetPersistentId(), WindowState::STATE_HIDDEN);
566     state_ = WindowState::STATE_HIDDEN;
567     requestState_ = WindowState::STATE_HIDDEN;
568     NotifyAfterBackground();
569     return WMError::WM_OK;
570 }
571 
DestroySubWindow()572 void WindowSessionImpl::DestroySubWindow()
573 {
574     int32_t parentPersistentId = property_->GetParentPersistentId();
575     const int32_t persistentId = GetPersistentId();
576     if (property_->GetExtensionFlag() == true) {
577         auto extensionWindow = FindExtensionWindowWithContext();
578         if (extensionWindow != nullptr) {
579             parentPersistentId = extensionWindow->GetPersistentId();
580         }
581     }
582     TLOGI(WmsLogTag::WMS_SUB, "Id: %{public}d, parentId: %{public}d", persistentId, parentPersistentId);
583     // remove from subWindowMap_ when destroy sub window
584     auto subIter = subWindowSessionMap_.find(parentPersistentId);
585     if (subIter != subWindowSessionMap_.end()) {
586         auto& subWindows = subIter->second;
587         for (auto iter = subWindows.begin(); iter != subWindows.end(); iter++) {
588             auto subWindow = *iter;
589             if (subWindow == nullptr) {
590                 continue;
591             }
592             if (subWindow->GetPersistentId() == persistentId) {
593                 TLOGD(WmsLogTag::WMS_SUB, "Destroy sub window, persistentId: %{public}d", persistentId);
594                 subWindows.erase(iter);
595                 break;
596             } else {
597                 TLOGD(WmsLogTag::WMS_SUB, "Exists other sub window, persistentId: %{public}d", persistentId);
598             }
599         }
600     }
601     // remove from subWindowMap_ when destroy parent window
602     auto mainIter = subWindowSessionMap_.find(persistentId);
603     if (mainIter != subWindowSessionMap_.end()) {
604         auto& subWindows = mainIter->second;
605         for (auto iter = subWindows.begin(); iter != subWindows.end(); iter = subWindows.begin()) {
606             auto subWindow = *iter;
607             if (subWindow == nullptr) {
608                 TLOGW(WmsLogTag::WMS_SUB, "Destroy sub window which is nullptr");
609                 subWindows.erase(iter);
610                 continue;
611             }
612             bool isExtDestroyed = subWindow->property_->GetExtensionFlag();
613             TLOGD(WmsLogTag::WMS_SUB, "Destroy sub window, persistentId: %{public}d, isExtDestroyed: %{public}d",
614                 subWindow->GetPersistentId(), isExtDestroyed);
615             auto ret = subWindow->Destroy(isExtDestroyed);
616             if (ret != WMError::WM_OK) {
617                 TLOGE(WmsLogTag::WMS_SUB, "Destroy failed. persistentId: %{public}d", subWindow->GetPersistentId());
618                 subWindows.erase(iter);
619             }
620         }
621         mainIter->second.clear();
622         subWindowSessionMap_.erase(mainIter);
623     }
624 }
625 
Destroy(bool needNotifyServer,bool needClearListener)626 WMError WindowSessionImpl::Destroy(bool needNotifyServer, bool needClearListener)
627 {
628     TLOGI(WmsLogTag::WMS_LIFE, "Id: %{public}d Destroy, state_:%{public}u, needNotifyServer: %{public}d, "
629         "needClearListener: %{public}d", GetPersistentId(), state_, needNotifyServer, needClearListener);
630     if (IsWindowSessionInvalid()) {
631         WLOGFW("[WMSLife]session is invalid");
632         return WMError::WM_ERROR_INVALID_WINDOW;
633     }
634     {
635         auto hostSession = GetHostSession();
636         if (hostSession != nullptr) {
637             hostSession->Disconnect();
638         }
639     }
640     NotifyBeforeDestroy(GetWindowName());
641     {
642         std::lock_guard<std::recursive_mutex> lock(mutex_);
643         state_ = WindowState::STATE_DESTROYED;
644         requestState_ = WindowState::STATE_DESTROYED;
645     }
646     DestroySubWindow();
647     {
648         std::lock_guard<std::mutex> lock(hostSessionMutex_);
649         hostSession_ = nullptr;
650     }
651     {
652         std::unique_lock<std::shared_mutex> lock(windowSessionMutex_);
653         windowSessionMap_.erase(property_->GetWindowName());
654     }
655     NotifyAfterDestroy();
656     if (needClearListener) {
657         ClearListenersById(GetPersistentId());
658     }
659     if (context_) {
660         context_.reset();
661     }
662     ClearVsyncStation();
663     return WMError::WM_OK;
664 }
665 
Destroy()666 WMError WindowSessionImpl::Destroy()
667 {
668     return Destroy(true);
669 }
670 
SetActive(bool active)671 WSError WindowSessionImpl::SetActive(bool active)
672 {
673     WLOGFD("active status: %{public}d", active);
674     if (active) {
675         NotifyAfterActive();
676     } else {
677         NotifyAfterInactive();
678     }
679     return WSError::WS_OK;
680 }
681 
UpdateRect(const WSRect & rect,SizeChangeReason reason,const SceneAnimationConfig & config)682 WSError WindowSessionImpl::UpdateRect(const WSRect& rect, SizeChangeReason reason,
683     const SceneAnimationConfig& config)
684 {
685     // delete after replace ws_common.h with wm_common.h
686     auto wmReason = static_cast<WindowSizeChangeReason>(reason);
687     Rect wmRect = { rect.posX_, rect.posY_, rect.width_, rect.height_ };
688     auto preRect = GetRect();
689     property_->SetWindowRect(wmRect);
690     if (preRect.width_ != wmRect.width_ || preRect.height_ != wmRect.height_) {
691         windowSizeChanged_ = true;
692     }
693     property_->SetRequestRect(wmRect);
694 
695     TLOGI(WmsLogTag::WMS_LAYOUT, "%{public}s, preRect:%{public}s, reason:%{public}u, hasRSTransaction:%{public}d"
696         ",duration:%{public}d, [name:%{public}s, id:%{public}d]", rect.ToString().c_str(), preRect.ToString().c_str(),
697         wmReason, config.rsTransaction_ != nullptr, config.animationDuration_,
698         GetWindowName().c_str(), GetPersistentId());
699     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER,
700         "WindowSessionImpl::UpdateRect id: %d [%d, %d, %u, %u] reason: %u hasRSTransaction: %u", GetPersistentId(),
701         wmRect.posX_, wmRect.posY_, wmRect.width_, wmRect.height_, wmReason, config.rsTransaction_ != nullptr);
702     if (handler_ != nullptr && wmReason == WindowSizeChangeReason::ROTATION) {
703         postTaskDone_ = false;
704         UpdateRectForRotation(wmRect, preRect, wmReason, config);
705     } else {
706         UpdateRectForOtherReason(wmRect, preRect, wmReason, config.rsTransaction_);
707     }
708 
709     if (wmReason == WindowSizeChangeReason::MOVE || wmReason == WindowSizeChangeReason::RESIZE) {
710         layoutCallback_->OnUpdateSessionRect(wmRect, wmReason, GetPersistentId());
711     }
712 
713     return WSError::WS_OK;
714 }
715 
716 /** @note @window.layout */
UpdateVirtualPixelRatio(const sptr<Display> & display)717 void WindowSessionImpl::UpdateVirtualPixelRatio(const sptr<Display>& display)
718 {
719     if (display == nullptr) {
720         TLOGE(WmsLogTag::WMS_LAYOUT, "display is null when rotation!");
721         return;
722     }
723     sptr<DisplayInfo> displayInfo = display->GetDisplayInfo();
724     if (displayInfo == nullptr) {
725         TLOGE(WmsLogTag::WMS_LAYOUT, "displayInfo is null when rotation!");
726         return;
727     }
728     virtualPixelRatio_ = GetVirtualPixelRatio(displayInfo);
729     TLOGD(WmsLogTag::WMS_LAYOUT, "virtualPixelRatio: %{public}f", virtualPixelRatio_);
730 }
731 
UpdateRectForRotation(const Rect & wmRect,const Rect & preRect,WindowSizeChangeReason wmReason,const SceneAnimationConfig & config)732 void WindowSessionImpl::UpdateRectForRotation(const Rect& wmRect, const Rect& preRect,
733     WindowSizeChangeReason wmReason, const SceneAnimationConfig& config)
734 {
735     handler_->PostTask([weak = wptr(this), wmReason, wmRect, preRect, config]() mutable {
736         HITRACE_METER_NAME(HITRACE_TAG_WINDOW_MANAGER, "WindowSessionImpl::UpdateRectForRotation");
737         auto window = weak.promote();
738         if (!window) {
739             return;
740         }
741         auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(window->property_->GetDisplayId());
742         sptr<DisplayInfo> displayInfo = display ? display->GetDisplayInfo() : nullptr;
743         window->UpdateVirtualPixelRatio(display);
744         const std::shared_ptr<RSTransaction>& rsTransaction = config.rsTransaction_;
745         if (rsTransaction) {
746             RSTransaction::FlushImplicitTransaction();
747             rsTransaction->Begin();
748         }
749         window->rotationAnimationCount_++;
750         RSAnimationTimingProtocol protocol;
751         protocol.SetDuration(config.animationDuration_);
752         // animation curve: cubic [0.2, 0.0, 0.2, 1.0]
753         auto curve = RSAnimationTimingCurve::CreateCubicCurve(0.2, 0.0, 0.2, 1.0);
754         RSNode::OpenImplicitAnimation(protocol, curve, [weak]() {
755             auto window = weak.promote();
756             if (!window) {
757                 return;
758             }
759             window->rotationAnimationCount_--;
760             if (window->rotationAnimationCount_ == 0) {
761                 window->NotifyRotationAnimationEnd();
762             }
763         });
764         if ((wmRect != preRect) || (wmReason != window->lastSizeChangeReason_)) {
765             window->NotifySizeChange(wmRect, wmReason);
766             window->lastSizeChangeReason_ = wmReason;
767         }
768         window->UpdateViewportConfig(wmRect, wmReason, rsTransaction, displayInfo);
769         RSNode::CloseImplicitAnimation();
770         if (rsTransaction) {
771             rsTransaction->Commit();
772         } else {
773             RSTransaction::FlushImplicitTransaction();
774         }
775         window->postTaskDone_ = true;
776     }, "WMS_WindowSessionImpl_UpdateRectForRotation");
777 }
778 
UpdateRectForOtherReasonTask(const Rect & wmRect,const Rect & preRect,WindowSizeChangeReason wmReason,const std::shared_ptr<RSTransaction> & rsTransaction)779 void WindowSessionImpl::UpdateRectForOtherReasonTask(const Rect& wmRect, const Rect& preRect,
780     WindowSizeChangeReason wmReason, const std::shared_ptr<RSTransaction>& rsTransaction)
781 {
782     if ((wmRect != preRect) || (wmReason != lastSizeChangeReason_) || !postTaskDone_) {
783         NotifySizeChange(wmRect, wmReason);
784         lastSizeChangeReason_ = wmReason;
785         postTaskDone_ = true;
786     }
787     UpdateViewportConfig(wmRect, wmReason, rsTransaction);
788     UpdateFrameLayoutCallbackIfNeeded(wmReason);
789 }
790 
UpdateRectForOtherReason(const Rect & wmRect,const Rect & preRect,WindowSizeChangeReason wmReason,const std::shared_ptr<RSTransaction> & rsTransaction)791 void WindowSessionImpl::UpdateRectForOtherReason(const Rect& wmRect, const Rect& preRect,
792     WindowSizeChangeReason wmReason, const std::shared_ptr<RSTransaction>& rsTransaction)
793 {
794     if (handler_ == nullptr) {
795         UpdateRectForOtherReasonTask(wmRect, preRect, wmReason, rsTransaction);
796         return;
797     }
798 
799     auto task = [weak = wptr(this), wmReason, wmRect, preRect, rsTransaction] {
800         auto window = weak.promote();
801         if (!window) {
802             TLOGE(WmsLogTag::WMS_LAYOUT, "window is null, updateViewPortConfig failed");
803             return;
804         }
805         bool ifNeedCommitRsTransaction = CheckIfNeedCommitRsTransaction(wmReason);
806         if (rsTransaction && ifNeedCommitRsTransaction) {
807             RSTransaction::FlushImplicitTransaction();
808             rsTransaction->Begin();
809         }
810         window->UpdateRectForOtherReasonTask(wmRect, preRect, wmReason, rsTransaction);
811         if (rsTransaction && ifNeedCommitRsTransaction) {
812             rsTransaction->Commit();
813         }
814     };
815     handler_->PostTask(task, "WMS_WindowSessionImpl_UpdateRectForOtherReason");
816 }
817 
NotifyRotationAnimationEnd()818 void WindowSessionImpl::NotifyRotationAnimationEnd()
819 {
820     auto task = [weak = wptr(this)] {
821         auto window = weak.promote();
822         if (!window) {
823             TLOGE(WmsLogTag::WMS_LAYOUT, "window is null");
824             return;
825         }
826         std::shared_ptr<Ace::UIContent> uiContent = window->GetUIContentSharedPtr();
827         if (uiContent == nullptr) {
828             WLOGFW("uiContent is null!");
829             return;
830         }
831         uiContent->NotifyRotationAnimationEnd();
832     };
833     if (handler_ == nullptr) {
834         TLOGW(WmsLogTag::WMS_LAYOUT, "handler is null!");
835         task();
836     } else {
837         handler_->PostTask(task, "WMS_WindowSessionImpl_NotifyRotationAnimationEnd");
838     }
839 }
840 
GetTitleButtonVisible(bool isPC,bool & hideMaximizeButton,bool & hideMinimizeButton,bool & hideSplitButton)841 void WindowSessionImpl::GetTitleButtonVisible(bool isPC, bool& hideMaximizeButton, bool& hideMinimizeButton,
842     bool& hideSplitButton)
843 {
844     if (!isPC) {
845         return;
846     }
847     if (hideMaximizeButton > !windowTitleVisibleFlags_.isMaximizeVisible) {
848         TLOGW(WmsLogTag::WMS_LAYOUT, "isMaximizeVisible param INVALID");
849     }
850     hideMaximizeButton = hideMaximizeButton || (!windowTitleVisibleFlags_.isMaximizeVisible);
851     if (hideMinimizeButton > !windowTitleVisibleFlags_.isMinimizeVisible) {
852         TLOGW(WmsLogTag::WMS_LAYOUT, "isMinimizeVisible param INVALID");
853     }
854     hideMinimizeButton = hideMinimizeButton || (!windowTitleVisibleFlags_.isMinimizeVisible);
855     if (hideSplitButton > !windowTitleVisibleFlags_.isSplitVisible) {
856         TLOGW(WmsLogTag::WMS_LAYOUT, "isSplitVisible param INVALID");
857     }
858     hideSplitButton = hideSplitButton || (!windowTitleVisibleFlags_.isSplitVisible);
859 }
860 
UpdateDensity()861 void WindowSessionImpl::UpdateDensity()
862 {
863     auto preRect = GetRect();
864     UpdateViewportConfig(preRect, WindowSizeChangeReason::UNDEFINED);
865     WLOGFI("WindowSessionImpl::UpdateDensity [%{public}d, %{public}d, %{public}u, %{public}u]",
866         preRect.posX_, preRect.posY_, preRect.width_, preRect.height_);
867 }
868 
SetUniqueVirtualPixelRatio(bool useUniqueDensity,float virtualPixelRatio)869 void WindowSessionImpl::SetUniqueVirtualPixelRatio(bool useUniqueDensity, float virtualPixelRatio)
870 {
871     TLOGI(WmsLogTag::DEFAULT, "old {useUniqueDensity: %{public}d, virtualPixelRatio: %{public}f}, "\
872         "new {useUniqueDensity: %{public}d, virtualPixelRatio: %{public}f}",
873         useUniqueDensity_, virtualPixelRatio_, useUniqueDensity, virtualPixelRatio);
874     bool oldUseUniqueDensity = useUniqueDensity_;
875     useUniqueDensity_ = useUniqueDensity;
876     if (useUniqueDensity_) {
877         float oldVirtualPixelRatio = virtualPixelRatio_;
878         virtualPixelRatio_ = virtualPixelRatio;
879         if (!MathHelper::NearZero(oldVirtualPixelRatio - virtualPixelRatio)) {
880             UpdateDensity();
881             SetUniqueVirtualPixelRatioForSub(useUniqueDensity, virtualPixelRatio);
882         }
883     } else {
884         if (oldUseUniqueDensity) {
885             UpdateDensity();
886             SetUniqueVirtualPixelRatioForSub(useUniqueDensity, virtualPixelRatio);
887         }
888     }
889 }
890 
CopyUniqueDensityParameter(sptr<WindowSessionImpl> parentWindow)891 void WindowSessionImpl::CopyUniqueDensityParameter(sptr<WindowSessionImpl> parentWindow)
892 {
893     if (parentWindow) {
894         useUniqueDensity_ = parentWindow->useUniqueDensity_;
895         virtualPixelRatio_ = parentWindow->virtualPixelRatio_;
896     }
897 }
898 
FindMainWindowWithContext()899 sptr<WindowSessionImpl> WindowSessionImpl::FindMainWindowWithContext()
900 {
901     if (context_ == nullptr) {
902         return nullptr;
903     }
904     std::shared_lock<std::shared_mutex> lock(windowSessionMutex_);
905     for (const auto& winPair : windowSessionMap_) {
906         auto win = winPair.second.second;
907         if (win && win->GetType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW &&
908             context_.get() == win->GetContext().get()) {
909             return win;
910         }
911     }
912     WLOGFW("Can not find main window, not app type");
913     return nullptr;
914 }
915 
FindExtensionWindowWithContext()916 sptr<WindowSessionImpl> WindowSessionImpl::FindExtensionWindowWithContext()
917 {
918     if (context_ == nullptr) {
919         return nullptr;
920     }
921     std::shared_lock<std::shared_mutex> lock(windowExtensionSessionMutex_);
922     for (const auto& window : windowExtensionSessionSet_) {
923         if (window && context_.get() == window->GetContext().get()) {
924             return window;
925         }
926     }
927     return nullptr;
928 }
929 
SetUniqueVirtualPixelRatioForSub(bool useUniqueDensity,float virtualPixelRatio)930 void WindowSessionImpl::SetUniqueVirtualPixelRatioForSub(bool useUniqueDensity, float virtualPixelRatio)
931 {
932     if (subWindowSessionMap_.count(GetPersistentId()) == 0) {
933         return;
934     }
935     for (auto& subWindowSession : subWindowSessionMap_.at(GetPersistentId())) {
936         subWindowSession->SetUniqueVirtualPixelRatio(useUniqueDensity, virtualPixelRatio);
937     }
938 }
939 
UpdateOrientation()940 WSError WindowSessionImpl::UpdateOrientation()
941 {
942     TLOGD(WmsLogTag::DMS, "UpdateOrientation, wid: %{public}d", GetPersistentId());
943     return WSError::WS_OK;
944 }
945 
UpdateDisplayId(uint64_t displayId)946 WSError WindowSessionImpl::UpdateDisplayId(uint64_t displayId)
947 {
948     property_->SetDisplayId(displayId);
949     return WSError::WS_OK;
950 }
951 
UpdateFocus(bool isFocused)952 WSError WindowSessionImpl::UpdateFocus(bool isFocused)
953 {
954     TLOGI(WmsLogTag::WMS_FOCUS, "Report update focus: %{public}u, id: %{public}d", isFocused, GetPersistentId());
955     isFocused_ = isFocused;
956     if (isFocused) {
957         HiSysEventWrite(
958             OHOS::HiviewDFX::HiSysEvent::Domain::WINDOW_MANAGER,
959             "FOCUS_WINDOW",
960             OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR,
961             "PID", getpid(),
962             "UID", getuid(),
963             "BUNDLE_NAME", property_->GetSessionInfo().bundleName_);
964         NotifyAfterFocused();
965     } else {
966         NotifyAfterUnfocused();
967     }
968     return WSError::WS_OK;
969 }
970 
IsFocused() const971 bool WindowSessionImpl::IsFocused() const
972 {
973     if (IsWindowSessionInvalid()) {
974         TLOGE(WmsLogTag::DEFAULT, "Session is invalid");
975         return false;
976     }
977 
978     TLOGD(WmsLogTag::WMS_FOCUS, "window id = %{public}d, isFocused = %{public}d", GetPersistentId(), isFocused_.load());
979     return isFocused_;
980 }
981 
RequestFocus() const982 WMError WindowSessionImpl::RequestFocus() const
983 {
984     if (IsWindowSessionInvalid()) {
985         WLOGFD("session is invalid");
986         return WMError::WM_ERROR_INVALID_WINDOW;
987     }
988     return SingletonContainer::Get<WindowAdapter>().RequestFocusStatus(GetPersistentId(), true);
989 }
990 
991 /** @note @window.focus */
RequestFocusByClient(bool isFocused) const992 WMError WindowSessionImpl::RequestFocusByClient(bool isFocused) const
993 {
994     if (!SessionPermission::IsSystemCalling()) {
995         TLOGE(WmsLogTag::WMS_FOCUS, "permission denied!");
996         return WMError::WM_ERROR_NOT_SYSTEM_APP;
997     }
998     if (IsWindowSessionInvalid()) {
999         TLOGD(WmsLogTag::WMS_FOCUS, "session is invalid");
1000         return WMError::WM_ERROR_INVALID_WINDOW;
1001     }
1002     auto hostSession = GetHostSession();
1003     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
1004     auto ret = hostSession->RequestFocus(isFocused);
1005     return static_cast<WMError>(ret);
1006 }
1007 
IsNotifyInteractiveDuplicative(bool interactive)1008 bool WindowSessionImpl::IsNotifyInteractiveDuplicative(bool interactive)
1009 {
1010     if (interactive == interactive_ && hasFirstNotifyInteractive_) {
1011         return true;
1012     }
1013     hasFirstNotifyInteractive_ = true;
1014     if (interactive_ != interactive) {
1015         interactive_ = interactive;
1016     }
1017     return false;
1018 }
1019 
NotifyForegroundInteractiveStatus(bool interactive)1020 void WindowSessionImpl::NotifyForegroundInteractiveStatus(bool interactive)
1021 {
1022     WLOGFI("NotifyForegroundInteractiveStatus %{public}d", interactive);
1023     if (IsWindowSessionInvalid() || state_ != WindowState::STATE_SHOWN) {
1024         return;
1025     }
1026     if (IsNotifyInteractiveDuplicative(interactive)) {
1027         return;
1028     }
1029     if (interactive) {
1030         NotifyAfterResumed();
1031     } else {
1032         NotifyAfterPaused();
1033     }
1034 }
1035 
UpdateWindowMode(WindowMode mode)1036 WSError WindowSessionImpl::UpdateWindowMode(WindowMode mode)
1037 {
1038     return WSError::WS_OK;
1039 }
1040 
1041 /** @note @window.layout */
GetVirtualPixelRatio()1042 float WindowSessionImpl::GetVirtualPixelRatio()
1043 {
1044     TLOGD(WmsLogTag::WMS_LAYOUT, "virtualPixelRatio: %{public}f", virtualPixelRatio_);
1045     return virtualPixelRatio_;
1046 }
1047 
GetVirtualPixelRatio(sptr<DisplayInfo> displayInfo)1048 float WindowSessionImpl::GetVirtualPixelRatio(sptr<DisplayInfo> displayInfo)
1049 {
1050     if (useUniqueDensity_) {
1051         return virtualPixelRatio_;
1052     }
1053     return displayInfo->GetVirtualPixelRatio();
1054 }
1055 
UpdateViewportConfig(const Rect & rect,WindowSizeChangeReason reason,const std::shared_ptr<RSTransaction> & rsTransaction,const sptr<DisplayInfo> & info,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)1056 void WindowSessionImpl::UpdateViewportConfig(const Rect& rect, WindowSizeChangeReason reason,
1057     const std::shared_ptr<RSTransaction>& rsTransaction, const sptr<DisplayInfo>& info,
1058     const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
1059 {
1060     sptr<DisplayInfo> displayInfo;
1061     if (info == nullptr) {
1062         auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
1063         if (display == nullptr) {
1064             WLOGFE("display is null!");
1065             return;
1066         }
1067         displayInfo = display->GetDisplayInfo();
1068     } else {
1069         displayInfo = info;
1070     }
1071     if (displayInfo == nullptr) {
1072         WLOGFE("displayInfo is null!");
1073         return;
1074     }
1075     if (rect.width_ <= 0 || rect.height_ <= 0) {
1076         TLOGW(WmsLogTag::WMS_LAYOUT, "invalid width: %{public}d, height: %{public}d, id: %{public}d",
1077               rect.width_, rect.height_, GetPersistentId());
1078         return;
1079     }
1080     auto rotation =  ONE_FOURTH_FULL_CIRCLE_DEGREE * static_cast<uint32_t>(displayInfo->GetRotation());
1081     auto deviceRotation = static_cast<uint32_t>(displayInfo->GetDefaultDeviceRotationOffset());
1082     uint32_t transformHint = (rotation + deviceRotation) % FULL_CIRCLE_DEGREE;
1083     float density = GetVirtualPixelRatio(displayInfo);
1084     int32_t orientation = static_cast<int32_t>(displayInfo->GetDisplayOrientation());
1085     virtualPixelRatio_ = density;
1086     TLOGI(WmsLogTag::WMS_LAYOUT, "[rotation,deviceRotation,transformHint,virtualPixelRatio]:[%{public}u,"
1087         "%{public}u,%{public}u,%{public}f]", rotation, deviceRotation, transformHint, virtualPixelRatio_);
1088     auto config = FillViewportConfig(rect, density, orientation, transformHint);
1089     std::map<AvoidAreaType, AvoidArea> avoidAreasToUpdate;
1090     if (reason == WindowSizeChangeReason::ROTATION) {
1091         if (auto hostSession = GetHostSession()) {
1092             hostSession->GetAllAvoidAreas(avoidAreasToUpdate);
1093         }
1094     } else {
1095         avoidAreasToUpdate = avoidAreas;
1096     }
1097     for (const auto& [type, avoidArea] : avoidAreasToUpdate) {
1098         TLOGD(WmsLogTag::WMS_IMMS, "avoid type %{public}u area %{public}s",
1099             type, avoidArea.ToString().c_str());
1100     }
1101     {
1102         std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1103         if (uiContent == nullptr) {
1104             WLOGFW("uiContent is null!");
1105             return;
1106         }
1107         uiContent->UpdateViewportConfig(config, reason, rsTransaction, avoidAreasToUpdate);
1108     }
1109     if (WindowHelper::IsUIExtensionWindow(GetType())) {
1110         TLOGD(WmsLogTag::WMS_LAYOUT, "Id:%{public}d reason:%{public}d windowRect:[%{public}d,%{public}d,"
1111             "%{public}u,%{public}u] displayOrientation:%{public}d",
1112             GetPersistentId(), reason, rect.posX_, rect.posY_, rect.width_, rect.height_, orientation);
1113     } else {
1114         TLOGI(WmsLogTag::WMS_LAYOUT, "Id:%{public}d reason:%{public}d windowRect:[%{public}d,%{public}d,"
1115             "%{public}u,%{public}u] displayOrientation:%{public}d",
1116             GetPersistentId(), reason, rect.posX_, rect.posY_, rect.width_, rect.height_, orientation);
1117     }
1118 }
1119 
GetFloatingWindowParentId()1120 int32_t WindowSessionImpl::GetFloatingWindowParentId()
1121 {
1122     if (context_.get() == nullptr) {
1123         return INVALID_SESSION_ID;
1124     }
1125     std::shared_lock<std::shared_mutex> lock(windowSessionMutex_);
1126     for (const auto& winPair : windowSessionMap_) {
1127         if (winPair.second.second && WindowHelper::IsMainWindow(winPair.second.second->GetType()) &&
1128             winPair.second.second->GetProperty() &&
1129             context_.get() == winPair.second.second->GetContext().get()) {
1130             WLOGFD("Find parent, [parentName: %{public}s, selfPersistentId: %{public}d]",
1131                 winPair.second.second->GetProperty()->GetWindowName().c_str(), GetPersistentId());
1132             return winPair.second.second->GetProperty()->GetPersistentId();
1133         }
1134     }
1135     return INVALID_SESSION_ID;
1136 }
1137 
GetRect() const1138 Rect WindowSessionImpl::GetRect() const
1139 {
1140     return property_->GetWindowRect();
1141 }
1142 
UpdateTitleButtonVisibility()1143 void WindowSessionImpl::UpdateTitleButtonVisibility()
1144 {
1145     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1146     if (uiContent == nullptr || !IsDecorEnable()) {
1147         return;
1148     }
1149     auto isPC = windowSystemConfig_.uiType_ == UI_TYPE_PC;
1150     WindowType windowType = GetType();
1151     bool isSubWindow = WindowHelper::IsSubWindow(windowType);
1152     bool isDialogWindow = WindowHelper::IsDialogWindow(windowType);
1153     if (IsPcOrPadCapabilityEnabled() && (isSubWindow || isDialogWindow)) {
1154         WLOGFD("hide other buttons except close");
1155         uiContent->HideWindowTitleButton(true, true, true);
1156         return;
1157     }
1158     auto modeSupportInfo = property_->GetModeSupportInfo();
1159     bool hideSplitButton = !(modeSupportInfo & WindowModeSupport::WINDOW_MODE_SUPPORT_SPLIT_PRIMARY);
1160     // not support fullscreen in split and floating mode, or not support float in fullscreen mode
1161     bool hideMaximizeButton = (!(modeSupportInfo & WindowModeSupport::WINDOW_MODE_SUPPORT_FULLSCREEN) &&
1162         (GetMode() == WindowMode::WINDOW_MODE_FLOATING || WindowHelper::IsSplitWindowMode(GetMode()))) ||
1163         (!(modeSupportInfo & WindowModeSupport::WINDOW_MODE_SUPPORT_FLOATING) &&
1164         GetMode() == WindowMode::WINDOW_MODE_FULLSCREEN);
1165     bool hideMinimizeButton = false;
1166     GetTitleButtonVisible(isPC, hideMaximizeButton, hideMinimizeButton, hideSplitButton);
1167     TLOGI(WmsLogTag::WMS_LAYOUT, "[hideSplit, hideMaximize, hideMinimizeButton]: [%{public}d, %{public}d, %{public}d]",
1168         hideSplitButton, hideMaximizeButton, hideMinimizeButton);
1169     if (property_->GetCompatibleModeInPc()) {
1170         if (IsFreeMultiWindowMode()) {
1171             uiContent->HideWindowTitleButton(true, hideMaximizeButton, hideMinimizeButton);
1172         } else {
1173             uiContent->HideWindowTitleButton(hideSplitButton, true, hideMinimizeButton);
1174         }
1175     } else {
1176         uiContent->HideWindowTitleButton(hideSplitButton, hideMaximizeButton, hideMinimizeButton);
1177     }
1178 }
1179 
NapiSetUIContent(const std::string & contentInfo,napi_env env,napi_value storage,bool isdistributed,sptr<IRemoteObject> token,AppExecFwk::Ability * ability)1180 WMError WindowSessionImpl::NapiSetUIContent(const std::string& contentInfo, napi_env env, napi_value storage,
1181     bool isdistributed, sptr<IRemoteObject> token, AppExecFwk::Ability* ability)
1182 {
1183     return SetUIContentInner(contentInfo, env, storage,
1184         isdistributed ? WindowSetUIContentType::DISTRIBUTE : WindowSetUIContentType::DEFAULT, ability);
1185 }
1186 
SetUIContentByName(const std::string & contentInfo,napi_env env,napi_value storage,AppExecFwk::Ability * ability)1187 WMError WindowSessionImpl::SetUIContentByName(
1188     const std::string& contentInfo, napi_env env, napi_value storage, AppExecFwk::Ability* ability)
1189 {
1190     return SetUIContentInner(contentInfo, env, storage, WindowSetUIContentType::BY_NAME, ability);
1191 }
1192 
SetUIContentByAbc(const std::string & contentInfo,napi_env env,napi_value storage,AppExecFwk::Ability * ability)1193 WMError WindowSessionImpl::SetUIContentByAbc(
1194     const std::string& contentInfo, napi_env env, napi_value storage, AppExecFwk::Ability* ability)
1195 {
1196     return SetUIContentInner(contentInfo, env, storage, WindowSetUIContentType::BY_ABC, ability);
1197 }
1198 
InitUIContent(const std::string & contentInfo,napi_env env,napi_value storage,WindowSetUIContentType type,AppExecFwk::Ability * ability,OHOS::Ace::UIContentErrorCode & aceRet)1199 WMError WindowSessionImpl::InitUIContent(const std::string& contentInfo, napi_env env, napi_value storage,
1200     WindowSetUIContentType type, AppExecFwk::Ability* ability, OHOS::Ace::UIContentErrorCode& aceRet)
1201 {
1202     {
1203         std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1204         if (uiContent) {
1205             uiContent->Destroy();
1206         }
1207     }
1208     std::unique_ptr<Ace::UIContent> uiContent = ability != nullptr ? Ace::UIContent::Create(ability) :
1209         Ace::UIContent::Create(context_.get(), reinterpret_cast<NativeEngine*>(env));
1210     if (uiContent == nullptr) {
1211         TLOGE(WmsLogTag::WMS_LIFE, "fail to NapiSetUIContent id: %{public}d", GetPersistentId());
1212         return WMError::WM_ERROR_NULLPTR;
1213     }
1214     switch (type) {
1215         default:
1216         case WindowSetUIContentType::DEFAULT:
1217             if (isUIExtensionAbilityProcess_ && property_->GetExtensionFlag() == true) {
1218                 // subWindow created by UIExtensionAbility
1219                 uiContent->SetUIExtensionSubWindow(true);
1220                 uiContent->SetUIExtensionAbilityProcess(true);
1221             }
1222             aceRet = uiContent->Initialize(this, contentInfo, storage);
1223             break;
1224         case WindowSetUIContentType::DISTRIBUTE:
1225             aceRet = uiContent->Restore(this, contentInfo, storage);
1226             break;
1227         case WindowSetUIContentType::BY_NAME:
1228             aceRet = uiContent->InitializeByName(this, contentInfo, storage);
1229             break;
1230         case WindowSetUIContentType::BY_ABC:
1231             auto abcContent = GetAbcContent(contentInfo);
1232             aceRet = uiContent->Initialize(this, abcContent, storage, contentInfo);
1233             break;
1234     }
1235     // make uiContent available after Initialize/Restore
1236     {
1237         std::unique_lock<std::shared_mutex> lock(uiContentMutex_);
1238         uiContent_ = std::move(uiContent);
1239         RegisterFrameLayoutCallback();
1240         WLOGFI("UIContent Initialize, isUIExtensionSubWindow:%{public}d, isUIExtensionAbilityProcess:%{public}d",
1241             uiContent_->IsUIExtensionSubWindow(), uiContent_->IsUIExtensionAbilityProcess());
1242     }
1243     return WMError::WM_OK;
1244 }
1245 
RegisterFrameLayoutCallback()1246 void WindowSessionImpl::RegisterFrameLayoutCallback()
1247 {
1248     if (!WindowHelper::IsMainWindow(GetType()) || windowSystemConfig_.uiType_ == UI_TYPE_PC) {
1249         return;
1250     }
1251     uiContent_->SetLatestFrameLayoutFinishCallback([weakThis = wptr(this)]() {
1252         auto window = weakThis.promote();
1253         if (window == nullptr) {
1254             return;
1255         }
1256         if (window->windowSizeChanged_ || window->enableFrameLayoutFinishCb_) {
1257             auto windowRect = window->GetRect();
1258             HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER,
1259                 "NotifyFrameLayoutFinish, id: %u, rect: %s, notifyListener: %d",
1260                 window->GetWindowId(), windowRect.ToString().c_str(), window->enableFrameLayoutFinishCb_.load());
1261             TLOGI(WmsLogTag::WMS_LAYOUT,
1262                 "NotifyFrameLayoutFinish, id: %{public}u, rect: %{public}s, notifyListener: %{public}d",
1263                 window->GetWindowId(), windowRect.ToString().c_str(), window->enableFrameLayoutFinishCb_.load());
1264             WSRect rect = { windowRect.posX_, windowRect.posY_,
1265                 static_cast<int32_t>(windowRect.width_), static_cast<int32_t>(windowRect.height_) };
1266             if (auto session = window->GetHostSession()) {
1267                 session->NotifyFrameLayoutFinishFromApp(window->enableFrameLayoutFinishCb_, rect);
1268             }
1269             window->windowSizeChanged_ = false;
1270             window->enableFrameLayoutFinishCb_ = false;
1271         }
1272     });
1273 }
1274 
SetUIContentInner(const std::string & contentInfo,napi_env env,napi_value storage,WindowSetUIContentType type,AppExecFwk::Ability * ability)1275 WMError WindowSessionImpl::SetUIContentInner(const std::string& contentInfo, napi_env env, napi_value storage,
1276     WindowSetUIContentType type, AppExecFwk::Ability* ability)
1277 {
1278     TLOGD(WmsLogTag::WMS_LIFE, "NapiSetUIContent: %{public}s state:%{public}u", contentInfo.c_str(), state_);
1279     if (IsWindowSessionInvalid()) {
1280         WLOGFE("[WMSLife]interrupt set uicontent because window is invalid! window state: %{public}d", state_);
1281         return WMError::WM_ERROR_INVALID_WINDOW;
1282     }
1283     OHOS::Ace::UIContentErrorCode aceRet = OHOS::Ace::UIContentErrorCode::NO_ERRORS;
1284     WMError initUIContentRet = InitUIContent(contentInfo, env, storage, type, ability, aceRet);
1285     if (initUIContentRet != WMError::WM_OK) {
1286         TLOGE(WmsLogTag::WMS_LIFE, "Init UIContent fail, ret:%{public}u", initUIContentRet);
1287         return initUIContentRet;
1288     }
1289     WindowType winType = GetType();
1290     bool isSubWindow = WindowHelper::IsSubWindow(winType);
1291     bool isDialogWindow = WindowHelper::IsDialogWindow(winType);
1292     if (IsDecorEnable()) {
1293         if (isSubWindow) {
1294             SetAPPWindowLabel(subWindowTitle_);
1295         } else if (isDialogWindow) {
1296             SetAPPWindowLabel(dialogTitle_);
1297         }
1298     }
1299 
1300     AppForceLandscapeConfig config = {};
1301     if (WindowHelper::IsMainWindow(winType) && GetAppForceLandscapeConfig(config) == WMError::WM_OK &&
1302         config.mode_ == FORCE_SPLIT_MODE) {
1303         SetForceSplitEnable(true, config.homePage_);
1304     }
1305 
1306     uint32_t version = 0;
1307     if ((context_ != nullptr) && (context_->GetApplicationInfo() != nullptr)) {
1308         version = context_->GetApplicationInfo()->apiCompatibleVersion;
1309     }
1310     // 10 ArkUI new framework support after API10
1311     if (version < 10) {
1312         SetLayoutFullScreenByApiVersion(isIgnoreSafeArea_);
1313         if (!isSystembarPropertiesSet_) {
1314             SetSystemBarProperty(WindowType::WINDOW_TYPE_STATUS_BAR, SystemBarProperty());
1315         }
1316     } else if (isIgnoreSafeAreaNeedNotify_) {
1317         SetLayoutFullScreenByApiVersion(isIgnoreSafeArea_);
1318     } else if (isSubWindow) {
1319         SetLayoutFullScreenByApiVersion(isIgnoreSafeArea_);
1320         isIgnoreSafeAreaNeedNotify_ = false;
1321     }
1322 
1323     // UIContent may be nullptr on setting system bar properties, need to set menubar color on UIContent init.
1324     if (auto uiContent = GetUIContentSharedPtr()) {
1325         auto property = GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_STATUS_BAR);
1326         uiContent->SetStatusBarItemColor(property.contentColor_);
1327     }
1328 
1329     UpdateDecorEnable(true);
1330     if (state_ == WindowState::STATE_SHOWN) {
1331         // UIContent may be nullptr when show window, need to notify again when window is shown
1332         {
1333             std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1334             if (uiContent != nullptr) {
1335                 uiContent->Foreground();
1336             }
1337         }
1338         UpdateTitleButtonVisibility();
1339     }
1340     UpdateViewportConfig(GetRect(), WindowSizeChangeReason::UNDEFINED);
1341     if (shouldReNotifyFocus_) {
1342         // uiContent may be nullptr when notify focus status, need to notify again when uiContent is not empty.
1343         NotifyUIContentFocusStatus();
1344         shouldReNotifyFocus_ = false;
1345     }
1346     if (aceRet != OHOS::Ace::UIContentErrorCode::NO_ERRORS) {
1347         WLOGFE("failed to init or restore uicontent with file %{public}s. errorCode: %{public}d",
1348             contentInfo.c_str(), static_cast<uint16_t>(aceRet));
1349         return WMError::WM_ERROR_INVALID_PARAM;
1350     }
1351     TLOGD(WmsLogTag::WMS_LIFE, "notify uiContent window size change end");
1352 
1353     NotifySetUIContentComplete();
1354     return WMError::WM_OK;
1355 }
1356 
GetAbcContent(const std::string & abcPath)1357 std::shared_ptr<std::vector<uint8_t>> WindowSessionImpl::GetAbcContent(const std::string& abcPath)
1358 {
1359     std::filesystem::path abcFile { abcPath };
1360     if (abcFile.empty() || !abcFile.is_absolute() || !std::filesystem::exists(abcFile)) {
1361         WLOGFE("abc file path is not valid");
1362         return nullptr;
1363     }
1364     int begin, end;
1365     std::fstream file(abcFile, std::ios::in | std::ios::binary);
1366     if (!file) {
1367         WLOGFE("abc file is not valid");
1368         return nullptr;
1369     }
1370     begin = file.tellg();
1371     file.seekg(0, std::ios::end);
1372     end = file.tellg();
1373     int len = end - begin;
1374     WLOGFD("abc file: %{public}s, size: %{public}d", abcPath.c_str(), len);
1375 
1376     if (len <= 0) {
1377         WLOGFE("abc file size is 0");
1378         return nullptr;
1379     }
1380     std::vector<uint8_t> abcBytes(len);
1381     file.seekg(0, std::ios::beg);
1382     file.read(reinterpret_cast<char *>(abcBytes.data()), len);
1383     return std::make_shared<std::vector<uint8_t>>(abcBytes);
1384 }
1385 
UpdateDecorEnableToAce(bool isDecorEnable)1386 void WindowSessionImpl::UpdateDecorEnableToAce(bool isDecorEnable)
1387 {
1388     {
1389         std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1390         if (uiContent != nullptr) {
1391             WindowMode mode = GetMode();
1392             bool decorVisible = mode == WindowMode::WINDOW_MODE_FLOATING ||
1393                 mode == WindowMode::WINDOW_MODE_SPLIT_PRIMARY || mode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY ||
1394                 (mode == WindowMode::WINDOW_MODE_FULLSCREEN && !property_->IsLayoutFullScreen());
1395             WLOGFD("[WSLayout]Notify uiContent window mode change end,decorVisible:%{public}d", decorVisible);
1396             if (windowSystemConfig_.freeMultiWindowSupport_) {
1397                 auto isSubWindow = WindowHelper::IsSubWindow(GetType());
1398                 decorVisible = decorVisible && (windowSystemConfig_.freeMultiWindowEnable_ ||
1399                         (property_->GetIsPcAppInPad() && isSubWindow));
1400             }
1401             uiContent->UpdateDecorVisible(decorVisible, isDecorEnable);
1402             return;
1403         }
1404     }
1405     std::lock_guard<std::recursive_mutex> lockListener(windowChangeListenerMutex_);
1406     auto windowChangeListeners = GetListeners<IWindowChangeListener>();
1407     for (auto& listener : windowChangeListeners) {
1408         if (listener.GetRefPtr() != nullptr) {
1409             listener.GetRefPtr()->OnModeChange(GetMode(), isDecorEnable);
1410         }
1411     }
1412 }
1413 
UpdateDecorEnable(bool needNotify,WindowMode mode)1414 void WindowSessionImpl::UpdateDecorEnable(bool needNotify, WindowMode mode)
1415 {
1416     if (mode == WindowMode::WINDOW_MODE_UNDEFINED) {
1417         mode = GetMode();
1418     }
1419     if (needNotify) {
1420         {
1421             std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1422             if (uiContent != nullptr) {
1423                 bool decorVisible = mode == WindowMode::WINDOW_MODE_FLOATING ||
1424                     mode == WindowMode::WINDOW_MODE_SPLIT_PRIMARY || mode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY ||
1425                     (mode == WindowMode::WINDOW_MODE_FULLSCREEN && !property_->IsLayoutFullScreen());
1426                 if (windowSystemConfig_.freeMultiWindowSupport_) {
1427                     auto isSubWindow = WindowHelper::IsSubWindow(GetType());
1428                     decorVisible = decorVisible && (windowSystemConfig_.freeMultiWindowEnable_ ||
1429                             (property_->GetIsPcAppInPad() && isSubWindow));
1430                 }
1431                 WLOGFD("[WSLayout]Notify uiContent window mode change end,decorVisible:%{public}d", decorVisible);
1432                 uiContent->UpdateDecorVisible(decorVisible, IsDecorEnable());
1433             }
1434         }
1435         NotifyModeChange(mode, IsDecorEnable());
1436     }
1437 }
1438 
NotifyModeChange(WindowMode mode,bool hasDeco)1439 void WindowSessionImpl::NotifyModeChange(WindowMode mode, bool hasDeco)
1440 {
1441     {
1442         std::lock_guard<std::recursive_mutex> lockListener(windowChangeListenerMutex_);
1443         auto windowChangeListeners = GetListeners<IWindowChangeListener>();
1444         for (auto& listener : windowChangeListeners) {
1445             if (listener.GetRefPtr() != nullptr) {
1446                 listener.GetRefPtr()->OnModeChange(mode, hasDeco);
1447             }
1448         }
1449     }
1450 
1451     if (GetHostSession()) {
1452         property_->SetWindowMode(mode);
1453         property_->SetDecorEnable(hasDeco);
1454     }
1455     UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_MODE);
1456     UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_DECOR_ENABLE);
1457 }
1458 
GetSurfaceNode() const1459 std::shared_ptr<RSSurfaceNode> WindowSessionImpl::GetSurfaceNode() const
1460 {
1461     TLOGI(WmsLogTag::DEFAULT, "name:%{public}s, id:%{public}d",
1462         property_->GetWindowName().c_str(), GetPersistentId());
1463     return surfaceNode_;
1464 }
1465 
GetContext() const1466 const std::shared_ptr<AbilityRuntime::Context> WindowSessionImpl::GetContext() const
1467 {
1468     TLOGI(WmsLogTag::DEFAULT, "name:%{public}s, id:%{public}d",
1469         property_->GetWindowName().c_str(), GetPersistentId());
1470     return context_;
1471 }
1472 
GetRequestRect() const1473 Rect WindowSessionImpl::GetRequestRect() const
1474 {
1475     return property_->GetRequestRect();
1476 }
1477 
GetType() const1478 WindowType WindowSessionImpl::GetType() const
1479 {
1480     return property_->GetWindowType();
1481 }
1482 
GetWindowName() const1483 const std::string& WindowSessionImpl::GetWindowName() const
1484 {
1485     return property_->GetWindowName();
1486 }
1487 
GetWindowState() const1488 WindowState WindowSessionImpl::GetWindowState() const
1489 {
1490     return state_;
1491 }
1492 
GetRequestWindowState() const1493 WindowState WindowSessionImpl::GetRequestWindowState() const
1494 {
1495     return requestState_;
1496 }
1497 
SetFocusable(bool isFocusable)1498 WMError WindowSessionImpl::SetFocusable(bool isFocusable)
1499 {
1500     if (IsWindowSessionInvalid()) {
1501         return WMError::WM_ERROR_INVALID_WINDOW;
1502     }
1503     TLOGI(WmsLogTag::WMS_FOCUS, "set focusable: windowId = %{public}d, isFocusable = %{public}d",
1504         property_->GetPersistentId(), isFocusable);
1505     property_->SetFocusable(isFocusable);
1506     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_FOCUSABLE);
1507 }
1508 
GetFocusable() const1509 bool WindowSessionImpl::GetFocusable() const
1510 {
1511     bool isFocusable = property_->GetFocusable();
1512     TLOGD(WmsLogTag::WMS_FOCUS, "get focusable: windowId = %{public}d, isFocusable = %{public}d",
1513         property_->GetPersistentId(), isFocusable);
1514     return isFocusable;
1515 }
1516 
SetTouchable(bool isTouchable)1517 WMError WindowSessionImpl::SetTouchable(bool isTouchable)
1518 {
1519     WLOGFD("set touchable");
1520     if (IsWindowSessionInvalid()) {
1521         return WMError::WM_ERROR_INVALID_WINDOW;
1522     }
1523     property_->SetTouchable(isTouchable);
1524     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_TOUCHABLE);
1525 }
1526 
1527 /** @note @window.hierarchy */
SetTopmost(bool topmost)1528 WMError WindowSessionImpl::SetTopmost(bool topmost)
1529 {
1530     TLOGD(WmsLogTag::WMS_LAYOUT, "set topmost");
1531     auto isPC = windowSystemConfig_.uiType_ == UI_TYPE_PC;
1532     if (!isPC) {
1533         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
1534     }
1535     if (IsWindowSessionInvalid()) {
1536         return WMError::WM_ERROR_INVALID_WINDOW;
1537     }
1538     property_->SetTopmost(topmost);
1539     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_TOPMOST);
1540 }
1541 
1542 /** @note @window.hierarchy */
IsTopmost() const1543 bool WindowSessionImpl::IsTopmost() const
1544 {
1545     return property_->IsTopmost();
1546 }
1547 
SetResizeByDragEnabled(bool dragEnabled)1548 WMError WindowSessionImpl::SetResizeByDragEnabled(bool dragEnabled)
1549 {
1550     if (IsWindowSessionInvalid()) {
1551         TLOGE(WmsLogTag::DEFAULT, "Session is invalid");
1552         return WMError::WM_ERROR_INVALID_WINDOW;
1553     }
1554 
1555     WLOGFD("set dragEnabled");
1556     if (IsWindowSessionInvalid()) {
1557         return WMError::WM_ERROR_INVALID_WINDOW;
1558     }
1559 
1560     if (WindowHelper::IsMainWindow(GetType())) {
1561         property_->SetDragEnabled(dragEnabled);
1562     } else {
1563         WLOGFE("This is not main window.");
1564         return WMError::WM_ERROR_INVALID_TYPE;
1565     }
1566     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_DRAGENABLED);
1567 }
1568 
1569 /** @note @window.hierarchy */
SetRaiseByClickEnabled(bool raiseEnabled)1570 WMError WindowSessionImpl::SetRaiseByClickEnabled(bool raiseEnabled)
1571 {
1572     WLOGFD("set raiseEnabled");
1573     if (IsWindowSessionInvalid()) {
1574         return WMError::WM_ERROR_INVALID_WINDOW;
1575     }
1576 
1577     property_->SetRaiseEnabled(raiseEnabled);
1578     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_RAISEENABLED);
1579 }
1580 
HideNonSystemFloatingWindows(bool shouldHide)1581 WMError WindowSessionImpl::HideNonSystemFloatingWindows(bool shouldHide)
1582 {
1583     WLOGFD("hide non-system floating windows");
1584     if (IsWindowSessionInvalid()) {
1585         return WMError::WM_ERROR_INVALID_WINDOW;
1586     }
1587     property_->SetHideNonSystemFloatingWindows(shouldHide);
1588     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_HIDE_NON_SYSTEM_FLOATING_WINDOWS);
1589 }
1590 
SetLandscapeMultiWindow(bool isLandscapeMultiWindow)1591 WMError WindowSessionImpl::SetLandscapeMultiWindow(bool isLandscapeMultiWindow)
1592 {
1593     TLOGI(WmsLogTag::WMS_MULTI_WINDOW, "SetLandscapeMultiWindow, isLandscapeMultiWindow:%{public}d",
1594         isLandscapeMultiWindow);
1595     if (IsWindowSessionInvalid()) {
1596         TLOGE(WmsLogTag::WMS_MULTI_WINDOW, "Session is invalid");
1597         return WMError::WM_ERROR_INVALID_WINDOW;
1598     }
1599     auto hostSession = GetHostSession();
1600     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
1601     hostSession->SetLandscapeMultiWindow(isLandscapeMultiWindow);
1602     return WMError::WM_OK;
1603 }
1604 
SetSingleFrameComposerEnabled(bool enable)1605 WMError WindowSessionImpl::SetSingleFrameComposerEnabled(bool enable)
1606 {
1607     WLOGFD("Set the enable flag of single frame composer.");
1608     if (IsWindowSessionInvalid()) {
1609         WLOGE("The window state is invalid ");
1610         return WMError::WM_ERROR_INVALID_WINDOW;
1611     }
1612 
1613     if (surfaceNode_ == nullptr) {
1614         WLOGE("The surface node is nullptr");
1615         return WMError::WM_ERROR_INVALID_WINDOW;
1616     }
1617 
1618     surfaceNode_->MarkNodeSingleFrameComposer(enable);
1619     RSTransaction::FlushImplicitTransaction();
1620     return WMError::WM_OK;
1621 }
1622 
IsFloatingWindowAppType() const1623 bool WindowSessionImpl::IsFloatingWindowAppType() const
1624 {
1625     if (IsWindowSessionInvalid()) {
1626         return false;
1627     }
1628     return property_ != nullptr && property_->IsFloatingWindowAppType();
1629 }
1630 
GetTouchable() const1631 bool WindowSessionImpl::GetTouchable() const
1632 {
1633     return property_->GetTouchable();
1634 }
1635 
SetWindowType(WindowType type)1636 WMError WindowSessionImpl::SetWindowType(WindowType type)
1637 {
1638     TLOGD(WmsLogTag::DEFAULT, "SetWindowType %{public}u type %{public}u", GetWindowId(), static_cast<uint32_t>(type));
1639     if (type != WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW && !SessionPermission::IsSystemCalling()) {
1640         TLOGE(WmsLogTag::DEFAULT, "set window type permission denied!");
1641         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1642     }
1643     if (IsWindowSessionInvalid()) {
1644         TLOGE(WmsLogTag::DEFAULT, "Session is invalid");
1645         return WMError::WM_ERROR_INVALID_WINDOW;
1646     }
1647     property_->SetWindowType(type);
1648     UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_OTHER_PROPS);
1649     return WMError::WM_OK;
1650 }
1651 
SetBrightness(float brightness)1652 WMError WindowSessionImpl::SetBrightness(float brightness)
1653 {
1654     if ((brightness < MINIMUM_BRIGHTNESS &&
1655         std::fabs(brightness - UNDEFINED_BRIGHTNESS) >= std::numeric_limits<float>::min()) ||
1656         brightness > MAXIMUM_BRIGHTNESS) {
1657         TLOGE(WmsLogTag::DEFAULT, "invalid brightness value: %{public}f", brightness);
1658         return WMError::WM_ERROR_INVALID_PARAM;
1659     }
1660     if (!WindowHelper::IsAppWindow(GetType())) {
1661         TLOGE(WmsLogTag::DEFAULT, "non app window does not support set brightness, type: %{public}u", GetType());
1662         return WMError::WM_ERROR_INVALID_TYPE;
1663     }
1664     if (!property_) {
1665         TLOGE(WmsLogTag::DEFAULT, "window property is not existed");
1666         return WMError::WM_ERROR_NULLPTR;
1667     }
1668     property_->SetBrightness(brightness);
1669     return UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_SET_BRIGHTNESS);
1670 }
1671 
GetBrightness() const1672 float WindowSessionImpl::GetBrightness() const
1673 {
1674     return property_->GetBrightness();
1675 }
1676 
SetRequestedOrientation(Orientation orientation)1677 void WindowSessionImpl::SetRequestedOrientation(Orientation orientation)
1678 {
1679     if (IsWindowSessionInvalid()) {
1680         TLOGE(WmsLogTag::DEFAULT, "windowSession is invalid");
1681         return;
1682     }
1683     TLOGI(WmsLogTag::WMS_MAIN, "id:%{public}u lastReqOrientation:%{public}u target:%{public}u state:%{public}u",
1684         GetPersistentId(), property_->GetRequestedOrientation(), orientation, state_);
1685     bool isUserOrientation = IsUserOrientation(orientation);
1686     if (property_->GetRequestedOrientation() == orientation && !isUserOrientation) {
1687         return;
1688     }
1689     property_->SetRequestedOrientation(orientation);
1690     UpdateProperty(WSPropertyChangeAction::ACTION_UPDATE_ORIENTATION);
1691 }
1692 
GetRequestedOrientation()1693 Orientation WindowSessionImpl::GetRequestedOrientation()
1694 {
1695     if (IsWindowSessionInvalid()) {
1696         TLOGE(WmsLogTag::DEFAULT, "windowSession is invalid");
1697         return Orientation::UNSPECIFIED;
1698     }
1699     return property_->GetRequestedOrientation();
1700 }
1701 
GetContentInfo()1702 std::string WindowSessionImpl::GetContentInfo()
1703 {
1704     WLOGFD("GetContentInfo");
1705     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1706     if (uiContent == nullptr) {
1707         WLOGFE("fail to GetContentInfo id: %{public}d", GetPersistentId());
1708         return "";
1709     }
1710     return uiContent->GetContentInfo();
1711 }
1712 
GetUIContent() const1713 Ace::UIContent* WindowSessionImpl::GetUIContent() const
1714 {
1715     std::shared_lock<std::shared_mutex> lock(uiContentMutex_);
1716     return uiContent_.get();
1717 }
1718 
GetUIContentSharedPtr() const1719 std::shared_ptr<Ace::UIContent> WindowSessionImpl::GetUIContentSharedPtr() const
1720 {
1721     std::shared_lock<std::shared_mutex> lock(uiContentMutex_);
1722     return uiContent_;
1723 }
1724 
GetUIContentWithId(uint32_t winId) const1725 Ace::UIContent* WindowSessionImpl::GetUIContentWithId(uint32_t winId) const
1726 {
1727     sptr<Window> targetWindow = FindWindowById(winId);
1728     if (targetWindow == nullptr) {
1729         WLOGE("target window is null");
1730         return nullptr;
1731     }
1732     return targetWindow->GetUIContent();
1733 }
1734 
OnNewWant(const AAFwk::Want & want)1735 void WindowSessionImpl::OnNewWant(const AAFwk::Want& want)
1736 {
1737     WLOGFI("Window [name:%{public}s, id:%{public}d]",
1738         property_->GetWindowName().c_str(), GetPersistentId());
1739     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1740     if (uiContent != nullptr) {
1741         uiContent->OnNewWant(want);
1742     }
1743 }
1744 
SetAPPWindowLabel(const std::string & label)1745 WMError WindowSessionImpl::SetAPPWindowLabel(const std::string& label)
1746 {
1747     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1748     if (uiContent == nullptr) {
1749         WLOGFE("uicontent is empty");
1750         return WMError::WM_ERROR_NULLPTR;
1751     }
1752     uiContent->SetAppWindowTitle(label);
1753     WLOGI("Set app window label success, label : %{public}s", label.c_str());
1754     return WMError::WM_OK;
1755 }
1756 
SetAPPWindowIcon(const std::shared_ptr<Media::PixelMap> & icon)1757 WMError WindowSessionImpl::SetAPPWindowIcon(const std::shared_ptr<Media::PixelMap>& icon)
1758 {
1759     if (icon == nullptr) {
1760         WLOGFE("window icon is empty");
1761         return WMError::WM_ERROR_NULLPTR;
1762     }
1763     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1764     if (uiContent == nullptr) {
1765         WLOGFE("uicontent is empty");
1766         return WMError::WM_ERROR_NULLPTR;
1767     }
1768     uiContent->SetAppWindowIcon(icon);
1769     WLOGI("Set app window icon success");
1770     return WMError::WM_OK;
1771 }
1772 
RegisterLifeCycleListener(const sptr<IWindowLifeCycle> & listener)1773 WMError WindowSessionImpl::RegisterLifeCycleListener(const sptr<IWindowLifeCycle>& listener)
1774 {
1775     WLOGFD("Start register");
1776     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
1777     return RegisterListener(lifecycleListeners_[GetPersistentId()], listener);
1778 }
1779 
RegisterDisplayMoveListener(sptr<IDisplayMoveListener> & listener)1780 WMError WindowSessionImpl::RegisterDisplayMoveListener(sptr<IDisplayMoveListener>& listener)
1781 {
1782     WLOGFD("Start register");
1783     std::lock_guard<std::mutex> lockListener(displayMoveListenerMutex_);
1784     return RegisterListener(displayMoveListeners_[GetPersistentId()], listener);
1785 }
1786 
UnregisterDisplayMoveListener(sptr<IDisplayMoveListener> & listener)1787 WMError WindowSessionImpl::UnregisterDisplayMoveListener(sptr<IDisplayMoveListener>& listener)
1788 {
1789     WLOGFD("Start unregister");
1790     std::lock_guard<std::mutex> lockListener(displayMoveListenerMutex_);
1791     return UnregisterListener(displayMoveListeners_[GetPersistentId()], listener);
1792 }
1793 
RegisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener> & listener)1794 WMError WindowSessionImpl::RegisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener>& listener)
1795 {
1796     WLOGFD("Start register");
1797     std::lock_guard<std::recursive_mutex> lockListener(occupiedAreaChangeListenerMutex_);
1798     return RegisterListener(occupiedAreaChangeListeners_[GetPersistentId()], listener);
1799 }
1800 
UnregisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener> & listener)1801 WMError WindowSessionImpl::UnregisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener>& listener)
1802 {
1803     WLOGFD("Start unregister");
1804     std::lock_guard<std::recursive_mutex> lockListener(occupiedAreaChangeListenerMutex_);
1805     return UnregisterListener(occupiedAreaChangeListeners_[GetPersistentId()], listener);
1806 }
1807 
UnregisterLifeCycleListener(const sptr<IWindowLifeCycle> & listener)1808 WMError WindowSessionImpl::UnregisterLifeCycleListener(const sptr<IWindowLifeCycle>& listener)
1809 {
1810     WLOGFD("Start unregister");
1811     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
1812     return UnregisterListener(lifecycleListeners_[GetPersistentId()], listener);
1813 }
1814 
RegisterWindowChangeListener(const sptr<IWindowChangeListener> & listener)1815 WMError WindowSessionImpl::RegisterWindowChangeListener(const sptr<IWindowChangeListener>& listener)
1816 {
1817     WLOGFD("Start register");
1818     std::lock_guard<std::recursive_mutex> lockListener(windowChangeListenerMutex_);
1819     return RegisterListener(windowChangeListeners_[GetPersistentId()], listener);
1820 }
1821 
UnregisterWindowChangeListener(const sptr<IWindowChangeListener> & listener)1822 WMError WindowSessionImpl::UnregisterWindowChangeListener(const sptr<IWindowChangeListener>& listener)
1823 {
1824     WLOGFD("Start register");
1825     std::lock_guard<std::recursive_mutex> lockListener(windowChangeListenerMutex_);
1826     return UnregisterListener(windowChangeListeners_[GetPersistentId()], listener);
1827 }
1828 
RegisterWindowStatusChangeListener(const sptr<IWindowStatusChangeListener> & listener)1829 WMError WindowSessionImpl::RegisterWindowStatusChangeListener(const sptr<IWindowStatusChangeListener>& listener)
1830 {
1831     WLOGFD("Start register");
1832     std::lock_guard<std::recursive_mutex> lockListener(windowStatusChangeListenerMutex_);
1833     return RegisterListener(windowStatusChangeListeners_[GetPersistentId()], listener);
1834 }
1835 
UnregisterWindowStatusChangeListener(const sptr<IWindowStatusChangeListener> & listener)1836 WMError WindowSessionImpl::UnregisterWindowStatusChangeListener(const sptr<IWindowStatusChangeListener>& listener)
1837 {
1838     WLOGFD("Start register");
1839     std::lock_guard<std::recursive_mutex> lockListener(windowStatusChangeListenerMutex_);
1840     return UnregisterListener(windowStatusChangeListeners_[GetPersistentId()], listener);
1841 }
1842 
SetDecorVisible(bool isVisible)1843 WMError WindowSessionImpl::SetDecorVisible(bool isVisible)
1844 {
1845     if (IsWindowSessionInvalid()) {
1846         return WMError::WM_ERROR_INVALID_WINDOW;
1847     }
1848     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1849     if (uiContent == nullptr) {
1850         WLOGFE("uicontent is empty");
1851         return WMError::WM_ERROR_NULLPTR;
1852     }
1853     uiContent->SetContainerModalTitleVisible(isVisible, true);
1854     WLOGI("Change the visibility of decor success");
1855     return WMError::WM_OK;
1856 }
1857 
SetSubWindowModal(bool isModal)1858 WMError WindowSessionImpl::SetSubWindowModal(bool isModal)
1859 {
1860     if (IsWindowSessionInvalid()) {
1861         return WMError::WM_ERROR_INVALID_WINDOW;
1862     }
1863     if (!WindowHelper::IsSubWindow(GetType())) {
1864         TLOGE(WmsLogTag::WMS_SUB, "called by invalid window type, type:%{public}d", GetType());
1865         return WMError::WM_ERROR_INVALID_CALLING;
1866     }
1867 
1868     return isModal ? AddWindowFlag(WindowFlag::WINDOW_FLAG_IS_MODAL) :
1869         RemoveWindowFlag(WindowFlag::WINDOW_FLAG_IS_MODAL);
1870 }
1871 
SetDecorHeight(int32_t decorHeight)1872 WMError WindowSessionImpl::SetDecorHeight(int32_t decorHeight)
1873 {
1874     if (IsWindowSessionInvalid()) {
1875         return WMError::WM_ERROR_INVALID_WINDOW;
1876     }
1877     auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
1878     if (display == nullptr) {
1879         WLOGFE("get display failed displayId:%{public}" PRIu64, property_->GetDisplayId());
1880         return WMError::WM_ERROR_NULLPTR;
1881     }
1882     auto displayInfo = display->GetDisplayInfo();
1883     if (displayInfo == nullptr) {
1884         WLOGFE("get display info failed displayId:%{public}" PRIu64, property_->GetDisplayId());
1885         return WMError::WM_ERROR_NULLPTR;
1886     }
1887     float vpr = GetVirtualPixelRatio(displayInfo);
1888     int32_t decorHeightWithPx = static_cast<int32_t>(decorHeight * vpr);
1889     {
1890         std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1891         if (uiContent == nullptr) {
1892             WLOGFE("uicontent is empty");
1893             return WMError::WM_ERROR_NULLPTR;
1894         }
1895         uiContent->SetContainerModalTitleHeight(decorHeightWithPx);
1896     }
1897     auto hostSession = GetHostSession();
1898     if (hostSession != nullptr) {
1899         hostSession->SetCustomDecorHeight(decorHeight);
1900     }
1901     WLOGI("Set app window decor height success, height : %{public}d", decorHeight);
1902     return WMError::WM_OK;
1903 }
1904 
GetDecorHeight(int32_t & height)1905 WMError WindowSessionImpl::GetDecorHeight(int32_t& height)
1906 {
1907     if (IsWindowSessionInvalid()) {
1908         return WMError::WM_ERROR_INVALID_WINDOW;
1909     }
1910     {
1911         std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1912         if (uiContent == nullptr) {
1913             WLOGFE("uiContent is nullptr, windowId: %{public}u", GetWindowId());
1914             return WMError::WM_ERROR_NULLPTR;
1915         }
1916         height = uiContent->GetContainerModalTitleHeight();
1917     }
1918     if (height == -1) {
1919         height = 0;
1920         WLOGFE("Get app window decor height failed");
1921         return WMError::WM_OK;
1922     }
1923     auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
1924     if (display == nullptr) {
1925         WLOGFE("get display failed displayId:%{public}" PRIu64, property_->GetDisplayId());
1926         return WMError::WM_ERROR_NULLPTR;
1927     }
1928     auto displayInfo = display->GetDisplayInfo();
1929     if (displayInfo == nullptr) {
1930         WLOGFE("get display info failed displayId:%{public}" PRIu64, property_->GetDisplayId());
1931         return WMError::WM_ERROR_NULLPTR;
1932     }
1933     float vpr = GetVirtualPixelRatio(displayInfo);
1934     if (MathHelper::NearZero(vpr)) {
1935         WLOGFE("get decor height failed, because of wrong vpr: %{public}f", vpr);
1936         return WMError::WM_ERROR_INVALID_WINDOW;
1937     }
1938     height = static_cast<int32_t>(height / vpr);
1939     WLOGI("Get app window decor height success, height : %{public}d", height);
1940     return WMError::WM_OK;
1941 }
1942 
GetTitleButtonArea(TitleButtonRect & titleButtonRect)1943 WMError WindowSessionImpl::GetTitleButtonArea(TitleButtonRect& titleButtonRect)
1944 {
1945     if (IsWindowSessionInvalid()) {
1946         return WMError::WM_ERROR_INVALID_WINDOW;
1947     }
1948     Rect decorRect;
1949     Rect titleButtonLeftRect;
1950     bool res = false;
1951     {
1952         std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1953         if (uiContent == nullptr) {
1954             WLOGFE("uicontent is empty");
1955             return WMError::WM_ERROR_NULLPTR;
1956         }
1957         res = uiContent->GetContainerModalButtonsRect(decorRect, titleButtonLeftRect);
1958     }
1959     if (!res) {
1960         WLOGFE("get window title buttons area failed");
1961         titleButtonRect.IsUninitializedRect();
1962         return WMError::WM_OK;
1963     }
1964     auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
1965     if (display == nullptr) {
1966         WLOGFE("get display failed displayId:%{public}" PRIu64, property_->GetDisplayId());
1967         return WMError::WM_ERROR_NULLPTR;
1968     }
1969     auto displayInfo = display->GetDisplayInfo();
1970     if (displayInfo == nullptr) {
1971         WLOGFE("get display info failed displayId:%{public}" PRIu64, property_->GetDisplayId());
1972         return WMError::WM_ERROR_NULLPTR;
1973     }
1974     float vpr = GetVirtualPixelRatio(displayInfo);
1975     if (MathHelper::NearZero(vpr)) {
1976         WLOGFE("get title buttons area failed, because of wrong vpr: %{public}f", vpr);
1977         return WMError::WM_ERROR_INVALID_WINDOW;
1978     }
1979     titleButtonRect.posX_ = static_cast<int32_t>(decorRect.width_) -
1980         static_cast<int32_t>(titleButtonLeftRect.width_) - titleButtonLeftRect.posX_;
1981     titleButtonRect.posX_ = static_cast<int32_t>(titleButtonRect.posX_ / vpr);
1982     titleButtonRect.posY_ = static_cast<int32_t>(titleButtonLeftRect.posY_ / vpr);
1983     titleButtonRect.width_ = static_cast<uint32_t>(titleButtonLeftRect.width_ / vpr);
1984     titleButtonRect.height_ = static_cast<uint32_t>(titleButtonLeftRect.height_ / vpr);
1985     return WMError::WM_OK;
1986 }
1987 
GetUIContentRemoteObj(sptr<IRemoteObject> & uiContentRemoteObj)1988 WSError WindowSessionImpl::GetUIContentRemoteObj(sptr<IRemoteObject>& uiContentRemoteObj)
1989 {
1990     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1991     if (uiContent == nullptr) {
1992         TLOGE(WmsLogTag::DEFAULT, "uiContent is nullptr. Failed to get uiContentRemoteObj");
1993         return WSError::WS_ERROR_NULLPTR;
1994     }
1995     uiContentRemoteObj = uiContent->GetRemoteObj();
1996     return WSError::WS_OK;
1997 }
1998 
RegisterWindowTitleButtonRectChangeListener(const sptr<IWindowTitleButtonRectChangedListener> & listener)1999 WMError WindowSessionImpl::RegisterWindowTitleButtonRectChangeListener(
2000     const sptr<IWindowTitleButtonRectChangedListener>& listener)
2001 {
2002     if (IsWindowSessionInvalid()) {
2003         return WMError::WM_ERROR_INVALID_WINDOW;
2004     }
2005     auto persistentId = GetPersistentId();
2006     WLOGFD("Start register windowTitleButtonRectChange listener, id:%{public}d", persistentId);
2007     if (listener == nullptr) {
2008         WLOGFE("listener is nullptr");
2009         return WMError::WM_ERROR_NULLPTR;
2010     }
2011 
2012     {
2013         std::lock_guard<std::recursive_mutex> lockListener(windowTitleButtonRectChangeListenerMutex_);
2014         WMError ret = RegisterListener(windowTitleButtonRectChangeListeners_[persistentId], listener);
2015         if (ret != WMError::WM_OK) {
2016             WLOGFE("register the listener of window title button rect change failed");
2017             return ret;
2018         }
2019     }
2020     auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
2021     if (display == nullptr) {
2022         WLOGFE("get display failed displayId:%{public}" PRIu64, property_->GetDisplayId());
2023         return WMError::WM_ERROR_NULLPTR;
2024     }
2025     auto displayInfo = display->GetDisplayInfo();
2026     if (displayInfo == nullptr) {
2027         WLOGFE("get display info failed displayId:%{public}" PRIu64, property_->GetDisplayId());
2028         return WMError::WM_ERROR_NULLPTR;
2029     }
2030     float vpr = GetVirtualPixelRatio(displayInfo);
2031     if (MathHelper::NearZero(vpr)) {
2032         WLOGFE("register title button rect change listener failed, because of wrong vpr: %{public}f", vpr);
2033         return WMError::WM_ERROR_INVALID_WINDOW;
2034     }
2035     if (auto uiContent = GetUIContentSharedPtr()) {
2036         uiContent->SubscribeContainerModalButtonsRectChange(
2037             [vpr, weakThis = wptr(this)](Rect& decorRect, Rect& titleButtonLeftRect) {
2038             auto window = weakThis.promote();
2039             if (!window) {
2040                 TLOGNE(WmsLogTag::WMS_LAYOUT, "window is null");
2041                 return;
2042             }
2043             TitleButtonRect titleButtonRect;
2044             titleButtonRect.posX_ = static_cast<int32_t>(decorRect.width_) -
2045                 static_cast<int32_t>(titleButtonLeftRect.width_) - titleButtonLeftRect.posX_;
2046             titleButtonRect.posX_ = static_cast<int32_t>(titleButtonRect.posX_ / vpr);
2047             titleButtonRect.posY_ = static_cast<int32_t>(titleButtonLeftRect.posY_ / vpr);
2048             titleButtonRect.width_ = static_cast<uint32_t>(titleButtonLeftRect.width_ / vpr);
2049             titleButtonRect.height_ = static_cast<uint32_t>(titleButtonLeftRect.height_ / vpr);
2050             window->NotifyWindowTitleButtonRectChange(titleButtonRect);
2051         });
2052     }
2053     return WMError::WM_OK;
2054 }
2055 
UnregisterWindowTitleButtonRectChangeListener(const sptr<IWindowTitleButtonRectChangedListener> & listener)2056 WMError WindowSessionImpl::UnregisterWindowTitleButtonRectChangeListener(
2057     const sptr<IWindowTitleButtonRectChangedListener>& listener)
2058 {
2059     if (IsWindowSessionInvalid()) {
2060         return WMError::WM_ERROR_INVALID_WINDOW;
2061     }
2062     WMError ret = WMError::WM_OK;
2063     auto persistentId = GetPersistentId();
2064     WLOGFD("Start unregister windowTitleButtonRectChange listener, id:%{public}d", persistentId);
2065     if (listener == nullptr) {
2066         WLOGFE("listener is nullptr");
2067         return WMError::WM_ERROR_NULLPTR;
2068     }
2069     {
2070         std::lock_guard<std::recursive_mutex> lockListener(windowTitleButtonRectChangeListenerMutex_);
2071         ret = UnregisterListener(windowTitleButtonRectChangeListeners_[persistentId], listener);
2072         if (ret != WMError::WM_OK) {
2073             WLOGFE("unregister the listener of window title button rect change failed");
2074             return ret;
2075         }
2076     }
2077     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
2078     if (uiContent != nullptr) {
2079         uiContent->SubscribeContainerModalButtonsRectChange(nullptr);
2080     }
2081     return ret;
2082 }
2083 
2084 template<typename T>
2085 EnableIfSame<T, IWindowTitleButtonRectChangedListener,
GetListeners()2086     std::vector<sptr<IWindowTitleButtonRectChangedListener>>> WindowSessionImpl::GetListeners()
2087 {
2088     std::vector<sptr<IWindowTitleButtonRectChangedListener>> windowTitleButtonRectListeners;
2089         for (auto& listener : windowTitleButtonRectChangeListeners_[GetPersistentId()]) {
2090             windowTitleButtonRectListeners.push_back(listener);
2091         }
2092     return windowTitleButtonRectListeners;
2093 }
2094 
NotifyWindowTitleButtonRectChange(TitleButtonRect titleButtonRect)2095 void WindowSessionImpl::NotifyWindowTitleButtonRectChange(TitleButtonRect titleButtonRect)
2096 {
2097     std::lock_guard<std::recursive_mutex> lockListener(windowTitleButtonRectChangeListenerMutex_);
2098     auto windowTitleButtonRectListeners = GetListeners<IWindowTitleButtonRectChangedListener>();
2099     for (auto& listener : windowTitleButtonRectListeners) {
2100         if (listener != nullptr) {
2101             listener->OnWindowTitleButtonRectChanged(titleButtonRect);
2102         }
2103     }
2104 }
2105 
2106 template<typename T>
2107 EnableIfSame<T, IWindowRectChangeListener,
GetListeners()2108     std::vector<sptr<IWindowRectChangeListener>>> WindowSessionImpl::GetListeners()
2109 {
2110     std::vector<sptr<IWindowRectChangeListener>> windowRectChangeListeners;
2111     for (auto& listener : windowRectChangeListeners_[GetPersistentId()]) {
2112         windowRectChangeListeners.push_back(listener);
2113     }
2114     return windowRectChangeListeners;
2115 }
2116 
RegisterWindowRectChangeListener(const sptr<IWindowRectChangeListener> & listener)2117 WMError WindowSessionImpl::RegisterWindowRectChangeListener(const sptr<IWindowRectChangeListener>& listener)
2118 {
2119     WMError ret = WMError::WM_OK;
2120     {
2121         std::lock_guard<std::mutex> lockListener(windowRectChangeListenerMutex_);
2122         ret = RegisterListener(windowRectChangeListeners_[GetPersistentId()], listener);
2123     }
2124     auto hostSession = GetHostSession();
2125     if (hostSession != nullptr && ret == WMError::WM_OK) {
2126         hostSession->UpdateRectChangeListenerRegistered(true);
2127     }
2128     return ret;
2129 }
2130 
UnregisterWindowRectChangeListener(const sptr<IWindowRectChangeListener> & listener)2131 WMError WindowSessionImpl::UnregisterWindowRectChangeListener(const sptr<IWindowRectChangeListener>& listener)
2132 {
2133     WMError ret = WMError::WM_OK;
2134     bool windowRectChangeListenersEmpty = false;
2135     {
2136         std::lock_guard<std::mutex> lockListener(windowRectChangeListenerMutex_);
2137         ret = UnregisterListener(windowRectChangeListeners_[GetPersistentId()], listener);
2138         windowRectChangeListenersEmpty = windowRectChangeListeners_.count(GetPersistentId()) == 0 ||
2139                                          windowRectChangeListeners_[GetPersistentId()].empty();
2140     }
2141     auto hostSession = GetHostSession();
2142     if (hostSession != nullptr && windowRectChangeListenersEmpty) {
2143         hostSession->UpdateRectChangeListenerRegistered(false);
2144     }
2145     return ret;
2146 }
2147 
2148 template<typename T>
GetListeners()2149 EnableIfSame<T, ISubWindowCloseListener, sptr<ISubWindowCloseListener>> WindowSessionImpl::GetListeners()
2150 {
2151     sptr<ISubWindowCloseListener> subWindowCloseListeners;
2152     subWindowCloseListeners = subWindowCloseListeners_[GetPersistentId()];
2153     return subWindowCloseListeners;
2154 }
2155 
RegisterSubWindowCloseListeners(const sptr<ISubWindowCloseListener> & listener)2156 WMError WindowSessionImpl::RegisterSubWindowCloseListeners(const sptr<ISubWindowCloseListener>& listener)
2157 {
2158     if (listener == nullptr) {
2159         WLOGFE("listener is nullptr");
2160         return WMError::WM_ERROR_NULLPTR;
2161     }
2162     if (!WindowHelper::IsSubWindow(GetType()) && !WindowHelper::IsSystemSubWindow(GetType())) {
2163         WLOGFE("window type is not supported");
2164         return WMError::WM_ERROR_INVALID_CALLING;
2165     }
2166     std::lock_guard<std::mutex> lockListener(subWindowCloseListenersMutex_);
2167     subWindowCloseListeners_[GetPersistentId()] = listener;
2168     return WMError::WM_OK;
2169 }
2170 
UnregisterSubWindowCloseListeners(const sptr<ISubWindowCloseListener> & listener)2171 WMError WindowSessionImpl::UnregisterSubWindowCloseListeners(const sptr<ISubWindowCloseListener>& listener)
2172 {
2173     if (listener == nullptr) {
2174         WLOGFE("listener could not be null");
2175         return WMError::WM_ERROR_NULLPTR;
2176     }
2177     if (!WindowHelper::IsSubWindow(GetType()) && !WindowHelper::IsSystemSubWindow(GetType())) {
2178         WLOGFE("window type is not supported");
2179         return WMError::WM_ERROR_INVALID_CALLING;
2180     }
2181     std::lock_guard<std::mutex> lockListener(subWindowCloseListenersMutex_);
2182     subWindowCloseListeners_[GetPersistentId()] = nullptr;
2183     return WMError::WM_OK;
2184 }
2185 
2186 template<typename T>
2187 EnableIfSame<T, ISwitchFreeMultiWindowListener,
GetListeners()2188     std::vector<sptr<ISwitchFreeMultiWindowListener>>> WindowSessionImpl::GetListeners()
2189 {
2190     std::vector<sptr<ISwitchFreeMultiWindowListener>> switchFreeMultiWindowListeners;
2191     for (auto& listener : switchFreeMultiWindowListeners_[GetPersistentId()]) {
2192         switchFreeMultiWindowListeners.push_back(listener);
2193     }
2194     return switchFreeMultiWindowListeners;
2195 }
2196 
RegisterSwitchFreeMultiWindowListener(const sptr<ISwitchFreeMultiWindowListener> & listener)2197 WMError WindowSessionImpl::RegisterSwitchFreeMultiWindowListener(const sptr<ISwitchFreeMultiWindowListener>& listener)
2198 {
2199     if (listener == nullptr) {
2200         WLOGFE("listener is nullptr");
2201         return WMError::WM_ERROR_NULLPTR;
2202     }
2203     if (!WindowHelper::IsMainWindow(GetType())) {
2204         WLOGFE("window type is not supported");
2205         return WMError::WM_ERROR_INVALID_CALLING;
2206     }
2207     WLOGFD("Start register");
2208     std::lock_guard<std::mutex> lockListener(switchFreeMultiWindowListenerMutex_);
2209     return RegisterListener(switchFreeMultiWindowListeners_[GetPersistentId()], listener);
2210 }
2211 
UnregisterSwitchFreeMultiWindowListener(const sptr<ISwitchFreeMultiWindowListener> & listener)2212 WMError WindowSessionImpl::UnregisterSwitchFreeMultiWindowListener(const sptr<ISwitchFreeMultiWindowListener>& listener)
2213 {
2214     if (listener == nullptr) {
2215         WLOGFE("listener could not be null");
2216         return WMError::WM_ERROR_NULLPTR;
2217     }
2218     if (!WindowHelper::IsMainWindow(GetType())) {
2219         WLOGFE("window type is not supported");
2220         return WMError::WM_ERROR_INVALID_CALLING;
2221     }
2222     WLOGFD("Start unregister");
2223     std::lock_guard<std::mutex> lockListener(switchFreeMultiWindowListenerMutex_);
2224     return UnregisterListener(switchFreeMultiWindowListeners_[GetPersistentId()], listener);
2225 }
2226 
RecoverSessionListener()2227 void WindowSessionImpl::RecoverSessionListener()
2228 {
2229     auto persistentId = GetPersistentId();
2230     TLOGI(WmsLogTag::WMS_RECOVER, "with persistentId=%{public}d", persistentId);
2231     {
2232         std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
2233         if (avoidAreaChangeListeners_.find(persistentId) != avoidAreaChangeListeners_.end() &&
2234             !avoidAreaChangeListeners_[persistentId].empty()) {
2235             SingletonContainer::Get<WindowAdapter>().UpdateSessionAvoidAreaListener(persistentId, true);
2236         }
2237     }
2238     {
2239         std::lock_guard<std::recursive_mutex> lockListener(touchOutsideListenerMutex_);
2240         if (touchOutsideListeners_.find(persistentId) != touchOutsideListeners_.end() &&
2241             !touchOutsideListeners_[persistentId].empty()) {
2242             SingletonContainer::Get<WindowAdapter>().UpdateSessionTouchOutsideListener(persistentId, true);
2243         }
2244     }
2245     {
2246         std::lock_guard<std::recursive_mutex> lockListener(windowVisibilityChangeListenerMutex_);
2247         if (windowVisibilityChangeListeners_.find(persistentId) != windowVisibilityChangeListeners_.end() &&
2248             !windowVisibilityChangeListeners_[persistentId].empty()) {
2249             SingletonContainer::Get<WindowAdapter>().UpdateSessionWindowVisibilityListener(persistentId, true);
2250         }
2251     }
2252     {
2253         std::lock_guard<std::mutex> lockListener(windowRectChangeListenerMutex_);
2254         if (windowRectChangeListeners_.find(persistentId) != windowRectChangeListeners_.end() &&
2255             !windowRectChangeListeners_[persistentId].empty()) {
2256             if (auto hostSession = GetHostSession()) {
2257                 hostSession->UpdateRectChangeListenerRegistered(true);
2258             }
2259         }
2260     }
2261 }
2262 
2263 template<typename T>
GetListeners()2264 EnableIfSame<T, IWindowLifeCycle, std::vector<sptr<IWindowLifeCycle>>> WindowSessionImpl::GetListeners()
2265 {
2266     std::vector<sptr<IWindowLifeCycle>> lifecycleListeners;
2267     for (auto& listener : lifecycleListeners_[GetPersistentId()]) {
2268         lifecycleListeners.push_back(listener);
2269     }
2270     return lifecycleListeners;
2271 }
2272 
2273 template<typename T>
GetListeners()2274 EnableIfSame<T, IWindowChangeListener, std::vector<sptr<IWindowChangeListener>>> WindowSessionImpl::GetListeners()
2275 {
2276     std::vector<sptr<IWindowChangeListener>> windowChangeListeners;
2277     for (auto& listener : windowChangeListeners_[GetPersistentId()]) {
2278         windowChangeListeners.push_back(listener);
2279     }
2280     return windowChangeListeners;
2281 }
2282 
2283 template<typename T>
2284 EnableIfSame<T, IOccupiedAreaChangeListener,
GetListeners()2285     std::vector<sptr<IOccupiedAreaChangeListener>>> WindowSessionImpl::GetListeners()
2286 {
2287     std::vector<sptr<IOccupiedAreaChangeListener>> occupiedAreaChangeListeners;
2288     for (auto& listener : occupiedAreaChangeListeners_[GetPersistentId()]) {
2289         occupiedAreaChangeListeners.push_back(listener);
2290     }
2291     return occupiedAreaChangeListeners;
2292 }
2293 
2294 template<typename T>
RegisterListener(std::vector<sptr<T>> & holder,const sptr<T> & listener)2295 WMError WindowSessionImpl::RegisterListener(std::vector<sptr<T>>& holder, const sptr<T>& listener)
2296 {
2297     if (listener == nullptr) {
2298         WLOGFE("listener is nullptr");
2299         return WMError::WM_ERROR_NULLPTR;
2300     }
2301     if (std::find(holder.begin(), holder.end(), listener) != holder.end()) {
2302         WLOGFE("Listener already registered");
2303         return WMError::WM_OK;
2304     }
2305     holder.emplace_back(listener);
2306     return WMError::WM_OK;
2307 }
2308 
2309 template<typename T>
UnregisterListener(std::vector<sptr<T>> & holder,const sptr<T> & listener)2310 WMError WindowSessionImpl::UnregisterListener(std::vector<sptr<T>>& holder, const sptr<T>& listener)
2311 {
2312     if (listener == nullptr) {
2313         WLOGFE("listener could not be null");
2314         return WMError::WM_ERROR_NULLPTR;
2315     }
2316     holder.erase(std::remove_if(holder.begin(), holder.end(),
2317         [listener](sptr<T> registeredListener) {
2318             return registeredListener == listener;
2319         }), holder.end());
2320     return WMError::WM_OK;
2321 }
2322 
2323 template<typename T>
ClearUselessListeners(std::map<int32_t,T> & listeners,int32_t persistentId)2324 void WindowSessionImpl::ClearUselessListeners(std::map<int32_t, T>& listeners, int32_t persistentId)
2325 {
2326     listeners.erase(persistentId);
2327 }
2328 
2329 template<typename T>
GetListeners()2330 EnableIfSame<T, IWindowStatusChangeListener, std::vector<sptr<IWindowStatusChangeListener>>> WindowSessionImpl::GetListeners()
2331 {
2332     std::vector<sptr<IWindowStatusChangeListener>> windowStatusChangeListeners;
2333     for (auto& listener : windowStatusChangeListeners_[GetPersistentId()]) {
2334         windowStatusChangeListeners.push_back(listener);
2335     }
2336     return windowStatusChangeListeners;
2337 }
2338 
ClearListenersById(int32_t persistentId)2339 void WindowSessionImpl::ClearListenersById(int32_t persistentId)
2340 {
2341     TLOGI(WmsLogTag::WMS_LIFE, "Called id: %{public}d.", GetPersistentId());
2342     {
2343         std::lock_guard<std::mutex> lockListener(displayMoveListenerMutex_);
2344         ClearUselessListeners(displayMoveListeners_, persistentId);
2345     }
2346     {
2347         std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
2348         ClearUselessListeners(lifecycleListeners_, persistentId);
2349     }
2350     {
2351         std::lock_guard<std::recursive_mutex> lockListener(windowChangeListenerMutex_);
2352         ClearUselessListeners(windowChangeListeners_, persistentId);
2353     }
2354     {
2355         std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
2356         ClearUselessListeners(avoidAreaChangeListeners_, persistentId);
2357     }
2358     {
2359         std::lock_guard<std::recursive_mutex> lockListener(dialogDeathRecipientListenerMutex_);
2360         ClearUselessListeners(dialogDeathRecipientListeners_, persistentId);
2361     }
2362     {
2363         std::lock_guard<std::recursive_mutex> lockListener(dialogTargetTouchListenerMutex_);
2364         ClearUselessListeners(dialogTargetTouchListener_, persistentId);
2365     }
2366     {
2367         std::lock_guard<std::recursive_mutex> lockListener(screenshotListenerMutex_);
2368         ClearUselessListeners(screenshotListeners_, persistentId);
2369     }
2370     {
2371         std::lock_guard<std::recursive_mutex> lockListener(windowStatusChangeListenerMutex_);
2372         ClearUselessListeners(windowStatusChangeListeners_, persistentId);
2373     }
2374     {
2375         std::lock_guard<std::recursive_mutex> lockListener(windowTitleButtonRectChangeListenerMutex_);
2376         ClearUselessListeners(windowTitleButtonRectChangeListeners_, persistentId);
2377     }
2378     {
2379         std::lock_guard<std::recursive_mutex> lockListener(windowNoInteractionListenerMutex_);
2380         ClearUselessListeners(windowNoInteractionListeners_, persistentId);
2381     }
2382     {
2383         std::lock_guard<std::mutex> lockListener(windowRectChangeListenerMutex_);
2384         ClearUselessListeners(windowRectChangeListeners_, persistentId);
2385     }
2386     {
2387         std::lock_guard<std::mutex> lockListener(subWindowCloseListenersMutex_);
2388         ClearUselessListeners(subWindowCloseListeners_, persistentId);
2389     }
2390     {
2391         std::lock_guard<std::recursive_mutex> lockListener(occupiedAreaChangeListenerMutex_);
2392         ClearUselessListeners(occupiedAreaChangeListeners_, persistentId);
2393     }
2394     ClearSwitchFreeMultiWindowListenersById(persistentId);
2395     TLOGI(WmsLogTag::WMS_LIFE, "Clear success, id: %{public}d.", GetPersistentId());
2396 }
2397 
ClearSwitchFreeMultiWindowListenersById(int32_t persistentId)2398 void WindowSessionImpl::ClearSwitchFreeMultiWindowListenersById(int32_t persistentId)
2399 {
2400     std::lock_guard<std::mutex> lockListener(switchFreeMultiWindowListenerMutex_);
2401     ClearUselessListeners(switchFreeMultiWindowListeners_, persistentId);
2402 }
2403 
RegisterWindowDestroyedListener(const NotifyNativeWinDestroyFunc & func)2404 void WindowSessionImpl::RegisterWindowDestroyedListener(const NotifyNativeWinDestroyFunc& func)
2405 {
2406     notifyNativeFunc_ = std::move(func);
2407 }
2408 
ClearVsyncStation()2409 void WindowSessionImpl::ClearVsyncStation()
2410 {
2411     std::lock_guard<std::recursive_mutex> lock(mutex_);
2412     if (vsyncStation_ != nullptr) {
2413         vsyncStation_.reset();
2414     }
2415 }
2416 
SetInputEventConsumer(const std::shared_ptr<IInputEventConsumer> & inputEventConsumer)2417 void WindowSessionImpl::SetInputEventConsumer(const std::shared_ptr<IInputEventConsumer>& inputEventConsumer)
2418 {
2419     TLOGI(WmsLogTag::WMS_EVENT, "called");
2420     std::lock_guard<std::recursive_mutex> lock(mutex_);
2421     inputEventConsumer_ = inputEventConsumer;
2422 }
2423 
SetTitleButtonVisible(bool isMaximizeVisible,bool isMinimizeVisible,bool isSplitVisible)2424 WMError WindowSessionImpl::SetTitleButtonVisible(bool isMaximizeVisible, bool isMinimizeVisible, bool isSplitVisible)
2425 {
2426     if (IsWindowSessionInvalid()) {
2427         return WMError::WM_ERROR_INVALID_WINDOW;
2428     }
2429     if (!WindowHelper::IsMainWindow(GetType())) {
2430         return WMError::WM_ERROR_INVALID_CALLING;
2431     }
2432     if (GetUIContentSharedPtr() == nullptr || !IsDecorEnable()) {
2433         return WMError::WM_ERROR_INVALID_WINDOW;
2434     }
2435     if (!IsPcOrPadCapabilityEnabled()) {
2436         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
2437     }
2438     windowTitleVisibleFlags_ = { isMaximizeVisible, isMinimizeVisible, isSplitVisible };
2439     UpdateTitleButtonVisibility();
2440     return WMError::WM_OK;
2441 }
2442 
NotifyAfterForeground(bool needNotifyListeners,bool needNotifyUiContent)2443 void WindowSessionImpl::NotifyAfterForeground(bool needNotifyListeners, bool needNotifyUiContent)
2444 {
2445     if (needNotifyListeners) {
2446         std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
2447         auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
2448         CALL_LIFECYCLE_LISTENER(AfterForeground, lifecycleListeners);
2449     }
2450     if (needNotifyUiContent) {
2451         CALL_UI_CONTENT(Foreground);
2452     }
2453     if (vsyncStation_ == nullptr) {
2454         TLOGE(WmsLogTag::WMS_MAIN, "SetFrameRateLinkerEnable true failed, vsyncStation is nullptr");
2455         return;
2456     }
2457     TLOGD(WmsLogTag::WMS_MAIN, "SetFrameRateLinkerEnable: true, linkerId = %{public}" PRIu64,
2458         vsyncStation_->GetFrameRateLinkerId());
2459     vsyncStation_->SetFrameRateLinkerEnable(true);
2460     if (WindowHelper::IsMainWindow(GetType())) {
2461         TLOGD(WmsLogTag::WMS_MAIN, "IsMainWindow: %{public}d, WindowType: %{public}d",
2462             WindowHelper::IsMainWindow(GetType()), GetType());
2463         vsyncStation_->SetDisplaySoloistFrameRateLinkerEnable(true);
2464     }
2465 }
2466 
NotifyAfterBackground(bool needNotifyListeners,bool needNotifyUiContent)2467 void WindowSessionImpl::NotifyAfterBackground(bool needNotifyListeners, bool needNotifyUiContent)
2468 {
2469     if (needNotifyListeners) {
2470         std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
2471         auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
2472         CALL_LIFECYCLE_LISTENER(AfterBackground, lifecycleListeners);
2473     }
2474     if (needNotifyUiContent) {
2475         CALL_UI_CONTENT(Background);
2476     }
2477     if (vsyncStation_ == nullptr) {
2478         TLOGE(WmsLogTag::WMS_MAIN, "SetFrameRateLinkerEnable false failed, vsyncStation is nullptr");
2479         return;
2480     }
2481     TLOGD(WmsLogTag::WMS_MAIN, "SetFrameRateLinkerEnable: false, linkerId = %{public}" PRIu64,
2482         vsyncStation_->GetFrameRateLinkerId());
2483     vsyncStation_->SetFrameRateLinkerEnable(false);
2484     if (WindowHelper::IsMainWindow(GetType())) {
2485         TLOGD(WmsLogTag::WMS_MAIN, "IsMainWindow: %{public}d, WindowType: %{public}d",
2486             WindowHelper::IsMainWindow(GetType()), GetType());
2487         vsyncStation_->SetDisplaySoloistFrameRateLinkerEnable(false);
2488     }
2489 }
2490 
RequestInputMethodCloseKeyboard(bool isNeedKeyboard,bool keepKeyboardFlag)2491 static void RequestInputMethodCloseKeyboard(bool isNeedKeyboard, bool keepKeyboardFlag)
2492 {
2493     if (!isNeedKeyboard && !keepKeyboardFlag) {
2494 #ifdef IMF_ENABLE
2495         TLOGI(WmsLogTag::WMS_KEYBOARD, "Notify InputMethod framework close keyboard start.");
2496         if (MiscServices::InputMethodController::GetInstance()) {
2497             MiscServices::InputMethodController::GetInstance()->RequestHideInput();
2498             TLOGI(WmsLogTag::WMS_KEYBOARD, "Notify InputMethod framework close keyboard end.");
2499         }
2500 #endif
2501     }
2502 }
2503 
NotifyUIContentFocusStatus()2504 void WindowSessionImpl::NotifyUIContentFocusStatus()
2505 {
2506     if (!isFocused_) {
2507         CALL_UI_CONTENT(UnFocus);
2508         return;
2509     }
2510     CALL_UI_CONTENT(Focus);
2511     auto task = [weak = wptr(this)]() {
2512         auto window = weak.promote();
2513         if (!window) {
2514             return;
2515         }
2516         bool isNeedKeyboard = false;
2517         {
2518             std::shared_ptr<Ace::UIContent> uiContent = window->GetUIContentSharedPtr();
2519             if (uiContent != nullptr) {
2520                 // isNeedKeyboard is set by arkui and indicates whether the window needs a keyboard or not.
2521                 isNeedKeyboard = uiContent->NeedSoftKeyboard();
2522             }
2523         }
2524         // whether keep the keyboard created by other windows, support system window and app subwindow.
2525         bool keepKeyboardFlag = (window->property_) ? window->property_->GetKeepKeyboardFlag() : false;
2526         TLOGI(WmsLogTag::WMS_KEYBOARD, "isNeedKeyboard: %{public}d, keepKeyboardFlag: %{public}d",
2527             isNeedKeyboard, keepKeyboardFlag);
2528         RequestInputMethodCloseKeyboard(isNeedKeyboard, keepKeyboardFlag);
2529     };
2530     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
2531     if (uiContent != nullptr) {
2532         uiContent->SetOnWindowFocused(task);
2533     }
2534 }
2535 
NotifyAfterFocused()2536 void WindowSessionImpl::NotifyAfterFocused()
2537 {
2538     NotifyWindowAfterFocused();
2539     if (GetUIContentSharedPtr() != nullptr) {
2540         NotifyUIContentFocusStatus();
2541     } else {
2542         shouldReNotifyFocus_ = true;
2543     }
2544 }
2545 
NotifyAfterUnfocused(bool needNotifyUiContent)2546 void WindowSessionImpl::NotifyAfterUnfocused(bool needNotifyUiContent)
2547 {
2548     NotifyWindowAfterUnfocused();
2549     if (needNotifyUiContent) {
2550         if (GetUIContentSharedPtr() == nullptr) {
2551             shouldReNotifyFocus_ = true;
2552         } else {
2553             CALL_UI_CONTENT(UnFocus);
2554         }
2555     }
2556 }
2557 
NotifyWindowAfterFocused()2558 void WindowSessionImpl::NotifyWindowAfterFocused()
2559 {
2560     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
2561     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
2562     CALL_LIFECYCLE_LISTENER(AfterFocused, lifecycleListeners);
2563 }
2564 
NotifyWindowAfterUnfocused()2565 void WindowSessionImpl::NotifyWindowAfterUnfocused()
2566 {
2567     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
2568     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
2569     // use needNotifyUinContent to separate ui content callbacks
2570     CALL_LIFECYCLE_LISTENER(AfterUnfocused, lifecycleListeners);
2571 }
2572 
NotifyBeforeDestroy(std::string windowName)2573 void WindowSessionImpl::NotifyBeforeDestroy(std::string windowName)
2574 {
2575     auto task = [this]() {
2576         {
2577             std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
2578             if (uiContent != nullptr) {
2579                 uiContent->Destroy();
2580             }
2581         }
2582         {
2583             std::unique_lock<std::shared_mutex> lock(uiContentMutex_);
2584             if (uiContent_ != nullptr) {
2585                 uiContent_ = nullptr;
2586                 TLOGD(WmsLogTag::WMS_LIFE, "NotifyBeforeDestroy: uiContent destroy success, persistentId:%{public}d",
2587                     GetPersistentId());
2588             }
2589         }
2590     };
2591     if (handler_) {
2592         handler_->PostSyncTask(task, "wms:NotifyBeforeDestroy");
2593     } else {
2594         task();
2595     }
2596     TLOGI(WmsLogTag::WMS_LIFE, "Release uicontent successfully, id: %{public}d.", GetPersistentId());
2597     if (notifyNativeFunc_) {
2598         notifyNativeFunc_(windowName);
2599     }
2600     TLOGI(WmsLogTag::WMS_LIFE, "successed with id: %{public}d.", GetPersistentId());
2601 }
2602 
NotifyAfterDestroy()2603 void WindowSessionImpl::NotifyAfterDestroy()
2604 {
2605     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
2606     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
2607     CALL_LIFECYCLE_LISTENER(AfterDestroyed, lifecycleListeners);
2608 }
2609 
NotifyAfterActive()2610 void WindowSessionImpl::NotifyAfterActive()
2611 {
2612     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
2613     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
2614     CALL_LIFECYCLE_LISTENER(AfterActive, lifecycleListeners);
2615 }
2616 
NotifyAfterInactive()2617 void WindowSessionImpl::NotifyAfterInactive()
2618 {
2619     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
2620     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
2621     CALL_LIFECYCLE_LISTENER(AfterInactive, lifecycleListeners);
2622 }
2623 
NotifyForegroundFailed(WMError ret)2624 void WindowSessionImpl::NotifyForegroundFailed(WMError ret)
2625 {
2626     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
2627     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
2628     CALL_LIFECYCLE_LISTENER_WITH_PARAM(ForegroundFailed, lifecycleListeners, static_cast<int32_t>(ret));
2629 }
2630 
NotifyBackgroundFailed(WMError ret)2631 void WindowSessionImpl::NotifyBackgroundFailed(WMError ret)
2632 {
2633     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
2634     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
2635     CALL_LIFECYCLE_LISTENER_WITH_PARAM(BackgroundFailed, lifecycleListeners, static_cast<int32_t>(ret));
2636 }
2637 
NotifyAfterResumed()2638 void WindowSessionImpl::NotifyAfterResumed()
2639 {
2640     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
2641     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
2642     CALL_LIFECYCLE_LISTENER(AfterResumed, lifecycleListeners);
2643 }
2644 
NotifyAfterPaused()2645 void WindowSessionImpl::NotifyAfterPaused()
2646 {
2647     std::lock_guard<std::recursive_mutex> lockListener(lifeCycleListenerMutex_);
2648     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
2649     CALL_LIFECYCLE_LISTENER(AfterPaused, lifecycleListeners);
2650 }
2651 
MarkProcessed(int32_t eventId)2652 WSError WindowSessionImpl::MarkProcessed(int32_t eventId)
2653 {
2654     if (IsWindowSessionInvalid()) {
2655         WLOGFE("HostSession is invalid");
2656         return WSError::WS_DO_NOTHING;
2657     }
2658     auto hostSession = GetHostSession();
2659     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WSError::WS_DO_NOTHING);
2660     return hostSession->MarkProcessed(eventId);
2661 }
2662 
RegisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener> & listener)2663 void WindowSessionImpl::RegisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener>& listener)
2664 {
2665     TLOGI(WmsLogTag::WMS_DIALOG, "window %{public}s id %{public}d register DialogDeathRecipientListener",
2666         GetWindowName().c_str(), GetPersistentId());
2667     if (listener == nullptr) {
2668         WLOGFE("listener is nullptr");
2669         return;
2670     }
2671     std::lock_guard<std::recursive_mutex> lockListener(dialogDeathRecipientListenerMutex_);
2672     RegisterListener(dialogDeathRecipientListeners_[GetPersistentId()], listener);
2673 }
2674 
UnregisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener> & listener)2675 void WindowSessionImpl::UnregisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener>& listener)
2676 {
2677     TLOGI(WmsLogTag::WMS_DIALOG, "window %{public}s id %{public}d unregister DialogDeathRecipientListener",
2678         GetWindowName().c_str(), GetPersistentId());
2679     std::lock_guard<std::recursive_mutex> lockListener(dialogDeathRecipientListenerMutex_);
2680     UnregisterListener(dialogDeathRecipientListeners_[GetPersistentId()], listener);
2681 }
2682 
RegisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener> & listener)2683 WMError WindowSessionImpl::RegisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener>& listener)
2684 {
2685     TLOGI(WmsLogTag::WMS_DIALOG, "window %{public}s id %{public}d register DialogTargetTouchListener",
2686         GetWindowName().c_str(), GetPersistentId());
2687     if (listener == nullptr) {
2688         WLOGFE("listener is nullptr");
2689         return WMError::WM_ERROR_NULLPTR;
2690     }
2691     std::lock_guard<std::recursive_mutex> lockListener(dialogTargetTouchListenerMutex_);
2692     return RegisterListener(dialogTargetTouchListener_[GetPersistentId()], listener);
2693 }
2694 
UnregisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener> & listener)2695 WMError WindowSessionImpl::UnregisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener>& listener)
2696 {
2697     TLOGI(WmsLogTag::WMS_DIALOG, "window %{public}s id %{public}d unregister DialogTargetTouchListener",
2698         GetWindowName().c_str(), GetPersistentId());
2699     std::lock_guard<std::recursive_mutex> lockListener(dialogTargetTouchListenerMutex_);
2700     return UnregisterListener(dialogTargetTouchListener_[GetPersistentId()], listener);
2701 }
2702 
RegisterScreenshotListener(const sptr<IScreenshotListener> & listener)2703 WMError WindowSessionImpl::RegisterScreenshotListener(const sptr<IScreenshotListener>& listener)
2704 {
2705     WLOGFD("Start register ScreenshotListener");
2706     std::lock_guard<std::recursive_mutex> lockListener(screenshotListenerMutex_);
2707     return RegisterListener(screenshotListeners_[GetPersistentId()], listener);
2708 }
2709 
UnregisterScreenshotListener(const sptr<IScreenshotListener> & listener)2710 WMError WindowSessionImpl::UnregisterScreenshotListener(const sptr<IScreenshotListener>& listener)
2711 {
2712     WLOGFD("Start unregister ScreenshotListener");
2713     std::lock_guard<std::recursive_mutex> lockListener(screenshotListenerMutex_);
2714     return UnregisterListener(screenshotListeners_[GetPersistentId()], listener);
2715 }
2716 
2717 template<typename T>
2718 EnableIfSame<T, IDialogDeathRecipientListener, std::vector<sptr<IDialogDeathRecipientListener>>> WindowSessionImpl::
GetListeners()2719     GetListeners()
2720 {
2721     std::vector<sptr<IDialogDeathRecipientListener>> dialogDeathRecipientListener;
2722     for (auto& listener : dialogDeathRecipientListeners_[GetPersistentId()]) {
2723         dialogDeathRecipientListener.push_back(listener);
2724     }
2725     return dialogDeathRecipientListener;
2726 }
2727 
2728 template<typename T>
2729 EnableIfSame<T, IDialogTargetTouchListener,
GetListeners()2730     std::vector<sptr<IDialogTargetTouchListener>>> WindowSessionImpl::GetListeners()
2731 {
2732     std::vector<sptr<IDialogTargetTouchListener>> dialogTargetTouchListener;
2733     for (auto& listener : dialogTargetTouchListener_[GetPersistentId()]) {
2734         dialogTargetTouchListener.push_back(listener);
2735     }
2736     return dialogTargetTouchListener;
2737 }
2738 
2739 template<typename T>
GetListeners()2740 EnableIfSame<T, IScreenshotListener, std::vector<sptr<IScreenshotListener>>> WindowSessionImpl::GetListeners()
2741 {
2742     std::vector<sptr<IScreenshotListener>> screenshotListeners;
2743     for (auto& listener : screenshotListeners_[GetPersistentId()]) {
2744         screenshotListeners.push_back(listener);
2745     }
2746     return screenshotListeners;
2747 }
2748 
NotifyDestroy()2749 WSError WindowSessionImpl::NotifyDestroy()
2750 {
2751     std::lock_guard<std::recursive_mutex> lockListener(dialogDeathRecipientListenerMutex_);
2752     auto dialogDeathRecipientListener = GetListeners<IDialogDeathRecipientListener>();
2753     for (auto& listener : dialogDeathRecipientListener) {
2754         if (listener != nullptr) {
2755             listener->OnDialogDeathRecipient();
2756         }
2757     }
2758     return WSError::WS_OK;
2759 }
2760 
2761 template<typename T>
GetListeners()2762 EnableIfSame<T, IDisplayMoveListener, std::vector<sptr<IDisplayMoveListener>>> WindowSessionImpl::GetListeners()
2763 {
2764     std::vector<sptr<IDisplayMoveListener>> displayMoveListeners;
2765     for (auto& listener : displayMoveListeners_[GetPersistentId()]) {
2766         displayMoveListeners.push_back(listener);
2767     }
2768     return displayMoveListeners;
2769 }
2770 
NotifyDisplayMove(DisplayId from,DisplayId to)2771 void WindowSessionImpl::NotifyDisplayMove(DisplayId from, DisplayId to)
2772 {
2773     WLOGFD("Notify display move from %{public}" PRIu64 " to %{public}" PRIu64, from, to);
2774     std::lock_guard<std::mutex> lockListener(displayMoveListenerMutex_);
2775     auto displayMoveListeners = GetListeners<IDisplayMoveListener>();
2776     for (auto& listener : displayMoveListeners) {
2777         if (listener != nullptr) {
2778             listener->OnDisplayMove(from, to);
2779         }
2780     }
2781 }
2782 
NotifyCloseExistPipWindow()2783 WSError WindowSessionImpl::NotifyCloseExistPipWindow()
2784 {
2785     TLOGI(WmsLogTag::WMS_PIP, "WindowSessionImpl::NotifyCloseExistPipWindow");
2786     auto task = []() {
2787         PictureInPictureManager::DoClose(true, true);
2788     };
2789     handler_->PostTask(task, "WMS_WindowSessionImpl_NotifyCloseExistPipWindow");
2790     return WSError::WS_OK;
2791 }
2792 
NotifyTouchDialogTarget(int32_t posX,int32_t posY)2793 void WindowSessionImpl::NotifyTouchDialogTarget(int32_t posX, int32_t posY)
2794 {
2795     TLOGI(WmsLogTag::WMS_DIALOG, "window %{public}s id %{public}d", GetWindowName().c_str(), GetPersistentId());
2796     auto hostSession = GetHostSession();
2797     if (hostSession != nullptr) {
2798         hostSession->ProcessPointDownSession(posX, posY);
2799     }
2800     std::lock_guard<std::recursive_mutex> lockListener(dialogTargetTouchListenerMutex_);
2801     auto dialogTargetTouchListener = GetListeners<IDialogTargetTouchListener>();
2802     for (auto& listener : dialogTargetTouchListener) {
2803         if (listener != nullptr) {
2804             listener->OnDialogTargetTouch();
2805         }
2806     }
2807 }
2808 
NotifyScreenshot()2809 void WindowSessionImpl::NotifyScreenshot()
2810 {
2811     std::lock_guard<std::recursive_mutex> lockListener(screenshotListenerMutex_);
2812     auto screenshotListeners = GetListeners<IScreenshotListener>();
2813     for (auto& listener : screenshotListeners) {
2814         if (listener != nullptr) {
2815             listener->OnScreenshot();
2816         }
2817     }
2818 }
2819 
NotifySizeChange(Rect rect,WindowSizeChangeReason reason)2820 void WindowSessionImpl::NotifySizeChange(Rect rect, WindowSizeChangeReason reason)
2821 {
2822     {
2823         std::lock_guard<std::recursive_mutex> lockListener(windowChangeListenerMutex_);
2824         auto windowChangeListeners = GetListeners<IWindowChangeListener>();
2825         for (auto& listener : windowChangeListeners) {
2826             if (listener != nullptr) {
2827                 listener->OnSizeChange(rect, reason);
2828             }
2829         }
2830     }
2831     {
2832         std::lock_guard<std::mutex> lockRectListener(windowRectChangeListenerMutex_);
2833         auto windowRectChangeListeners = GetListeners<IWindowRectChangeListener>();
2834         for (auto& listener : windowRectChangeListeners) {
2835             if (listener != nullptr) {
2836                 listener->OnRectChange(rect, reason);
2837             }
2838         }
2839     }
2840 }
2841 
NotifySubWindowClose(bool & terminateCloseProcess)2842 void WindowSessionImpl::NotifySubWindowClose(bool& terminateCloseProcess)
2843 {
2844     WLOGFD("WindowSessionImpl::NotifySubWindowClose");
2845     std::lock_guard<std::mutex> lockListener(subWindowCloseListenersMutex_);
2846     auto subWindowCloseListeners = GetListeners<ISubWindowCloseListener>();
2847     if (subWindowCloseListeners != nullptr) {
2848         subWindowCloseListeners->OnSubWindowClose(terminateCloseProcess);
2849     }
2850 }
2851 
NotifySwitchFreeMultiWindow(bool enable)2852 void WindowSessionImpl::NotifySwitchFreeMultiWindow(bool enable)
2853 {
2854     std::lock_guard<std::mutex> lockListener(switchFreeMultiWindowListenerMutex_);
2855     auto switchFreeMultiWindowListeners = GetListeners<ISwitchFreeMultiWindowListener>();
2856     for (auto& listener : switchFreeMultiWindowListeners) {
2857         if (listener != nullptr) {
2858             listener->OnSwitchFreeMultiWindow(enable);
2859         }
2860     }
2861 }
2862 
RegisterAvoidAreaChangeListener(sptr<IAvoidAreaChangedListener> & listener)2863 WMError WindowSessionImpl::RegisterAvoidAreaChangeListener(sptr<IAvoidAreaChangedListener>& listener)
2864 {
2865     bool isUpdate = false;
2866     WMError ret = WMError::WM_OK;
2867     auto persistentId = GetPersistentId();
2868     TLOGI(WmsLogTag::WMS_IMMS, "Start register avoidAreaChange listener, id:%{public}d", persistentId);
2869     if (listener == nullptr) {
2870         TLOGE(WmsLogTag::WMS_IMMS, "listener is nullptr");
2871         return WMError::WM_ERROR_NULLPTR;
2872     }
2873 
2874     {
2875         std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
2876         ret = RegisterListener(avoidAreaChangeListeners_[persistentId], listener);
2877         if (ret != WMError::WM_OK) {
2878             return ret;
2879         }
2880         if (avoidAreaChangeListeners_[persistentId].size() == 1) {
2881             isUpdate = true;
2882         }
2883     }
2884     if (isUpdate) {
2885         ret = SingletonContainer::Get<WindowAdapter>().UpdateSessionAvoidAreaListener(persistentId, true);
2886     }
2887     return ret;
2888 }
2889 
UnregisterAvoidAreaChangeListener(sptr<IAvoidAreaChangedListener> & listener)2890 WMError WindowSessionImpl::UnregisterAvoidAreaChangeListener(sptr<IAvoidAreaChangedListener>& listener)
2891 {
2892     bool isUpdate = false;
2893     WMError ret = WMError::WM_OK;
2894     auto persistentId = GetPersistentId();
2895     TLOGI(WmsLogTag::WMS_IMMS, "Start unregister avoidAreaChange listener, id:%{public}d", persistentId);
2896     if (listener == nullptr) {
2897         WLOGFE("listener is nullptr");
2898         return WMError::WM_ERROR_NULLPTR;
2899     }
2900 
2901     {
2902         std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
2903         ret = UnregisterListener(avoidAreaChangeListeners_[persistentId], listener);
2904         if (ret != WMError::WM_OK) {
2905             return ret;
2906         }
2907         if (avoidAreaChangeListeners_[persistentId].empty()) {
2908             isUpdate = true;
2909         }
2910     }
2911     if (isUpdate) {
2912         ret = SingletonContainer::Get<WindowAdapter>().UpdateSessionAvoidAreaListener(persistentId, false);
2913     }
2914     return ret;
2915 }
2916 
RegisterExtensionAvoidAreaChangeListener(sptr<IAvoidAreaChangedListener> & listener)2917 WMError WindowSessionImpl::RegisterExtensionAvoidAreaChangeListener(sptr<IAvoidAreaChangedListener>& listener)
2918 {
2919     auto persistentId = GetPersistentId();
2920     WLOGI("Start register extension avoidAreaChange listener, id:%{public}d", persistentId);
2921     std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
2922     return RegisterListener(avoidAreaChangeListeners_[persistentId], listener);
2923 }
2924 
UnregisterExtensionAvoidAreaChangeListener(sptr<IAvoidAreaChangedListener> & listener)2925 WMError WindowSessionImpl::UnregisterExtensionAvoidAreaChangeListener(sptr<IAvoidAreaChangedListener>& listener)
2926 {
2927     auto persistentId = GetPersistentId();
2928     WLOGI("Start unregister extension avoidAreaChange listener, id:%{public}d", persistentId);
2929     std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
2930     return UnregisterListener(avoidAreaChangeListeners_[persistentId], listener);
2931 }
2932 
2933 template<typename T>
2934 EnableIfSame<T, IAvoidAreaChangedListener,
GetListeners()2935     std::vector<sptr<IAvoidAreaChangedListener>>> WindowSessionImpl::GetListeners()
2936 {
2937     std::vector<sptr<IAvoidAreaChangedListener>> windowChangeListeners;
2938     for (auto& listener : avoidAreaChangeListeners_[GetPersistentId()]) {
2939         windowChangeListeners.push_back(listener);
2940     }
2941     return windowChangeListeners;
2942 }
2943 
NotifyAvoidAreaChange(const sptr<AvoidArea> & avoidArea,AvoidAreaType type)2944 void WindowSessionImpl::NotifyAvoidAreaChange(const sptr<AvoidArea>& avoidArea, AvoidAreaType type)
2945 {
2946     TLOGI(WmsLogTag::WMS_IMMS,
2947           "window [%{public}d, %{public}s] type %{public}d area %{public}s",
2948           GetPersistentId(), GetWindowName().c_str(), type, avoidArea->ToString().c_str());
2949     std::lock_guard<std::recursive_mutex> lockListener(avoidAreaChangeListenerMutex_);
2950     auto avoidAreaChangeListeners = GetListeners<IAvoidAreaChangedListener>();
2951     for (auto& listener : avoidAreaChangeListeners) {
2952         if (listener != nullptr) {
2953             listener->OnAvoidAreaChanged(*avoidArea, type);
2954         }
2955     }
2956 }
2957 
NotifyTransferComponentData(const AAFwk::WantParams & wantParams)2958 WSError WindowSessionImpl::NotifyTransferComponentData(const AAFwk::WantParams& wantParams)
2959 {
2960     return WSError::WS_OK;
2961 }
2962 
NotifyTransferComponentDataSync(const AAFwk::WantParams & wantParams,AAFwk::WantParams & reWantParams)2963 WSErrorCode WindowSessionImpl::NotifyTransferComponentDataSync(const AAFwk::WantParams& wantParams,
2964     AAFwk::WantParams& reWantParams)
2965 {
2966     return WSErrorCode::WS_OK;
2967 }
2968 
UpdateAvoidArea(const sptr<AvoidArea> & avoidArea,AvoidAreaType type)2969 WSError WindowSessionImpl::UpdateAvoidArea(const sptr<AvoidArea>& avoidArea, AvoidAreaType type)
2970 {
2971     UpdateViewportConfig(GetRect(), WindowSizeChangeReason::UNDEFINED, nullptr, nullptr, {{type, *avoidArea}});
2972     NotifyAvoidAreaChange(avoidArea, type);
2973     return WSError::WS_OK;
2974 }
2975 
SetPipActionEvent(const std::string & action,int32_t status)2976 WSError WindowSessionImpl::SetPipActionEvent(const std::string& action, int32_t status)
2977 {
2978     TLOGI(WmsLogTag::WMS_PIP, "action: %{public}s, status: %{public}d", action.c_str(), status);
2979     auto task = [action, status]() {
2980         PictureInPictureManager::DoActionEvent(action, status);
2981     };
2982     handler_->PostTask(task, "WMS_WindowSessionImpl_SetPipActionEvent");
2983     return WSError::WS_OK;
2984 }
2985 
SetPiPControlEvent(WsPiPControlType controlType,WsPiPControlStatus status)2986 WSError WindowSessionImpl::SetPiPControlEvent(WsPiPControlType controlType, WsPiPControlStatus status)
2987 {
2988     TLOGI(WmsLogTag::WMS_PIP, "controlType:%{public}u, enabled:%{public}d", controlType, status);
2989     auto task = [controlType, status]() {
2990         PictureInPictureManager::DoControlEvent(static_cast<PiPControlType>(controlType),
2991             static_cast<PiPControlStatus>(status));
2992     };
2993     handler_->PostTask(task, "WMS_WindowSessionImpl_SetPiPControlEvent");
2994     return WSError::WS_OK;
2995 }
2996 
RegisterTouchOutsideListener(const sptr<ITouchOutsideListener> & listener)2997 WMError WindowSessionImpl::RegisterTouchOutsideListener(const sptr<ITouchOutsideListener>& listener)
2998 {
2999     bool isUpdate = false;
3000     WMError ret = WMError::WM_OK;
3001     auto persistentId = GetPersistentId();
3002     TLOGI(WmsLogTag::WMS_EVENT, "Start register touchOutside listener, window: name=%{public}s, id=%{public}u",
3003         GetWindowName().c_str(), GetPersistentId());
3004     if (listener == nullptr) {
3005         TLOGE(WmsLogTag::WMS_EVENT, "listener is nullptr");
3006         return WMError::WM_ERROR_NULLPTR;
3007     }
3008 
3009     {
3010         std::lock_guard<std::recursive_mutex> lockListener(touchOutsideListenerMutex_);
3011         ret = RegisterListener(touchOutsideListeners_[persistentId], listener);
3012         if (ret != WMError::WM_OK) {
3013             TLOGE(WmsLogTag::WMS_EVENT, "Register touchOutside listener fail, ret:%{public}u", ret);
3014             return ret;
3015         }
3016         if (touchOutsideListeners_[persistentId].size() == 1) {
3017             isUpdate = true;
3018         }
3019     }
3020     if (isUpdate) {
3021         ret = SingletonContainer::Get<WindowAdapter>().UpdateSessionTouchOutsideListener(persistentId, true);
3022     }
3023     return ret;
3024 }
3025 
UnregisterTouchOutsideListener(const sptr<ITouchOutsideListener> & listener)3026 WMError WindowSessionImpl::UnregisterTouchOutsideListener(const sptr<ITouchOutsideListener>& listener)
3027 {
3028     bool isUpdate = false;
3029     WMError ret = WMError::WM_OK;
3030     auto persistentId = GetPersistentId();
3031     TLOGI(WmsLogTag::WMS_EVENT, "Start unregister touchOutside listener, window: name=%{public}s, id=%{public}u",
3032         GetWindowName().c_str(), GetPersistentId());
3033     if (listener == nullptr) {
3034         TLOGE(WmsLogTag::WMS_EVENT, "listener is nullptr");
3035         return WMError::WM_ERROR_NULLPTR;
3036     }
3037 
3038     {
3039         std::lock_guard<std::recursive_mutex> lockListener(touchOutsideListenerMutex_);
3040         ret = UnregisterListener(touchOutsideListeners_[persistentId], listener);
3041         if (ret != WMError::WM_OK) {
3042             TLOGE(WmsLogTag::WMS_EVENT, "Unregister touchOutside listener fail, ret:%{public}u", ret);
3043             return ret;
3044         }
3045         if (touchOutsideListeners_[persistentId].empty()) {
3046             isUpdate = true;
3047         }
3048     }
3049     if (isUpdate) {
3050         ret = SingletonContainer::Get<WindowAdapter>().UpdateSessionTouchOutsideListener(persistentId, false);
3051     }
3052     return ret;
3053 }
3054 
3055 template<typename T>
GetListeners()3056 EnableIfSame<T, ITouchOutsideListener, std::vector<sptr<ITouchOutsideListener>>> WindowSessionImpl::GetListeners()
3057 {
3058     std::vector<sptr<ITouchOutsideListener>> windowChangeListeners;
3059     for (auto& listener : touchOutsideListeners_[GetPersistentId()]) {
3060         windowChangeListeners.push_back(listener);
3061     }
3062     return windowChangeListeners;
3063 }
3064 
NotifyTouchOutside()3065 WSError WindowSessionImpl::NotifyTouchOutside()
3066 {
3067     TLOGI(WmsLogTag::WMS_EVENT, "Notify touch outside, window: name=%{public}s, id=%{public}u",
3068         GetWindowName().c_str(), GetPersistentId());
3069     std::lock_guard<std::recursive_mutex> lockListener(touchOutsideListenerMutex_);
3070     auto touchOutsideListeners = GetListeners<ITouchOutsideListener>();
3071     for (auto& listener : touchOutsideListeners) {
3072         if (listener != nullptr) {
3073             listener->OnTouchOutside();
3074         }
3075     }
3076     return WSError::WS_OK;
3077 }
3078 
RegisterWindowVisibilityChangeListener(const IWindowVisibilityListenerSptr & listener)3079 WMError WindowSessionImpl::RegisterWindowVisibilityChangeListener(const IWindowVisibilityListenerSptr& listener)
3080 {
3081     auto persistentId = GetPersistentId();
3082     WLOGFD("Start to register window visibility change listener, persistentId=%{public}d.", persistentId);
3083     WMError ret = WMError::WM_OK;
3084     bool isFirstRegister = false;
3085     {
3086         std::lock_guard<std::recursive_mutex> lockListener(windowVisibilityChangeListenerMutex_);
3087         ret = RegisterListener(windowVisibilityChangeListeners_[persistentId], listener);
3088         if (ret != WMError::WM_OK) {
3089             return ret;
3090         }
3091         isFirstRegister = windowVisibilityChangeListeners_[persistentId].size() == 1;
3092     }
3093 
3094     if (isFirstRegister) {
3095         ret = SingletonContainer::Get<WindowAdapter>().UpdateSessionWindowVisibilityListener(persistentId, true);
3096     }
3097     return ret;
3098 }
3099 
UnregisterWindowVisibilityChangeListener(const IWindowVisibilityListenerSptr & listener)3100 WMError WindowSessionImpl::UnregisterWindowVisibilityChangeListener(const IWindowVisibilityListenerSptr& listener)
3101 {
3102     auto persistentId = GetPersistentId();
3103     WLOGFD("Start to unregister window visibility change listener, persistentId=%{public}d.", persistentId);
3104     WMError ret = WMError::WM_OK;
3105     bool isLastUnregister = false;
3106     {
3107         std::lock_guard<std::recursive_mutex> lockListener(windowVisibilityChangeListenerMutex_);
3108         ret = UnregisterListener(windowVisibilityChangeListeners_[persistentId], listener);
3109         if (ret != WMError::WM_OK) {
3110             return ret;
3111         }
3112         isLastUnregister = windowVisibilityChangeListeners_[persistentId].empty();
3113     }
3114 
3115     if (isLastUnregister) {
3116         ret = SingletonContainer::Get<WindowAdapter>().UpdateSessionWindowVisibilityListener(persistentId, false);
3117     }
3118     return ret;
3119 }
3120 
RegisterWindowNoInteractionListener(const IWindowNoInteractionListenerSptr & listener)3121 WMError WindowSessionImpl::RegisterWindowNoInteractionListener(const IWindowNoInteractionListenerSptr& listener)
3122 {
3123     WLOGFD("Start to register window no interaction listener.");
3124     std::lock_guard<std::recursive_mutex> lockListener(windowNoInteractionListenerMutex_);
3125     WMError ret = RegisterListener(windowNoInteractionListeners_[GetPersistentId()], listener);
3126     if (ret != WMError::WM_OK) {
3127         WLOGFE("register no interaction listener failed.");
3128     } else {
3129         SubmitNoInteractionMonitorTask(this->lastInteractionEventId_.load(), listener);
3130     }
3131     return ret;
3132 }
3133 
UnregisterWindowNoInteractionListener(const IWindowNoInteractionListenerSptr & listener)3134 WMError WindowSessionImpl::UnregisterWindowNoInteractionListener(const IWindowNoInteractionListenerSptr& listener)
3135 {
3136     WLOGFD("Start to unregister window no interaction listener.");
3137     std::lock_guard<std::recursive_mutex> lockListener(windowNoInteractionListenerMutex_);
3138     WMError ret = UnregisterListener(windowNoInteractionListeners_[GetPersistentId()], listener);
3139     if (windowNoInteractionListeners_[GetPersistentId()].empty()) {
3140         lastInteractionEventId_.store(-1);
3141     }
3142     return ret;
3143 }
3144 
3145 template<typename T>
GetListeners()3146 EnableIfSame<T, IWindowVisibilityChangedListener, std::vector<IWindowVisibilityListenerSptr>> WindowSessionImpl::GetListeners()
3147 {
3148     std::vector<IWindowVisibilityListenerSptr> windowVisibilityChangeListeners;
3149     for (auto& listener : windowVisibilityChangeListeners_[GetPersistentId()]) {
3150         windowVisibilityChangeListeners.push_back(listener);
3151     }
3152     return windowVisibilityChangeListeners;
3153 }
3154 
3155 template<typename T>
GetListeners()3156 EnableIfSame<T, IWindowNoInteractionListener, std::vector<IWindowNoInteractionListenerSptr>> WindowSessionImpl::GetListeners()
3157 {
3158     std::vector<IWindowNoInteractionListenerSptr> noInteractionListeners;
3159     for (auto& listener : windowNoInteractionListeners_[GetPersistentId()]) {
3160         noInteractionListeners.push_back(listener);
3161     }
3162     return noInteractionListeners;
3163 }
3164 
NotifyWindowVisibility(bool isVisible)3165 WSError WindowSessionImpl::NotifyWindowVisibility(bool isVisible)
3166 {
3167     WLOGFD("Notify window visibility Change, window: name=%{public}s, id=%{public}u, isVisible:%{public}d",
3168         GetWindowName().c_str(), GetPersistentId(), isVisible);
3169     std::lock_guard<std::recursive_mutex> lockListener(windowVisibilityChangeListenerMutex_);
3170     auto windowVisibilityListeners = GetListeners<IWindowVisibilityChangedListener>();
3171     for (auto& listener : windowVisibilityListeners) {
3172         if (listener != nullptr) {
3173             listener->OnWindowVisibilityChangedCallback(isVisible);
3174         }
3175     }
3176     return WSError::WS_OK;
3177 }
3178 
NotifyNoInteractionTimeout(const IWindowNoInteractionListenerSptr & listener)3179 WSError WindowSessionImpl::NotifyNoInteractionTimeout(const IWindowNoInteractionListenerSptr& listener)
3180 {
3181     if (listener == nullptr) {
3182         WLOGFE("invalid listener: nullptr");
3183         return WSError::WS_ERROR_NULLPTR;
3184     }
3185     WLOGFD("Notify window no interaction timeout, window: name=%{public}s, id=%{public}u, timeout=%{public}" PRId64,
3186         GetWindowName().c_str(), GetPersistentId(), listener->GetTimeout());
3187 
3188     listener->OnWindowNoInteractionCallback();
3189     return WSError::WS_OK;
3190 }
3191 
NotifyPointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)3192 void WindowSessionImpl::NotifyPointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
3193 {
3194     if (!pointerEvent) {
3195         TLOGE(WmsLogTag::WMS_INPUT_KEY_FLOW, "Pointer event is nullptr");
3196         return;
3197     }
3198 
3199     std::shared_ptr<IInputEventConsumer> inputEventConsumer;
3200     {
3201         std::lock_guard<std::recursive_mutex> lock(mutex_);
3202         inputEventConsumer = inputEventConsumer_;
3203     }
3204     if (inputEventConsumer != nullptr) {
3205         WLOGFD("Transfer pointer event to inputEventConsumer");
3206         if (pointerEvent->GetPointerAction() != MMI::PointerEvent::POINTER_ACTION_MOVE) {
3207             TLOGI(WmsLogTag::WMS_INPUT_KEY_FLOW,
3208                 "Transfer pointer event to inputEventConsumer InputTracking id:%{public}d",
3209                 pointerEvent->GetId());
3210         }
3211         if (!(inputEventConsumer->OnInputEvent(pointerEvent))) {
3212             pointerEvent->MarkProcessed();
3213         }
3214         return;
3215     }
3216 
3217     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3218     if (uiContent != nullptr) {
3219         if (pointerEvent->GetPointerAction() != MMI::PointerEvent::POINTER_ACTION_MOVE) {
3220             TLOGI(WmsLogTag::WMS_EVENT, "Input id:%{public}d",
3221                 pointerEvent->GetId());
3222         }
3223         if (!(uiContent->ProcessPointerEvent(pointerEvent))) {
3224             TLOGI(WmsLogTag::WMS_INPUT_KEY_FLOW, "UI content dose not consume this pointer event");
3225             pointerEvent->MarkProcessed();
3226         }
3227     } else {
3228         TLOGW(WmsLogTag::WMS_INPUT_KEY_FLOW, "pointerEvent is not consumed, windowId: %{public}u", GetWindowId());
3229         pointerEvent->MarkProcessed();
3230     }
3231 }
3232 
SetKeyEventFilter(KeyEventFilterFunc filter)3233 WMError WindowSessionImpl::SetKeyEventFilter(KeyEventFilterFunc filter)
3234 {
3235     std::unique_lock<std::shared_mutex> lock(keyEventFilterMutex_);
3236     keyEventFilter_ = std::move(filter);
3237     return WMError::WM_OK;
3238 }
3239 
ClearKeyEventFilter()3240 WMError WindowSessionImpl::ClearKeyEventFilter()
3241 {
3242     std::unique_lock<std::shared_mutex> lock(keyEventFilterMutex_);
3243     keyEventFilter_ = nullptr;
3244     return WMError::WM_OK;
3245 }
3246 
FilterKeyEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent)3247 bool WindowSessionImpl::FilterKeyEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
3248 {
3249     std::shared_lock<std::shared_mutex> lock(keyEventFilterMutex_);
3250     if (keyEventFilter_ != nullptr) {
3251         bool isFilter = keyEventFilter_(*keyEvent.get());
3252         TLOGE(WmsLogTag::WMS_SYSTEM, "keyCode:%{public}d isFilter:%{public}d",
3253             keyEvent->GetKeyCode(), isFilter);
3254         if (isFilter) {
3255             keyEvent->MarkProcessed();
3256             return true;
3257         }
3258     }
3259     return false;
3260 }
3261 
DispatchKeyEventCallback(const std::shared_ptr<MMI::KeyEvent> & keyEvent,bool & isConsumed)3262 void WindowSessionImpl::DispatchKeyEventCallback(const std::shared_ptr<MMI::KeyEvent>& keyEvent, bool& isConsumed)
3263 {
3264     std::shared_ptr<IInputEventConsumer> inputEventConsumer;
3265     {
3266         std::lock_guard<std::recursive_mutex> lock(mutex_);
3267         inputEventConsumer = inputEventConsumer_;
3268     }
3269     int32_t keyCode = keyEvent->GetKeyCode();
3270     int32_t keyAction = keyEvent->GetKeyAction();
3271     if (keyCode == MMI::KeyEvent::KEYCODE_BACK && keyAction == MMI::KeyEvent::KEY_ACTION_UP) {
3272         WLOGFI("input event is consumed by back, return");
3273         if (inputEventConsumer != nullptr) {
3274             WLOGFD("Transfer key event to inputEventConsumer");
3275             if (inputEventConsumer->OnInputEvent(keyEvent)) {
3276                 return;
3277             }
3278             PerformBack();
3279             keyEvent->MarkProcessed();
3280             return;
3281         }
3282         HandleBackEvent();
3283         keyEvent->MarkProcessed();
3284         return;
3285     }
3286 
3287     if (inputEventConsumer != nullptr) {
3288         WLOGD("Transfer key event to inputEventConsumer");
3289         if (!(inputEventConsumer->OnInputEvent(keyEvent))) {
3290             keyEvent->MarkProcessed();
3291         }
3292         return;
3293     }
3294 
3295     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3296     if (uiContent) {
3297         if (FilterKeyEvent(keyEvent)) return;
3298         isConsumed = uiContent->ProcessKeyEvent(keyEvent);
3299         if (!isConsumed && keyEvent->GetKeyCode() == MMI::KeyEvent::KEYCODE_ESCAPE &&
3300             property_->GetWindowMode() == WindowMode::WINDOW_MODE_FULLSCREEN &&
3301             GetImmersiveModeEnabledState() &&
3302             keyAction == MMI::KeyEvent::KEY_ACTION_DOWN && !escKeyEventTriggered_) {
3303             WLOGI("recover from fullscreen cause KEYCODE_ESCAPE");
3304             Recover();
3305         }
3306         if (!isConsumed) {
3307             keyEvent->MarkProcessed();
3308         }
3309         if (keyEvent->GetKeyCode() == MMI::KeyEvent::KEYCODE_ESCAPE) {
3310             escKeyEventTriggered_ = (keyAction == MMI::KeyEvent::KEY_ACTION_UP) ? false : true;
3311         }
3312     }
3313 }
3314 
HandleBackEvent()3315 WSError WindowSessionImpl::HandleBackEvent()
3316 {
3317     TLOGI(WmsLogTag::WMS_EVENT, "called");
3318     bool isConsumed = false;
3319     std::shared_ptr<IInputEventConsumer> inputEventConsumer;
3320     {
3321         std::lock_guard<std::recursive_mutex> lock(mutex_);
3322         inputEventConsumer = inputEventConsumer_;
3323     }
3324     if (inputEventConsumer != nullptr) {
3325         WLOGFD("Transfer back event to inputEventConsumer");
3326         std::shared_ptr<MMI::KeyEvent> backKeyEvent = MMI::KeyEvent::Create();
3327         if (backKeyEvent == nullptr) {
3328             WLOGFE("backKeyEvent is null");
3329             return WSError::WS_ERROR_NULLPTR;
3330         }
3331         backKeyEvent->SetKeyCode(MMI::KeyEvent::KEYCODE_BACK);
3332         backKeyEvent->SetKeyAction(MMI::KeyEvent::KEY_ACTION_UP);
3333         isConsumed = inputEventConsumer->OnInputEvent(backKeyEvent);
3334     } else {
3335         std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3336         if (uiContent != nullptr) {
3337             WLOGFD("Transfer back event to uiContent");
3338             isConsumed = uiContent->ProcessBackPressed();
3339         } else {
3340             WLOGFE("There is no back event consumer");
3341         }
3342     }
3343 
3344     if (isConsumed) {
3345         WLOGD("Back key event is consumed");
3346         return WSError::WS_OK;
3347     }
3348     WLOGFD("report Back");
3349     SingletonContainer::Get<WindowInfoReporter>().ReportBackButtonInfoImmediately();
3350     if (handler_ == nullptr) {
3351         WLOGFE("HandleBackEvent handler_ is nullptr!");
3352         return WSError::WS_ERROR_INVALID_PARAM;
3353     }
3354     // notify back event to host session
3355     wptr<WindowSessionImpl> weak = this;
3356     auto task = [weak]() {
3357         auto weakSession = weak.promote();
3358         if (weakSession == nullptr) {
3359             WLOGFE("HandleBackEvent session wptr is nullptr");
3360             return;
3361         }
3362         weakSession->PerformBack();
3363     };
3364     if (!handler_->PostTask(task, "wms:PerformBack")) {
3365         WLOGFE("Failed to post PerformBack");
3366         return WSError::WS_ERROR_INVALID_OPERATION;
3367     }
3368     return WSError::WS_OK;
3369 }
3370 
NotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent,bool & isConsumed,bool notifyInputMethod)3371 void WindowSessionImpl::NotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent, bool& isConsumed,
3372     bool notifyInputMethod)
3373 {
3374     if (keyEvent == nullptr) {
3375         WLOGFE("keyEvent is nullptr");
3376         return;
3377     }
3378 
3379 #ifdef IMF_ENABLE
3380     bool isKeyboardEvent = IsKeyboardEvent(keyEvent);
3381     if (isKeyboardEvent && notifyInputMethod) {
3382         WLOGD("Async dispatch keyEvent to input method");
3383         auto callback = [weakThis = wptr(this)] (std::shared_ptr<MMI::KeyEvent>& keyEvent, bool consumed) {
3384             if (keyEvent == nullptr) {
3385                 WLOGFW("keyEvent is null, consumed:%{public}" PRId32, consumed);
3386                 return;
3387             }
3388 
3389             if (consumed) {
3390                 WLOGD("Input method has processed key event, id:%{public}" PRId32, keyEvent->GetId());
3391                 return;
3392             }
3393 
3394             auto promoteThis = weakThis.promote();
3395             if (promoteThis == nullptr) {
3396                 WLOGFW("promoteThis is nullptr");
3397                 keyEvent->MarkProcessed();
3398                 return;
3399             }
3400             bool isConsumed = false;
3401             promoteThis->DispatchKeyEventCallback(keyEvent, isConsumed);
3402         };
3403         auto ret = MiscServices::InputMethodController::GetInstance()->DispatchKeyEvent(
3404             const_cast<std::shared_ptr<MMI::KeyEvent>&>(keyEvent), callback);
3405         if (ret != 0) {
3406             WLOGFE("DispatchKeyEvent failed, ret:%{public}" PRId32 ", id:%{public}" PRId32, ret, keyEvent->GetId());
3407             DispatchKeyEventCallback(keyEvent, isConsumed);
3408         }
3409         return;
3410     }
3411 #endif // IMF_ENABLE
3412     DispatchKeyEventCallback(keyEvent, isConsumed);
3413 }
3414 
IsKeyboardEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent) const3415 bool WindowSessionImpl::IsKeyboardEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent) const
3416 {
3417     int32_t keyCode = keyEvent->GetKeyCode();
3418     bool isKeyFN = (keyCode == MMI::KeyEvent::KEYCODE_FN);
3419     bool isKeyBack = (keyCode == MMI::KeyEvent::KEYCODE_BACK);
3420     bool isKeyboard = (keyCode >= MMI::KeyEvent::KEYCODE_0 && keyCode <= MMI::KeyEvent::KEYCODE_NUMPAD_RIGHT_PAREN);
3421     bool isKeySound = (keyCode == MMI::KeyEvent::KEYCODE_SOUND);
3422     WLOGD("isKeyFN: %{public}d, isKeyboard: %{public}d", isKeyFN, isKeyboard);
3423     return (isKeyFN || isKeyboard || isKeyBack || isKeySound);
3424 }
3425 
RequestVsync(const std::shared_ptr<VsyncCallback> & vsyncCallback)3426 void WindowSessionImpl::RequestVsync(const std::shared_ptr<VsyncCallback>& vsyncCallback)
3427 {
3428     std::lock_guard<std::recursive_mutex> lock(mutex_);
3429     if (state_ == WindowState::STATE_DESTROYED) {
3430         WLOGFE("Receive vsync request failed, window is destroyed");
3431         return;
3432     }
3433 
3434     if (vsyncStation_ == nullptr) {
3435         TLOGE(WmsLogTag::WMS_MAIN, "Receive vsync request failed, vsyncStation is nullptr");
3436         return;
3437     }
3438     vsyncStation_->RequestVsync(vsyncCallback);
3439 }
3440 
GetVSyncPeriod()3441 int64_t WindowSessionImpl::GetVSyncPeriod()
3442 {
3443     std::lock_guard<std::recursive_mutex> lock(mutex_);
3444     if (vsyncStation_ == nullptr) {
3445         TLOGE(WmsLogTag::WMS_MAIN, "Get vsync period failed, vsyncStation is nullptr");
3446         return 0;
3447     }
3448     return vsyncStation_->GetVSyncPeriod();
3449 }
3450 
FlushFrameRate(uint32_t rate,int32_t animatorExpectedFrameRate,uint32_t rateType)3451 void WindowSessionImpl::FlushFrameRate(uint32_t rate, int32_t animatorExpectedFrameRate, uint32_t rateType)
3452 {
3453     std::lock_guard<std::recursive_mutex> lock(mutex_);
3454     if (vsyncStation_ == nullptr) {
3455         TLOGE(WmsLogTag::WMS_MAIN, "FlushFrameRate failed, vsyncStation is nullptr");
3456         return;
3457     }
3458     vsyncStation_->FlushFrameRate(rate, animatorExpectedFrameRate, rateType);
3459 }
3460 
UpdateProperty(WSPropertyChangeAction action)3461 WMError WindowSessionImpl::UpdateProperty(WSPropertyChangeAction action)
3462 {
3463     TLOGD(WmsLogTag::DEFAULT, "action:%{public}u", action);
3464     if (IsWindowSessionInvalid()) {
3465         TLOGE(WmsLogTag::DEFAULT, "session is invalid");
3466         return WMError::WM_ERROR_INVALID_WINDOW;
3467     }
3468     auto hostSession = GetHostSession();
3469     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
3470     return hostSession->UpdateSessionPropertyByAction(property_, action);
3471 }
3472 
Find(const std::string & name)3473 sptr<Window> WindowSessionImpl::Find(const std::string& name)
3474 {
3475     std::shared_lock<std::shared_mutex> lock(windowSessionMutex_);
3476     TLOGI(WmsLogTag::DEFAULT, "Try to find window %{public}s", name.c_str());
3477     auto iter = windowSessionMap_.find(name);
3478     if (iter == windowSessionMap_.end()) {
3479         TLOGE(WmsLogTag::DEFAULT, "Can not find window %{public}s", name.c_str());
3480         return nullptr;
3481     }
3482     return iter->second.second;
3483 }
3484 
SetAceAbilityHandler(const sptr<IAceAbilityHandler> & handler)3485 void WindowSessionImpl::SetAceAbilityHandler(const sptr<IAceAbilityHandler>& handler)
3486 {
3487     if (handler == nullptr) {
3488         WLOGE("ace ability handler is nullptr");
3489     }
3490     std::lock_guard<std::recursive_mutex> lock(mutex_);
3491     aceAbilityHandler_ = handler;
3492 }
3493 
SetBackgroundColor(const std::string & color)3494 WMError WindowSessionImpl::SetBackgroundColor(const std::string& color)
3495 {
3496     if (IsWindowSessionInvalid()) {
3497         TLOGE(WmsLogTag::DEFAULT, "session is invalid");
3498         return WMError::WM_ERROR_INVALID_WINDOW;
3499     }
3500     uint32_t colorValue;
3501     if (ColorParser::Parse(color, colorValue)) {
3502         TLOGD(WmsLogTag::DEFAULT, "SetBackgroundColor: window: %{public}s, value: [%{public}s, %{public}u]",
3503             GetWindowName().c_str(), color.c_str(), colorValue);
3504         return SetBackgroundColor(colorValue);
3505     }
3506     TLOGE(WmsLogTag::DEFAULT, "invalid color string: %{public}s", color.c_str());
3507     return WMError::WM_ERROR_INVALID_PARAM;
3508 }
3509 
SetBackgroundColor(uint32_t color)3510 WMError WindowSessionImpl::SetBackgroundColor(uint32_t color)
3511 {
3512     TLOGI(WmsLogTag::DEFAULT, "window: %{public}s, value:%{public}u", GetWindowName().c_str(), color);
3513 
3514     // 0xff000000: ARGB style, means Opaque color.
3515     const bool isAlphaZero = !(color & 0xff000000);
3516     std::string bundleName;
3517     std::string abilityName;
3518     if ((context_ != nullptr) && (context_->GetApplicationInfo() != nullptr)) {
3519         bundleName = context_->GetBundleName();
3520         abilityName = context_->GetApplicationInfo()->name;
3521     }
3522 
3523     if (isAlphaZero && WindowHelper::IsMainWindow(GetType())) {
3524         auto& reportInstance = SingletonContainer::Get<WindowInfoReporter>();
3525         reportInstance.ReportZeroOpacityInfoImmediately(bundleName, abilityName);
3526     }
3527     {
3528         std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3529         if (uiContent != nullptr) {
3530             uiContent->SetBackgroundColor(color);
3531             return WMError::WM_OK;
3532         }
3533     }
3534     if (aceAbilityHandler_ != nullptr) {
3535         aceAbilityHandler_->SetBackgroundColor(color);
3536         return WMError::WM_OK;
3537     }
3538     TLOGD(WmsLogTag::DEFAULT, "FA mode could not set bg color: %{public}u", GetWindowId());
3539     return WMError::WM_ERROR_INVALID_OPERATION;
3540 }
3541 
FindWindowById(uint32_t winId)3542 sptr<Window> WindowSessionImpl::FindWindowById(uint32_t winId)
3543 {
3544     std::shared_lock<std::shared_mutex> lock(windowSessionMutex_);
3545     if (windowSessionMap_.empty()) {
3546         WLOGFE("Please create mainWindow First!");
3547         return nullptr;
3548     }
3549     for (auto iter = windowSessionMap_.begin(); iter != windowSessionMap_.end(); iter++) {
3550         if (static_cast<int32_t>(winId) == iter->second.first) {
3551             WLOGD("FindWindow id: %{public}u", winId);
3552             return iter->second.second;
3553         }
3554     }
3555     WLOGFE("Cannot find Window, id: %{public}d", winId);
3556     return nullptr;
3557 }
3558 
GetSubWindow(int parentId)3559 std::vector<sptr<Window>> WindowSessionImpl::GetSubWindow(int parentId)
3560 {
3561     auto iter = subWindowSessionMap_.find(parentId);
3562     if (iter == subWindowSessionMap_.end()) {
3563         return std::vector<sptr<Window>>();
3564     }
3565     return std::vector<sptr<Window>>(subWindowSessionMap_[parentId].begin(), subWindowSessionMap_[parentId].end());
3566 }
3567 
GetBackgroundColor() const3568 uint32_t WindowSessionImpl::GetBackgroundColor() const
3569 {
3570     {
3571         std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3572         if (uiContent != nullptr) {
3573             return uiContent->GetBackgroundColor();
3574         }
3575     }
3576     WLOGD("uiContent is nullptr, windowId: %{public}u, use FA mode", GetWindowId());
3577     if (aceAbilityHandler_ != nullptr) {
3578         return aceAbilityHandler_->GetBackgroundColor();
3579     }
3580     WLOGFD("FA mode does not get bg color: %{public}u", GetWindowId());
3581     return 0xffffffff; // means no background color been set, default color is white
3582 }
3583 
SetLayoutFullScreenByApiVersion(bool status)3584 WMError WindowSessionImpl::SetLayoutFullScreenByApiVersion(bool status)
3585 {
3586     return WMError::WM_OK;
3587 }
3588 
SetWindowGravity(WindowGravity gravity,uint32_t percent)3589 WMError WindowSessionImpl::SetWindowGravity(WindowGravity gravity, uint32_t percent)
3590 {
3591     auto sessionGravity = static_cast<SessionGravity>(gravity);
3592     TLOGI(WmsLogTag::WMS_KEYBOARD, "Set window gravity: %{public}u, percent: %{public}u", sessionGravity, percent);
3593     if (property_ != nullptr) {
3594         property_->SetKeyboardSessionGravity(sessionGravity, percent);
3595     }
3596 
3597     auto hostSession = GetHostSession();
3598     if (hostSession != nullptr) {
3599         return static_cast<WMError>(hostSession->SetKeyboardSessionGravity(
3600             static_cast<SessionGravity>(gravity), percent));
3601     }
3602     return WMError::WM_OK;
3603 }
3604 
SetSystemBarProperty(WindowType type,const SystemBarProperty & property)3605 WMError WindowSessionImpl::SetSystemBarProperty(WindowType type, const SystemBarProperty& property)
3606 {
3607     return WMError::WM_OK;
3608 }
3609 
SetSpecificBarProperty(WindowType type,const SystemBarProperty & property)3610 WMError WindowSessionImpl::SetSpecificBarProperty(WindowType type, const SystemBarProperty& property)
3611 {
3612     return WMError::WM_OK;
3613 }
3614 
NotifyOccupiedAreaChangeInfoInner(sptr<OccupiedAreaChangeInfo> info)3615 void WindowSessionImpl::NotifyOccupiedAreaChangeInfoInner(sptr<OccupiedAreaChangeInfo> info)
3616 {
3617     std::lock_guard<std::recursive_mutex> lockListener(occupiedAreaChangeListenerMutex_);
3618     auto occupiedAreaChangeListeners = GetListeners<IOccupiedAreaChangeListener>();
3619     for (auto& listener : occupiedAreaChangeListeners) {
3620         if (listener != nullptr) {
3621             listener->OnSizeChange(info);
3622         }
3623     }
3624 }
3625 
NotifyOccupiedAreaChangeInfo(sptr<OccupiedAreaChangeInfo> info,const std::shared_ptr<RSTransaction> & rsTransaction)3626 void WindowSessionImpl::NotifyOccupiedAreaChangeInfo(sptr<OccupiedAreaChangeInfo> info,
3627                                                      const std::shared_ptr<RSTransaction>& rsTransaction)
3628 {
3629     TLOGI(WmsLogTag::WMS_KEYBOARD, "hasRSTransaction: %{public}d, safeHeight: %{public}u"
3630         ", occupied rect: x %{public}u, y %{public}u, w %{public}u, h %{public}u", rsTransaction != nullptr,
3631         info->safeHeight_, info->rect_.posX_, info->rect_.posY_, info->rect_.width_, info->rect_.height_);
3632     if (handler_ == nullptr) {
3633         TLOGE(WmsLogTag::WMS_KEYBOARD, "handler_ is nullptr, notify occupied area change info failed");
3634         return;
3635     }
3636     auto task = [weak = wptr(this), info, rsTransaction]() {
3637         auto window = weak.promote();
3638         if (!window) {
3639             TLOGE(WmsLogTag::WMS_KEYBOARD, "window is nullptr, notify occupied area change info failed");
3640             return;
3641         }
3642         if (rsTransaction) {
3643             RSTransaction::FlushImplicitTransaction();
3644             rsTransaction->Begin();
3645         }
3646         window->NotifyOccupiedAreaChangeInfoInner(info);
3647         if (rsTransaction) {
3648             rsTransaction->Commit();
3649         }
3650     };
3651     handler_->PostTask(task, "WMS_WindowSessionImpl_NotifyOccupiedAreaChangeInfo");
3652 }
3653 
GetKeyboardAnimationConfig()3654 KeyboardAnimationConfig WindowSessionImpl::GetKeyboardAnimationConfig()
3655 {
3656     return { windowSystemConfig_.animationIn_, windowSystemConfig_.animationOut_ };
3657 }
3658 
DumpSessionElementInfo(const std::vector<std::string> & params)3659 void WindowSessionImpl::DumpSessionElementInfo(const std::vector<std::string>& params)
3660 {
3661     WLOGFD("DumpSessionElementInfo");
3662 }
3663 
UpdateMaximizeMode(MaximizeMode mode)3664 WSError WindowSessionImpl::UpdateMaximizeMode(MaximizeMode mode)
3665 {
3666     return WSError::WS_OK;
3667 }
3668 
TransferAccessibilityEvent(const Accessibility::AccessibilityEventInfo & info,int64_t uiExtensionIdLevel)3669 WMError WindowSessionImpl::TransferAccessibilityEvent(const Accessibility::AccessibilityEventInfo& info,
3670     int64_t uiExtensionIdLevel)
3671 {
3672     return WMError::WM_OK;
3673 }
3674 
NotifySessionForeground(uint32_t reason,bool withAnimation)3675 void WindowSessionImpl::NotifySessionForeground(uint32_t reason, bool withAnimation)
3676 {
3677     WLOGFD("NotifySessionForeground");
3678 }
3679 
NotifySessionBackground(uint32_t reason,bool withAnimation,bool isFromInnerkits)3680 void WindowSessionImpl::NotifySessionBackground(uint32_t reason, bool withAnimation, bool isFromInnerkits)
3681 {
3682     WLOGFD("NotifySessionBackground");
3683 }
3684 
UpdateTitleInTargetPos(bool isShow,int32_t height)3685 WSError WindowSessionImpl::UpdateTitleInTargetPos(bool isShow, int32_t height)
3686 {
3687     return WSError::WS_OK;
3688 }
3689 
SwitchFreeMultiWindow(bool enable)3690 WSError WindowSessionImpl::SwitchFreeMultiWindow(bool enable)
3691 {
3692     return WSError::WS_OK;
3693 }
3694 
NotifyDialogStateChange(bool isForeground)3695 WSError WindowSessionImpl::NotifyDialogStateChange(bool isForeground)
3696 {
3697     return WSError::WS_OK;
3698 }
3699 
UpdatePiPRect(const Rect & rect,WindowSizeChangeReason reason)3700 void WindowSessionImpl::UpdatePiPRect(const Rect& rect, WindowSizeChangeReason reason)
3701 {
3702     if (IsWindowSessionInvalid()) {
3703         TLOGE(WmsLogTag::WMS_PIP, "HostSession is invalid");
3704         return;
3705     }
3706     auto hostSession = GetHostSession();
3707     CHECK_HOST_SESSION_RETURN_IF_NULL(hostSession);
3708     hostSession->UpdatePiPRect(rect, static_cast<SizeChangeReason>(reason));
3709 }
3710 
UpdatePiPControlStatus(PiPControlType controlType,PiPControlStatus status)3711 void WindowSessionImpl::UpdatePiPControlStatus(PiPControlType controlType, PiPControlStatus status)
3712 {
3713     TLOGI(WmsLogTag::WMS_PIP, "controlType:%{public}u, status:%{public}d", controlType, status);
3714     if (IsWindowSessionInvalid()) {
3715         TLOGE(WmsLogTag::WMS_PIP, "HostSession is invalid");
3716         return;
3717     }
3718     auto hostSession = GetHostSession();
3719     CHECK_HOST_SESSION_RETURN_IF_NULL(hostSession);
3720     hostSession->UpdatePiPControlStatus(static_cast<WsPiPControlType>(controlType),
3721         static_cast<WsPiPControlStatus>(status));
3722 }
3723 
SetAutoStartPiP(bool isAutoStart,uint32_t priority)3724 void WindowSessionImpl::SetAutoStartPiP(bool isAutoStart, uint32_t priority)
3725 {
3726     if (IsWindowSessionInvalid()) {
3727         TLOGE(WmsLogTag::WMS_PIP, "session is invalid");
3728         return;
3729     }
3730     if (auto hostSession = GetHostSession()) {
3731         hostSession->SetAutoStartPiP(isAutoStart, priority);
3732     }
3733 }
3734 
GetWindowStatusInner(WindowMode mode)3735 WindowStatus WindowSessionImpl::GetWindowStatusInner(WindowMode mode)
3736 {
3737     auto windowStatus = WindowStatus::WINDOW_STATUS_UNDEFINED;
3738     if (mode == WindowMode::WINDOW_MODE_FLOATING) {
3739         windowStatus = WindowStatus::WINDOW_STATUS_FLOATING;
3740         if (property_->GetMaximizeMode() == MaximizeMode::MODE_AVOID_SYSTEM_BAR) {
3741             windowStatus = WindowStatus::WINDOW_STATUS_MAXIMIZE;
3742         }
3743     } else if (mode == WindowMode::WINDOW_MODE_SPLIT_PRIMARY || mode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY) {
3744         windowStatus = WindowStatus::WINDOW_STATUS_SPLITSCREEN;
3745     }
3746     if (mode == WindowMode::WINDOW_MODE_FULLSCREEN) {
3747         windowStatus = WindowStatus::WINDOW_STATUS_FULLSCREEN;
3748     }
3749     if (state_ == WindowState::STATE_HIDDEN) {
3750         windowStatus = WindowStatus::WINDOW_STATUS_MINIMIZE;
3751     }
3752     return windowStatus;
3753 }
3754 
NotifyWindowStatusChange(WindowMode mode)3755 void WindowSessionImpl::NotifyWindowStatusChange(WindowMode mode)
3756 {
3757     auto windowStatus = GetWindowStatusInner(mode);
3758     TLOGD(WmsLogTag::WMS_LAYOUT, "WindowMode: %{public}d, windowStatus: %{public}d", mode, windowStatus);
3759     std::lock_guard<std::recursive_mutex> lockListener(windowStatusChangeListenerMutex_);
3760     auto windowStatusChangeListeners = GetListeners<IWindowStatusChangeListener>();
3761     for (auto& listener : windowStatusChangeListeners) {
3762         if (listener != nullptr) {
3763             listener->OnWindowStatusChange(windowStatus);
3764         }
3765     }
3766 }
3767 
NotifyTransformChange(const Transform & transform)3768 void WindowSessionImpl::NotifyTransformChange(const Transform& transform)
3769 {
3770     WLOGFI("NotifyWindowStatusChange");
3771     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3772     if (uiContent != nullptr) {
3773         uiContent->UpdateTransform(transform);
3774     }
3775 }
3776 
SubmitNoInteractionMonitorTask(int32_t eventId,const IWindowNoInteractionListenerSptr & listener)3777 void WindowSessionImpl::SubmitNoInteractionMonitorTask(int32_t eventId,
3778     const IWindowNoInteractionListenerSptr& listener)
3779 {
3780     auto task = [sessionWptr = wptr(this), eventId, listenerWptr = wptr(listener)]() {
3781         auto session = sessionWptr.promote();
3782         if (session == nullptr) {
3783             WLOGFE("windowInteractionMonitor task running failed, window session is null");
3784             return;
3785         }
3786         if (eventId != session->lastInteractionEventId_.load()) {
3787             WLOGFD("event id of windowInteractionMonitor has been changed, need not notify!");
3788             return;
3789         }
3790         if (session->state_ != WindowState::STATE_SHOWN) {
3791             WLOGFD("window state is not show, need not notify!");
3792             return;
3793         }
3794         session->NotifyNoInteractionTimeout(listenerWptr.promote());
3795     };
3796     handler_->PostTask(task, listener->GetTimeout());
3797 }
3798 
RefreshNoInteractionTimeoutMonitor()3799 void WindowSessionImpl::RefreshNoInteractionTimeoutMonitor()
3800 {
3801     std::lock_guard<std::recursive_mutex> lockListener(windowNoInteractionListenerMutex_);
3802     if (windowNoInteractionListeners_[GetPersistentId()].empty()) {
3803         return;
3804     }
3805     this->lastInteractionEventId_.fetch_add(1);
3806     int32_t eventId = lastInteractionEventId_.load();
3807     auto noInteractionListeners = GetListeners<IWindowNoInteractionListener>();
3808     for (const auto& listenerItem : noInteractionListeners) {
3809         SubmitNoInteractionMonitorTask(eventId, listenerItem);
3810     }
3811 }
3812 
IsUserOrientation(Orientation orientation) const3813 bool WindowSessionImpl::IsUserOrientation(Orientation orientation) const
3814 {
3815     if (orientation == Orientation::USER_ROTATION_PORTRAIT ||
3816         orientation == Orientation::USER_ROTATION_LANDSCAPE ||
3817         orientation == Orientation::USER_ROTATION_PORTRAIT_INVERTED ||
3818         orientation == Orientation::USER_ROTATION_LANDSCAPE_INVERTED) {
3819         return true;
3820     }
3821     return false;
3822 }
3823 
GetCallingWindowWindowStatus(WindowStatus & windowStatus) const3824 WMError WindowSessionImpl::GetCallingWindowWindowStatus(WindowStatus& windowStatus) const
3825 {
3826     TLOGI(WmsLogTag::WMS_KEYBOARD, "id: %{public}d", GetPersistentId());
3827     if (IsWindowSessionInvalid()) {
3828         TLOGE(WmsLogTag::WMS_KEYBOARD, "session is invalid");
3829         return WMError::WM_ERROR_INVALID_WINDOW;
3830     }
3831     return SingletonContainer::Get<WindowAdapter>().GetCallingWindowWindowStatus(GetPersistentId(), windowStatus);
3832 }
3833 
GetCallingWindowRect(Rect & rect) const3834 WMError WindowSessionImpl::GetCallingWindowRect(Rect& rect) const
3835 {
3836     TLOGI(WmsLogTag::WMS_KEYBOARD, "Get CallingWindow Rect");
3837     if (IsWindowSessionInvalid()) {
3838         TLOGE(WmsLogTag::WMS_KEYBOARD, "session is invalid");
3839         return WMError::WM_ERROR_INVALID_WINDOW;
3840     }
3841     return SingletonContainer::Get<WindowAdapter>().GetCallingWindowRect(GetPersistentId(), rect);
3842 }
3843 
SetUiDvsyncSwitch(bool dvsyncSwitch)3844 void WindowSessionImpl::SetUiDvsyncSwitch(bool dvsyncSwitch)
3845 {
3846     std::lock_guard<std::recursive_mutex> lock(mutex_);
3847     if (vsyncStation_ == nullptr) {
3848         TLOGE(WmsLogTag::WMS_MAIN, "vsyncStation is nullptr");
3849         return;
3850     }
3851     vsyncStation_->SetUiDvsyncSwitch(dvsyncSwitch);
3852 }
3853 
GetAppForceLandscapeConfig(AppForceLandscapeConfig & config)3854 WMError WindowSessionImpl::GetAppForceLandscapeConfig(AppForceLandscapeConfig& config)
3855 {
3856     if (IsWindowSessionInvalid()) {
3857         TLOGE(WmsLogTag::DEFAULT, "HostSession is invalid");
3858         return WMError::WM_ERROR_INVALID_WINDOW;
3859     }
3860     auto hostSession = GetHostSession();
3861     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_NULLPTR);
3862     return hostSession->GetAppForceLandscapeConfig(config);
3863 }
3864 
SetForceSplitEnable(bool isForceSplit,const std::string & homePage)3865 void WindowSessionImpl::SetForceSplitEnable(bool isForceSplit, const std::string& homePage)
3866 {
3867     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
3868     if (uiContent == nullptr) {
3869         TLOGE(WmsLogTag::DEFAULT, "uiContent is null!");
3870         return;
3871     }
3872     TLOGI(WmsLogTag::DEFAULT, "isForceSplit: %{public}u, homePage: %{public}s",
3873         isForceSplit, homePage.c_str());
3874     uiContent->SetForceSplitEnable(isForceSplit, homePage);
3875 }
3876 
SetFrameLayoutCallbackEnable(bool enable)3877 void WindowSessionImpl::SetFrameLayoutCallbackEnable(bool enable)
3878 {
3879     enableFrameLayoutFinishCb_ = enable;
3880 }
3881 
UpdateFrameLayoutCallbackIfNeeded(WindowSizeChangeReason wmReason)3882 void WindowSessionImpl::UpdateFrameLayoutCallbackIfNeeded(WindowSizeChangeReason wmReason)
3883 {
3884     bool isDragInPcmode = IsFreeMultiWindowMode() && (wmReason == WindowSizeChangeReason::DRAG_END);
3885     if (wmReason == WindowSizeChangeReason::FULL_TO_SPLIT || wmReason == WindowSizeChangeReason::SPLIT_TO_FULL ||
3886         wmReason == WindowSizeChangeReason::FULL_TO_FLOATING || wmReason == WindowSizeChangeReason::FLOATING_TO_FULL ||
3887         isDragInPcmode) {
3888         TLOGI(WmsLogTag::WMS_MULTI_WINDOW, "enable framelayoutfinish callback reason:%{public}u", wmReason);
3889         SetFrameLayoutCallbackEnable(true);
3890     }
3891 }
3892 
SetContinueState(int32_t continueState)3893 WMError WindowSessionImpl::SetContinueState(int32_t continueState)
3894 {
3895     if (continueState > ContinueState::CONTINUESTATE_MAX || continueState < ContinueState::CONTINUESTATE_UNKNOWN) {
3896         TLOGE(WmsLogTag::WMS_MAIN, "continueState is invalid: %{public}d", continueState);
3897         return WMError::WM_ERROR_INVALID_PARAM;
3898     }
3899     property_->EditSessionInfo().continueState = static_cast<ContinueState>(continueState);
3900     return WMError::WM_OK;
3901 }
3902 
SetUIContentComplete()3903 void WindowSessionImpl::SetUIContentComplete()
3904 {
3905     bool setUIContentCompleted = false;
3906     if (setUIContentCompleted_.compare_exchange_strong(setUIContentCompleted, true)) {
3907         TLOGI(WmsLogTag::WMS_LIFE, "persistentId=%{public}d", GetPersistentId());
3908         handler_->RemoveTask(SET_UICONTENT_TIMEOUT_LISTENER_TASK_NAME + std::to_string(GetPersistentId()));
3909     } else {
3910         TLOGI(WmsLogTag::WMS_LIFE, "already SetUIContent");
3911     }
3912 }
3913 
AddSetUIContentTimeoutCheck()3914 void WindowSessionImpl::AddSetUIContentTimeoutCheck()
3915 {
3916     auto task = [weakThis = wptr(this)] {
3917         auto window = weakThis.promote();
3918         if (window == nullptr) {
3919             TLOGI(WmsLogTag::WMS_LIFE, "window is nullptr");
3920             return;
3921         }
3922 
3923         if (window->setUIContentCompleted_.load()) {
3924             TLOGI(WmsLogTag::WMS_LIFE, "already SetUIContent");
3925             return;
3926         }
3927 
3928         TLOGI(WmsLogTag::WMS_LIFE, "SetUIContent timeout, persistentId=%{public}d", window->GetPersistentId());
3929         std::ostringstream oss;
3930         oss << "SetUIContent timeout uid: " << getuid();
3931         oss << ", windowName: " << window->GetWindowName();
3932         if (window->context_) {
3933             oss << ", bundleName: " << window->context_->GetBundleName();
3934         }
3935         SingletonContainer::Get<WindowInfoReporter>().ReportWindowException(
3936             static_cast<int32_t>(WindowDFXHelperType::WINDOW_TRANSPARENT_CHECK), getpid(), oss.str());
3937 
3938         if (WindowHelper::IsUIExtensionWindow(window->GetType())) {
3939             window->NotifyExtensionTimeout(TimeoutErrorCode::SET_UICONTENT_TIMEOUT);
3940         }
3941     };
3942     handler_->PostTask(task, SET_UICONTENT_TIMEOUT_LISTENER_TASK_NAME + std::to_string(GetPersistentId()),
3943         SET_UICONTENT_TIMEOUT_TIME_MS, AppExecFwk::EventQueue::Priority::HIGH);
3944 }
3945 
NotifySetUIContentComplete()3946 void WindowSessionImpl::NotifySetUIContentComplete()
3947 {
3948     if (WindowHelper::IsMainWindow(GetType())) { // main window
3949         SetUIContentComplete();
3950     } else if (WindowHelper::IsSubWindow(GetType()) ||
3951                WindowHelper::IsSystemWindow(GetType())) { // sub window or system window
3952         // created by UIExtension
3953         auto extWindow = FindExtensionWindowWithContext();
3954         if (extWindow != nullptr) {
3955             extWindow->SetUIContentComplete();
3956             return;
3957         }
3958 
3959         // created by main window
3960         auto mainWindow = FindMainWindowWithContext();
3961         if (mainWindow != nullptr) {
3962             mainWindow->SetUIContentComplete();
3963         }
3964     }
3965 }
3966 
SetEnableDragBySystem(bool enableDrag)3967 WSError WindowSessionImpl::SetEnableDragBySystem(bool enableDrag)
3968 {
3969     TLOGI(WmsLogTag::WMS_LAYOUT, "enableDrag:%{publlic}d", enableDrag);
3970     property_->SetDragEnabled(enableDrag);
3971     return WSError::WS_OK;
3972 }
3973 } // namespace Rosen
3974 } // namespace OHOS
3975