• 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 "session/host/include/session.h"
17 
18 #include <regex>
19 
20 #include "ability_info.h"
21 #include "input_manager.h"
22 #include "key_event.h"
23 #include "pointer_event.h"
24 #include <transaction/rs_interfaces.h>
25 #include <transaction/rs_transaction.h>
26 #include <ui/rs_surface_node.h>
27 #include "proxy/include/window_info.h"
28 
29 #include "common/include/session_permission.h"
30 #include "session_helper.h"
31 #include "surface_capture_future.h"
32 #include "window_helper.h"
33 #include "window_manager_hilog.h"
34 #include "parameters.h"
35 #include <hisysevent.h>
36 #include "hitrace_meter.h"
37 #include "screen_session_manager_client/include/screen_session_manager_client.h"
38 #include "session/host/include/pc_fold_screen_manager.h"
39 #include "perform_reporter.h"
40 
41 namespace OHOS::Rosen {
42 namespace {
43 constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, HILOG_DOMAIN_WINDOW, "Session" };
44 std::atomic<int32_t> g_persistentId = INVALID_SESSION_ID;
45 std::set<int32_t> g_persistentIdSet;
46 std::mutex g_persistentIdSetMutex;
47 constexpr float INNER_BORDER_VP = 5.0f;
48 constexpr float OUTSIDE_BORDER_VP = 4.0f;
49 constexpr float INNER_ANGLE_VP = 16.0f;
50 constexpr uint32_t MAX_LIFE_CYCLE_TASK_IN_QUEUE = 15;
51 constexpr int64_t LIFE_CYCLE_TASK_EXPIRED_TIME_LIMIT = 350;
52 static bool g_enableForceUIFirst = system::GetParameter("window.forceUIFirst.enabled", "1") == "1";
53 constexpr int64_t STATE_DETECT_DELAYTIME = 3 * 1000;
54 constexpr DisplayId VIRTUAL_DISPLAY_ID = 999;
55 const std::map<SessionState, bool> ATTACH_MAP = {
56     { SessionState::STATE_DISCONNECT, false },
57     { SessionState::STATE_CONNECT, false },
58     { SessionState::STATE_FOREGROUND, true },
59     { SessionState::STATE_ACTIVE, true },
60     { SessionState::STATE_INACTIVE, false },
61     { SessionState::STATE_BACKGROUND, false },
62 };
63 const std::map<SessionState, bool> DETACH_MAP = {
64     { SessionState::STATE_DISCONNECT, true },
65     { SessionState::STATE_CONNECT, false },
66     { SessionState::STATE_FOREGROUND, false },
67     { SessionState::STATE_ACTIVE, false },
68     { SessionState::STATE_INACTIVE, true },
69     { SessionState::STATE_BACKGROUND, true },
70 };
71 } // namespace
72 
73 std::shared_ptr<AppExecFwk::EventHandler> Session::mainHandler_;
74 bool Session::isScbCoreEnabled_ = false;
75 bool Session::isBackgroundUpdateRectNotifyEnabled_ = false;
76 
Session(const SessionInfo & info)77 Session::Session(const SessionInfo& info) : sessionInfo_(info)
78 {
79     property_ = sptr<WindowSessionProperty>::MakeSptr();
80     property_->SetWindowType(static_cast<WindowType>(info.windowType_));
81 
82     if (!mainHandler_) {
83         auto runner = AppExecFwk::EventRunner::GetMainEventRunner();
84         mainHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
85     }
86 
87     using type = std::underlying_type_t<MMI::WindowArea>;
88     for (type area = static_cast<type>(MMI::WindowArea::FOCUS_ON_TOP);
89         area <= static_cast<type>(MMI::WindowArea::FOCUS_ON_BOTTOM_RIGHT); ++area) {
90         auto ret = windowAreas_.insert(
91             std::pair<MMI::WindowArea, WSRectF>(static_cast<MMI::WindowArea>(area), WSRectF()));
92         if (!ret.second) {
93             WLOGFE("Failed to insert area:%{public}d", area);
94         }
95     }
96 
97     if (info.want != nullptr) {
98         auto focusedOnShow = info.want->GetBoolParam(AAFwk::Want::PARAM_RESV_WINDOW_FOCUSED, true);
99         TLOGI(WmsLogTag::WMS_FOCUS, "focusedOnShow:%{public}d", focusedOnShow);
100         SetFocusedOnShow(focusedOnShow);
101     }
102 
103     static const std::regex pattern(R"(^SCBScreenLock[0-9]+$)");
104     if (std::regex_match(info.bundleName_, pattern)) {
105         TLOGD(WmsLogTag::WMS_LIFE, "bundleName: %{public}s", info.bundleName_.c_str());
106         isScreenLockWindow_ = true;
107     }
108 }
109 
~Session()110 Session::~Session()
111 {
112     TLOGI(WmsLogTag::WMS_LIFE, "id:%{public}d", GetPersistentId());
113     if (mainHandler_) {
114         mainHandler_->PostTask([surfaceNode = std::move(surfaceNode_)]() {
115             // do nothing
116         });
117     }
118 }
119 
SetEventHandler(const std::shared_ptr<AppExecFwk::EventHandler> & handler,const std::shared_ptr<AppExecFwk::EventHandler> & exportHandler)120 void Session::SetEventHandler(const std::shared_ptr<AppExecFwk::EventHandler>& handler,
121     const std::shared_ptr<AppExecFwk::EventHandler>& exportHandler)
122 {
123     handler_ = handler;
124     exportHandler_ = exportHandler;
125 }
126 
PostTask(Task && task,const std::string & name,int64_t delayTime)127 void Session::PostTask(Task&& task, const std::string& name, int64_t delayTime)
128 {
129     if (!handler_ || handler_->GetEventRunner()->IsCurrentRunnerThread()) {
130         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "s:%s", name.c_str());
131         return task();
132     }
133     auto localTask = [task = std::move(task), name] {
134         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "s:%s", name.c_str());
135         task();
136     };
137     handler_->PostTask(std::move(localTask), "wms:" + name, delayTime, AppExecFwk::EventQueue::Priority::IMMEDIATE);
138 }
139 
PostExportTask(Task && task,const std::string & name,int64_t delayTime)140 void Session::PostExportTask(Task&& task, const std::string& name, int64_t delayTime)
141 {
142     if (!exportHandler_ || exportHandler_->GetEventRunner()->IsCurrentRunnerThread()) {
143         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "s:%s", name.c_str());
144         return task();
145     }
146     auto localTask = [task = std::move(task), name] {
147         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "s:%s", name.c_str());
148         task();
149     };
150     exportHandler_->PostTask(std::move(localTask), "wms:" + name, delayTime,
151         AppExecFwk::EventQueue::Priority::IMMEDIATE);
152 }
153 
GetPersistentId() const154 int32_t Session::GetPersistentId() const
155 {
156     return persistentId_;
157 }
158 
SetSurfaceNode(const std::shared_ptr<RSSurfaceNode> & surfaceNode)159 void Session::SetSurfaceNode(const std::shared_ptr<RSSurfaceNode>& surfaceNode)
160 {
161     std::lock_guard<std::mutex> lock(surfaceNodeMutex_);
162     surfaceNode_ = surfaceNode;
163 }
164 
GetSurfaceNode() const165 std::shared_ptr<RSSurfaceNode> Session::GetSurfaceNode() const
166 {
167     std::lock_guard<std::mutex> lock(surfaceNodeMutex_);
168     return surfaceNode_;
169 }
170 
GetSurfaceNodeId() const171 std::optional<NodeId> Session::GetSurfaceNodeId() const
172 {
173     std::lock_guard<std::mutex> lock(surfaceNodeMutex_);
174     if (surfaceNode_ != nullptr) {
175         return surfaceNode_->GetId();
176     }
177     return std::nullopt;
178 }
179 
SetLeashWinSurfaceNode(std::shared_ptr<RSSurfaceNode> leashWinSurfaceNode)180 void Session::SetLeashWinSurfaceNode(std::shared_ptr<RSSurfaceNode> leashWinSurfaceNode)
181 {
182     if (g_enableForceUIFirst) {
183         auto rsTransaction = RSTransactionProxy::GetInstance();
184         if (rsTransaction) {
185             rsTransaction->Begin();
186         }
187         if (!leashWinSurfaceNode && leashWinSurfaceNode_) {
188             leashWinSurfaceNode_->SetForceUIFirst(false);
189         }
190         if (rsTransaction) {
191             rsTransaction->Commit();
192         }
193     }
194     std::lock_guard<std::mutex> lock(leashWinSurfaceNodeMutex_);
195     leashWinSurfaceNode_ = leashWinSurfaceNode;
196 }
197 
SetFrameLayoutFinishListener(const NotifyFrameLayoutFinishFunc & func)198 void Session::SetFrameLayoutFinishListener(const NotifyFrameLayoutFinishFunc& func)
199 {
200     frameLayoutFinishFunc_ = func;
201 }
202 
GetLeashWinSurfaceNode() const203 std::shared_ptr<RSSurfaceNode> Session::GetLeashWinSurfaceNode() const
204 {
205     std::lock_guard<std::mutex> lock(leashWinSurfaceNodeMutex_);
206     return leashWinSurfaceNode_;
207 }
208 
GetSurfaceNodeForMoveDrag() const209 std::shared_ptr<RSSurfaceNode> Session::GetSurfaceNodeForMoveDrag() const
210 {
211     auto movedSurfaceNode = GetLeashWinSurfaceNode();
212     if (!movedSurfaceNode) {
213         movedSurfaceNode = GetSurfaceNode();
214     }
215     return movedSurfaceNode;
216 }
217 
GetSnapshot() const218 std::shared_ptr<Media::PixelMap> Session::GetSnapshot() const
219 {
220     std::lock_guard<std::mutex> lock(snapshotMutex_);
221     return snapshot_;
222 }
223 
SetSessionInfoAncoSceneState(int32_t ancoSceneState)224 void Session::SetSessionInfoAncoSceneState(int32_t ancoSceneState)
225 {
226     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
227     sessionInfo_.ancoSceneState = ancoSceneState;
228 }
229 
SetSessionInfoTime(const std::string & time)230 void Session::SetSessionInfoTime(const std::string& time)
231 {
232     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
233     sessionInfo_.time = time;
234 }
235 
SetSessionInfoAbilityInfo(const std::shared_ptr<AppExecFwk::AbilityInfo> & abilityInfo)236 void Session::SetSessionInfoAbilityInfo(const std::shared_ptr<AppExecFwk::AbilityInfo>& abilityInfo)
237 {
238     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
239     sessionInfo_.abilityInfo = abilityInfo;
240 }
241 
SetSessionInfoWant(const std::shared_ptr<AAFwk::Want> & want)242 void Session::SetSessionInfoWant(const std::shared_ptr<AAFwk::Want>& want)
243 {
244     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
245     sessionInfo_.want = want;
246 }
247 
ResetSessionInfoResultCode()248 void Session::ResetSessionInfoResultCode()
249 {
250     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
251     sessionInfo_.resultCode = -1; // -1: initial result code
252 }
253 
SetSessionInfoPersistentId(int32_t persistentId)254 void Session::SetSessionInfoPersistentId(int32_t persistentId)
255 {
256     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
257     sessionInfo_.persistentId_ = persistentId;
258 }
259 
SetSessionInfoCallerPersistentId(int32_t callerPersistentId)260 void Session::SetSessionInfoCallerPersistentId(int32_t callerPersistentId)
261 {
262     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
263     sessionInfo_.callerPersistentId_ = callerPersistentId;
264 }
265 
SetSessionInfoContinueState(ContinueState state)266 void Session::SetSessionInfoContinueState(ContinueState state)
267 {
268     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
269     sessionInfo_.continueState = state;
270 }
271 
SetSessionInfoLockedState(bool lockedState)272 void Session::SetSessionInfoLockedState(bool lockedState)
273 {
274     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
275     sessionInfo_.lockedState = lockedState;
276     NotifySessionInfoLockedStateChange(lockedState);
277 }
278 
SetSessionInfoIsClearSession(bool isClearSession)279 void Session::SetSessionInfoIsClearSession(bool isClearSession)
280 {
281     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
282     sessionInfo_.isClearSession = isClearSession;
283 }
284 
SetSessionInfoAffinity(std::string affinity)285 void Session::SetSessionInfoAffinity(std::string affinity)
286 {
287     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
288     sessionInfo_.sessionAffinity = affinity;
289 }
290 
GetCloseAbilityWantAndClean(AAFwk::Want & outWant)291 void Session::GetCloseAbilityWantAndClean(AAFwk::Want& outWant)
292 {
293     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
294     if (sessionInfo_.closeAbilityWant != nullptr) {
295         outWant = *sessionInfo_.closeAbilityWant;
296         sessionInfo_.closeAbilityWant = nullptr;
297     }
298 }
299 
SetSessionInfo(const SessionInfo & info)300 void Session::SetSessionInfo(const SessionInfo& info)
301 {
302     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
303     sessionInfo_.want = info.want;
304     sessionInfo_.callerToken_ = info.callerToken_;
305     sessionInfo_.requestCode = info.requestCode;
306     sessionInfo_.callerPersistentId_ = info.callerPersistentId_;
307     sessionInfo_.callingTokenId_ = info.callingTokenId_;
308     sessionInfo_.uiAbilityId_ = info.uiAbilityId_;
309     sessionInfo_.requestId = info.requestId;
310     sessionInfo_.startSetting = info.startSetting;
311     sessionInfo_.continueSessionId_ = info.continueSessionId_;
312     sessionInfo_.isAtomicService_ = info.isAtomicService_;
313     sessionInfo_.callState_ = info.callState_;
314     sessionInfo_.processOptions = info.processOptions;
315 }
316 
GetScreenId() const317 DisplayId Session::GetScreenId() const
318 {
319     return sessionInfo_.screenId_;
320 }
321 
SetScreenId(uint64_t screenId)322 void Session::SetScreenId(uint64_t screenId)
323 {
324     sessionInfo_.screenId_ = screenId;
325     if (sessionStage_) {
326         sessionStage_->UpdateDisplayId(screenId);
327     }
328 }
329 
SetAppInstanceKey(const std::string & appInstanceKey)330 void Session::SetAppInstanceKey(const std::string& appInstanceKey)
331 {
332     sessionInfo_.appInstanceKey_ = appInstanceKey;
333 }
334 
GetAppInstanceKey() const335 std::string Session::GetAppInstanceKey() const
336 {
337     return sessionInfo_.appInstanceKey_;
338 }
339 
GetSessionInfo() const340 const SessionInfo& Session::GetSessionInfo() const
341 {
342     return sessionInfo_;
343 }
344 
EditSessionInfo()345 SessionInfo& Session::EditSessionInfo()
346 {
347     return sessionInfo_;
348 }
349 
RegisterLifecycleListener(const std::shared_ptr<ILifecycleListener> & listener)350 bool Session::RegisterLifecycleListener(const std::shared_ptr<ILifecycleListener>& listener)
351 {
352     return RegisterListenerLocked(lifecycleListeners_, listener);
353 }
354 
UnregisterLifecycleListener(const std::shared_ptr<ILifecycleListener> & listener)355 bool Session::UnregisterLifecycleListener(const std::shared_ptr<ILifecycleListener>& listener)
356 {
357     return UnregisterListenerLocked(lifecycleListeners_, listener);
358 }
359 
360 template<typename T>
RegisterListenerLocked(std::vector<std::shared_ptr<T>> & holder,const std::shared_ptr<T> & listener)361 bool Session::RegisterListenerLocked(std::vector<std::shared_ptr<T>>& holder, const std::shared_ptr<T>& listener)
362 {
363     if (listener == nullptr) {
364         WLOGFE("listener is nullptr");
365         return false;
366     }
367     std::lock_guard<std::recursive_mutex> lock(lifecycleListenersMutex_);
368     if (std::find(holder.begin(), holder.end(), listener) != holder.end()) {
369         WLOGFE("Listener already registered");
370         return false;
371     }
372     holder.emplace_back(listener);
373     return true;
374 }
375 
376 template<typename T>
UnregisterListenerLocked(std::vector<std::shared_ptr<T>> & holder,const std::shared_ptr<T> & listener)377 bool Session::UnregisterListenerLocked(std::vector<std::shared_ptr<T>>& holder, const std::shared_ptr<T>& listener)
378 {
379     if (listener == nullptr) {
380         WLOGFE("listener could not be null");
381         return false;
382     }
383     std::lock_guard<std::recursive_mutex> lock(lifecycleListenersMutex_);
384     holder.erase(std::remove_if(holder.begin(), holder.end(),
385         [listener](std::shared_ptr<T> registeredListener) { return registeredListener == listener; }),
386         holder.end());
387     return true;
388 }
389 
NotifyActivation()390 void Session::NotifyActivation()
391 {
392     auto lifecycleListeners = GetListeners<ILifecycleListener>();
393     for (auto& listener : lifecycleListeners) {
394         if (auto listenerPtr = listener.lock()) {
395             listenerPtr->OnActivation();
396         }
397     }
398 }
399 
NotifyConnect()400 void Session::NotifyConnect()
401 {
402     auto lifecycleListeners = GetListeners<ILifecycleListener>();
403     for (auto& listener : lifecycleListeners) {
404         if (auto listenerPtr = listener.lock()) {
405             listenerPtr->OnConnect();
406         }
407     }
408 }
409 
NotifyForeground()410 void Session::NotifyForeground()
411 {
412     auto lifecycleListeners = GetListeners<ILifecycleListener>();
413     for (auto& listener : lifecycleListeners) {
414         if (auto listenerPtr = listener.lock()) {
415             listenerPtr->OnForeground();
416         }
417     }
418 }
419 
NotifyBackground()420 void Session::NotifyBackground()
421 {
422     auto lifecycleListeners = GetListeners<ILifecycleListener>();
423     for (auto& listener : lifecycleListeners) {
424         if (auto listenerPtr = listener.lock()) {
425             listenerPtr->OnBackground();
426         }
427     }
428 }
429 
NotifyDisconnect()430 void Session::NotifyDisconnect()
431 {
432     auto lifecycleListeners = GetListeners<ILifecycleListener>();
433     for (auto& listener : lifecycleListeners) {
434         if (auto listenerPtr = listener.lock()) {
435             listenerPtr->OnDisconnect();
436         }
437     }
438 }
439 
NotifyLayoutFinished()440 void Session::NotifyLayoutFinished()
441 {
442     auto lifecycleListeners = GetListeners<ILifecycleListener>();
443     for (auto& listener : lifecycleListeners) {
444         if (auto listenerPtr = listener.lock()) {
445             listenerPtr->OnLayoutFinished();
446         }
447     }
448 }
449 
NotifyRemoveBlank()450 void Session::NotifyRemoveBlank()
451 {
452     auto lifecycleListeners = GetListeners<ILifecycleListener>();
453     for (auto& listener : lifecycleListeners) {
454         if (auto listenerPtr = listener.lock()) {
455             listenerPtr->OnRemoveBlank();
456         }
457     }
458 }
459 
NotifyAddSnapshot()460 void Session::NotifyAddSnapshot()
461 {
462     /*
463      * for blankness prolems, persist snapshot could conflict with background process,
464      * thus no need to persist snapshot here
465      */
466     SaveSnapshot(false, false);
467     auto lifecycleListeners = GetListeners<ILifecycleListener>();
468     for (auto& listener : lifecycleListeners) {
469         if (auto listenerPtr = listener.lock()) {
470             listenerPtr->OnAddSnapshot();
471         }
472     }
473 }
474 
NotifyRemoveSnapshot()475 void Session::NotifyRemoveSnapshot()
476 {
477     auto lifecycleListeners = GetListeners<ILifecycleListener>();
478     for (auto& listener : lifecycleListeners) {
479         if (auto listenerPtr = listener.lock()) {
480             listenerPtr->OnRemoveSnapshot();
481         }
482     }
483 }
484 
NotifyExtensionDied()485 void Session::NotifyExtensionDied()
486 {
487     if (!SessionPermission::IsSystemCalling()) {
488         TLOGE(WmsLogTag::WMS_UIEXT, "permission denied!");
489         return;
490     }
491     TLOGI(WmsLogTag::WMS_UIEXT, "NotifyExtensionDied called in session(persistentId:%{public}d).", persistentId_);
492     auto lifecycleListeners = GetListeners<ILifecycleListener>();
493     for (auto& listener : lifecycleListeners) {
494         if (auto listenerPtr = listener.lock()) {
495             listenerPtr->OnExtensionDied();
496         }
497     }
498 }
499 
NotifyExtensionTimeout(int32_t errorCode)500 void Session::NotifyExtensionTimeout(int32_t errorCode)
501 {
502     if (!SessionPermission::IsSystemCalling()) {
503         TLOGE(WmsLogTag::WMS_UIEXT, "permission denied!");
504         return;
505     }
506     TLOGI(WmsLogTag::WMS_UIEXT, "NotifyExtensionTimeout(errorCode:%{public}d) in session(persistentId:%{public}d).",
507         errorCode, persistentId_);
508     auto lifecycleListeners = GetListeners<ILifecycleListener>();
509     for (auto& listener : lifecycleListeners) {
510         if (auto listenerPtr = listener.lock()) {
511             listenerPtr->OnExtensionTimeout(errorCode);
512         }
513     }
514 }
515 
NotifyTransferAccessibilityEvent(const Accessibility::AccessibilityEventInfo & info,int64_t uiExtensionIdLevel)516 void Session::NotifyTransferAccessibilityEvent(const Accessibility::AccessibilityEventInfo& info,
517     int64_t uiExtensionIdLevel)
518 {
519     auto lifecycleListeners = GetListeners<ILifecycleListener>();
520     for (auto& listener : lifecycleListeners) {
521         if (auto listenerPtr = listener.lock()) {
522             listenerPtr->OnAccessibilityEvent(info, uiExtensionIdLevel);
523         }
524     }
525 }
526 
NotifyExtensionDetachToDisplay()527 void Session::NotifyExtensionDetachToDisplay()
528 {
529     TLOGI(WmsLogTag::WMS_UIEXT, "called");
530     if (!SessionPermission::IsSystemCalling()) {
531         TLOGE(WmsLogTag::WMS_UIEXT, "permission denied!");
532         return;
533     }
534 
535     auto lifecycleListeners = GetListeners<ILifecycleListener>();
536     for (auto& listener : lifecycleListeners) {
537         if (auto listenerPtr = listener.lock()) {
538             listenerPtr->OnExtensionDetachToDisplay();
539         }
540     }
541 }
542 
GetAspectRatio() const543 float Session::GetAspectRatio() const
544 {
545     return aspectRatio_;
546 }
547 
SetAspectRatio(float ratio)548 WSError Session::SetAspectRatio(float ratio)
549 {
550     aspectRatio_ = ratio;
551     return WSError::WS_OK;
552 }
553 
GetSessionState() const554 SessionState Session::GetSessionState() const
555 {
556     return state_;
557 }
558 
SetSessionState(SessionState state)559 void Session::SetSessionState(SessionState state)
560 {
561     if (state < SessionState::STATE_DISCONNECT || state > SessionState::STATE_END) {
562         WLOGFD("Invalid session state: %{public}u", state);
563         return;
564     }
565     state_ = state;
566     SetMainSessionUIStateDirty(true);
567 }
568 
UpdateSessionState(SessionState state)569 void Session::UpdateSessionState(SessionState state)
570 {
571     // Remove unexecuted detection tasks when the window state changes to background or destroyed.
572     if (state == SessionState::STATE_DISCONNECT ||
573         state == SessionState::STATE_INACTIVE ||
574         state == SessionState::STATE_BACKGROUND) {
575         RemoveWindowDetectTask();
576     }
577     /* The state will be set background first when destroy keyboard, there is no need to notify scb if the state is
578      * already background, which may cause performance deterioration.
579      */
580     if (GetWindowType() == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT && state == state_ &&
581         state == SessionState::STATE_BACKGROUND) {
582         TLOGI(WmsLogTag::WMS_KEYBOARD, "Keyboard is already hide");
583         return;
584     }
585     state_ = state;
586     SetMainSessionUIStateDirty(true);
587     NotifySessionStateChange(state);
588 }
589 
UpdateSessionTouchable(bool touchable)590 void Session::UpdateSessionTouchable(bool touchable)
591 {
592     GetSessionProperty()->SetTouchable(touchable);
593     NotifySessionTouchableChange(touchable);
594 }
595 
SetFocusable(bool isFocusable)596 WSError Session::SetFocusable(bool isFocusable)
597 {
598     WLOGFI("SetFocusable id: %{public}d, focusable: %{public}d", GetPersistentId(), isFocusable);
599     GetSessionProperty()->SetFocusable(isFocusable);
600     if (isFocused_ && !GetFocusable()) {
601         FocusChangeReason reason = FocusChangeReason::FOCUSABLE;
602         NotifyRequestFocusStatusNotifyManager(false, true, reason);
603     }
604     return WSError::WS_OK;
605 }
606 
SetSystemFocusable(bool systemFocusable)607 void Session::SetSystemFocusable(bool systemFocusable)
608 {
609     TLOGI(WmsLogTag::WMS_FOCUS, "id: %{public}d, systemFocusable: %{public}d", GetPersistentId(), systemFocusable);
610     systemFocusable_ = systemFocusable;
611     if (isFocused_ && !systemFocusable) {
612         FocusChangeReason reason = FocusChangeReason::FOCUSABLE;
613         NotifyRequestFocusStatusNotifyManager(false, true, reason);
614     }
615 }
616 
SetFocusableOnShow(bool isFocusableOnShow)617 WSError Session::SetFocusableOnShow(bool isFocusableOnShow)
618 {
619     PostTask([weakThis = wptr(this), isFocusableOnShow]() {
620         auto session = weakThis.promote();
621         if (session == nullptr) {
622             TLOGNE(WmsLogTag::WMS_FOCUS, "session is null");
623             return;
624         }
625         TLOGND(WmsLogTag::WMS_FOCUS, "id: %{public}d, focusableOnShow: %{public}d",
626             session->GetPersistentId(), isFocusableOnShow);
627         session->focusableOnShow_ = isFocusableOnShow;
628     }, __func__);
629     return WSError::WS_OK;
630 }
631 
GetFocusable() const632 bool Session::GetFocusable() const
633 {
634     return GetSessionProperty()->GetFocusable();
635 }
636 
GetSystemFocusable() const637 bool Session::GetSystemFocusable() const
638 {
639     if (parentSession_) {
640         return systemFocusable_ && parentSession_->GetSystemFocusable();
641     }
642     return systemFocusable_;
643 }
644 
CheckFocusable() const645 bool Session::CheckFocusable() const
646 {
647     return GetFocusable() && GetSystemFocusable();
648 }
649 
IsFocusableOnShow() const650 bool Session::IsFocusableOnShow() const
651 {
652     return focusableOnShow_;
653 }
654 
IsFocused() const655 bool Session::IsFocused() const
656 {
657     return isFocused_;
658 }
659 
SetNeedNotify(bool needNotify)660 void Session::SetNeedNotify(bool needNotify)
661 {
662     needNotify_ = needNotify;
663 }
664 
NeedNotify() const665 bool Session::NeedNotify() const
666 {
667     return needNotify_;
668 }
669 
SetFocusedOnShow(bool focusedOnShow)670 void Session::SetFocusedOnShow(bool focusedOnShow)
671 {
672     if (focusedOnShow == focusedOnShow_) {
673         return;
674     }
675     TLOGI(WmsLogTag::WMS_FOCUS, "SetFocusedOnShow:%{public}d, id: %{public}d", focusedOnShow, GetPersistentId());
676     focusedOnShow_ = focusedOnShow;
677 }
678 
IsFocusedOnShow() const679 bool Session::IsFocusedOnShow() const
680 {
681     TLOGD(WmsLogTag::WMS_FOCUS, "IsFocusedOnShow:%{public}d, id: %{public}d", focusedOnShow_, GetPersistentId());
682     return focusedOnShow_;
683 }
684 
SetStartingBeforeVisible(bool isStartingBeforeVisible)685 void Session::SetStartingBeforeVisible(bool isStartingBeforeVisible)
686 {
687     isStartingBeforeVisible_ = isStartingBeforeVisible;
688 }
689 
GetStartingBeforeVisible() const690 bool Session::GetStartingBeforeVisible() const
691 {
692     return isStartingBeforeVisible_;
693 }
694 
SetTouchable(bool touchable)695 WSError Session::SetTouchable(bool touchable)
696 {
697     SetSystemTouchable(touchable);
698     if (!IsSessionValid()) {
699         TLOGW(WmsLogTag::WMS_MAIN, "Session is invalid, id: %{public}d state: %{public}u",
700             GetPersistentId(), GetSessionState());
701         return WSError::WS_ERROR_INVALID_SESSION;
702     }
703     if (touchable != GetSessionProperty()->GetTouchable()) {
704         TLOGI(WmsLogTag::WMS_EVENT, "id:%{public}d, %{public}d", GetPersistentId(), touchable);
705     }
706     UpdateSessionTouchable(touchable);
707     return WSError::WS_OK;
708 }
709 
GetTouchable() const710 bool Session::GetTouchable() const
711 {
712     return GetSessionProperty()->GetTouchable();
713 }
714 
SetForceTouchable(bool forceTouchable)715 void Session::SetForceTouchable(bool forceTouchable)
716 {
717     if (forceTouchable != forceTouchable_) {
718         TLOGI(WmsLogTag::WMS_EVENT, "id:%{public}d, %{public}d", GetPersistentId(), forceTouchable);
719     }
720     forceTouchable_ = forceTouchable;
721 }
722 
SetSystemTouchable(bool touchable)723 void Session::SetSystemTouchable(bool touchable)
724 {
725     if (touchable != systemTouchable_) {
726         TLOGI(WmsLogTag::WMS_EVENT, "id:%{public}d, %{public}d", GetPersistentId(), touchable);
727     }
728     systemTouchable_ = touchable;
729     NotifySessionInfoChange();
730 }
731 
GetSystemTouchable() const732 bool Session::GetSystemTouchable() const
733 {
734     return forceTouchable_ && systemTouchable_ && GetTouchable();
735 }
736 
IsSystemActive() const737 bool Session::IsSystemActive() const
738 {
739     return isSystemActive_;
740 }
741 
SetSystemActive(bool systemActive)742 void Session::SetSystemActive(bool systemActive)
743 {
744     isSystemActive_ = systemActive;
745     NotifySessionInfoChange();
746 }
747 
SetRSVisible(bool isVisible)748 WSError Session::SetRSVisible(bool isVisible)
749 {
750     isRSVisible_ = isVisible;
751     return WSError::WS_OK;
752 }
753 
GetRSVisible() const754 bool Session::GetRSVisible() const
755 {
756     return isRSVisible_;
757 }
758 
GetFocused() const759 bool Session::GetFocused() const
760 {
761     return isFocused_;
762 }
763 
SetVisibilityState(WindowVisibilityState state)764 WSError Session::SetVisibilityState(WindowVisibilityState state)
765 {
766     visibilityState_ = state;
767     return WSError::WS_OK;
768 }
769 
GetVisibilityState() const770 WindowVisibilityState Session::GetVisibilityState() const
771 {
772     return visibilityState_;
773 }
774 
SetDrawingContentState(bool isRSDrawing)775 WSError Session::SetDrawingContentState(bool isRSDrawing)
776 {
777     isRSDrawing_ = isRSDrawing;
778     return WSError::WS_OK;
779 }
780 
GetDrawingContentState() const781 bool Session::GetDrawingContentState() const
782 {
783     return isRSDrawing_;
784 }
785 
GetWindowId() const786 int32_t Session::GetWindowId() const
787 {
788     return GetPersistentId();
789 }
790 
SetCallingPid(int32_t id)791 void Session::SetCallingPid(int32_t id)
792 {
793     TLOGI(WmsLogTag::WMS_EVENT, "id:%{public}d, %{public}d", persistentId_, id);
794     callingPid_ = id;
795     if (visibilityChangedDetectFunc_ && isVisible_) {
796         visibilityChangedDetectFunc_(callingPid_, false, isVisible_);
797     }
798 }
799 
SetCallingUid(int32_t id)800 void Session::SetCallingUid(int32_t id)
801 {
802     callingUid_ = id;
803 }
804 
GetCallingPid() const805 int32_t Session::GetCallingPid() const
806 {
807     return callingPid_;
808 }
809 
GetCallingUid() const810 int32_t Session::GetCallingUid() const
811 {
812     return callingUid_;
813 }
814 
SetAbilityToken(sptr<IRemoteObject> token)815 void Session::SetAbilityToken(sptr<IRemoteObject> token)
816 {
817     abilityToken_ = token;
818 }
819 
GetAbilityToken() const820 sptr<IRemoteObject> Session::GetAbilityToken() const
821 {
822     return abilityToken_;
823 }
824 
SetBrightness(float brightness)825 WSError Session::SetBrightness(float brightness)
826 {
827     GetSessionProperty()->SetBrightness(brightness);
828     return WSError::WS_OK;
829 }
830 
GetBrightness() const831 float Session::GetBrightness() const
832 {
833     return GetSessionProperty()->GetBrightness();
834 }
835 
IsSessionValid() const836 bool Session::IsSessionValid() const
837 {
838     if (sessionInfo_.isSystem_) {
839         WLOGFD("session is system, id: %{public}d, name: %{public}s, state: %{public}u",
840             GetPersistentId(), sessionInfo_.bundleName_.c_str(), GetSessionState());
841         return false;
842     }
843     bool res = state_ > SessionState::STATE_DISCONNECT && state_ < SessionState::STATE_END;
844     return res;
845 }
846 
IsActive() const847 bool Session::IsActive() const
848 {
849     return isActive_;
850 }
851 
IsSystemSession() const852 bool Session::IsSystemSession() const
853 {
854     return sessionInfo_.isSystem_;
855 }
856 
IsTerminated() const857 bool Session::IsTerminated() const
858 {
859     return (GetSessionState() == SessionState::STATE_DISCONNECT || isTerminating_);
860 }
861 
IsSessionForeground() const862 bool Session::IsSessionForeground() const
863 {
864     return state_ == SessionState::STATE_FOREGROUND || state_ == SessionState::STATE_ACTIVE;
865 }
866 
UpdateTopBottomArea(const WSRectF & rect,MMI::WindowArea area)867 WSRectF Session::UpdateTopBottomArea(const WSRectF& rect, MMI::WindowArea area)
868 {
869     const float innerBorder = INNER_BORDER_VP * vpr_;
870     const float outsideBorder = OUTSIDE_BORDER_VP * vpr_;
871     const float innerAngle = INNER_ANGLE_VP * vpr_;
872     const float horizontalBorderLength = outsideBorder + innerAngle;
873     const float verticalBorderLength = outsideBorder + innerBorder;
874     const size_t innerAngleCount = 2;
875     WSRectF tbRect;
876     tbRect.posX_ = rect.posX_ + horizontalBorderLength;
877     tbRect.width_ = rect.width_ - horizontalBorderLength * innerAngleCount;
878     tbRect.height_ = verticalBorderLength;
879     if (area == MMI::WindowArea::FOCUS_ON_TOP) {
880         tbRect.posY_ = rect.posY_;
881     } else if (area == MMI::WindowArea::FOCUS_ON_BOTTOM) {
882         tbRect.posY_ = rect.posY_ + rect.height_ - verticalBorderLength;
883     } else {
884         return WSRectF();
885     }
886     return tbRect;
887 }
888 
UpdateLeftRightArea(const WSRectF & rect,MMI::WindowArea area)889 WSRectF Session::UpdateLeftRightArea(const WSRectF& rect, MMI::WindowArea area)
890 {
891     const float innerBorder = INNER_BORDER_VP * vpr_;
892     const float outsideBorder = OUTSIDE_BORDER_VP * vpr_;
893     const float innerAngle = INNER_ANGLE_VP * vpr_;
894     const float verticalBorderLength = outsideBorder + innerAngle;
895     const float horizontalBorderLength = outsideBorder + innerBorder;
896     const size_t innerAngleCount = 2;
897     WSRectF lrRect;
898     lrRect.posY_ = rect.posY_ + verticalBorderLength;
899     lrRect.width_ = horizontalBorderLength;
900     lrRect.height_ = rect.height_ - verticalBorderLength * innerAngleCount;
901     if (area == MMI::WindowArea::FOCUS_ON_LEFT) {
902         lrRect.posX_ = rect.posX_;
903     } else if (area == MMI::WindowArea::FOCUS_ON_RIGHT) {
904         lrRect.posX_ = rect.posX_ + rect.width_ - horizontalBorderLength;
905     } else {
906         return WSRectF();
907     }
908     return lrRect;
909 }
910 
UpdateInnerAngleArea(const WSRectF & rect,MMI::WindowArea area)911 WSRectF Session::UpdateInnerAngleArea(const WSRectF& rect, MMI::WindowArea area)
912 {
913     const float outsideBorder = OUTSIDE_BORDER_VP * vpr_;
914     const float innerAngle = INNER_ANGLE_VP * vpr_;
915     WSRectF iaRect;
916     iaRect.width_ = outsideBorder + innerAngle;
917     iaRect.height_ = outsideBorder + innerAngle;
918     if (area == MMI::WindowArea::FOCUS_ON_TOP_LEFT) {
919         iaRect.posX_ = rect.posX_;
920         iaRect.posY_ = rect.posY_;
921     } else if (area == MMI::WindowArea::FOCUS_ON_TOP_RIGHT) {
922         iaRect.posX_ = rect.posX_ + rect.width_ - iaRect.width_;
923         iaRect.posY_ = rect.posY_;
924     } else if (area == MMI::WindowArea::FOCUS_ON_BOTTOM_LEFT) {
925         iaRect.posX_ = rect.posX_;
926         iaRect.posY_ = rect.posY_ + rect.height_ - iaRect.height_;
927     } else if (area == MMI::WindowArea::FOCUS_ON_BOTTOM_RIGHT) {
928         iaRect.posX_ = rect.posX_ + rect.width_ - iaRect.width_;
929         iaRect.posY_ = rect.posY_ + rect.height_ - iaRect.height_;
930     } else {
931         return WSRectF();
932     }
933     return iaRect;
934 }
935 
UpdateHotRect(const WSRect & rect)936 WSRectF Session::UpdateHotRect(const WSRect& rect)
937 {
938     WSRectF newRect;
939     const float outsideBorder = OUTSIDE_BORDER_VP * vpr_;
940     const size_t outsideBorderCount = 2;
941     newRect.posX_ = rect.posX_ - outsideBorder;
942     newRect.posY_ = rect.posY_ - outsideBorder;
943     newRect.width_ = rect.width_ + outsideBorder * outsideBorderCount;
944     newRect.height_ = rect.height_ + outsideBorder * outsideBorderCount;
945     return newRect;
946 }
947 
UpdatePointerArea(const WSRect & rect)948 void Session::UpdatePointerArea(const WSRect& rect)
949 {
950     if (preRect_ == rect) {
951         WLOGFD("The window area does not change");
952         return;
953     }
954     WSRectF hotRect = UpdateHotRect(rect);
955     for (const auto &[area, _] : windowAreas_) {
956         if (area == MMI::WindowArea::FOCUS_ON_TOP || area == MMI::WindowArea::FOCUS_ON_BOTTOM) {
957             windowAreas_[area] = UpdateTopBottomArea(hotRect, area);
958         } else if (area == MMI::WindowArea::FOCUS_ON_RIGHT || area == MMI::WindowArea::FOCUS_ON_LEFT) {
959             windowAreas_[area] = UpdateLeftRightArea(hotRect, area);
960         } else if (area == MMI::WindowArea::FOCUS_ON_TOP_LEFT || area == MMI::WindowArea::FOCUS_ON_TOP_RIGHT ||
961             area == MMI::WindowArea::FOCUS_ON_BOTTOM_LEFT || area == MMI::WindowArea::FOCUS_ON_BOTTOM_RIGHT) {
962             windowAreas_[area] = UpdateInnerAngleArea(hotRect, area);
963         }
964     }
965     preRect_ = rect;
966 }
967 
UpdateSizeChangeReason(SizeChangeReason reason)968 WSError Session::UpdateSizeChangeReason(SizeChangeReason reason)
969 {
970     if (reason_ == reason) {
971         return WSError::WS_DO_NOTHING;
972     }
973     reason_ = reason;
974     return WSError::WS_OK;
975 }
976 
UpdateClientDisplayId(DisplayId displayId)977 WSError Session::UpdateClientDisplayId(DisplayId displayId)
978 {
979     if (sessionStage_ == nullptr) {
980         TLOGE(WmsLogTag::WMS_LAYOUT, "sessionStage_ is nullptr");
981         return WSError::WS_ERROR_NULLPTR;
982     }
983     TLOGI(WmsLogTag::WMS_LAYOUT, "windowId: %{public}d move display %{public}" PRIu64 " from %{public}" PRIu64,
984           GetPersistentId(), displayId, clientDisplayId_);
985     clientDisplayId_ = displayId;
986     sessionStage_->UpdateDisplayId(displayId);
987     return WSError::WS_OK;
988 }
989 
TransformGlobalRectToRelativeRect(WSRect & rect) const990 DisplayId Session::TransformGlobalRectToRelativeRect(WSRect& rect) const
991 {
992     const auto& [defaultDisplayRect, virtualDisplayRect, foldCreaseRect] =
993         PcFoldScreenManager::GetInstance().GetDisplayRects();
994     int32_t lowerScreenPosY = defaultDisplayRect.height_ + foldCreaseRect.height_;
995     TLOGI(WmsLogTag::WMS_LAYOUT, "lowerScreenPosY: %{public}d", lowerScreenPosY);
996     auto screenHeight = defaultDisplayRect.height_ + foldCreaseRect.height_ + virtualDisplayRect.height_;
997     if (rect.posY_ > screenHeight) {
998         rect.posY_ -= lowerScreenPosY;
999         return clientDisplayId_;
1000     }
1001     DisplayId updatedDisplayId = DEFAULT_DISPLAY_ID;
1002     if (rect.posY_ >= lowerScreenPosY) {
1003         updatedDisplayId = VIRTUAL_DISPLAY_ID;
1004         rect.posY_ -= lowerScreenPosY;
1005     }
1006     return updatedDisplayId;
1007 }
1008 
UpdateClientRectPosYAndDisplayId(WSRect & rect)1009 void Session::UpdateClientRectPosYAndDisplayId(WSRect& rect)
1010 {
1011     if (GetSessionProperty()->IsSystemKeyboard()) {
1012         TLOGI(WmsLogTag::WMS_LAYOUT, "skip update SystemKeyboard: %{public}d", GetPersistentId());
1013         return;
1014     }
1015     if (WindowHelper::IsUIExtensionWindow(GetWindowType())) {
1016         TLOGI(WmsLogTag::WMS_LAYOUT, "skip update UIExtension: %{public}d, rect: %{public}s",
1017             GetPersistentId(), rect.ToString().c_str());
1018         return;
1019     }
1020     if (rect.IsInvalid()) {
1021         TLOGI(WmsLogTag::WMS_LAYOUT, "skip window: %{public}d invalid rect: %{public}s",
1022             GetPersistentId(), rect.ToString().c_str());
1023         return;
1024     }
1025     auto currScreenFoldStatus = PcFoldScreenManager::GetInstance().GetScreenFoldStatus();
1026     if (currScreenFoldStatus == SuperFoldStatus::UNKNOWN || currScreenFoldStatus == SuperFoldStatus::FOLDED) {
1027         TLOGD(WmsLogTag::WMS_LAYOUT, "Error status");
1028         return;
1029     }
1030     if (GetScreenId() != DISPLAY_ID_INVALID &&
1031         !PcFoldScreenManager::GetInstance().IsPcFoldScreen(GetScreenId())) {
1032         TLOGI(WmsLogTag::WMS_LAYOUT, "winId: %{public}d, displayId: %{public}" PRIu64 " not need",
1033             GetPersistentId(), GetScreenId());
1034         return;
1035     }
1036     TLOGI(WmsLogTag::WMS_LAYOUT, "lastStatus: %{public}d, curStatus: %{public}d",
1037         lastScreenFoldStatus_, currScreenFoldStatus);
1038     if (currScreenFoldStatus == SuperFoldStatus::EXPANDED || currScreenFoldStatus == SuperFoldStatus::KEYBOARD) {
1039         lastScreenFoldStatus_ = currScreenFoldStatus;
1040         auto ret = UpdateClientDisplayId(DEFAULT_DISPLAY_ID);
1041         TLOGI(WmsLogTag::WMS_LAYOUT, "JustUpdateId: winId: %{public}d, result: %{public}d",
1042             GetPersistentId(), ret);
1043         return;
1044     }
1045     WSRect lastRect = rect;
1046     auto updatedDisplayId = TransformGlobalRectToRelativeRect(rect);
1047     auto ret = UpdateClientDisplayId(updatedDisplayId);
1048     lastScreenFoldStatus_ = currScreenFoldStatus;
1049     configDisplayId_ = DISPLAY_ID_INVALID;
1050     TLOGI(WmsLogTag::WMS_LAYOUT, "CalculatedRect: winId: %{public}d, input: %{public}s, output: %{public}s,"
1051         " result: %{public}d, clientDisplayId: %{public}" PRIu64, GetPersistentId(), lastRect.ToString().c_str(),
1052         rect.ToString().c_str(), ret, updatedDisplayId);
1053 }
1054 
SetSingleHandTransform(const SingleHandTransform & transform)1055 void Session::SetSingleHandTransform(const SingleHandTransform& transform)
1056 {
1057     singleHandTransform_ = transform;
1058 }
1059 
GetSingleHandTransform() const1060 SingleHandTransform Session::GetSingleHandTransform() const
1061 {
1062     return singleHandTransform_;
1063 }
1064 
SetSingleHandModeFlag(bool flag)1065 void Session::SetSingleHandModeFlag(bool flag)
1066 {
1067     singleHandModeFlag_ = flag;
1068 }
1069 
SessionIsSingleHandMode()1070 bool Session::SessionIsSingleHandMode()
1071 {
1072     return singleHandModeFlag_;
1073 }
1074 
1075 
UpdateRect(const WSRect & rect,SizeChangeReason reason,const std::string & updateReason,const std::shared_ptr<RSTransaction> & rsTransaction)1076 WSError Session::UpdateRect(const WSRect& rect, SizeChangeReason reason,
1077     const std::string& updateReason, const std::shared_ptr<RSTransaction>& rsTransaction)
1078 {
1079     return UpdateRectWithLayoutInfo(rect, reason, updateReason, rsTransaction, {});
1080 }
1081 
UpdateRectWithLayoutInfo(const WSRect & rect,SizeChangeReason reason,const std::string & updateReason,const std::shared_ptr<RSTransaction> & rsTransaction,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)1082 WSError Session::UpdateRectWithLayoutInfo(const WSRect& rect, SizeChangeReason reason,
1083     const std::string& updateReason, const std::shared_ptr<RSTransaction>& rsTransaction,
1084     const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
1085 {
1086     TLOGD(WmsLogTag::WMS_LAYOUT, "session update rect: id: %{public}d, rect:%{public}s, "
1087         "reason:%{public}u %{public}s", GetPersistentId(), rect.ToString().c_str(), reason, updateReason.c_str());
1088     if (!IsSessionValid()) {
1089         winRect_ = rect;
1090         TLOGD(WmsLogTag::WMS_MAIN, "Session is invalid, id: %{public}d state: %{public}u",
1091             GetPersistentId(), GetSessionState());
1092         return WSError::WS_ERROR_INVALID_SESSION;
1093     }
1094     winRect_ = rect;
1095     if (!Session::IsBackgroundUpdateRectNotifyEnabled() && !IsSessionForeground()) {
1096         return WSError::WS_DO_NOTHING;
1097     }
1098     if (sessionStage_ != nullptr) {
1099         int32_t rotateAnimationDuration = GetRotateAnimationDuration();
1100         SceneAnimationConfig config { .rsTransaction_ = rsTransaction, .animationDuration_ = rotateAnimationDuration };
1101         WSRect updatedRect = rect;
1102         UpdateClientRectPosYAndDisplayId(updatedRect);
1103         sessionStage_->UpdateRect(updatedRect, reason, config, avoidAreas);
1104         SetClientRect(rect);
1105         RectCheckProcess();
1106     } else {
1107         WLOGFE("sessionStage_ is nullptr");
1108     }
1109     UpdatePointerArea(winRect_);
1110     return WSError::WS_OK;
1111 }
1112 
UpdateDensity()1113 WSError Session::UpdateDensity()
1114 {
1115     WLOGFI("session update density: id: %{public}d.", GetPersistentId());
1116     if (!IsSessionValid()) {
1117         TLOGW(WmsLogTag::WMS_MAIN, "Session is invalid, id: %{public}d state: %{public}u",
1118             GetPersistentId(), GetSessionState());
1119         return WSError::WS_ERROR_INVALID_SESSION;
1120     }
1121     if (sessionStage_ != nullptr) {
1122         sessionStage_->UpdateDensity();
1123     } else {
1124         WLOGFE("Session::UpdateDensity sessionStage_ is nullptr");
1125         return WSError::WS_ERROR_NULLPTR;
1126     }
1127     return WSError::WS_OK;
1128 }
1129 
UpdateOrientation()1130 WSError Session::UpdateOrientation()
1131 {
1132     TLOGD(WmsLogTag::DMS, "update orientation: id: %{public}d.", GetPersistentId());
1133     if (!IsSessionValid()) {
1134         TLOGE(WmsLogTag::DMS, "update orientation failed because of session is invalid, id=%{public}d.",
1135             GetPersistentId());
1136         return WSError::WS_ERROR_INVALID_SESSION;
1137     }
1138     if (sessionStage_ == nullptr) {
1139         TLOGE(WmsLogTag::DMS, "update orientation failed because of sessionStage_ is nullptr, id=%{public}d.",
1140             GetPersistentId());
1141         return WSError::WS_ERROR_NULLPTR;
1142     }
1143     return sessionStage_->UpdateOrientation();
1144 }
1145 
ConnectInner(const sptr<ISessionStage> & sessionStage,const sptr<IWindowEventChannel> & eventChannel,const std::shared_ptr<RSSurfaceNode> & surfaceNode,SystemSessionConfig & systemConfig,sptr<WindowSessionProperty> property,sptr<IRemoteObject> token,int32_t pid,int32_t uid,const std::string & identityToken)1146 __attribute__((no_sanitize("cfi"))) WSError Session::ConnectInner(const sptr<ISessionStage>& sessionStage,
1147     const sptr<IWindowEventChannel>& eventChannel,
1148     const std::shared_ptr<RSSurfaceNode>& surfaceNode,
1149     SystemSessionConfig& systemConfig, sptr<WindowSessionProperty> property,
1150     sptr<IRemoteObject> token, int32_t pid, int32_t uid, const std::string& identityToken)
1151 {
1152     TLOGI(WmsLogTag::WMS_LIFE, "ConnectInner session, id: %{public}d, state: %{public}u,"
1153         "isTerminating:%{public}d, callingPid:%{public}d", GetPersistentId(),
1154         static_cast<uint32_t>(GetSessionState()), isTerminating_, pid);
1155     if (GetSessionState() != SessionState::STATE_DISCONNECT && !isTerminating_) {
1156         TLOGE(WmsLogTag::WMS_LIFE, "state is not disconnect state:%{public}u id:%{public}u!",
1157             GetSessionState(), GetPersistentId());
1158         return WSError::WS_ERROR_INVALID_SESSION;
1159     }
1160     if (sessionStage == nullptr || eventChannel == nullptr) {
1161         TLOGE(WmsLogTag::WMS_LIFE, "session stage or eventChannel is nullptr");
1162         return WSError::WS_ERROR_NULLPTR;
1163     }
1164     sessionStage_ = sessionStage;
1165     windowEventChannel_ = eventChannel;
1166     SetSurfaceNode(surfaceNode);
1167     abilityToken_ = token;
1168     systemConfig = systemConfig_;
1169     InitSessionPropertyWhenConnect(property);
1170     SetCallingPid(pid);
1171     callingUid_ = uid;
1172     UpdateSessionState(SessionState::STATE_CONNECT);
1173     WindowHelper::IsUIExtensionWindow(GetWindowType()) ? UpdateRect(winRect_, SizeChangeReason::UNDEFINED, "Connect") :
1174         NotifyClientToUpdateRect("Connect", nullptr);
1175     NotifyConnect();
1176     return WSError::WS_OK;
1177 }
1178 
InitSessionPropertyWhenConnect(const sptr<WindowSessionProperty> & property)1179 void Session::InitSessionPropertyWhenConnect(const sptr<WindowSessionProperty>& property)
1180 {
1181     if (property == nullptr) {
1182         return;
1183     }
1184     if (GetSessionProperty()->GetIsNeedUpdateWindowMode()) {
1185         property->SetIsNeedUpdateWindowMode(true);
1186         property->SetWindowMode(GetSessionProperty()->GetWindowMode());
1187     }
1188     if (SessionHelper::IsMainWindow(GetWindowType()) && GetSessionInfo().screenId_ != SCREEN_ID_INVALID) {
1189         property->SetDisplayId(GetSessionInfo().screenId_);
1190     }
1191     InitSystemSessionDragEnable(property);
1192     property->SetSessionPropertyChangeCallback(
1193         [weakThis = wptr(this)]() {
1194             auto session = weakThis.promote();
1195             if (session == nullptr) {
1196                 TLOGNE(WmsLogTag::DEFAULT, "session is null");
1197                 return;
1198             }
1199             session->NotifySessionInfoChange();
1200         });
1201 
1202     Rect rect = {winRect_.posX_, winRect_.posY_, static_cast<uint32_t>(winRect_.width_),
1203         static_cast<uint32_t>(winRect_.height_)};
1204     property->SetWindowRect(rect);
1205     property->SetPersistentId(GetPersistentId());
1206     property->SetFullScreenStart(GetSessionInfo().fullScreenStart_);
1207     property->SetSupportedWindowModes(GetSessionInfo().supportedWindowModes);
1208     property->SetWindowSizeLimits(GetSessionInfo().windowSizeLimits);
1209     property->SetIsAtomicService(GetSessionInfo().isAtomicService_);
1210     property->SetRequestedOrientation(GetSessionProperty()->GetRequestedOrientation());
1211     property->SetDefaultRequestedOrientation(GetSessionProperty()->GetDefaultRequestedOrientation());
1212     TLOGI(WmsLogTag::WMS_MAIN, "Id: %{public}d, requestedOrientation: %{public}u,"
1213         " defaultRequestedOrientation: %{public}u", GetPersistentId(),
1214         static_cast<uint32_t>(GetSessionProperty()->GetRequestedOrientation()),
1215         static_cast<uint32_t>(GetSessionProperty()->GetDefaultRequestedOrientation()));
1216     property->SetCompatibleModeInPc(GetSessionProperty()->GetCompatibleModeInPc());
1217     property->SetIsSupportDragInPcCompatibleMode(GetSessionProperty()->GetIsSupportDragInPcCompatibleMode());
1218     if (GetSessionProperty()->GetCompatibleModeInPc()) {
1219         property->SetDragEnabled(GetSessionProperty()->GetIsSupportDragInPcCompatibleMode());
1220     }
1221     property->SetCompatibleModeEnableInPad(GetSessionProperty()->GetCompatibleModeEnableInPad());
1222     property->SetCompatibleWindowSizeInPc(GetSessionProperty()->GetCompatibleInPcPortraitWidth(),
1223         GetSessionProperty()->GetCompatibleInPcPortraitHeight(),
1224         GetSessionProperty()->GetCompatibleInPcLandscapeWidth(),
1225         GetSessionProperty()->GetCompatibleInPcLandscapeHeight());
1226     property->SetIsAppSupportPhoneInPc(GetSessionProperty()->GetIsAppSupportPhoneInPc());
1227     std::optional<bool> clientDragEnable = GetClientDragEnable();
1228     if (clientDragEnable.has_value()) {
1229         property->SetDragEnabled(clientDragEnable.value());
1230     }
1231     if (SessionHelper::IsMainWindow(GetWindowType())) {
1232         property->SetIsPcAppInPad(GetSessionProperty()->GetIsPcAppInPad());
1233     }
1234     SetSessionProperty(property);
1235 }
1236 
InitSystemSessionDragEnable(const sptr<WindowSessionProperty> & property)1237 void Session::InitSystemSessionDragEnable(const sptr<WindowSessionProperty>& property)
1238 {
1239     auto defaultDragEnable = false;
1240     auto isSystemWindow = WindowHelper::IsSystemWindow(property->GetWindowType());
1241     bool isDialog = WindowHelper::IsDialogWindow(property->GetWindowType());
1242     bool isSystemCalling = property->GetSystemCalling();
1243     TLOGI(WmsLogTag::WMS_LAYOUT, "windId: %{public}d, defaultDragEnable: %{public}d, isSystemWindow: %{public}d, "
1244         "isDialog: %{public}d, isSystemCalling: %{public}d", GetPersistentId(), defaultDragEnable,
1245         isSystemWindow, isDialog, isSystemCalling);
1246     if (isSystemWindow && !isDialog && !isSystemCalling) {
1247         property->SetDragEnabled(defaultDragEnable);
1248     }
1249 }
1250 
Reconnect(const sptr<ISessionStage> & sessionStage,const sptr<IWindowEventChannel> & eventChannel,const std::shared_ptr<RSSurfaceNode> & surfaceNode,sptr<WindowSessionProperty> property,sptr<IRemoteObject> token,int32_t pid,int32_t uid)1251 WSError Session::Reconnect(const sptr<ISessionStage>& sessionStage, const sptr<IWindowEventChannel>& eventChannel,
1252     const std::shared_ptr<RSSurfaceNode>& surfaceNode, sptr<WindowSessionProperty> property, sptr<IRemoteObject> token,
1253     int32_t pid, int32_t uid)
1254 {
1255     if (property == nullptr) {
1256         TLOGE(WmsLogTag::WMS_RECOVER, "property is nullptr");
1257         return WSError::WS_ERROR_NULLPTR;
1258     }
1259     TLOGI(WmsLogTag::WMS_RECOVER, "id:%{public}d, state:%{public}u, pid:%{public}d",
1260         property->GetPersistentId(), static_cast<uint32_t>(property->GetWindowState()), pid);
1261     if (sessionStage == nullptr || eventChannel == nullptr) {
1262         TLOGE(WmsLogTag::WMS_RECOVER, "session stage or eventChannel is nullptr");
1263         return WSError::WS_ERROR_NULLPTR;
1264     }
1265     sessionStage_ = sessionStage;
1266     SetSurfaceNode(surfaceNode);
1267     windowEventChannel_ = eventChannel;
1268     abilityToken_ = token;
1269     SetSessionPropertyForReconnect(property);
1270     persistentId_ = property->GetPersistentId();
1271     SetCallingPid(pid);
1272     callingUid_ = uid;
1273     bufferAvailable_ = true;
1274     auto windowRect = property->GetWindowRect();
1275     layoutRect_ = { windowRect.posX_, windowRect.posY_,
1276         static_cast<int32_t>(windowRect.width_), static_cast<int32_t>(windowRect.height_) };
1277     UpdateSessionState(SessionState::STATE_CONNECT);
1278     return WSError::WS_OK;
1279 }
1280 
Foreground(sptr<WindowSessionProperty> property,bool isFromClient,const std::string & identityToken)1281 WSError Session::Foreground(sptr<WindowSessionProperty> property, bool isFromClient, const std::string& identityToken)
1282 {
1283     HandleDialogForeground();
1284     SessionState state = GetSessionState();
1285     TLOGI(WmsLogTag::WMS_LIFE, "id:%{public}d, state:%{public}u, isTerminating:%{public}d",
1286         GetPersistentId(), static_cast<uint32_t>(state), isTerminating_);
1287     if (state != SessionState::STATE_CONNECT && state != SessionState::STATE_BACKGROUND &&
1288         state != SessionState::STATE_INACTIVE) {
1289         TLOGE(WmsLogTag::WMS_LIFE, "Foreground state invalid! state:%{public}u", state);
1290         return WSError::WS_ERROR_INVALID_SESSION;
1291     }
1292 
1293     UpdateSessionState(SessionState::STATE_FOREGROUND);
1294     if (!isActive_) {
1295         SetActive(true);
1296     }
1297     isStarting_ = false;
1298 
1299     NotifyForeground();
1300 
1301     isTerminating_ = false;
1302     return WSError::WS_OK;
1303 }
1304 
HandleDialogBackground()1305 void Session::HandleDialogBackground()
1306 {
1307     const auto& type = GetWindowType();
1308     if (type < WindowType::APP_MAIN_WINDOW_BASE || type >= WindowType::APP_MAIN_WINDOW_END) {
1309         TLOGD(WmsLogTag::WMS_DIALOG, "Current session is not main window, id: %{public}d, type: %{public}d",
1310             GetPersistentId(), type);
1311         return;
1312     }
1313 
1314     auto dialogVec = GetDialogVector();
1315     for (const auto& dialog : dialogVec) {
1316         if (dialog == nullptr) {
1317             continue;
1318         }
1319         TLOGI(WmsLogTag::WMS_DIALOG, "Background dialog, id: %{public}d, dialogId: %{public}d",
1320             GetPersistentId(), dialog->GetPersistentId());
1321         if (!dialog->sessionStage_) {
1322             TLOGE(WmsLogTag::WMS_DIALOG, "dialog session stage is nullptr");
1323             return;
1324         }
1325         dialog->sessionStage_->NotifyDialogStateChange(false);
1326     }
1327 }
1328 
HandleDialogForeground()1329 void Session::HandleDialogForeground()
1330 {
1331     const auto& type = GetWindowType();
1332     if (type < WindowType::APP_MAIN_WINDOW_BASE || type >= WindowType::APP_MAIN_WINDOW_END) {
1333         TLOGD(WmsLogTag::WMS_DIALOG, "Current session is not main window, id: %{public}d, type: %{public}d",
1334             GetPersistentId(), type);
1335         return;
1336     }
1337 
1338     auto dialogVec = GetDialogVector();
1339     for (const auto& dialog : dialogVec) {
1340         if (dialog == nullptr) {
1341             continue;
1342         }
1343         TLOGI(WmsLogTag::WMS_DIALOG, "Foreground dialog, id: %{public}d, dialogId: %{public}d",
1344             GetPersistentId(), dialog->GetPersistentId());
1345         if (!dialog->sessionStage_) {
1346             TLOGE(WmsLogTag::WMS_DIALOG, "dialog session stage is nullptr");
1347             return;
1348         }
1349         dialog->sessionStage_->NotifyDialogStateChange(true);
1350     }
1351 }
1352 
Background(bool isFromClient,const std::string & identityToken)1353 WSError Session::Background(bool isFromClient, const std::string& identityToken)
1354 {
1355     HandleDialogBackground();
1356     SessionState state = GetSessionState();
1357     TLOGI(WmsLogTag::WMS_LIFE, "Background session, id: %{public}d, state: %{public}" PRIu32, GetPersistentId(),
1358         static_cast<uint32_t>(state));
1359     if (state == SessionState::STATE_ACTIVE && GetWindowType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW) {
1360         UpdateSessionState(SessionState::STATE_INACTIVE);
1361         state = SessionState::STATE_INACTIVE;
1362         isActive_ = false;
1363     }
1364     isStarting_ = false;
1365     isStartingBeforeVisible_ = false;
1366     if (state != SessionState::STATE_INACTIVE) {
1367         TLOGW(WmsLogTag::WMS_LIFE, "Background state invalid! id: %{public}d, state: %{public}u",
1368             GetPersistentId(), state);
1369         return WSError::WS_ERROR_INVALID_SESSION;
1370     }
1371     UpdateSessionState(SessionState::STATE_BACKGROUND);
1372     SetIsPendingToBackgroundState(false);
1373     NotifyBackground();
1374     return WSError::WS_OK;
1375 }
1376 
ResetSessionConnectState()1377 void Session::ResetSessionConnectState()
1378 {
1379     TLOGI(WmsLogTag::WMS_LIFE, "ResetSessionState, id: %{public}d, state: %{public}u",
1380         GetPersistentId(), GetSessionState());
1381     SetSessionState(SessionState::STATE_DISCONNECT);
1382     SetCallingPid(-1);
1383 }
1384 
ResetIsActive()1385 void Session::ResetIsActive()
1386 {
1387     TLOGI(WmsLogTag::WMS_LIFE, "id: %{public}d, isActive: %{public}u",
1388         GetPersistentId(), IsActive());
1389     isActive_ = false;
1390 }
1391 
Disconnect(bool isFromClient,const std::string & identityToken)1392 WSError Session::Disconnect(bool isFromClient, const std::string& identityToken)
1393 {
1394     auto state = GetSessionState();
1395     TLOGI(WmsLogTag::WMS_LIFE, "Disconnect session, id: %{public}d, state: %{public}u", GetPersistentId(), state);
1396     isActive_ = false;
1397     isStarting_ = false;
1398     isStartingBeforeVisible_ = false;
1399     bufferAvailable_ = false;
1400     isNeedSyncSessionRect_ = true;
1401     if (mainHandler_) {
1402         std::shared_ptr<RSSurfaceNode> surfaceNode;
1403         {
1404             std::lock_guard<std::mutex> lock(surfaceNodeMutex_);
1405             surfaceNode_.swap(surfaceNode);
1406         }
1407         mainHandler_->PostTask([surfaceNode = std::move(surfaceNode)]() mutable {
1408             surfaceNode.reset();
1409         });
1410     }
1411     UpdateSessionState(SessionState::STATE_BACKGROUND);
1412     UpdateSessionState(SessionState::STATE_DISCONNECT);
1413     NotifyDisconnect();
1414     if (visibilityChangedDetectFunc_) {
1415         visibilityChangedDetectFunc_(GetCallingPid(), isVisible_, false);
1416     }
1417     return WSError::WS_OK;
1418 }
1419 
Show(sptr<WindowSessionProperty> property)1420 WSError Session::Show(sptr<WindowSessionProperty> property)
1421 {
1422     TLOGD(WmsLogTag::WMS_LIFE, "Show session, id: %{public}d", GetPersistentId());
1423     return WSError::WS_OK;
1424 }
1425 
Hide()1426 WSError Session::Hide()
1427 {
1428     TLOGD(WmsLogTag::WMS_LIFE, "Hide session, id: %{public}d", GetPersistentId());
1429     return WSError::WS_OK;
1430 }
1431 
DrawingCompleted()1432 WSError Session::DrawingCompleted()
1433 {
1434     TLOGI(WmsLogTag::WMS_LIFE, "id: %{public}d", GetPersistentId());
1435     if (!SessionPermission::IsSystemAppCall()) {
1436         TLOGE(WmsLogTag::WMS_LIFE, "permission denied!");
1437         return WSError::WS_ERROR_INVALID_PERMISSION;
1438     }
1439     auto lifecycleListeners = GetListeners<ILifecycleListener>();
1440     for (auto& listener : lifecycleListeners) {
1441         if (auto listenerPtr = listener.lock()) {
1442             listenerPtr->OnDrawingCompleted();
1443         }
1444     }
1445     return WSError::WS_OK;
1446 }
1447 
RemoveStartingWindow()1448 WSError Session::RemoveStartingWindow()
1449 {
1450     auto lifecycleListeners = GetListeners<ILifecycleListener>();
1451     for (auto& listener : lifecycleListeners) {
1452         if (auto listenerPtr = listener.lock()) {
1453             listenerPtr->OnAppRemoveStartingWindow();
1454         }
1455     }
1456     return WSError::WS_OK;
1457 }
1458 
SetActive(bool active)1459 WSError Session::SetActive(bool active)
1460 {
1461     SessionState state = GetSessionState();
1462     TLOGI(WmsLogTag::WMS_LIFE, "new active:%{public}d, id:%{public}d, state:%{public}u",
1463         active, GetPersistentId(), static_cast<uint32_t>(state));
1464     if (!IsSessionValid()) {
1465         TLOGW(WmsLogTag::WMS_LIFE, "Session is invalid, id: %{public}d state: %{public}u",
1466             GetPersistentId(), GetSessionState());
1467         return WSError::WS_ERROR_INVALID_SESSION;
1468     }
1469     if (active == isActive_) {
1470         TLOGD(WmsLogTag::WMS_LIFE, "Session active do not change: [%{public}d]", active);
1471         return WSError::WS_DO_NOTHING;
1472     }
1473     if (!sessionStage_) {
1474         TLOGE(WmsLogTag::WMS_LIFE, "session stage is nullptr");
1475         return WSError::WS_ERROR_NULLPTR;
1476     }
1477     if (active && GetSessionState() == SessionState::STATE_FOREGROUND) {
1478         sessionStage_->SetActive(true);
1479         UpdateSessionState(SessionState::STATE_ACTIVE);
1480         isActive_ = active;
1481     }
1482     if (!active && GetSessionState() == SessionState::STATE_ACTIVE) {
1483         sessionStage_->SetActive(false);
1484         UpdateSessionState(SessionState::STATE_INACTIVE);
1485         isActive_ = active;
1486     }
1487     return WSError::WS_OK;
1488 }
1489 
ProcessClickModalWindowOutside(int32_t posX,int32_t posY)1490 void Session::ProcessClickModalWindowOutside(int32_t posX, int32_t posY)
1491 {
1492     if (clickModalWindowOutsideFunc_ && !winRect_.IsInRegion(posX, posY)) {
1493         clickModalWindowOutsideFunc_();
1494     }
1495 }
1496 
SetClickModalWindowOutsideListener(NotifyClickModalWindowOutsideFunc && func)1497 void Session::SetClickModalWindowOutsideListener(NotifyClickModalWindowOutsideFunc&& func)
1498 {
1499     const char* const where = __func__;
1500     PostTask([weakThis = wptr(this), func = std::move(func), where] {
1501         auto session = weakThis.promote();
1502         if (!session || !func) {
1503             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session or func is null", where);
1504             return;
1505         }
1506         session->clickModalWindowOutsideFunc_ = std::move(func);
1507         TLOGNI(WmsLogTag::WMS_DIALOG, "%{public}s id: %{public}d", where, session->GetPersistentId());
1508     }, __func__);
1509 }
1510 
SetClientDragEnable(bool dragEnable)1511 void Session::SetClientDragEnable(bool dragEnable)
1512 {
1513     clientDragEnable_ = dragEnable;
1514 }
1515 
GetClientDragEnable() const1516 std::optional<bool> Session::GetClientDragEnable() const
1517 {
1518     return clientDragEnable_;
1519 }
1520 
SetDragActivated(bool dragActivated)1521 void Session::SetDragActivated(bool dragActivated)
1522 {
1523     dragActivated_ = dragActivated;
1524 }
1525 
IsDragAccessible() const1526 bool Session::IsDragAccessible() const
1527 {
1528     bool isDragEnabled = GetSessionProperty()->GetDragEnabled();
1529     TLOGD(WmsLogTag::WMS_LAYOUT, "PersistentId: %{public}d, dragEnabled: %{public}d, dragActivate: %{public}d",
1530         GetPersistentId(), isDragEnabled, dragActivated_);
1531     return isDragEnabled && dragActivated_;
1532 }
1533 
IsScreenLockWindow() const1534 bool Session::IsScreenLockWindow() const
1535 {
1536     return isScreenLockWindow_;
1537 }
1538 
NotifyForegroundInteractiveStatus(bool interactive)1539 void Session::NotifyForegroundInteractiveStatus(bool interactive)
1540 {
1541     SetForegroundInteractiveStatus(interactive);
1542 }
1543 
SetForegroundInteractiveStatus(bool interactive)1544 void Session::SetForegroundInteractiveStatus(bool interactive)
1545 {
1546     if (interactive != GetForegroundInteractiveStatus()) {
1547         TLOGI(WmsLogTag::WMS_EVENT, "id:%{public}d, %{public}d", GetPersistentId(),
1548             static_cast<int>(interactive));
1549     }
1550     foregroundInteractiveStatus_.store(interactive);
1551     if (Session::IsScbCoreEnabled()) {
1552         return;
1553     }
1554     NotifySessionInfoChange();
1555 }
1556 
GetForegroundInteractiveStatus() const1557 bool Session::GetForegroundInteractiveStatus() const
1558 {
1559     return foregroundInteractiveStatus_.load();
1560 }
1561 
GetIsPendingToBackgroundState() const1562 bool Session::GetIsPendingToBackgroundState() const
1563 {
1564     return isPendingToBackgroundState_.load();
1565 }
1566 
SetIsPendingToBackgroundState(bool isPendingToBackgroundState)1567 void Session::SetIsPendingToBackgroundState(bool isPendingToBackgroundState)
1568 {
1569     TLOGI(WmsLogTag::WMS_LIFE, "id:%{public}d isPendingToBackgroundState:%{public}d",
1570         GetPersistentId(), isPendingToBackgroundState);
1571     return isPendingToBackgroundState_.store(isPendingToBackgroundState);
1572 }
1573 
IsActivatedAfterScreenLocked() const1574 bool Session::IsActivatedAfterScreenLocked() const
1575 {
1576     return isActivatedAfterScreenLocked_.load();
1577 }
1578 
SetIsActivatedAfterScreenLocked(bool isActivatedAfterScreenLocked)1579 void Session::SetIsActivatedAfterScreenLocked(bool isActivatedAfterScreenLocked)
1580 {
1581     TLOGI(WmsLogTag::WMS_LIFE, "id:%{public}d, isActivatedAfterScreenLocked:%{public}d",
1582         GetPersistentId(), isActivatedAfterScreenLocked);
1583     isActivatedAfterScreenLocked_.store(isActivatedAfterScreenLocked);
1584 }
1585 
SetAttachState(bool isAttach,WindowMode windowMode)1586 void Session::SetAttachState(bool isAttach, WindowMode windowMode)
1587 {
1588     isAttach_ = isAttach;
1589     PostTask([weakThis = wptr(this), isAttach]() {
1590         auto session = weakThis.promote();
1591         if (session == nullptr) {
1592             TLOGND(WmsLogTag::WMS_LIFE, "session is null");
1593             return;
1594         }
1595         if (session->needNotifyAttachState_.load() && session->sessionStage_) {
1596             session->sessionStage_->NotifyWindowAttachStateChange(isAttach);
1597         }
1598         TLOGND(WmsLogTag::WMS_LIFE, "isAttach:%{public}d persistentId:%{public}d", isAttach,
1599             session->GetPersistentId());
1600         if (!isAttach && session->detachCallback_ != nullptr) {
1601             TLOGNI(WmsLogTag::WMS_LIFE, "Session detach, persistentId:%{public}d", session->GetPersistentId());
1602             session->detachCallback_->OnPatternDetach(session->GetPersistentId());
1603             session->detachCallback_ = nullptr;
1604         }
1605     }, "SetAttachState");
1606     CreateDetectStateTask(isAttach, windowMode);
1607 }
1608 
SetNeedNotifyAttachState(bool needNotify)1609 void Session::SetNeedNotifyAttachState(bool needNotify)
1610 {
1611     needNotifyAttachState_.store(needNotify);
1612 }
1613 
CreateDetectStateTask(bool isAttach,WindowMode windowMode)1614 void Session::CreateDetectStateTask(bool isAttach, WindowMode windowMode)
1615 {
1616     if (!IsSupportDetectWindow(isAttach)) {
1617         return;
1618     }
1619     if (showRecent_) {
1620         return;
1621     }
1622     if (!ShouldCreateDetectTask(isAttach, windowMode)) {
1623         RemoveWindowDetectTask();
1624         DetectTaskInfo detectTaskInfo;
1625         SetDetectTaskInfo(detectTaskInfo);
1626         return;
1627     }
1628     CreateWindowStateDetectTask(isAttach, windowMode);
1629 }
1630 
RegisterDetachCallback(const sptr<IPatternDetachCallback> & callback)1631 void Session::RegisterDetachCallback(const sptr<IPatternDetachCallback>& callback)
1632 {
1633     detachCallback_ = callback;
1634     if (!isAttach_ && detachCallback_ != nullptr) {
1635         TLOGI(WmsLogTag::WMS_LIFE, "Session detach before register, persistentId:%{public}d", GetPersistentId());
1636         detachCallback_->OnPatternDetach(GetPersistentId());
1637         detachCallback_ = nullptr;
1638     }
1639 }
1640 
SetChangeSessionVisibilityWithStatusBarEventListener(NotifyChangeSessionVisibilityWithStatusBarFunc && func)1641 void Session::SetChangeSessionVisibilityWithStatusBarEventListener(
1642     NotifyChangeSessionVisibilityWithStatusBarFunc&& func)
1643 {
1644     PostTask([weakThis = wptr(this), func = std::move(func), where = __func__] {
1645         auto session = weakThis.promote();
1646         if (!session || !func) {
1647             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session is nullptr", where);
1648             return;
1649         }
1650         session->changeSessionVisibilityWithStatusBarFunc_ = std::move(func);
1651     }, __func__);
1652 }
1653 
SetPendingSessionActivationEventListener(NotifyPendingSessionActivationFunc && func)1654 void Session::SetPendingSessionActivationEventListener(NotifyPendingSessionActivationFunc&& func)
1655 {
1656     const char* const where = __func__;
1657     PostTask([weakThis = wptr(this), func = std::move(func), where] {
1658         auto session = weakThis.promote();
1659         if (!session) {
1660             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session is nullptr", where);
1661             return;
1662         }
1663         session->pendingSessionActivationFunc_ = std::move(func);
1664     }, where);
1665 }
1666 
SetBackPressedListenser(NotifyBackPressedFunc && func)1667 void Session::SetBackPressedListenser(NotifyBackPressedFunc&& func)
1668 {
1669     const char* const where = __func__;
1670     PostTask([weakThis = wptr(this), func = std::move(func), where] {
1671         auto session = weakThis.promote();
1672         if (!session) {
1673             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session is nullptr", where);
1674             return;
1675         }
1676         session->backPressedFunc_ = std::move(func);
1677     }, where);
1678 }
1679 
SetTerminateSessionListener(NotifyTerminateSessionFunc && func)1680 void Session::SetTerminateSessionListener(NotifyTerminateSessionFunc&& func)
1681 {
1682     const char* const where = __func__;
1683     PostTask([weakThis = wptr(this), func = std::move(func), where] {
1684         auto session = weakThis.promote();
1685         if (!session) {
1686             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session is nullptr", where);
1687             return;
1688         }
1689         session->terminateSessionFunc_ = std::move(func);
1690     }, where);
1691 }
1692 
RemoveLifeCycleTask(const LifeCycleTaskType & taskType)1693 void Session::RemoveLifeCycleTask(const LifeCycleTaskType& taskType)
1694 {
1695     sptr<SessionLifeCycleTask> frontLifeCycleTask = nullptr;
1696     {
1697         std::lock_guard<std::mutex> lock(lifeCycleTaskQueueMutex_);
1698         if (lifeCycleTaskQueue_.empty()) {
1699             return;
1700         }
1701         sptr<SessionLifeCycleTask> currLifeCycleTask = lifeCycleTaskQueue_.front();
1702         if (currLifeCycleTask->type != taskType) {
1703             TLOGW(WmsLogTag::WMS_LIFE,
1704                 "not match, current running taskName=%{public}s, PersistentId=%{public}d",
1705                 currLifeCycleTask->name.c_str(), persistentId_);
1706             return;
1707         }
1708         TLOGI(WmsLogTag::WMS_LIFE, "Removed lifeCyleTask %{public}s. PersistentId=%{public}d",
1709             currLifeCycleTask->name.c_str(), persistentId_);
1710         lifeCycleTaskQueue_.pop_front();
1711         if (lifeCycleTaskQueue_.empty()) {
1712             return;
1713         }
1714         frontLifeCycleTask = lifeCycleTaskQueue_.front();
1715     }
1716     StartLifeCycleTask(frontLifeCycleTask);
1717 }
1718 
PostLifeCycleTask(Task && task,const std::string & name,const LifeCycleTaskType & taskType)1719 void Session::PostLifeCycleTask(Task&& task, const std::string& name, const LifeCycleTaskType& taskType)
1720 {
1721     sptr<SessionLifeCycleTask> frontlifeCycleTask = nullptr;
1722     {
1723         std::lock_guard<std::mutex> lock(lifeCycleTaskQueueMutex_);
1724         if (!lifeCycleTaskQueue_.empty()) {
1725         // remove current running task if expired
1726             sptr<SessionLifeCycleTask> currLifeCycleTask = lifeCycleTaskQueue_.front();
1727             std::chrono::steady_clock::time_point currentTime = std::chrono::steady_clock::now();
1728             bool isCurrentTaskExpired =
1729                 std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - currLifeCycleTask->startTime)
1730                     .count() > LIFE_CYCLE_TASK_EXPIRED_TIME_LIMIT;
1731             if (isCurrentTaskExpired) {
1732                 TLOGE(WmsLogTag::WMS_LIFE, "Remove expired LifeCycleTask %{public}s. PersistentId=%{public}d",
1733                     currLifeCycleTask->name.c_str(), persistentId_);
1734                 lifeCycleTaskQueue_.pop_front();
1735             }
1736         }
1737 
1738         if (lifeCycleTaskQueue_.size() == MAX_LIFE_CYCLE_TASK_IN_QUEUE) {
1739             TLOGE(WmsLogTag::WMS_LIFE, "Failed to add task %{public}s to life cycle queue", name.c_str());
1740             return;
1741         }
1742         sptr<SessionLifeCycleTask> lifeCycleTask =
1743             sptr<SessionLifeCycleTask>::MakeSptr(std::move(task), name, taskType);
1744         lifeCycleTaskQueue_.push_back(lifeCycleTask);
1745         TLOGI(WmsLogTag::WMS_LIFE, "Add task %{public}s to life cycle queue, PersistentId=%{public}d",
1746             name.c_str(), persistentId_);
1747         frontlifeCycleTask = lifeCycleTaskQueue_.front();
1748     }
1749     StartLifeCycleTask(frontlifeCycleTask);
1750 }
1751 
StartLifeCycleTask(sptr<SessionLifeCycleTask> lifeCycleTask)1752 void Session::StartLifeCycleTask(sptr<SessionLifeCycleTask> lifeCycleTask)
1753 {
1754     if (lifeCycleTask->running) {
1755         return;
1756     }
1757     TLOGI(WmsLogTag::WMS_LIFE, "Execute LifeCycleTask %{public}s. PersistentId: %{public}d",
1758         lifeCycleTask->name.c_str(), persistentId_);
1759     lifeCycleTask->running = true;
1760     lifeCycleTask->startTime = std::chrono::steady_clock::now();
1761     PostTask(std::move(lifeCycleTask->task), lifeCycleTask->name);
1762 }
1763 
TerminateSessionNew(const sptr<AAFwk::SessionInfo> abilitySessionInfo,bool needStartCaller,bool isFromBroker)1764 WSError Session::TerminateSessionNew(
1765     const sptr<AAFwk::SessionInfo> abilitySessionInfo, bool needStartCaller, bool isFromBroker)
1766 {
1767     if (abilitySessionInfo == nullptr) {
1768         TLOGE(WmsLogTag::WMS_LIFE, "abilitySessionInfo is null");
1769         return WSError::WS_ERROR_INVALID_SESSION;
1770     }
1771     auto task = [weakThis = wptr(this), abilitySessionInfo, needStartCaller, isFromBroker]() {
1772         auto session = weakThis.promote();
1773         if (session == nullptr) {
1774             TLOGNI(WmsLogTag::WMS_LIFE, "session is null.");
1775             return;
1776         }
1777         session->isTerminating_ = true;
1778         SessionInfo info;
1779         info.abilityName_ = abilitySessionInfo->want.GetElement().GetAbilityName();
1780         info.bundleName_ = abilitySessionInfo->want.GetElement().GetBundleName();
1781         info.callerToken_ = abilitySessionInfo->callerToken;
1782         info.persistentId_ = static_cast<int32_t>(abilitySessionInfo->persistentId);
1783         {
1784             std::lock_guard<std::recursive_mutex> lock(session->sessionInfoMutex_);
1785             session->sessionInfo_.closeAbilityWant = std::make_shared<AAFwk::Want>(abilitySessionInfo->want);
1786             session->sessionInfo_.resultCode = abilitySessionInfo->resultCode;
1787         }
1788         if (session->terminateSessionFuncNew_) {
1789             session->terminateSessionFuncNew_(info, needStartCaller, isFromBroker);
1790         }
1791         TLOGNI(WmsLogTag::WMS_LIFE,
1792             "TerminateSessionNew, id: %{public}d, needStartCaller: %{public}d, isFromBroker: %{public}d",
1793             session->GetPersistentId(), needStartCaller, isFromBroker);
1794     };
1795     PostLifeCycleTask(task, "TerminateSessionNew", LifeCycleTaskType::STOP);
1796     return WSError::WS_OK;
1797 }
1798 
SetTerminateSessionListenerNew(NotifyTerminateSessionFuncNew && func)1799 void Session::SetTerminateSessionListenerNew(NotifyTerminateSessionFuncNew&& func)
1800 {
1801     const char* const where = __func__;
1802     PostTask([weakThis = wptr(this), func = std::move(func), where] {
1803         auto session = weakThis.promote();
1804         if (!session) {
1805             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session is nullptr", where);
1806             return;
1807         }
1808         session->terminateSessionFuncNew_ = std::move(func);
1809     }, where);
1810 }
1811 
TerminateSessionTotal(const sptr<AAFwk::SessionInfo> abilitySessionInfo,TerminateType terminateType)1812 WSError Session::TerminateSessionTotal(const sptr<AAFwk::SessionInfo> abilitySessionInfo, TerminateType terminateType)
1813 {
1814     if (abilitySessionInfo == nullptr) {
1815         TLOGE(WmsLogTag::WMS_LIFE, "abilitySessionInfo is null");
1816         return WSError::WS_ERROR_INVALID_SESSION;
1817     }
1818     if (isTerminating_) {
1819         TLOGE(WmsLogTag::WMS_LIFE, "is terminating, return!");
1820         return WSError::WS_ERROR_INVALID_OPERATION;
1821     }
1822     isTerminating_ = true;
1823     SessionInfo info;
1824     info.abilityName_ = abilitySessionInfo->want.GetElement().GetAbilityName();
1825     info.bundleName_ = abilitySessionInfo->want.GetElement().GetBundleName();
1826     info.callerToken_ = abilitySessionInfo->callerToken;
1827     info.persistentId_ = static_cast<int32_t>(abilitySessionInfo->persistentId);
1828     {
1829         std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
1830         sessionInfo_.closeAbilityWant = std::make_shared<AAFwk::Want>(abilitySessionInfo->want);
1831         sessionInfo_.resultCode = abilitySessionInfo->resultCode;
1832     }
1833     if (terminateSessionFuncTotal_) {
1834         terminateSessionFuncTotal_(info, terminateType);
1835     }
1836     return WSError::WS_OK;
1837 }
1838 
SetTerminateSessionListenerTotal(NotifyTerminateSessionFuncTotal && func)1839 void Session::SetTerminateSessionListenerTotal(NotifyTerminateSessionFuncTotal&& func)
1840 {
1841     const char* const where = __func__;
1842     PostTask([weakThis = wptr(this), func = std::move(func), where] {
1843         auto session = weakThis.promote();
1844         if (!session) {
1845             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session is nullptr", where);
1846             return;
1847         }
1848         session->terminateSessionFuncTotal_ = std::move(func);
1849     }, where);
1850 }
1851 
SetSessionLabel(const std::string & label)1852 WSError Session::SetSessionLabel(const std::string& label)
1853 {
1854     WLOGFI("run Session::SetSessionLabel");
1855     if (updateSessionLabelFunc_) {
1856         updateSessionLabelFunc_(label);
1857     }
1858     return WSError::WS_OK;
1859 }
1860 
SetUpdateSessionLabelListener(const NofitySessionLabelUpdatedFunc & func)1861 void Session::SetUpdateSessionLabelListener(const NofitySessionLabelUpdatedFunc& func)
1862 {
1863     updateSessionLabelFunc_ = func;
1864 }
1865 
SetSessionIcon(const std::shared_ptr<Media::PixelMap> & icon)1866 WSError Session::SetSessionIcon(const std::shared_ptr<Media::PixelMap>& icon)
1867 {
1868     WLOGFD("run Session::SetSessionIcon, id: %{public}d", GetPersistentId());
1869     if (scenePersistence_ == nullptr) {
1870         WLOGFE("scenePersistence_ is nullptr.");
1871         return WSError::WS_ERROR_INVALID_OPERATION;
1872     }
1873     scenePersistence_->SaveUpdatedIcon(icon);
1874     std::string updatedIconPath = scenePersistence_->GetUpdatedIconPath();
1875     if (updateSessionIconFunc_) {
1876         updateSessionIconFunc_(updatedIconPath);
1877     }
1878     return WSError::WS_OK;
1879 }
1880 
SetUpdateSessionIconListener(const NofitySessionIconUpdatedFunc & func)1881 void Session::SetUpdateSessionIconListener(const NofitySessionIconUpdatedFunc& func)
1882 {
1883     updateSessionIconFunc_ = func;
1884 }
1885 
Clear(bool needStartCaller)1886 WSError Session::Clear(bool needStartCaller)
1887 {
1888     TLOGI(WmsLogTag::WMS_LIFE, "id:%{public}d, needStartCaller:%{public}u", GetPersistentId(), needStartCaller);
1889     auto task = [weakThis = wptr(this), needStartCaller]() {
1890         auto session = weakThis.promote();
1891         if (session == nullptr) {
1892             TLOGNE(WmsLogTag::WMS_LIFE, "session is null");
1893             return;
1894         }
1895         session->isTerminating_ = true;
1896         if (session->terminateSessionFuncNew_) {
1897             session->terminateSessionFuncNew_(session->GetSessionInfo(), needStartCaller, false);
1898         }
1899     };
1900     PostLifeCycleTask(task, "Clear", LifeCycleTaskType::STOP);
1901     return WSError::WS_OK;
1902 }
1903 
SetSessionExceptionListener(NotifySessionExceptionFunc && func,bool fromJsScene)1904 void Session::SetSessionExceptionListener(NotifySessionExceptionFunc&& func, bool fromJsScene)
1905 {
1906     PostTask([weakThis = wptr(this), where = __func__, func = std::move(func), fromJsScene] {
1907         auto session = weakThis.promote();
1908         if (!session) {
1909             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session is nullptr", where);
1910             return;
1911         }
1912         if (fromJsScene) {
1913             session->jsSceneSessionExceptionFunc_ = std::move(func);
1914         } else {
1915             session->sessionExceptionFunc_ = std::move(func);
1916         }
1917     }, __func__);
1918 }
1919 
SetSessionSnapshotListener(const NotifySessionSnapshotFunc & func)1920 void Session::SetSessionSnapshotListener(const NotifySessionSnapshotFunc& func)
1921 {
1922     if (func == nullptr) {
1923         WLOGFE("func is nullptr");
1924         return;
1925     }
1926     notifySessionSnapshotFunc_ = func;
1927 }
1928 
SetPendingSessionToForegroundListener(NotifyPendingSessionToForegroundFunc && func)1929 void Session::SetPendingSessionToForegroundListener(NotifyPendingSessionToForegroundFunc&& func)
1930 {
1931     PostTask([weakThis = wptr(this), func = std::move(func), where = __func__] {
1932         auto session = weakThis.promote();
1933         if (!session) {
1934             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session is nullptr", where);
1935             return;
1936         }
1937         session->pendingSessionToForegroundFunc_ = std::move(func);
1938     }, __func__);
1939 }
1940 
PendingSessionToForeground()1941 WSError Session::PendingSessionToForeground()
1942 {
1943     TLOGI(WmsLogTag::WMS_LIFE, "id: %{public}d", GetPersistentId());
1944     if (pendingSessionActivationFunc_) {
1945         SessionInfo info = GetSessionInfo();
1946         pendingSessionActivationFunc_(info);
1947     }
1948     return WSError::WS_OK;
1949 }
1950 
SetPendingSessionToBackgroundForDelegatorListener(NotifyPendingSessionToBackgroundForDelegatorFunc && func)1951 void Session::SetPendingSessionToBackgroundForDelegatorListener(
1952     NotifyPendingSessionToBackgroundForDelegatorFunc&& func)
1953 {
1954     PostTask([weakThis = wptr(this), func = std::move(func), where = __func__] {
1955         auto session = weakThis.promote();
1956         if (!session) {
1957             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session is nullptr", where);
1958             return;
1959         }
1960         session->pendingSessionToBackgroundForDelegatorFunc_ = std::move(func);
1961     }, __func__);
1962 }
1963 
PendingSessionToBackgroundForDelegator(bool shouldBackToCaller)1964 WSError Session::PendingSessionToBackgroundForDelegator(bool shouldBackToCaller)
1965 {
1966     TLOGI(WmsLogTag::WMS_LIFE, "id: %{public}d, shouldBackToCaller: %{public}d",
1967         GetPersistentId(), shouldBackToCaller);
1968     if (pendingSessionToBackgroundForDelegatorFunc_) {
1969         pendingSessionToBackgroundForDelegatorFunc_(GetSessionInfo(), shouldBackToCaller);
1970     }
1971     return WSError::WS_OK;
1972 }
1973 
SetRaiseToAppTopForPointDownFunc(const NotifyRaiseToTopForPointDownFunc & func)1974 void Session::SetRaiseToAppTopForPointDownFunc(const NotifyRaiseToTopForPointDownFunc& func)
1975 {
1976     raiseToTopForPointDownFunc_ = func;
1977 }
1978 
NotifyScreenshot()1979 void Session::NotifyScreenshot()
1980 {
1981     if (!sessionStage_) {
1982         return;
1983     }
1984     sessionStage_->NotifyScreenshot();
1985 }
1986 
NotifyCloseExistPipWindow()1987 WSError Session::NotifyCloseExistPipWindow()
1988 {
1989     if (!sessionStage_) {
1990         return WSError::WS_ERROR_NULLPTR;
1991     }
1992     return sessionStage_->NotifyCloseExistPipWindow();
1993 }
1994 
NotifyDestroy()1995 WSError Session::NotifyDestroy()
1996 {
1997     if (!sessionStage_) {
1998         return WSError::WS_ERROR_NULLPTR;
1999     }
2000     return sessionStage_->NotifyDestroy();
2001 }
2002 
SetParentSession(const sptr<Session> & session)2003 void Session::SetParentSession(const sptr<Session>& session)
2004 {
2005     if (session == nullptr) {
2006         WLOGFW("Session is nullptr");
2007         return;
2008     }
2009     {
2010         std::unique_lock<std::shared_mutex> lock(parentSessionMutex_);
2011         parentSession_ = session;
2012     }
2013     TLOGD(WmsLogTag::WMS_SUB, "[WMSDialog][WMSSub]Set parent success, parentId: %{public}d, id: %{public}d",
2014         session->GetPersistentId(), GetPersistentId());
2015 }
2016 
GetParentSession() const2017 sptr<Session> Session::GetParentSession() const
2018 {
2019     std::shared_lock<std::shared_mutex> lock(parentSessionMutex_);
2020     return parentSession_;
2021 }
2022 
GetMainSession() const2023 sptr<Session> Session::GetMainSession() const
2024 {
2025     if (SessionHelper::IsMainWindow(GetWindowType())) {
2026         return const_cast<Session*>(this);
2027     } else if (parentSession_) {
2028         return parentSession_->GetMainSession();
2029     } else {
2030         return nullptr;
2031     }
2032 }
2033 
GetMainOrFloatSession() const2034 sptr<Session> Session::GetMainOrFloatSession() const
2035 {
2036     auto windowType = GetWindowType();
2037     if (SessionHelper::IsMainWindow(windowType) || windowType == WindowType::WINDOW_TYPE_FLOAT) {
2038         return const_cast<Session*>(this);
2039     } else if (parentSession_) {
2040         return parentSession_->GetMainOrFloatSession();
2041     } else {
2042         return nullptr;
2043     }
2044 }
2045 
IsAncestorsSession(int ancestorsId) const2046 bool Session::IsAncestorsSession(int ancestorsId) const
2047 {
2048     if (GetSessionProperty()->GetParentPersistentId() == ancestorsId) {
2049         return true;
2050     }
2051     auto parentSession = GetParentSession();
2052     if (parentSession != nullptr) {
2053         return parentSession->IsAncestorsSession(ancestorsId);
2054     }
2055     return false;
2056 }
2057 
BindDialogToParentSession(const sptr<Session> & session)2058 void Session::BindDialogToParentSession(const sptr<Session>& session)
2059 {
2060     std::unique_lock<std::shared_mutex> lock(dialogVecMutex_);
2061     auto iter = std::find(dialogVec_.begin(), dialogVec_.end(), session);
2062     if (iter != dialogVec_.end()) {
2063         TLOGW(WmsLogTag::WMS_DIALOG, "Dialog is existed in parentVec, id: %{public}d, parentId: %{public}d",
2064             session->GetPersistentId(), GetPersistentId());
2065         return;
2066     }
2067     dialogVec_.push_back(session);
2068     TLOGD(WmsLogTag::WMS_DIALOG, "Bind dialog success, id: %{public}d, parentId: %{public}d",
2069         session->GetPersistentId(), GetPersistentId());
2070 }
2071 
RemoveDialogToParentSession(const sptr<Session> & session)2072 void Session::RemoveDialogToParentSession(const sptr<Session>& session)
2073 {
2074     std::unique_lock<std::shared_mutex> lock(dialogVecMutex_);
2075     auto iter = std::find(dialogVec_.begin(), dialogVec_.end(), session);
2076     if (iter != dialogVec_.end()) {
2077         TLOGD(WmsLogTag::WMS_DIALOG, "Remove dialog success, id: %{public}d, parentId: %{public}d",
2078             session->GetPersistentId(), GetPersistentId());
2079         dialogVec_.erase(iter);
2080     }
2081     TLOGW(WmsLogTag::WMS_DIALOG, "Remove dialog failed, id: %{public}d, parentId: %{public}d",
2082         session->GetPersistentId(), GetPersistentId());
2083 }
2084 
GetDialogVector() const2085 std::vector<sptr<Session>> Session::GetDialogVector() const
2086 {
2087     std::shared_lock<std::shared_mutex> lock(dialogVecMutex_);
2088     return dialogVec_;
2089 }
2090 
ClearDialogVector()2091 void Session::ClearDialogVector()
2092 {
2093     std::unique_lock<std::shared_mutex> lock(dialogVecMutex_);
2094     dialogVec_.clear();
2095     TLOGD(WmsLogTag::WMS_DIALOG, "parentId: %{public}d", GetPersistentId());
2096     return;
2097 }
2098 
CheckDialogOnForeground()2099 bool Session::CheckDialogOnForeground()
2100 {
2101     auto dialogVec = GetDialogVector();
2102     if (dialogVec.empty()) {
2103         TLOGD(WmsLogTag::WMS_DIALOG, "Dialog is empty, id: %{public}d", GetPersistentId());
2104         return false;
2105     }
2106     for (auto iter = dialogVec.rbegin(); iter != dialogVec.rend(); iter++) {
2107         auto dialogSession = *iter;
2108         if (dialogSession && (dialogSession->GetSessionState() == SessionState::STATE_ACTIVE ||
2109             dialogSession->GetSessionState() == SessionState::STATE_FOREGROUND)) {
2110             TLOGD(WmsLogTag::WMS_DIALOG, "Notify touch dialog window, id: %{public}d", GetPersistentId());
2111             return true;
2112         }
2113     }
2114     return false;
2115 }
2116 
CheckPointerEventDispatch(const std::shared_ptr<MMI::PointerEvent> & pointerEvent) const2117 bool Session::CheckPointerEventDispatch(const std::shared_ptr<MMI::PointerEvent>& pointerEvent) const
2118 {
2119     return true;
2120 }
2121 
IsTopDialog() const2122 bool Session::IsTopDialog() const
2123 {
2124     int32_t currentPersistentId = GetPersistentId();
2125     auto parentSession = GetParentSession();
2126     if (parentSession == nullptr) {
2127         TLOGW(WmsLogTag::WMS_DIALOG, "Dialog's Parent is NULL. id: %{public}d", currentPersistentId);
2128         return false;
2129     }
2130     auto parentDialogVec = parentSession->GetDialogVector();
2131     if (parentDialogVec.size() <= 1) {
2132         return true;
2133     }
2134     for (auto iter = parentDialogVec.rbegin(); iter != parentDialogVec.rend(); iter++) {
2135         auto dialogSession = *iter;
2136         if (dialogSession && (dialogSession->GetSessionState() == SessionState::STATE_ACTIVE ||
2137             dialogSession->GetSessionState() == SessionState::STATE_FOREGROUND)) {
2138             WLOGFI("Dialog id: %{public}d, current dialog id: %{public}d", dialogSession->GetPersistentId(),
2139                 currentPersistentId);
2140             return dialogSession->GetPersistentId() == currentPersistentId;
2141         }
2142     }
2143     return false;
2144 }
2145 
DumpPointerWindowArea(MMI::WindowArea area) const2146 const char* Session::DumpPointerWindowArea(MMI::WindowArea area) const
2147 {
2148     const std::map<MMI::WindowArea, const char*> areaMap = {
2149         { MMI::WindowArea::FOCUS_ON_INNER, "FOCUS_ON_INNER" },
2150         { MMI::WindowArea::FOCUS_ON_TOP, "FOCUS_ON_TOP" },
2151         { MMI::WindowArea::FOCUS_ON_BOTTOM, "FOCUS_ON_BOTTOM" },
2152         { MMI::WindowArea::FOCUS_ON_LEFT, "FOCUS_ON_LEFT" },
2153         { MMI::WindowArea::FOCUS_ON_RIGHT, "FOCUS_ON_RIGHT" },
2154         { MMI::WindowArea::FOCUS_ON_BOTTOM_LEFT, "FOCUS_ON_BOTTOM_LEFT" },
2155         { MMI::WindowArea::FOCUS_ON_BOTTOM_RIGHT, "FOCUS_ON_BOTTOM_RIGHT" },
2156         { MMI::WindowArea::FOCUS_ON_TOP_LEFT, "FOCUS_ON_TOP_LEFT" },
2157         { MMI::WindowArea::FOCUS_ON_TOP_RIGHT, "FOCUS_ON_TOP_RIGHT" },
2158         { MMI::WindowArea::EXIT, "EXIT" }
2159     };
2160     auto iter = areaMap.find(area);
2161     if (iter == areaMap.end()) {
2162         return "UNKNOWN";
2163     }
2164     return iter->second;
2165 }
2166 
RaiseToAppTopForPointDown()2167 WSError Session::RaiseToAppTopForPointDown()
2168 {
2169     if (raiseToTopForPointDownFunc_) {
2170         raiseToTopForPointDownFunc_();
2171         WLOGFD("RaiseToAppTopForPointDown, id: %{public}d, type: %{public}d", GetPersistentId(), GetWindowType());
2172     }
2173     return WSError::WS_OK;
2174 }
2175 
PresentFocusIfPointDown()2176 void Session::PresentFocusIfPointDown()
2177 {
2178     WLOGFI("id: %{public}d,type: %{public}d", GetPersistentId(), GetWindowType());
2179     if (!isFocused_ && GetFocusable()) {
2180         FocusChangeReason reason = FocusChangeReason::CLICK;
2181         NotifyRequestFocusStatusNotifyManager(true, false, reason);
2182     }
2183     NotifyClick();
2184 }
2185 
HandlePointDownDialog()2186 void Session::HandlePointDownDialog()
2187 {
2188     auto dialogVec = GetDialogVector();
2189     sptr<Session> lastValidDialog = nullptr;
2190     for (auto dialog : dialogVec) {
2191         if (dialog && (dialog->GetSessionState() == SessionState::STATE_FOREGROUND ||
2192             dialog->GetSessionState() == SessionState::STATE_ACTIVE)) {
2193             dialog->RaiseToAppTopForPointDown();
2194             lastValidDialog = dialog;
2195             TLOGD(WmsLogTag::WMS_DIALOG, "Point main window, raise to top and dialog need focus, "
2196                 "id: %{public}d, dialogId: %{public}d", GetPersistentId(), dialog->GetPersistentId());
2197         }
2198     }
2199     if (lastValidDialog != nullptr) {
2200         lastValidDialog->PresentFocusIfPointDown();
2201     }
2202 }
2203 
HandleSubWindowClick(int32_t action,bool isExecuteDelayRaise)2204 WSError Session::HandleSubWindowClick(int32_t action, bool isExecuteDelayRaise)
2205 {
2206     auto parentSession = GetParentSession();
2207     if (parentSession && parentSession->CheckDialogOnForeground()) {
2208         TLOGD(WmsLogTag::WMS_DIALOG, "Its main window has dialog on foreground, id: %{public}d", GetPersistentId());
2209         return WSError::WS_ERROR_INVALID_PERMISSION;
2210     }
2211     bool raiseEnabled = GetSessionProperty()->GetRaiseEnabled();
2212     bool isPointDown = action == MMI::PointerEvent::POINTER_ACTION_DOWN ||
2213         action == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN;
2214     if (isExecuteDelayRaise) {
2215         if (raiseEnabled && action == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP) {
2216             RaiseToAppTopForPointDown();
2217         }
2218         if (!raiseEnabled && parentSession) {
2219             parentSession->NotifyClick(!IsScbCoreEnabled());
2220         }
2221         return WSError::WS_OK;
2222     }
2223     if (raiseEnabled && isPointDown) {
2224         RaiseToAppTopForPointDown();
2225     } else if (parentSession) {
2226         // sub window is forbidden to raise to top after click, but its parent should raise
2227         parentSession->NotifyClick(!IsScbCoreEnabled());
2228     }
2229     return WSError::WS_OK;
2230 }
2231 
TransferPointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent,bool needNotifyClient,bool isExecuteDelayRaise)2232 WSError Session::TransferPointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent,
2233     bool needNotifyClient, bool isExecuteDelayRaise)
2234 {
2235     WLOGFD("Session TransferPointEvent, id: %{public}d", GetPersistentId());
2236     if (!IsSystemSession() && !IsSessionValid()) {
2237         return WSError::WS_ERROR_INVALID_SESSION;
2238     }
2239     if (pointerEvent == nullptr) {
2240         WLOGFE("PointerEvent is nullptr");
2241         return WSError::WS_ERROR_NULLPTR;
2242     }
2243     auto pointerAction = pointerEvent->GetPointerAction();
2244     bool isPointDown = (pointerAction == MMI::PointerEvent::POINTER_ACTION_DOWN) ||
2245         (pointerAction == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN);
2246     if (GetWindowType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW) {
2247         if (CheckDialogOnForeground() && isPointDown) {
2248             HandlePointDownDialog();
2249             return WSError::WS_ERROR_INVALID_PERMISSION;
2250         }
2251     } else if (GetWindowType() == WindowType::WINDOW_TYPE_APP_SUB_WINDOW) {
2252         WSError ret = HandleSubWindowClick(pointerAction, isExecuteDelayRaise);
2253         if (ret != WSError::WS_OK) {
2254             return ret;
2255         }
2256     } else if (GetWindowType() == WindowType::WINDOW_TYPE_DIALOG) {
2257         auto parentSession = GetParentSession();
2258         if (parentSession && parentSession->CheckDialogOnForeground() && isPointDown) {
2259             parentSession->HandlePointDownDialog();
2260             if (!IsTopDialog()) {
2261                 TLOGI(WmsLogTag::WMS_DIALOG, "There is at least one active dialog upon this dialog, id: %{public}d",
2262                     GetPersistentId());
2263                 return WSError::WS_ERROR_INVALID_PERMISSION;
2264             }
2265         }
2266     }
2267     if (!isExecuteDelayRaise) {
2268         PresentFoucusIfNeed(pointerAction);
2269     } else if (pointerAction == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP) {
2270         if (!isFocused_ && GetFocusable()) {
2271             NotifyRequestFocusStatusNotifyManager(true, false, FocusChangeReason::CLICK);
2272         }
2273         NotifyClick();
2274     }
2275     if (!windowEventChannel_) {
2276         if (!IsSystemSession()) {
2277             WLOGFE("windowEventChannel_ is null");
2278         }
2279         return WSError::WS_ERROR_NULLPTR;
2280     }
2281 
2282     if (needNotifyClient) {
2283         WSError ret = windowEventChannel_->TransferPointerEvent(pointerEvent);
2284         if (ret != WSError::WS_OK) {
2285             WLOGFE("InputTracking id:%{public}d, TransferPointer failed, ret:%{public}d ",
2286                 pointerEvent->GetId(), ret);
2287         }
2288         return ret;
2289     } else {
2290         pointerEvent->MarkProcessed();
2291     }
2292     if (pointerAction == MMI::PointerEvent::POINTER_ACTION_MOVE ||
2293         pointerAction == MMI::PointerEvent::POINTER_ACTION_PULL_MOVE) {
2294         TLOGD(WmsLogTag::WMS_EVENT, "eventId:%{public}d, action:%{public}s, persistentId:%{public}d, "
2295             "bundleName:%{public}s, pid:%{public}d", pointerEvent->GetId(), pointerEvent->DumpPointerAction(),
2296             persistentId_, callingBundleName_.c_str(), callingPid_);
2297     } else {
2298         TLOGD(WmsLogTag::WMS_EVENT, "eventId:%{public}d, action:%{public}s, "
2299             "persistentId:%{public}d, bundleName:%{public}s, pid:%{public}d",
2300             pointerEvent->GetId(), pointerEvent->DumpPointerAction(),
2301             persistentId_, callingBundleName_.c_str(), callingPid_);
2302     }
2303     if (pointerAction == MMI::PointerEvent::POINTER_ACTION_ENTER_WINDOW ||
2304         pointerAction == MMI::PointerEvent::POINTER_ACTION_LEAVE_WINDOW ||
2305         pointerAction == MMI::PointerEvent::POINTER_ACTION_PULL_IN_WINDOW ||
2306         pointerAction == MMI::PointerEvent::POINTER_ACTION_PULL_OUT_WINDOW) {
2307         WLOGFD("Action:%{public}s, eventId:%{public}d, report without timer",
2308             pointerEvent->DumpPointerAction(), pointerEvent->GetId());
2309     }
2310     return WSError::WS_OK;
2311 }
2312 
TransferKeyEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent)2313 WSError Session::TransferKeyEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
2314 {
2315     WLOGFD("Session TransferKeyEvent eventId:%{public}d persistentId:%{public}d bundleName:%{public}s pid:%{public}d",
2316         keyEvent->GetId(), persistentId_, callingBundleName_.c_str(), callingPid_);
2317     if (!windowEventChannel_) {
2318         WLOGFE("windowEventChannel_ is null");
2319         return WSError::WS_ERROR_NULLPTR;
2320     }
2321     WLOGD("TransferKeyEvent, id: %{public}d", persistentId_);
2322     WSError ret = windowEventChannel_->TransferKeyEvent(keyEvent);
2323     if (ret != WSError::WS_OK) {
2324         WLOGFE("TransferKeyEvent failed, ret:%{public}d", ret);
2325         return ret;
2326     }
2327     return WSError::WS_OK;
2328 }
2329 
TransferBackPressedEventForConsumed(bool & isConsumed)2330 WSError Session::TransferBackPressedEventForConsumed(bool& isConsumed)
2331 {
2332     if (!windowEventChannel_) {
2333         WLOGFE("windowEventChannel_ is null");
2334         return WSError::WS_ERROR_NULLPTR;
2335     }
2336     return windowEventChannel_->TransferBackpressedEventForConsumed(isConsumed);
2337 }
2338 
TransferKeyEventForConsumed(const std::shared_ptr<MMI::KeyEvent> & keyEvent,bool & isConsumed,bool isPreImeEvent)2339 WSError Session::TransferKeyEventForConsumed(const std::shared_ptr<MMI::KeyEvent>& keyEvent, bool& isConsumed,
2340     bool isPreImeEvent)
2341 {
2342     if (!windowEventChannel_) {
2343         WLOGFE("windowEventChannel_ is null");
2344         return WSError::WS_ERROR_NULLPTR;
2345     }
2346     if (keyEvent == nullptr) {
2347         WLOGFE("KeyEvent is nullptr");
2348         return WSError::WS_ERROR_NULLPTR;
2349     }
2350     return windowEventChannel_->TransferKeyEventForConsumed(keyEvent, isConsumed, isPreImeEvent);
2351 }
2352 
TransferFocusActiveEvent(bool isFocusActive)2353 WSError Session::TransferFocusActiveEvent(bool isFocusActive)
2354 {
2355     if (!windowEventChannel_) {
2356         WLOGFE("windowEventChannel_ is null");
2357         return WSError::WS_ERROR_NULLPTR;
2358     }
2359     return windowEventChannel_->TransferFocusActiveEvent(isFocusActive);
2360 }
2361 
TransferFocusStateEvent(bool focusState)2362 WSError Session::TransferFocusStateEvent(bool focusState)
2363 {
2364     if (!windowEventChannel_) {
2365         if (!IsSystemSession()) {
2366             WLOGFW("windowEventChannel_ is null");
2367         }
2368         return WSError::WS_ERROR_NULLPTR;
2369     }
2370     return windowEventChannel_->TransferFocusState(focusState);
2371 }
2372 
Snapshot(bool runInFfrt,float scaleParam,bool useCurWindow) const2373 std::shared_ptr<Media::PixelMap> Session::Snapshot(bool runInFfrt, float scaleParam, bool useCurWindow) const
2374 {
2375     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "Snapshot[%d][%s]", persistentId_, sessionInfo_.bundleName_.c_str());
2376     if (scenePersistence_ == nullptr) {
2377         return nullptr;
2378     }
2379     auto surfaceNode = GetSurfaceNode();
2380     if (!surfaceNode || !surfaceNode->IsBufferAvailable()) {
2381         scenePersistence_->SetHasSnapshot(false);
2382         return nullptr;
2383     }
2384     scenePersistence_->SetHasSnapshot(true);
2385     auto callback = std::make_shared<SurfaceCaptureFuture>();
2386     auto scaleValue = (scaleParam < 0.0f || std::fabs(scaleParam) < std::numeric_limits<float>::min()) ?
2387         snapshotScale_ : scaleParam;
2388     RSSurfaceCaptureConfig config = {
2389         .scaleX = scaleValue,
2390         .scaleY = scaleValue,
2391         .useDma = true,
2392         .useCurWindow = useCurWindow,
2393     };
2394     bool ret = RSInterfaces::GetInstance().TakeSurfaceCapture(surfaceNode, callback, config);
2395     if (!ret) {
2396         TLOGE(WmsLogTag::WMS_MAIN, "TakeSurfaceCapture failed");
2397         return nullptr;
2398     }
2399     constexpr int32_t FFRT_SNAPSHOT_TIMEOUT_MS = 5000;
2400     auto pixelMap = callback->GetResult(runInFfrt ? FFRT_SNAPSHOT_TIMEOUT_MS : SNAPSHOT_TIMEOUT_MS);
2401     if (pixelMap != nullptr) {
2402         TLOGI(WmsLogTag::WMS_MAIN, "Save snapshot WxH=%{public}dx%{public}d, id: %{public}d",
2403             pixelMap->GetWidth(), pixelMap->GetHeight(), persistentId_);
2404         if (notifySessionSnapshotFunc_) {
2405             notifySessionSnapshotFunc_(persistentId_);
2406         }
2407         return pixelMap;
2408     }
2409     TLOGE(WmsLogTag::WMS_MAIN, "Save snapshot failed, id: %{public}d", persistentId_);
2410     return nullptr;
2411 }
2412 
ResetSnapshot()2413 void Session::ResetSnapshot()
2414 {
2415     TLOGI(WmsLogTag::WMS_PATTERN, "id: %{public}d", persistentId_);
2416     std::lock_guard lock(snapshotMutex_);
2417     snapshot_ = nullptr;
2418     if (scenePersistence_ == nullptr) {
2419         TLOGI(WmsLogTag::WMS_PATTERN, "scenePersistence_ %{public}d nullptr", persistentId_);
2420         return;
2421     }
2422     scenePersistence_->ResetSnapshotCache();
2423 }
2424 
SaveSnapshot(bool useFfrt,bool needPersist)2425 void Session::SaveSnapshot(bool useFfrt, bool needPersist)
2426 {
2427     if (scenePersistence_ == nullptr) {
2428         return;
2429     }
2430     auto task = [weakThis = wptr(this), runInFfrt = useFfrt, requirePersist = needPersist]() {
2431         auto session = weakThis.promote();
2432         if (session == nullptr) {
2433             TLOGNE(WmsLogTag::WMS_LIFE, "session is null");
2434             return;
2435         }
2436         session->lastLayoutRect_ = session->layoutRect_;
2437         auto pixelMap = session->Snapshot(runInFfrt);
2438         if (pixelMap == nullptr) {
2439             return;
2440         }
2441         {
2442             std::lock_guard<std::mutex> lock(session->snapshotMutex_);
2443             session->snapshot_ = pixelMap;
2444         }
2445         {
2446             std::lock_guard lock(session->saveSnapshotCallbackMutex_);
2447             session->saveSnapshotCallback_();
2448         }
2449         if (!requirePersist) {
2450             return;
2451         }
2452         if (!session->scenePersistence_) {
2453             TLOGNE(WmsLogTag::WMS_PATTERN, "scenePersistence_ is null");
2454             return;
2455         }
2456         Task removeSnapshotCallback = []() {};
2457         {
2458             std::lock_guard lock(session->removeSnapshotCallbackMutex_);
2459             removeSnapshotCallback = session->removeSnapshotCallback_;
2460         }
2461         session->scenePersistence_->SaveSnapshot(pixelMap, removeSnapshotCallback);
2462     };
2463     if (!useFfrt) {
2464         task();
2465         return;
2466     }
2467     auto snapshotFfrtHelper = scenePersistence_->GetSnapshotFfrtHelper();
2468     std::string taskName = "Session::SaveSnapshot" + std::to_string(persistentId_);
2469     snapshotFfrtHelper->CancelTask(taskName);
2470     snapshotFfrtHelper->SubmitTask(std::move(task), taskName);
2471 }
2472 
SetSessionStateChangeListenser(const NotifySessionStateChangeFunc & func)2473 void Session::SetSessionStateChangeListenser(const NotifySessionStateChangeFunc& func)
2474 {
2475     PostTask([weakThis = wptr(this), func]() {
2476         auto session = weakThis.promote();
2477         if (session == nullptr) {
2478             WLOGFE("session is null");
2479             return;
2480         }
2481         session->sessionStateChangeFunc_ = func;
2482         auto changedState = session->GetSessionState(); // read and write state should in one thread
2483         if (changedState == SessionState::STATE_ACTIVE) {
2484             changedState = SessionState::STATE_FOREGROUND;
2485         } else if (changedState == SessionState::STATE_INACTIVE) {
2486             changedState = SessionState::STATE_BACKGROUND;
2487         } else if (changedState == SessionState::STATE_DISCONNECT) {
2488             return;
2489         }
2490         session->NotifySessionStateChange(changedState);
2491         TLOGNI(WmsLogTag::WMS_LIFE, "id: %{public}d, state_: %{public}d, changedState: %{public}d",
2492             session->GetPersistentId(), session->GetSessionState(), changedState);
2493     }, "SetSessionStateChangeListenser");
2494 }
2495 
SetBufferAvailableChangeListener(const NotifyBufferAvailableChangeFunc & func)2496 void Session::SetBufferAvailableChangeListener(const NotifyBufferAvailableChangeFunc& func)
2497 {
2498     bufferAvailableChangeFunc_ = func;
2499     if (bufferAvailable_ && bufferAvailableChangeFunc_ != nullptr) {
2500         bufferAvailableChangeFunc_(bufferAvailable_);
2501     }
2502     WLOGFD("SetBufferAvailableChangeListener, id: %{public}d", GetPersistentId());
2503 }
2504 
SetAcquireRotateAnimationConfigFunc(const AcquireRotateAnimationConfigFunc & func)2505 void Session::SetAcquireRotateAnimationConfigFunc(const AcquireRotateAnimationConfigFunc& func)
2506 {
2507     if (func == nullptr) {
2508         TLOGI(WmsLogTag::DEFAULT, "func is nullptr");
2509         return;
2510     }
2511     acquireRotateAnimationConfigFunc_ = func;
2512 }
2513 
GetRotateAnimationDuration()2514 int32_t Session::GetRotateAnimationDuration()
2515 {
2516     if (acquireRotateAnimationConfigFunc_) {
2517         RotateAnimationConfig rotateAnimationConfig;
2518         acquireRotateAnimationConfigFunc_(rotateAnimationConfig);
2519         return rotateAnimationConfig.duration_;
2520     }
2521     return ROTATE_ANIMATION_DURATION;
2522 }
2523 
UnregisterSessionChangeListeners()2524 void Session::UnregisterSessionChangeListeners()
2525 {
2526     sessionStateChangeFunc_ = nullptr;
2527     keyboardStateChangeFunc_ = nullptr;
2528     sessionFocusableChangeFunc_ = nullptr;
2529     sessionTouchableChangeFunc_ = nullptr;
2530     clickFunc_ = nullptr;
2531     jsSceneSessionExceptionFunc_ = nullptr;
2532     sessionExceptionFunc_ = nullptr;
2533     terminateSessionFunc_ = nullptr;
2534     pendingSessionActivationFunc_ = nullptr;
2535     changeSessionVisibilityWithStatusBarFunc_ = nullptr;
2536     bufferAvailableChangeFunc_ = nullptr;
2537     backPressedFunc_ = nullptr;
2538     terminateSessionFuncNew_ = nullptr;
2539     terminateSessionFuncTotal_ = nullptr;
2540     updateSessionLabelFunc_ = nullptr;
2541     updateSessionIconFunc_ = nullptr;
2542     pendingSessionToForegroundFunc_ = nullptr;
2543     pendingSessionToBackgroundForDelegatorFunc_ = nullptr;
2544     raiseToTopForPointDownFunc_ = nullptr;
2545     sessionInfoLockedStateChangeFunc_ = nullptr;
2546     contextTransparentFunc_ = nullptr;
2547     sessionRectChangeFunc_ = nullptr;
2548     updateSessionLabelAndIconFunc_ = nullptr;
2549     WLOGFD("UnregisterSessionChangeListenser, id: %{public}d", GetPersistentId());
2550 }
2551 
SetSessionStateChangeNotifyManagerListener(const NotifySessionStateChangeNotifyManagerFunc & func)2552 void Session::SetSessionStateChangeNotifyManagerListener(const NotifySessionStateChangeNotifyManagerFunc& func)
2553 {
2554     sessionStateChangeNotifyManagerFunc_ = func;
2555     if (state_ == SessionState::STATE_DISCONNECT) {
2556         return;
2557     }
2558     NotifySessionStateChange(state_);
2559 }
2560 
SetSessionInfoChangeNotifyManagerListener(const NotifySessionInfoChangeNotifyManagerFunc & func)2561 void Session::SetSessionInfoChangeNotifyManagerListener(const NotifySessionInfoChangeNotifyManagerFunc& func)
2562 {
2563     sessionInfoChangeNotifyManagerFunc_ = func;
2564 }
2565 
SetRequestFocusStatusNotifyManagerListener(const NotifyRequestFocusStatusNotifyManagerFunc & func)2566 void Session::SetRequestFocusStatusNotifyManagerListener(const NotifyRequestFocusStatusNotifyManagerFunc& func)
2567 {
2568     requestFocusStatusNotifyManagerFunc_ = func;
2569 }
2570 
SetNotifyUIRequestFocusFunc(const NotifyUIRequestFocusFunc & func)2571 void Session::SetNotifyUIRequestFocusFunc(const NotifyUIRequestFocusFunc& func)
2572 {
2573     std::unique_lock<std::shared_mutex> lock(uiRequestFocusMutex_);
2574     requestFocusFunc_ = func;
2575 }
2576 
SetNotifyUILostFocusFunc(const NotifyUILostFocusFunc & func)2577 void Session::SetNotifyUILostFocusFunc(const NotifyUILostFocusFunc& func)
2578 {
2579     std::unique_lock<std::shared_mutex> lock(uiLostFocusMutex_);
2580     lostFocusFunc_ = func;
2581 }
2582 
SetGetStateFromManagerListener(const GetStateFromManagerFunc & func)2583 void Session::SetGetStateFromManagerListener(const GetStateFromManagerFunc& func)
2584 {
2585     getStateFromManagerFunc_ = func;
2586 }
2587 
NotifySessionStateChange(const SessionState & state)2588 void Session::NotifySessionStateChange(const SessionState& state)
2589 {
2590     PostTask([weakThis = wptr(this), state]() {
2591         auto session = weakThis.promote();
2592         if (session == nullptr) {
2593             WLOGFE("session is null");
2594             return;
2595         }
2596         TLOGND(WmsLogTag::WMS_LIFE, "NotifySessionStateChange, [state: %{public}u, persistent: %{public}d]",
2597             static_cast<uint32_t>(state), session->GetPersistentId());
2598         if (session->GetWindowType() == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT &&
2599             session->keyboardStateChangeFunc_) {
2600             session->keyboardStateChangeFunc_(state, session->GetSessionProperty()->GetKeyboardViewMode());
2601         } else if (session->sessionStateChangeFunc_) {
2602             session->sessionStateChangeFunc_(state);
2603         } else {
2604             TLOGNI(WmsLogTag::WMS_LIFE, "sessionStateChangeFunc is null");
2605         }
2606 
2607         if (session->sessionStateChangeNotifyManagerFunc_) {
2608             session->sessionStateChangeNotifyManagerFunc_(session->GetPersistentId(), state);
2609         } else {
2610             TLOGNI(WmsLogTag::WMS_LIFE, "sessionStateChangeNotifyManagerFunc is null");
2611         }
2612     }, "NotifySessionStateChange");
2613 }
2614 
SetSessionFocusableChangeListener(const NotifySessionFocusableChangeFunc & func)2615 void Session::SetSessionFocusableChangeListener(const NotifySessionFocusableChangeFunc& func)
2616 {
2617     sessionFocusableChangeFunc_ = func;
2618     NotifySessionFocusableChange(GetFocusable());
2619 }
2620 
SetSessionTouchableChangeListener(const NotifySessionTouchableChangeFunc & func)2621 void Session::SetSessionTouchableChangeListener(const NotifySessionTouchableChangeFunc& func)
2622 {
2623     sessionTouchableChangeFunc_ = func;
2624     sessionTouchableChangeFunc_(GetTouchable());
2625 }
2626 
SetClickListener(const NotifyClickFunc & func)2627 void Session::SetClickListener(const NotifyClickFunc& func)
2628 {
2629     clickFunc_ = func;
2630 }
2631 
NotifySessionFocusableChange(bool isFocusable)2632 void Session::NotifySessionFocusableChange(bool isFocusable)
2633 {
2634     TLOGI(WmsLogTag::WMS_FOCUS, "id: %{public}d, focusable: %{public}u", GetPersistentId(), isFocusable);
2635     if (sessionFocusableChangeFunc_) {
2636         sessionFocusableChangeFunc_(isFocusable);
2637     }
2638 }
2639 
NotifySessionTouchableChange(bool touchable)2640 void Session::NotifySessionTouchableChange(bool touchable)
2641 {
2642     WLOGFD("Notify session touchable change: %{public}d", touchable);
2643     if (sessionTouchableChangeFunc_) {
2644         sessionTouchableChangeFunc_(touchable);
2645     }
2646 }
2647 
NotifyClick(bool requestFocus,bool isClick)2648 void Session::NotifyClick(bool requestFocus, bool isClick)
2649 {
2650     TLOGD(WmsLogTag::WMS_FOCUS, "requestFocus: %{public}u, isClick: %{public}u", requestFocus, isClick);
2651     if (clickFunc_) {
2652         clickFunc_(requestFocus, isClick);
2653     }
2654 }
2655 
NotifyRequestFocusStatusNotifyManager(bool isFocused,bool byForeground,FocusChangeReason reason)2656 void Session::NotifyRequestFocusStatusNotifyManager(bool isFocused, bool byForeground, FocusChangeReason reason)
2657 {
2658     TLOGD(WmsLogTag::WMS_FOCUS, "NotifyRequestFocusStatusNotifyManager id: %{public}d, focused: %{public}d,\
2659         reason:  %{public}d", GetPersistentId(), isFocused, reason);
2660     if (requestFocusStatusNotifyManagerFunc_) {
2661         requestFocusStatusNotifyManagerFunc_(GetPersistentId(), isFocused, byForeground, reason);
2662     }
2663 }
2664 
GetStateFromManager(const ManagerState key)2665 bool Session::GetStateFromManager(const ManagerState key)
2666 {
2667     if (getStateFromManagerFunc_) {
2668         return getStateFromManagerFunc_(key);
2669     }
2670     switch (key) {
2671         case ManagerState::MANAGER_STATE_SCREEN_LOCKED:
2672             return false;
2673             break;
2674         default:
2675             return false;
2676     }
2677 }
2678 
NotifyUIRequestFocus()2679 void Session::NotifyUIRequestFocus()
2680 {
2681     WLOGFD("NotifyUIRequestFocus id: %{public}d", GetPersistentId());
2682     std::shared_lock<std::shared_mutex> lock(uiRequestFocusMutex_);
2683     if (requestFocusFunc_) {
2684         requestFocusFunc_();
2685     }
2686 }
2687 
NotifyUILostFocus()2688 void Session::NotifyUILostFocus()
2689 {
2690     WLOGFD("NotifyUILostFocus id: %{public}d", GetPersistentId());
2691     std::shared_lock<std::shared_mutex> lock(uiLostFocusMutex_);
2692     if (lostFocusFunc_) {
2693         lostFocusFunc_();
2694     }
2695 }
2696 
PresentFoucusIfNeed(int32_t pointerAction)2697 void Session::PresentFoucusIfNeed(int32_t pointerAction)
2698 {
2699     WLOGFD("OnClick down, id: %{public}d", GetPersistentId());
2700     if (pointerAction == MMI::PointerEvent::POINTER_ACTION_DOWN ||
2701         pointerAction == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN) {
2702         if (!isFocused_ && GetFocusable()) {
2703             FocusChangeReason reason = FocusChangeReason::CLICK;
2704             NotifyRequestFocusStatusNotifyManager(true, false, reason);
2705         }
2706         NotifyClick();
2707     }
2708 }
2709 
UpdateFocus(bool isFocused)2710 WSError Session::UpdateFocus(bool isFocused)
2711 {
2712     if (isFocused_ == isFocused) {
2713         TLOGD(WmsLogTag::WMS_FOCUS, "Session focus do not change");
2714         return WSError::WS_DO_NOTHING;
2715     }
2716     isFocused_ = isFocused;
2717     UpdateGestureBackEnabled();
2718     // notify scb arkui focus
2719     if (!isFocused) {
2720         NotifyUILostFocus();
2721     }
2722     return WSError::WS_OK;
2723 }
2724 
NotifyFocusStatus(bool isFocused)2725 WSError Session::NotifyFocusStatus(bool isFocused)
2726 {
2727     if (!IsSessionValid()) {
2728         TLOGD(WmsLogTag::WMS_FOCUS, "Session is invalid, id: %{public}d state: %{public}u",
2729             GetPersistentId(), GetSessionState());
2730         return WSError::WS_ERROR_INVALID_SESSION;
2731     }
2732     if (!sessionStage_) {
2733         TLOGE(WmsLogTag::WMS_FOCUS, "Session stage is invalid, id: %{public}d state: %{public}u",
2734             GetPersistentId(), GetSessionState());
2735         return WSError::WS_ERROR_NULLPTR;
2736     }
2737     sessionStage_->UpdateFocus(isFocused);
2738 
2739     return WSError::WS_OK;
2740 }
2741 
RequestFocus(bool isFocused)2742 WSError Session::RequestFocus(bool isFocused)
2743 {
2744     if (!SessionPermission::IsSystemCalling()) {
2745         TLOGE(WmsLogTag::WMS_FOCUS, "permission denied!");
2746         return WSError::WS_ERROR_NOT_SYSTEM_APP;
2747     }
2748     FocusChangeReason reason = FocusChangeReason::CLIENT_REQUEST;
2749     NotifyRequestFocusStatusNotifyManager(isFocused, false, reason);
2750     return WSError::WS_OK;
2751 }
2752 
SetExclusivelyHighlighted(bool isExclusivelyHighlighted)2753 void Session::SetExclusivelyHighlighted(bool isExclusivelyHighlighted)
2754 {
2755     auto property = GetSessionProperty();
2756     if (property == nullptr) {
2757         TLOGE(WmsLogTag::WMS_FOCUS, "property is nullptr, windowId: %{public}d", persistentId_);
2758         return;
2759     }
2760     if (isExclusivelyHighlighted == property->GetExclusivelyHighlighted()) {
2761         return;
2762     }
2763     TLOGI(WmsLogTag::WMS_FOCUS, "windowId: %{public}d, isExclusivelyHighlighted: %{public}d", persistentId_,
2764         isExclusivelyHighlighted);
2765     property->SetExclusivelyHighlighted(isExclusivelyHighlighted);
2766 }
2767 
UpdateHighlightStatus(bool isHighlight,bool needBlockHighlightNotify)2768 WSError Session::UpdateHighlightStatus(bool isHighlight, bool needBlockHighlightNotify)
2769 {
2770     TLOGD(WmsLogTag::WMS_FOCUS,
2771         "windowId: %{public}d, currHighlight: %{public}d, nextHighlight: %{public}d, needBlockNotify:%{public}d",
2772         persistentId_, isHighlighted_, isHighlight, needBlockHighlightNotify);
2773     if (isHighlighted_ == isHighlight) {
2774         return WSError::WS_DO_NOTHING;
2775     }
2776     isHighlighted_ = isHighlight;
2777     if (!needBlockHighlightNotify) {
2778         NotifyHighlightChange(isHighlight);
2779     }
2780     std::lock_guard lock(highlightChangeFuncMutex_);
2781     if (highlightChangeFunc_ != nullptr) {
2782         highlightChangeFunc_(isHighlight);
2783     }
2784     return WSError::WS_OK;
2785 }
2786 
NotifyHighlightChange(bool isHighlight)2787 WSError Session::NotifyHighlightChange(bool isHighlight)
2788 {
2789     if (IsSystemSession()) {
2790         TLOGW(WmsLogTag::WMS_FOCUS, "Session is invalid, id: %{public}d state: %{public}u",
2791             persistentId_, GetSessionState());
2792         return WSError::WS_ERROR_INVALID_SESSION;
2793     }
2794     if (!sessionStage_) {
2795         TLOGE(WmsLogTag::WMS_FOCUS, "sessionStage is null");
2796         return WSError::WS_ERROR_NULLPTR;
2797     }
2798     sessionStage_->NotifyHighlightChange(isHighlight);
2799     return WSError::WS_OK;
2800 }
2801 
GetIsHighlighted(bool & isHighlighted)2802 WSError Session::GetIsHighlighted(bool& isHighlighted)
2803 {
2804     isHighlighted = isHighlighted_;
2805     TLOGD(WmsLogTag::WMS_FOCUS, "windowId: %{public}d, isHighlighted: %{public}d",
2806         GetPersistentId(), isHighlighted_);
2807     return WSError::WS_OK;
2808 }
2809 
SetCompatibleModeInPc(bool enable,bool isSupportDragInPcCompatibleMode)2810 WSError Session::SetCompatibleModeInPc(bool enable, bool isSupportDragInPcCompatibleMode)
2811 {
2812     TLOGI(WmsLogTag::WMS_SCB, "SetCompatibleModeInPc enable: %{public}d, isSupportDragInPcCompatibleMode: %{public}d",
2813         enable, isSupportDragInPcCompatibleMode);
2814     GetSessionProperty()->SetCompatibleModeInPc(enable);
2815     GetSessionProperty()->SetIsSupportDragInPcCompatibleMode(isSupportDragInPcCompatibleMode);
2816     if (enable) {
2817         GetSessionProperty()->SetDragEnabled(isSupportDragInPcCompatibleMode);
2818     }
2819     return WSError::WS_OK;
2820 }
2821 
SetCompatibleModeEnableInPad(bool enable)2822 WSError Session::SetCompatibleModeEnableInPad(bool enable)
2823 {
2824     TLOGI(WmsLogTag::WMS_SCB, "id: %{public}d, enable: %{public}d", persistentId_, enable);
2825     if (!IsSessionValid()) {
2826         TLOGW(WmsLogTag::WMS_SCB, "Session is invalid, id: %{public}d state: %{public}u",
2827             GetPersistentId(), GetSessionState());
2828         return WSError::WS_ERROR_INVALID_SESSION;
2829     }
2830     GetSessionProperty()->SetCompatibleModeEnableInPad(enable);
2831 
2832     if (!sessionStage_) {
2833         TLOGE(WmsLogTag::WMS_SCB, "sessionStage is null");
2834         return WSError::WS_ERROR_NULLPTR;
2835     }
2836     return sessionStage_->NotifyCompatibleModeEnableInPad(enable);
2837 }
2838 
SetAppSupportPhoneInPc(bool isSupportPhone)2839 WSError Session::SetAppSupportPhoneInPc(bool isSupportPhone)
2840 {
2841     TLOGI(WmsLogTag::WMS_SCB, "isSupportPhone: %{public}d", isSupportPhone);
2842     GetSessionProperty()->SetIsAppSupportPhoneInPc(isSupportPhone);
2843     return WSError::WS_OK;
2844 }
2845 
SetCompatibleWindowSizeInPc(int32_t portraitWidth,int32_t portraitHeight,int32_t landscapeWidth,int32_t landscapeHeight)2846 WSError Session::SetCompatibleWindowSizeInPc(int32_t portraitWidth, int32_t portraitHeight,
2847     int32_t landscapeWidth, int32_t landscapeHeight)
2848 {
2849     TLOGI(WmsLogTag::WMS_COMPAT, "compatible size: [%{public}d, %{public}d, %{public}d, %{public}d]",
2850         portraitWidth, portraitHeight, landscapeWidth, landscapeHeight);
2851     GetSessionProperty()->SetCompatibleWindowSizeInPc(portraitWidth, portraitHeight, landscapeWidth, landscapeHeight);
2852     return WSError::WS_OK;
2853 }
2854 
SetIsPcAppInPad(bool enable)2855 WSError Session::SetIsPcAppInPad(bool enable)
2856 {
2857     TLOGI(WmsLogTag::WMS_COMPAT, "SetIsPcAppInPad enable: %{public}d", enable);
2858     GetSessionProperty()->SetIsPcAppInPad(enable);
2859     return WSError::WS_OK;
2860 }
2861 
CompatibleFullScreenRecover()2862 WSError Session::CompatibleFullScreenRecover()
2863 {
2864     TLOGD(WmsLogTag::WMS_COMPAT, "recover compatible full screen windowId:%{public}d", GetPersistentId());
2865     if (!IsSessionValid()) {
2866         TLOGD(WmsLogTag::WMS_COMPAT, "Session is invalid, id: %{public}d state: %{public}u",
2867             GetPersistentId(), GetSessionState());
2868         return WSError::WS_ERROR_INVALID_SESSION;
2869     }
2870     if (sessionStage_ == nullptr) {
2871         TLOGE(WmsLogTag::WMS_COMPAT, "session stage is nullptr id: %{public}d state: %{public}u",
2872               GetPersistentId(), GetSessionState());
2873         return WSError::WS_ERROR_NULLPTR;
2874     }
2875     return sessionStage_->CompatibleFullScreenRecover();
2876 }
2877 
CompatibleFullScreenMinimize()2878 WSError Session::CompatibleFullScreenMinimize()
2879 {
2880     TLOGD(WmsLogTag::WMS_MAIN, "minimize compatible full screen windowId:%{public}d", GetPersistentId());
2881     if (!IsSessionValid()) {
2882         TLOGD(WmsLogTag::WMS_MAIN, "Session is invalid, id: %{public}d state: %{public}u",
2883             GetPersistentId(), GetSessionState());
2884         return WSError::WS_ERROR_INVALID_SESSION;
2885     }
2886     if (sessionStage_ == nullptr) {
2887         TLOGE(WmsLogTag::WMS_MAIN, "session stage is nullptr id: %{public}d state: %{public}u",
2888               GetPersistentId(), GetSessionState());
2889         return WSError::WS_ERROR_NULLPTR;
2890     }
2891     return sessionStage_->CompatibleFullScreenMinimize();
2892 }
2893 
CompatibleFullScreenClose()2894 WSError Session::CompatibleFullScreenClose()
2895 {
2896     TLOGD(WmsLogTag::WMS_COMPAT, "close compatible full screen windowId:%{public}d", GetPersistentId());
2897     if (!IsSessionValid()) {
2898         TLOGD(WmsLogTag::WMS_COMPAT, "Session is invalid, id: %{public}d state: %{public}u",
2899             GetPersistentId(), GetSessionState());
2900         return WSError::WS_ERROR_INVALID_SESSION;
2901     }
2902     if (sessionStage_ == nullptr) {
2903         TLOGE(WmsLogTag::WMS_COMPAT, "session stage is nullptr id: %{public}d state: %{public}u",
2904               GetPersistentId(), GetSessionState());
2905         return WSError::WS_ERROR_NULLPTR;
2906     }
2907     return sessionStage_->CompatibleFullScreenClose();
2908 }
2909 
PcAppInPadNormalClose()2910 WSError Session::PcAppInPadNormalClose()
2911 {
2912     TLOGD(WmsLogTag::WMS_COMPAT, "windowId:%{public}d", GetPersistentId());
2913     if (!IsSessionValid()) {
2914         TLOGD(WmsLogTag::WMS_COMPAT, "Session is invalid, id: %{public}d state: %{public}u",
2915             GetPersistentId(), GetSessionState());
2916         return WSError::WS_ERROR_INVALID_SESSION;
2917     }
2918     if (sessionStage_ == nullptr) {
2919         TLOGE(WmsLogTag::WMS_COMPAT, "session stage is nullptr id: %{public}d state: %{public}u",
2920               GetPersistentId(), GetSessionState());
2921         return WSError::WS_ERROR_NULLPTR;
2922     }
2923     return sessionStage_->PcAppInPadNormalClose();
2924 }
2925 
UpdateWindowMode(WindowMode mode)2926 WSError Session::UpdateWindowMode(WindowMode mode)
2927 {
2928     WLOGFD("Session update window mode, id: %{public}d, mode: %{public}d", GetPersistentId(),
2929         static_cast<int32_t>(mode));
2930     if (state_ == SessionState::STATE_END) {
2931         WLOGFI("session is already destroyed or property is nullptr! id: %{public}d state: %{public}u",
2932             GetPersistentId(), GetSessionState());
2933         return WSError::WS_ERROR_INVALID_SESSION;
2934     } else if (state_ == SessionState::STATE_DISCONNECT) {
2935         GetSessionProperty()->SetWindowMode(mode);
2936         GetSessionProperty()->SetIsNeedUpdateWindowMode(true);
2937         UpdateGestureBackEnabled();
2938     } else {
2939         GetSessionProperty()->SetWindowMode(mode);
2940         if (mode == WindowMode::WINDOW_MODE_SPLIT_PRIMARY || mode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY) {
2941             GetSessionProperty()->SetMaximizeMode(MaximizeMode::MODE_RECOVER);
2942         }
2943         UpdateGestureBackEnabled();
2944         UpdateGravityWhenUpdateWindowMode(mode);
2945         if (!sessionStage_) {
2946             return WSError::WS_ERROR_NULLPTR;
2947         }
2948         return sessionStage_->UpdateWindowMode(mode);
2949     }
2950     return WSError::WS_OK;
2951 }
2952 
UpdateGravityWhenUpdateWindowMode(WindowMode mode)2953 void Session::UpdateGravityWhenUpdateWindowMode(WindowMode mode)
2954 {
2955     auto surfaceNode = GetSurfaceNode();
2956     if ((systemConfig_.IsPcWindow() || systemConfig_.IsFreeMultiWindowMode()) && surfaceNode != nullptr) {
2957         if (mode == WindowMode::WINDOW_MODE_SPLIT_PRIMARY) {
2958             surfaceNode->SetFrameGravity(Gravity::LEFT);
2959         } else if (mode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY) {
2960             surfaceNode->SetFrameGravity(Gravity::RIGHT);
2961         } else if (mode == WindowMode::WINDOW_MODE_FLOATING || mode == WindowMode::WINDOW_MODE_FULLSCREEN) {
2962             surfaceNode->SetFrameGravity(Gravity::RESIZE);
2963         }
2964     }
2965 }
2966 
SetSystemSceneBlockingFocus(bool blocking)2967 WSError Session::SetSystemSceneBlockingFocus(bool blocking)
2968 {
2969     TLOGW(WmsLogTag::WMS_FOCUS, "Session set blocking focus, id: %{public}d, mode: %{public}d, Session is not system.",
2970         GetPersistentId(), blocking);
2971     return WSError::WS_ERROR_INVALID_SESSION;
2972 }
2973 
GetBlockingFocus() const2974 bool Session::GetBlockingFocus() const
2975 {
2976     return blockingFocus_;
2977 }
2978 
SetSessionProperty(const sptr<WindowSessionProperty> & property)2979 WSError Session::SetSessionProperty(const sptr<WindowSessionProperty>& property)
2980 {
2981     property_->CopyFrom(property);
2982 
2983     NotifySessionInfoChange();
2984     return WSError::WS_OK;
2985 }
2986 
SetSessionPropertyForReconnect(const sptr<WindowSessionProperty> & property)2987 WSError Session::SetSessionPropertyForReconnect(const sptr<WindowSessionProperty>& property)
2988 {
2989     property_->CopyFrom(property);
2990 
2991     auto hotAreasChangeCallback = [weakThis = wptr(this)]() {
2992         auto session = weakThis.promote();
2993         if (session == nullptr) {
2994             TLOGNE(WmsLogTag::WMS_EVENT, "session is nullptr");
2995             return;
2996         }
2997         session->NotifySessionInfoChange();
2998     };
2999     property_->SetSessionPropertyChangeCallback(hotAreasChangeCallback);
3000     NotifySessionInfoChange();
3001     return WSError::WS_OK;
3002 }
3003 
3004 /** @note @window.layout */
RectSizeCheckProcess(uint32_t curWidth,uint32_t curHeight,uint32_t minWidth,uint32_t minHeight,uint32_t maxFloatingWindowSize)3005 void Session::RectSizeCheckProcess(uint32_t curWidth, uint32_t curHeight, uint32_t minWidth,
3006     uint32_t minHeight, uint32_t maxFloatingWindowSize)
3007 {
3008     constexpr uint32_t marginOfError = 2; // The max vp bias for preventing giant logs.
3009     if (curWidth + marginOfError < minWidth || curWidth > maxFloatingWindowSize + marginOfError ||
3010         curHeight + marginOfError < minHeight || curHeight > maxFloatingWindowSize + marginOfError) {
3011         TLOGE(WmsLogTag::WMS_LAYOUT, "RectCheck err sessionID: %{public}d rect %{public}s",
3012             GetPersistentId(), GetSessionRect().ToString().c_str());
3013         std::ostringstream oss;
3014         oss << " RectCheck err size ";
3015         oss << " cur persistentId: " << GetPersistentId() << ",";
3016         oss << " windowType: " << static_cast<uint32_t>(GetWindowType()) << ",";
3017         oss << " windowName: " << GetSessionProperty()->GetWindowName() << ",";
3018         oss << " windowState: " << static_cast<uint32_t>(GetSessionProperty()->GetWindowState()) << ",";
3019         oss << " curWidth: " << curWidth << ",";
3020         oss << " curHeight: " << curHeight << ",";
3021         oss << " minWidth: " << minWidth << ",";
3022         oss << " minHeight: " << minHeight << ",";
3023         oss << " maxFloatingWindowSize: " << maxFloatingWindowSize << ",";
3024         oss << " sessionRect: " << GetSessionRect().ToString() << ";";
3025         WindowInfoReporter::GetInstance().ReportWindowException(
3026             static_cast<int32_t>(WindowDFXHelperType::WINDOW_RECT_CHECK), getpid(), oss.str());
3027     }
3028 }
3029 
3030 /** @note @window.layout */
RectCheckProcess()3031 void Session::RectCheckProcess()
3032 {
3033     if (!(IsSessionForeground() || isVisible_)) {
3034         return;
3035     }
3036     auto displayId = GetSessionProperty()->GetDisplayId();
3037     std::map<ScreenId, ScreenProperty> screensProperties =
3038         Rosen::ScreenSessionManagerClient::GetInstance().GetAllScreensProperties();
3039     if (screensProperties.find(displayId) == screensProperties.end()) {
3040         return;
3041     }
3042     auto screenProperty = screensProperties[displayId];
3043     float density = screenProperty.GetDensity();
3044     if (!NearZero(density) && !NearZero(GetSessionRect().height_)) {
3045         float curWidth = GetSessionRect().width_ / density;
3046         float curHeight = GetSessionRect().height_ / density;
3047         float ratio = GetAspectRatio();
3048         float actRatio = curWidth / curHeight;
3049         if ((ratio != 0) && !NearEqual(ratio, actRatio)) {
3050             TLOGE(WmsLogTag::WMS_LAYOUT, "RectCheck err ratio %{public}f != actRatio: %{public}f", ratio, actRatio);
3051             std::ostringstream oss;
3052             oss << " RectCheck err ratio ";
3053             oss << " cur persistentId: " << GetPersistentId() << ",";
3054             oss << " windowType: " << static_cast<uint32_t>(GetWindowType()) << ",";
3055             oss << " windowName: " << GetSessionProperty()->GetWindowName() << ",";
3056             oss << " windowState: " << static_cast<uint32_t>(GetSessionProperty()->GetWindowState()) << ",";
3057             oss << " curWidth: " << curWidth << ",";
3058             oss << " curHeight: " << curHeight << ",";
3059             oss << " setting ratio: " << ratio << ",";
3060             oss << " sessionRect: " << GetSessionRect().ToString() << ";";
3061             WindowInfoReporter::GetInstance().ReportWindowException(
3062                 static_cast<int32_t>(WindowDFXHelperType::WINDOW_RECT_CHECK), getpid(), oss.str());
3063         }
3064         RectCheck(curWidth, curHeight);
3065     }
3066 }
3067 
3068 /** @note @window.layout */
SetSessionRect(const WSRect & rect)3069 void Session::SetSessionRect(const WSRect& rect)
3070 {
3071     if (winRect_ == rect) {
3072         WLOGFW("id: %{public}d skip same rect", persistentId_);
3073         return;
3074     }
3075     winRect_ = rect;
3076     dirtyFlags_ |= static_cast<uint32_t>(SessionUIDirtyFlag::RECT);
3077     RectCheckProcess();
3078 }
3079 
3080 /** @note @window.layout */
GetSessionRect() const3081 WSRect Session::GetSessionRect() const
3082 {
3083     return winRect_;
3084 }
3085 
3086 /** @note @window.layout */
GetGlobalScaledRect(Rect & globalScaledRect)3087 WMError Session::GetGlobalScaledRect(Rect& globalScaledRect)
3088 {
3089     auto task = [weakThis = wptr(this), &globalScaledRect] {
3090         auto session = weakThis.promote();
3091         if (!session) {
3092             TLOGNE(WmsLogTag::WMS_LAYOUT, "session is null");
3093             return WMError::WM_ERROR_DESTROYED_OBJECT;
3094         }
3095         WSRect scaledRect = session->GetSessionGlobalRect();
3096         scaledRect.width_ *= session->scaleX_;
3097         scaledRect.height_ *= session->scaleY_;
3098         globalScaledRect = { scaledRect.posX_, scaledRect.posY_, scaledRect.width_, scaledRect.height_ };
3099         TLOGNI(WmsLogTag::WMS_LAYOUT, "Id:%{public}d globalScaledRect:%{public}s",
3100             session->GetPersistentId(), globalScaledRect.ToString().c_str());
3101         return WMError::WM_OK;
3102     };
3103     return PostSyncTask(task, __func__);
3104 }
3105 
3106 /** @note @window.layout */
GetSessionGlobalRect() const3107 WSRect Session::GetSessionGlobalRect() const
3108 {
3109     if (IsScbCoreEnabled()) {
3110         std::lock_guard<std::mutex> lock(globalRectMutex_);
3111         return globalRect_;
3112     }
3113     return winRect_;
3114 }
3115 
3116 /** @note @window.layout */
SetSessionGlobalRect(const WSRect & rect)3117 void Session::SetSessionGlobalRect(const WSRect& rect)
3118 {
3119     std::lock_guard<std::mutex> lock(globalRectMutex_);
3120     if (globalRect_ != rect) {
3121         dirtyFlags_ |= static_cast<uint32_t>(SessionUIDirtyFlag::GLOBAL_RECT);
3122     }
3123     globalRect_ = rect;
3124 }
3125 
3126 /** @note @window.layout */
GetLastLayoutRect() const3127 WSRect Session::GetLastLayoutRect() const
3128 {
3129     return lastLayoutRect_;
3130 }
3131 
3132 /** @note @window.layout */
GetLayoutRect() const3133 WSRect Session::GetLayoutRect() const
3134 {
3135     return layoutRect_;
3136 }
3137 
SetSessionRequestRect(const WSRect & rect)3138 void Session::SetSessionRequestRect(const WSRect& rect)
3139 {
3140     GetSessionProperty()->SetRequestRect(SessionHelper::TransferToRect(rect));
3141     WLOGFD("is: %{public}d, rect: [%{public}d, %{public}d, %{public}u, %{public}u]", persistentId_,
3142         rect.posX_, rect.posY_, rect.width_, rect.height_);
3143 }
3144 
GetSessionRequestRect() const3145 WSRect Session::GetSessionRequestRect() const
3146 {
3147     WSRect rect = SessionHelper::TransferToWSRect(GetSessionProperty()->GetRequestRect());
3148     WLOGFD("id: %{public}d, rect: %{public}s", persistentId_, rect.ToString().c_str());
3149     return rect;
3150 }
3151 
3152 /** @note @window.layout */
SetClientRect(const WSRect & rect)3153 void Session::SetClientRect(const WSRect& rect)
3154 {
3155     clientRect_ = rect;
3156     TLOGD(WmsLogTag::WMS_LAYOUT, "Id:%{public}d, update client rect:%{public}s",
3157         GetPersistentId(), rect.ToString().c_str());
3158 }
3159 
3160 /** @note @window.layout */
GetClientRect() const3161 WSRect Session::GetClientRect() const
3162 {
3163     return clientRect_;
3164 }
3165 
SetEnableRemoveStartingWindow(bool enableRemoveStartingWindow)3166 void Session::SetEnableRemoveStartingWindow(bool enableRemoveStartingWindow)
3167 {
3168     enableRemoveStartingWindow_ = enableRemoveStartingWindow;
3169 }
3170 
GetEnableRemoveStartingWindow() const3171 bool Session::GetEnableRemoveStartingWindow() const
3172 {
3173     return enableRemoveStartingWindow_;
3174 }
3175 
SetAppBufferReady(bool appBufferReady)3176 void Session::SetAppBufferReady(bool appBufferReady)
3177 {
3178     appBufferReady_ = appBufferReady;
3179 }
3180 
GetAppBufferReady() const3181 bool Session::GetAppBufferReady() const
3182 {
3183     return appBufferReady_;
3184 }
3185 
SetUseStartingWindowAboveLocked(bool useStartingWindowAboveLocked)3186 void Session::SetUseStartingWindowAboveLocked(bool useStartingWindowAboveLocked)
3187 {
3188     useStartingWindowAboveLocked_ = useStartingWindowAboveLocked;
3189 }
3190 
UseStartingWindowAboveLocked() const3191 bool Session::UseStartingWindowAboveLocked() const
3192 {
3193     return useStartingWindowAboveLocked_;
3194 }
3195 
SetRequestRectAnimationConfig(const RectAnimationConfig & rectAnimationConfig)3196 void Session::SetRequestRectAnimationConfig(const RectAnimationConfig& rectAnimationConfig)
3197 {
3198     auto property = GetSessionProperty();
3199     if (property == nullptr) {
3200         TLOGE(WmsLogTag::WMS_LAYOUT, "id: %{public}d property is nullptr", persistentId_);
3201         return;
3202     }
3203     property->SetRectAnimationConfig(rectAnimationConfig);
3204     TLOGI(WmsLogTag::WMS_LAYOUT, "id: %{public}d, animation duration: [%{public}u]", persistentId_,
3205         rectAnimationConfig.duration);
3206 }
3207 
GetRequestRectAnimationConfig() const3208 RectAnimationConfig Session::GetRequestRectAnimationConfig() const
3209 {
3210     RectAnimationConfig rectAnimationConfig;
3211     auto property = GetSessionProperty();
3212     if (property == nullptr) {
3213         TLOGE(WmsLogTag::WMS_LAYOUT, "id: %{public}d property is nullptr", persistentId_);
3214         return rectAnimationConfig;
3215     }
3216     rectAnimationConfig = property->GetRectAnimationConfig();
3217     TLOGI(WmsLogTag::WMS_LAYOUT, "id: %{public}d, animation duration: [%{public}u]", persistentId_,
3218         rectAnimationConfig.duration);
3219     return rectAnimationConfig;
3220 }
3221 
GetWindowType() const3222 WindowType Session::GetWindowType() const
3223 {
3224     return GetSessionProperty()->GetWindowType();
3225 }
3226 
GetWindowName() const3227 std::string Session::GetWindowName() const
3228 {
3229     if (GetSessionInfo().isSystem_) {
3230         return GetSessionInfo().abilityName_;
3231     } else {
3232         return GetSessionProperty()->GetWindowName();
3233     }
3234 }
3235 
SetSystemConfig(const SystemSessionConfig & systemConfig)3236 void Session::SetSystemConfig(const SystemSessionConfig& systemConfig)
3237 {
3238     systemConfig_ = systemConfig;
3239 }
3240 
GetSystemConfig() const3241 SystemSessionConfig Session::GetSystemConfig() const
3242 {
3243     return systemConfig_;
3244 }
3245 
SetSnapshotScale(const float snapshotScale)3246 void Session::SetSnapshotScale(const float snapshotScale)
3247 {
3248     snapshotScale_ = snapshotScale;
3249 }
3250 
ProcessBackEvent()3251 WSError Session::ProcessBackEvent()
3252 {
3253     if (!IsSessionValid()) {
3254         TLOGW(WmsLogTag::WMS_EVENT, "Session is invalid, id: %{public}d state: %{public}u",
3255             GetPersistentId(), GetSessionState());
3256         return WSError::WS_ERROR_INVALID_SESSION;
3257     }
3258     if (!sessionStage_) {
3259         TLOGE(WmsLogTag::WMS_EVENT, "session stage is nullptr");
3260         return WSError::WS_ERROR_NULLPTR;
3261     }
3262     if (auto remoteObject = sessionStage_->AsObject();
3263         remoteObject && !remoteObject->IsProxyObject()) {
3264         PostExportTask([sessionStage = sessionStage_] {
3265             sessionStage->HandleBackEvent();
3266         });
3267         return WSError::WS_OK;
3268     }
3269     return sessionStage_->HandleBackEvent();
3270 }
3271 
GeneratePersistentId(bool isExtension,int32_t persistentId)3272 void Session::GeneratePersistentId(bool isExtension, int32_t persistentId)
3273 {
3274     std::lock_guard lock(g_persistentIdSetMutex);
3275     if (persistentId != INVALID_SESSION_ID  && !g_persistentIdSet.count(persistentId)) {
3276         g_persistentIdSet.insert(persistentId);
3277         persistentId_ = persistentId;
3278         return;
3279     }
3280 
3281     if (g_persistentId == INVALID_SESSION_ID) {
3282         g_persistentId++; // init non system session id from 2
3283     }
3284 
3285     g_persistentId++;
3286     while (g_persistentIdSet.count(g_persistentId)) {
3287         g_persistentId++;
3288     }
3289     if (isExtension) {
3290         constexpr uint32_t pidLength = 18;
3291         constexpr uint32_t pidMask = (1 << pidLength) - 1;
3292         constexpr uint32_t persistentIdLength = 12;
3293         constexpr uint32_t persistentIdMask = (1 << persistentIdLength) - 1;
3294         uint32_t assembledPersistentId = ((static_cast<uint32_t>(getpid()) & pidMask) << persistentIdLength) |
3295             (static_cast<uint32_t>(g_persistentId.load()) & persistentIdMask);
3296         persistentId_ = assembledPersistentId | 0x40000000;
3297     } else {
3298         persistentId_ = static_cast<uint32_t>(g_persistentId.load()) & 0x3fffffff;
3299     }
3300     g_persistentIdSet.insert(g_persistentId);
3301     TLOGI(WmsLogTag::WMS_LIFE,
3302         "persistentId: %{public}d, persistentId_: %{public}d", persistentId, persistentId_);
3303 }
3304 
GetScenePersistence() const3305 sptr<ScenePersistence> Session::GetScenePersistence() const
3306 {
3307     return scenePersistence_;
3308 }
3309 
CheckEmptyKeyboardAvoidAreaIfNeeded() const3310 bool Session::CheckEmptyKeyboardAvoidAreaIfNeeded() const
3311 {
3312     bool isMainFloating =
3313         GetWindowMode() == WindowMode::WINDOW_MODE_FLOATING && WindowHelper::IsMainWindow(GetWindowType());
3314     bool isParentFloating = SessionHelper::IsNonSecureToUIExtension(GetWindowType()) &&
3315         GetParentSession() != nullptr &&
3316         GetParentSession()->GetWindowMode() == WindowMode::WINDOW_MODE_FLOATING;
3317     bool isMidScene = GetIsMidScene();
3318     bool isPhoneOrPadNotFreeMultiWindow =
3319         systemConfig_.IsPhoneWindow() || (systemConfig_.IsPadWindow() && !systemConfig_.IsFreeMultiWindowMode());
3320     return (isMainFloating || isParentFloating) && !isMidScene && isPhoneOrPadNotFreeMultiWindow;
3321 }
3322 
SetKeyboardStateChangeListener(const NotifyKeyboardStateChangeFunc & func)3323 void Session::SetKeyboardStateChangeListener(const NotifyKeyboardStateChangeFunc& func)
3324 {
3325     PostTask([weakThis = wptr(this), func, where = __func__]() {
3326         auto session = weakThis.promote();
3327         if (session == nullptr || func == nullptr) {
3328             TLOGNE(WmsLogTag::WMS_KEYBOARD, "%{public}s session or func is null", where);
3329             return;
3330         }
3331         session->keyboardStateChangeFunc_ = func;
3332         auto newState = session->GetSessionState(); // read and write state should in one thread
3333         if (newState == SessionState::STATE_ACTIVE) {
3334             newState = SessionState::STATE_FOREGROUND;
3335         } else if (newState == SessionState::STATE_INACTIVE) {
3336             newState = SessionState::STATE_BACKGROUND;
3337         } else if (newState == SessionState::STATE_DISCONNECT) {
3338             return;
3339         }
3340         session->NotifySessionStateChange(newState);
3341         TLOGNI(WmsLogTag::WMS_KEYBOARD, "%{public}s id: %{public}d, state_: %{public}d, newState: %{public}d",
3342             where, session->GetPersistentId(), session->GetSessionState(), newState);
3343     }, __func__);
3344 }
3345 
NotifyOccupiedAreaChangeInfo(sptr<OccupiedAreaChangeInfo> info,const std::shared_ptr<RSTransaction> & rsTransaction)3346 void Session::NotifyOccupiedAreaChangeInfo(sptr<OccupiedAreaChangeInfo> info,
3347                                            const std::shared_ptr<RSTransaction>& rsTransaction)
3348 {
3349     if (!sessionStage_) {
3350         TLOGD(WmsLogTag::WMS_KEYBOARD, "session stage is nullptr");
3351         return;
3352     }
3353     if (CheckEmptyKeyboardAvoidAreaIfNeeded()) {
3354         info = sptr<OccupiedAreaChangeInfo>::MakeSptr();
3355         TLOGD(WmsLogTag::WMS_KEYBOARD, "Occupied area needs to be empty when in floating mode");
3356     }
3357     sessionStage_->NotifyOccupiedAreaChangeInfo(info, rsTransaction);
3358 }
3359 
GetWindowMode() const3360 WindowMode Session::GetWindowMode() const
3361 {
3362     return GetSessionProperty()->GetWindowMode();
3363 }
3364 
UpdateMaximizeMode(bool isMaximize)3365 WSError Session::UpdateMaximizeMode(bool isMaximize)
3366 {
3367     WLOGFD("Session update maximize mode, isMaximize: %{public}d", isMaximize);
3368     if (!IsSessionValid()) {
3369         TLOGW(WmsLogTag::WMS_LAYOUT, "Session is invalid, id: %{public}d state: %{public}u",
3370             GetPersistentId(), GetSessionState());
3371         return WSError::WS_ERROR_INVALID_SESSION;
3372     }
3373     MaximizeMode mode = MaximizeMode::MODE_RECOVER;
3374     if (isMaximize) {
3375         mode = MaximizeMode::MODE_AVOID_SYSTEM_BAR;
3376     } else if (GetWindowMode() == WindowMode::WINDOW_MODE_FULLSCREEN) {
3377         mode = MaximizeMode::MODE_FULL_FILL;
3378     }
3379     GetSessionProperty()->SetMaximizeMode(mode);
3380     if (!sessionStage_) {
3381         TLOGE(WmsLogTag::WMS_MAIN, "sessionStage_ is null");
3382         return WSError::WS_ERROR_NULLPTR;
3383     }
3384     return sessionStage_->UpdateMaximizeMode(mode);
3385 }
3386 
3387 /** @note @window.hierarchy */
SetZOrder(uint32_t zOrder)3388 void Session::SetZOrder(uint32_t zOrder)
3389 {
3390     lastZOrder_ = zOrder_;
3391     zOrder_ = zOrder;
3392     NotifySessionInfoChange();
3393 }
3394 
3395 /** @note @window.hierarchy */
GetZOrder() const3396 uint32_t Session::GetZOrder() const
3397 {
3398     return zOrder_;
3399 }
3400 
3401 /** @note @window.hierarchy */
GetLastZOrder() const3402 uint32_t Session::GetLastZOrder() const
3403 {
3404     return lastZOrder_;
3405 }
3406 
SetUINodeId(uint32_t uiNodeId)3407 void Session::SetUINodeId(uint32_t uiNodeId)
3408 {
3409     if (uiNodeId_ != 0 && uiNodeId != 0 && !IsSystemSession() && SessionPermission::IsBetaVersion()) {
3410         int32_t eventRet = HiSysEventWrite(
3411             OHOS::HiviewDFX::HiSysEvent::Domain::WINDOW_MANAGER,
3412             "REPEAT_SET_UI_NODE_ID",
3413             OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC,
3414             "PID", getpid(),
3415             "UID", getuid());
3416         TLOGE(WmsLogTag::WMS_LIFE, " SetUINodeId: Repeat set UINodeId ret:%{public}d", eventRet);
3417         return;
3418     }
3419     uiNodeId_ = uiNodeId;
3420 }
3421 
GetUINodeId() const3422 uint32_t Session::GetUINodeId() const
3423 {
3424     return uiNodeId_;
3425 }
3426 
SetShowRecent(bool showRecent)3427 void Session::SetShowRecent(bool showRecent)
3428 {
3429     TLOGI(WmsLogTag::WMS_MAIN, "in recents: %{public}d, id: %{public}d", showRecent, persistentId_);
3430     bool isAttach = GetAttachState();
3431     if (!IsSupportDetectWindow(isAttach) ||
3432         !ShouldCreateDetectTaskInRecent(showRecent, showRecent_, isAttach)) {
3433         showRecent_ = showRecent;
3434         return;
3435     }
3436     showRecent_ = showRecent;
3437     WindowMode windowMode = GetWindowMode();
3438     if (!showRecent_ && ShouldCreateDetectTask(isAttach, windowMode)) {
3439         CreateWindowStateDetectTask(isAttach, windowMode);
3440     }
3441 }
3442 
GetShowRecent() const3443 bool Session::GetShowRecent() const
3444 {
3445     return showRecent_;
3446 }
3447 
GetAttachState() const3448 bool Session::GetAttachState() const
3449 {
3450     return isAttach_;
3451 }
3452 
GetDetectTaskInfo() const3453 DetectTaskInfo Session::GetDetectTaskInfo() const
3454 {
3455     std::shared_lock<std::shared_mutex> lock(detectTaskInfoMutex_);
3456     return detectTaskInfo_;
3457 }
3458 
SetDetectTaskInfo(const DetectTaskInfo & detectTaskInfo)3459 void Session::SetDetectTaskInfo(const DetectTaskInfo& detectTaskInfo)
3460 {
3461     std::unique_lock<std::shared_mutex> lock(detectTaskInfoMutex_);
3462     detectTaskInfo_ = detectTaskInfo;
3463 }
3464 
IsStateMatch(bool isAttach) const3465 bool Session::IsStateMatch(bool isAttach) const
3466 {
3467     return isAttach ? ATTACH_MAP.at(GetSessionState()) : DETACH_MAP.at(GetSessionState());
3468 }
3469 
IsSupportDetectWindow(bool isAttach)3470 bool Session::IsSupportDetectWindow(bool isAttach)
3471 {
3472     if (!systemConfig_.IsPcWindow() && !systemConfig_.IsPhoneWindow()) {
3473         TLOGD(WmsLogTag::WMS_LIFE, "device type not support, id:%{public}d", persistentId_);
3474         return false;
3475     }
3476     if (isScreenLockedCallback_ && isScreenLockedCallback_()) {
3477         TLOGD(WmsLogTag::WMS_LIFE, "screen locked, id:%{public}d", persistentId_);
3478         return false;
3479     }
3480     if (!SessionHelper::IsMainWindow(GetWindowType())) {
3481         TLOGD(WmsLogTag::WMS_LIFE, "only support main window, id:%{public}d", persistentId_);
3482         return false;
3483     }
3484     // Only detecting cold start scenarios on PC
3485     if (systemConfig_.IsPcWindow() && (!isAttach || state_ != SessionState::STATE_DISCONNECT)) {
3486         TLOGD(WmsLogTag::WMS_LIFE, "pc only support cold start, id:%{public}d", persistentId_);
3487         RemoveWindowDetectTask();
3488         return false;
3489     }
3490     return true;
3491 }
3492 
RemoveWindowDetectTask()3493 void Session::RemoveWindowDetectTask()
3494 {
3495     if (handler_) {
3496         handler_->RemoveTask(GetWindowDetectTaskName());
3497     }
3498 }
3499 
ShouldCreateDetectTask(bool isAttach,WindowMode windowMode) const3500 bool Session::ShouldCreateDetectTask(bool isAttach, WindowMode windowMode) const
3501 {
3502     // Create detect task directy without pre-exiting tasks.
3503     if (GetDetectTaskInfo().taskState == DetectTaskState::NO_TASK) {
3504         return true;
3505     }
3506     // If the taskState matches the attach detach state, it will be create detect task directly.
3507     if ((GetDetectTaskInfo().taskState == DetectTaskState::ATTACH_TASK && isAttach) ||
3508         (GetDetectTaskInfo().taskState == DetectTaskState::DETACH_TASK && !isAttach)) {
3509         return true;
3510     } else {
3511         // Do not create detect task if the windowMode changes.
3512         return GetDetectTaskInfo().taskWindowMode == windowMode;
3513     }
3514 }
3515 
ShouldCreateDetectTaskInRecent(bool newShowRecent,bool oldShowRecent,bool isAttach) const3516 bool Session::ShouldCreateDetectTaskInRecent(bool newShowRecent, bool oldShowRecent, bool isAttach) const
3517 {
3518     if (newShowRecent) {
3519         return false;
3520     }
3521     return oldShowRecent ? isAttach : false;
3522 }
3523 
RegisterIsScreenLockedCallback(const std::function<bool ()> & callback)3524 void Session::RegisterIsScreenLockedCallback(const std::function<bool()>& callback)
3525 {
3526     isScreenLockedCallback_ = callback;
3527 }
3528 
GetWindowDetectTaskName() const3529 std::string Session::GetWindowDetectTaskName() const
3530 {
3531     return "wms:WindowStateDetect" + std::to_string(persistentId_);
3532 }
3533 
RecordWindowStateAttachExceptionEvent(bool isAttached)3534 void Session::RecordWindowStateAttachExceptionEvent(bool isAttached)
3535 {
3536     int32_t ret = HiSysEventWrite(
3537         OHOS::HiviewDFX::HiSysEvent::Domain::WINDOW_MANAGER,
3538         "WINDOW_STATE_ERROR",
3539         OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
3540         "TYPE", "WINDOW_STATE_ATTACH_EXCEPTION",
3541         "PERSISTENT_ID", GetPersistentId(),
3542         "WINDOW_NAME", GetWindowName().c_str(),
3543         "ATTACH_STATE", isAttached,
3544         "SESSION_STATE", static_cast<uint32_t>(GetSessionState()));
3545     if (ret != 0) {
3546         TLOGE(WmsLogTag::WMS_LIFE, "write HiSysEvent error, ret: %{public}d", ret);
3547     }
3548 }
3549 
CreateWindowStateDetectTask(bool isAttach,WindowMode windowMode)3550 void Session::CreateWindowStateDetectTask(bool isAttach, WindowMode windowMode)
3551 {
3552     if (!handler_) {
3553         return;
3554     }
3555     std::string taskName = GetWindowDetectTaskName();
3556     RemoveWindowDetectTask();
3557     auto detectTask = [weakThis = wptr(this), isAttach]() {
3558         auto session = weakThis.promote();
3559         if (session == nullptr) {
3560             if (isAttach) {
3561                 TLOGNE(WmsLogTag::WMS_LIFE, "Window attach state and session"
3562                     "state mismatch, session is nullptr, attach:%{public}d", isAttach);
3563             }
3564             return;
3565         }
3566         // Skip state detect when screen locked.
3567         if (session->isScreenLockedCallback_ && !session->isScreenLockedCallback_()) {
3568             if (!session->IsStateMatch(isAttach)) {
3569                 TLOGNE(WmsLogTag::WMS_LIFE, "Window attach state and session state mismatch, "
3570                     "attach:%{public}d, sessioniState:%{public}d, persistenId:%{public}d, bundleName:%{public}s",
3571                     isAttach, static_cast<uint32_t>(session->GetSessionState()),
3572                     session->GetPersistentId(), session->GetSessionInfo().bundleName_.c_str());
3573                 session->RecordWindowStateAttachExceptionEvent(isAttach);
3574             }
3575         }
3576         DetectTaskInfo detectTaskInfo;
3577         session->SetDetectTaskInfo(detectTaskInfo);
3578     };
3579     handler_->PostTask(detectTask, taskName, STATE_DETECT_DELAYTIME);
3580     DetectTaskInfo detectTaskInfo;
3581     detectTaskInfo.taskWindowMode = windowMode;
3582     detectTaskInfo.taskState = isAttach ? DetectTaskState::ATTACH_TASK : DetectTaskState::DETACH_TASK;
3583     SetDetectTaskInfo(detectTaskInfo);
3584 }
3585 
SetBufferAvailable(bool bufferAvailable)3586 void Session::SetBufferAvailable(bool bufferAvailable)
3587 {
3588     TLOGD(WmsLogTag::DEFAULT, "Set:%{public}d", bufferAvailable);
3589     if (bufferAvailableChangeFunc_) {
3590         bufferAvailableChangeFunc_(bufferAvailable);
3591     }
3592     bufferAvailable_ = bufferAvailable;
3593 }
3594 
GetBufferAvailable() const3595 bool Session::GetBufferAvailable() const
3596 {
3597     return bufferAvailable_;
3598 }
3599 
SetNeedSnapshot(bool needSnapshot)3600 void Session::SetNeedSnapshot(bool needSnapshot)
3601 {
3602     needSnapshot_ = needSnapshot;
3603 }
3604 
SetExitSplitOnBackground(bool isExitSplitOnBackground)3605 void Session::SetExitSplitOnBackground(bool isExitSplitOnBackground)
3606 {
3607     TLOGW(WmsLogTag::WMS_MULTI_WINDOW, "id: %{public}d, SetExitSplitOnBackground not implement", persistentId_);
3608 }
3609 
IsExitSplitOnBackground() const3610 bool Session::IsExitSplitOnBackground() const
3611 {
3612     TLOGW(WmsLogTag::WMS_MULTI_WINDOW, "id: %{public}d, IsExitSplitOnBackground not implement", persistentId_);
3613     return false;
3614 }
3615 
SetFloatingScale(float floatingScale)3616 void Session::SetFloatingScale(float floatingScale)
3617 {
3618     floatingScale_ = floatingScale;
3619 }
3620 
GetFloatingScale() const3621 float Session::GetFloatingScale() const
3622 {
3623     return floatingScale_;
3624 }
3625 
SetScale(float scaleX,float scaleY,float pivotX,float pivotY)3626 void Session::SetScale(float scaleX, float scaleY, float pivotX, float pivotY)
3627 {
3628     scaleX_ = scaleX;
3629     scaleY_ = scaleY;
3630     pivotX_ = pivotX;
3631     pivotY_ = pivotY;
3632 }
3633 
SetClientScale(float scaleX,float scaleY,float pivotX,float pivotY)3634 void Session::SetClientScale(float scaleX, float scaleY, float pivotX, float pivotY)
3635 {
3636     TLOGD(WmsLogTag::WMS_LAYOUT, "Id:%{public}d, preScaleX:%{public}f, preScaleY:%{public}f, "
3637         "newScaleX:%{public}f, newScaleY:%{public}f", GetPersistentId(), clientScaleX_, clientScaleY_, scaleX, scaleY);
3638     clientScaleX_ = scaleX;
3639     clientScaleY_ = scaleY;
3640     clientPivotX_ = pivotX;
3641     clientPivotY_ = pivotY;
3642 }
3643 
GetScaleX() const3644 float Session::GetScaleX() const
3645 {
3646     return scaleX_;
3647 }
3648 
GetScaleY() const3649 float Session::GetScaleY() const
3650 {
3651     return scaleY_;
3652 }
3653 
GetPivotX() const3654 float Session::GetPivotX() const
3655 {
3656     return pivotX_;
3657 }
3658 
GetPivotY() const3659 float Session::GetPivotY() const
3660 {
3661     return pivotY_;
3662 }
3663 
SetSCBKeepKeyboard(bool scbKeepKeyboardFlag)3664 void Session::SetSCBKeepKeyboard(bool scbKeepKeyboardFlag)
3665 {
3666     scbKeepKeyboardFlag_ = scbKeepKeyboardFlag;
3667 }
3668 
GetSCBKeepKeyboardFlag() const3669 bool Session::GetSCBKeepKeyboardFlag() const
3670 {
3671     return scbKeepKeyboardFlag_;
3672 }
3673 
SetOffset(float x,float y)3674 void Session::SetOffset(float x, float y)
3675 {
3676     offsetX_ = x;
3677     offsetY_ = y;
3678     WSRect newRect {
3679         .posX_ = std::round(bounds_.posX_ + x),
3680         .posY_ = std::round(bounds_.posY_ + y),
3681         .width_ = std::round(bounds_.width_),
3682         .height_ = std::round(bounds_.height_),
3683     };
3684     if (newRect != winRect_) {
3685         UpdateRect(newRect, SizeChangeReason::UNDEFINED, "SetOffset");
3686     }
3687 }
3688 
GetOffsetX() const3689 float Session::GetOffsetX() const
3690 {
3691     return offsetX_;
3692 }
3693 
GetOffsetY() const3694 float Session::GetOffsetY() const
3695 {
3696     return offsetY_;
3697 }
3698 
SetBounds(const WSRectF & bounds)3699 void Session::SetBounds(const WSRectF& bounds)
3700 {
3701     bounds_ = bounds;
3702 }
3703 
GetBounds()3704 WSRectF Session::GetBounds()
3705 {
3706     return bounds_;
3707 }
3708 
SetRotation(Rotation rotation)3709 void Session::SetRotation(Rotation rotation)
3710 {
3711     rotation_ = rotation;
3712 }
3713 
GetRotation() const3714 Rotation Session::GetRotation() const
3715 {
3716     return rotation_;
3717 }
3718 
UpdateTitleInTargetPos(bool isShow,int32_t height)3719 WSError Session::UpdateTitleInTargetPos(bool isShow, int32_t height)
3720 {
3721     WLOGFD("Session update title in target position, id: %{public}d, isShow: %{public}d, height: %{public}d",
3722         GetPersistentId(), isShow, height);
3723     if (!IsSessionValid()) {
3724         TLOGW(WmsLogTag::WMS_MAIN, "Session is invalid, id: %{public}d state: %{public}u",
3725             GetPersistentId(), GetSessionState());
3726         return WSError::WS_ERROR_INVALID_SESSION;
3727     }
3728     if (!sessionStage_) {
3729         TLOGE(WmsLogTag::WMS_MAIN, "sessionStage_ is null");
3730         return WSError::WS_ERROR_NULLPTR;
3731     }
3732     return sessionStage_->UpdateTitleInTargetPos(isShow, height);
3733 }
3734 
SetSessionInfoLockedStateChangeListener(const NotifySessionInfoLockedStateChangeFunc & func)3735 void Session::SetSessionInfoLockedStateChangeListener(const NotifySessionInfoLockedStateChangeFunc& func)
3736 {
3737     sessionInfoLockedStateChangeFunc_ = func;
3738 }
3739 
NotifySessionInfoLockedStateChange(bool lockedState)3740 void Session::NotifySessionInfoLockedStateChange(bool lockedState)
3741 {
3742     WLOGFD("Notify sessioninfo lockedstate change: %{public}u", lockedState);
3743     if (sessionInfoLockedStateChangeFunc_) {
3744         sessionInfoLockedStateChangeFunc_(lockedState);
3745     }
3746 }
3747 
SwitchFreeMultiWindow(bool enable)3748 WSError Session::SwitchFreeMultiWindow(bool enable)
3749 {
3750     TLOGD(WmsLogTag::WMS_LAYOUT_PC, "windowId:%{public}d enable: %{public}d", GetPersistentId(), enable);
3751     systemConfig_.freeMultiWindowEnable_ = enable;
3752     if (!IsSessionValid()) {
3753         TLOGW(WmsLogTag::WMS_LAYOUT_PC, "Session is invalid, id: %{public}d state: %{public}u",
3754             GetPersistentId(), GetSessionState());
3755         return WSError::WS_ERROR_INVALID_SESSION;
3756     }
3757     if (!sessionStage_) {
3758         TLOGE(WmsLogTag::WMS_LAYOUT_PC, "sessionStage_ is null");
3759         return WSError::WS_ERROR_NULLPTR;
3760     }
3761     bool isUiExtSubWindow = WindowHelper::IsSubWindow(GetSessionProperty()->GetWindowType()) &&
3762         GetSessionProperty()->GetIsUIExtFirstSubWindow();
3763     if (WindowHelper::IsMainWindow(GetWindowType()) || isUiExtSubWindow) {
3764         return sessionStage_->SwitchFreeMultiWindow(enable);
3765     }
3766     return WSError::WS_OK;
3767 }
3768 
GetIsMidScene(bool & isMidScene)3769 WSError Session::GetIsMidScene(bool& isMidScene)
3770 {
3771     isMidScene = GetIsMidScene();
3772     return WSError::WS_OK;
3773 }
3774 
GetUIContentRemoteObj(sptr<IRemoteObject> & uiContentRemoteObj)3775 WSError Session::GetUIContentRemoteObj(sptr<IRemoteObject>& uiContentRemoteObj)
3776 {
3777     if (!IsSessionValid()) {
3778         TLOGE(WmsLogTag::DEFAULT, "session %{public}d is invalid. Failed to get UIContentRemoteObj", GetPersistentId());
3779         return WSError::WS_ERROR_INVALID_SESSION;
3780     }
3781     if (sessionStage_ == nullptr) {
3782         TLOGE(WmsLogTag::DEFAULT, "sessionStage_ is nullptr");
3783         return WSError::WS_ERROR_NULLPTR;
3784     }
3785     return sessionStage_->GetUIContentRemoteObj(uiContentRemoteObj);
3786 }
3787 
SetNotifySystemSessionPointerEventFunc(const NotifySystemSessionPointerEventFunc & func)3788 void Session::SetNotifySystemSessionPointerEventFunc(const NotifySystemSessionPointerEventFunc& func)
3789 {
3790     std::lock_guard<std::mutex> lock(pointerEventMutex_);
3791     systemSessionPointerEventFunc_ = func;
3792 }
3793 
SetNotifySystemSessionKeyEventFunc(const NotifySystemSessionKeyEventFunc & func)3794 void Session::SetNotifySystemSessionKeyEventFunc(const NotifySystemSessionKeyEventFunc& func)
3795 {
3796     std::unique_lock<std::shared_mutex> lock(keyEventMutex_);
3797     systemSessionKeyEventFunc_ = func;
3798 }
3799 
NotifySessionInfoChange()3800 void Session::NotifySessionInfoChange()
3801 {
3802     if (sessionInfoChangeNotifyManagerFunc_) {
3803         sessionInfoChangeNotifyManagerFunc_(GetPersistentId());
3804     } else {
3805         TLOGD(WmsLogTag::WMS_EVENT, "sessionInfoChangeNotifyManagerFunc is nullptr");
3806     }
3807 }
3808 
NeedCheckContextTransparent() const3809 bool Session::NeedCheckContextTransparent() const
3810 {
3811     return contextTransparentFunc_ != nullptr;
3812 }
3813 
SetContextTransparentFunc(const NotifyContextTransparentFunc & func)3814 void Session::SetContextTransparentFunc(const NotifyContextTransparentFunc& func)
3815 {
3816     contextTransparentFunc_ = func;
3817 }
3818 
NotifyContextTransparent()3819 void Session::NotifyContextTransparent()
3820 {
3821     if (contextTransparentFunc_) {
3822         int32_t eventRet = HiSysEventWrite(
3823             OHOS::HiviewDFX::HiSysEvent::Domain::WINDOW_MANAGER,
3824             "SESSION_IS_TRANSPARENT",
3825             OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
3826             "PERSISTENT_ID", GetPersistentId(),
3827             "BUNDLE_NAME", sessionInfo_.bundleName_);
3828         WLOGFE("Session context is transparent, persistentId:%{public}d, eventRet:%{public}d",
3829             GetPersistentId(), eventRet);
3830         contextTransparentFunc_();
3831     }
3832 }
3833 
IsSystemInput()3834 bool Session::IsSystemInput()
3835 {
3836     return sessionInfo_.sceneType_ == SceneType::INPUT_SCENE;
3837 }
3838 
SetIsMidScene(bool isMidScene)3839 void Session::SetIsMidScene(bool isMidScene)
3840 {
3841     PostTask([weakThis = wptr(this), isMidScene] {
3842         auto session = weakThis.promote();
3843         if (session == nullptr) {
3844             TLOGI(WmsLogTag::WMS_MULTI_WINDOW, "session is null");
3845             return;
3846         }
3847         if (session->isMidScene_ != isMidScene) {
3848             TLOGI(WmsLogTag::WMS_MULTI_WINDOW, "persistentId:%{public}d, isMidScene:%{public}d",
3849                 session->GetPersistentId(), isMidScene);
3850             session->isMidScene_ = isMidScene;
3851         }
3852     }, "SetIsMidScene");
3853 }
3854 
GetIsMidScene() const3855 bool Session::GetIsMidScene() const
3856 {
3857     return isMidScene_;
3858 }
3859 
SetTouchHotAreas(const std::vector<Rect> & touchHotAreas)3860 void Session::SetTouchHotAreas(const std::vector<Rect>& touchHotAreas)
3861 {
3862     std::vector<Rect> lastTouchHotAreas;
3863     GetSessionProperty()->GetTouchHotAreas(lastTouchHotAreas);
3864     if (touchHotAreas == lastTouchHotAreas) {
3865         return;
3866     }
3867 
3868     dirtyFlags_ |= static_cast<uint32_t>(SessionUIDirtyFlag::TOUCH_HOT_AREA);
3869     std::string rectStr;
3870     for (const auto& rect : touchHotAreas) {
3871         rectStr = rectStr + " " + rect.ToString();
3872     }
3873     TLOGI(WmsLogTag::WMS_EVENT, "id:%{public}d hot:%{public}s", GetPersistentId(), rectStr.c_str());
3874     GetSessionProperty()->SetTouchHotAreas(touchHotAreas);
3875 }
3876 
GetSnapshotPixelMap(const float oriScale,const float newScale)3877 std::shared_ptr<Media::PixelMap> Session::GetSnapshotPixelMap(const float oriScale, const float newScale)
3878 {
3879     TLOGI(WmsLogTag::WMS_MAIN, "id %{public}d", GetPersistentId());
3880     if (scenePersistence_ == nullptr) {
3881         return nullptr;
3882     }
3883     return scenePersistence_->IsSavingSnapshot() ? GetSnapshot() :
3884         scenePersistence_->GetLocalSnapshotPixelMap(oriScale, newScale);
3885 }
3886 
IsVisibleForeground() const3887 bool Session::IsVisibleForeground() const
3888 {
3889     return isVisible_ && IsSessionForeground();
3890 }
3891 
SetIsStarting(bool isStarting)3892 void Session::SetIsStarting(bool isStarting)
3893 {
3894     isStarting_ = isStarting;
3895 }
3896 
ResetDirtyFlags()3897 void Session::ResetDirtyFlags()
3898 {
3899     if (!isVisible_) {
3900         dirtyFlags_ &= static_cast<uint32_t>(SessionUIDirtyFlag::AVOID_AREA);
3901     } else {
3902         dirtyFlags_ = 0;
3903     }
3904 }
3905 
SetUIStateDirty(bool dirty)3906 void Session::SetUIStateDirty(bool dirty)
3907 {
3908     mainUIStateDirty_.store(dirty);
3909 }
3910 
GetUIStateDirty() const3911 bool Session::GetUIStateDirty() const
3912 {
3913     return mainUIStateDirty_.load();
3914 }
3915 
SetMainSessionUIStateDirty(bool dirty)3916 void Session::SetMainSessionUIStateDirty(bool dirty)
3917 {
3918     if (GetParentSession() && WindowHelper::IsMainWindow(GetParentSession()->GetWindowType())) {
3919         GetParentSession()->SetUIStateDirty(dirty);
3920     }
3921 }
3922 
IsScbCoreEnabled()3923 bool Session::IsScbCoreEnabled()
3924 {
3925     return isScbCoreEnabled_;
3926 }
3927 
SetScbCoreEnabled(bool enabled)3928 void Session::SetScbCoreEnabled(bool enabled)
3929 {
3930     TLOGI(WmsLogTag::WMS_PIPELINE, "%{public}d", enabled);
3931     isScbCoreEnabled_ = enabled;
3932 }
3933 
IsBackgroundUpdateRectNotifyEnabled()3934 bool Session::IsBackgroundUpdateRectNotifyEnabled()
3935 {
3936     return isBackgroundUpdateRectNotifyEnabled_;
3937 }
3938 
SetBackgroundUpdateRectNotifyEnabled(const bool enabled)3939 void Session::SetBackgroundUpdateRectNotifyEnabled(const bool enabled)
3940 {
3941     TLOGI(WmsLogTag::WMS_LAYOUT, "%{public}d", enabled);
3942     isBackgroundUpdateRectNotifyEnabled_ = enabled;
3943 }
3944 
IsVisible() const3945 bool Session::IsVisible() const
3946 {
3947     return isVisible_;
3948 }
3949 
GetEventHandler() const3950 std::shared_ptr<AppExecFwk::EventHandler> Session::GetEventHandler() const
3951 {
3952     return handler_;
3953 }
3954 
SetFreezeImmediately(float scale,bool isFreeze,float blur) const3955 std::shared_ptr<Media::PixelMap> Session::SetFreezeImmediately(float scale, bool isFreeze, float blur) const
3956 {
3957     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "GetSnapshotWithFreeze[%d][%s]",
3958         persistentId_, sessionInfo_.bundleName_.c_str());
3959     auto surfaceNode = GetSurfaceNode();
3960     if (!surfaceNode || !surfaceNode->IsBufferAvailable()) {
3961         return nullptr;
3962     }
3963     auto callback = std::make_shared<SurfaceCaptureFuture>();
3964     auto scaleValue = (!MathHelper::GreatNotEqual(scale, 0.0f) ||
3965         !MathHelper::GreatNotEqual(scale, std::numeric_limits<float>::min())) ? snapshotScale_ : scale;
3966     RSSurfaceCaptureConfig config = {
3967         .scaleX = scaleValue,
3968         .scaleY = scaleValue,
3969         .useDma = true,
3970         .useCurWindow = true,
3971     };
3972     bool ret = RSInterfaces::GetInstance().SetWindowFreezeImmediately(surfaceNode, isFreeze, callback, config, blur);
3973     if (!ret) {
3974         TLOGE(WmsLogTag::WMS_PATTERN, "failed");
3975         return nullptr;
3976     }
3977     if (isFreeze) {
3978         auto pixelMap = callback->GetResult(SNAPSHOT_TIMEOUT_MS);
3979         TLOGI(WmsLogTag::WMS_PATTERN, "get result: %{public}d, id: %{public}d", pixelMap != nullptr, persistentId_);
3980         return pixelMap;
3981     }
3982     return nullptr;
3983 }
3984 
IsPcWindow() const3985 bool Session::IsPcWindow() const
3986 {
3987     return systemConfig_.IsPcWindow();
3988 }
3989 
GetWindowUIInfoForWindowInfo() const3990 WindowUIInfo Session::GetWindowUIInfoForWindowInfo() const
3991 {
3992     WindowUIInfo windowUIInfo;
3993     windowUIInfo.visibilityState = GetVisibilityState();
3994     return windowUIInfo;
3995 }
3996 
GetWindowDisplayInfoForWindowInfo() const3997 WindowDisplayInfo Session::GetWindowDisplayInfoForWindowInfo() const
3998 {
3999     WindowDisplayInfo windowDisplayInfo;
4000     if (PcFoldScreenManager::GetInstance().IsHalfFoldedOnMainDisplay(GetSessionProperty()->GetDisplayId())) {
4001         WSRect sessionGlobalRect = GetSessionGlobalRect();
4002         windowDisplayInfo.displayId = TransformGlobalRectToRelativeRect(sessionGlobalRect);
4003     } else {
4004         windowDisplayInfo.displayId = GetSessionProperty()->GetDisplayId() ;
4005     }
4006     return windowDisplayInfo;
4007 }
4008 
GetWindowLayoutInfoForWindowInfo() const4009 WindowLayoutInfo Session::GetWindowLayoutInfoForWindowInfo() const
4010 {
4011     WindowLayoutInfo windowLayoutInfo;
4012     WSRect sessionGlobalRect = GetSessionGlobalRect();
4013     sessionGlobalRect.width_ *= GetScaleX();
4014     sessionGlobalRect.height_ *= GetScaleY();
4015     if (PcFoldScreenManager::GetInstance().IsHalfFoldedOnMainDisplay(GetSessionProperty()->GetDisplayId())) {
4016         TransformGlobalRectToRelativeRect(sessionGlobalRect);
4017     }
4018     windowLayoutInfo.rect = { sessionGlobalRect.posX_, sessionGlobalRect.posY_,
4019                               sessionGlobalRect.width_, sessionGlobalRect.height_};
4020     return windowLayoutInfo;
4021 }
4022 
GetWindowMetaInfoForWindowInfo() const4023 WindowMetaInfo Session::GetWindowMetaInfoForWindowInfo() const
4024 {
4025     WindowMetaInfo windowMetaInfo;
4026     windowMetaInfo.windowId = GetWindowId();
4027     if (GetSessionInfo().isSystem_) {
4028         windowMetaInfo.windowName = GetSessionInfo().abilityName_;
4029     } else {
4030         windowMetaInfo.windowName = GetSessionProperty()->GetWindowName();
4031     }
4032     windowMetaInfo.bundleName = GetSessionInfo().bundleName_;
4033     windowMetaInfo.abilityName = GetSessionInfo().abilityName_;
4034     windowMetaInfo.appIndex = GetSessionInfo().appIndex_;
4035     return windowMetaInfo;
4036 }
4037 
GetClientDisplayId() const4038 DisplayId Session::GetClientDisplayId() const
4039 {
4040     return clientDisplayId_;
4041 }
4042 
SetClientDisplayId(DisplayId displayid)4043 void Session::SetClientDisplayId(DisplayId displayid)
4044 {
4045     clientDisplayId_ = displayid;
4046 }
4047 } // namespace OHOS::Rosen