• 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 "ability_info.h"
19 #include "ability_start_setting.h"
20 #include "input_manager.h"
21 #include "ipc_skeleton.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 "anr_manager.h"
30 #include "session_helper.h"
31 #include "surface_capture_future.h"
32 #include "util.h"
33 #include "window_helper.h"
34 #include "window_manager_hilog.h"
35 #include "parameters.h"
36 #include <hisysevent.h>
37 #include "hitrace_meter.h"
38 #include "wm_common.h"
39 
40 namespace OHOS::Rosen {
41 namespace {
42 constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, HILOG_DOMAIN_WINDOW, "Session" };
43 std::atomic<int32_t> g_persistentId = INVALID_SESSION_ID;
44 std::set<int32_t> g_persistentIdSet;
45 constexpr float INNER_BORDER_VP = 5.0f;
46 constexpr float OUTSIDE_BORDER_VP = 4.0f;
47 constexpr float INNER_ANGLE_VP = 16.0f;
48 constexpr uint32_t MAX_LIFE_CYCLE_TASK_IN_QUEUE = 15;
49 constexpr int64_t LIFE_CYCLE_TASK_EXPIRED_TIME_MILLI = 200;
50 static bool g_enableForceUIFirst = system::GetParameter("window.forceUIFirst.enabled", "1") == "1";
51 } // namespace
52 
Session(const SessionInfo & info)53 Session::Session(const SessionInfo& info) : sessionInfo_(info)
54 {
55     property_ = new WindowSessionProperty();
56     property_->SetWindowType(static_cast<WindowType>(info.windowType_));
57     auto runner = AppExecFwk::EventRunner::GetMainEventRunner();
58     mainHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
59 
60     using type = std::underlying_type_t<MMI::WindowArea>;
61     for (type area = static_cast<type>(MMI::WindowArea::FOCUS_ON_TOP);
62         area <= static_cast<type>(MMI::WindowArea::FOCUS_ON_BOTTOM_RIGHT); ++area) {
63         auto ret = windowAreas_.insert(
64             std::pair<MMI::WindowArea, WSRectF>(static_cast<MMI::WindowArea>(area), WSRectF()));
65         if (!ret.second) {
66             WLOGFE("Failed to insert area:%{public}d", area);
67         }
68     }
69 }
70 
SetEventHandler(const std::shared_ptr<AppExecFwk::EventHandler> & handler,const std::shared_ptr<AppExecFwk::EventHandler> & exportHandler)71 void Session::SetEventHandler(const std::shared_ptr<AppExecFwk::EventHandler>& handler,
72     const std::shared_ptr<AppExecFwk::EventHandler>& exportHandler)
73 {
74     handler_ = handler;
75     exportHandler_ = exportHandler;
76 }
77 
PostTask(Task && task,const std::string & name,int64_t delayTime)78 void Session::PostTask(Task&& task, const std::string& name, int64_t delayTime)
79 {
80     if (!handler_ || handler_->GetEventRunner()->IsCurrentRunnerThread()) {
81         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "s:%s", name.c_str());
82         return task();
83     }
84     auto localTask = [task, name]() {
85         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "s:%s", name.c_str());
86         task();
87     };
88     handler_->PostTask(std::move(localTask), "wms:" + name, delayTime, AppExecFwk::EventQueue::Priority::IMMEDIATE);
89 }
90 
PostExportTask(Task && task,const std::string & name,int64_t delayTime)91 void Session::PostExportTask(Task&& task, const std::string& name, int64_t delayTime)
92 {
93     if (!exportHandler_ || exportHandler_->GetEventRunner()->IsCurrentRunnerThread()) {
94         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "s:%s", name.c_str());
95         return task();
96     }
97     auto localTask = [task, name]() {
98         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "s:%s", name.c_str());
99         task();
100     };
101     exportHandler_->PostTask(std::move(localTask), "wms:" + name, delayTime,
102         AppExecFwk::EventQueue::Priority::IMMEDIATE);
103 }
104 
GetPersistentId() const105 int32_t Session::GetPersistentId() const
106 {
107     return persistentId_;
108 }
109 
GetSurfaceNode() const110 std::shared_ptr<RSSurfaceNode> Session::GetSurfaceNode() const
111 {
112     return surfaceNode_;
113 }
114 
SetLeashWinSurfaceNode(std::shared_ptr<RSSurfaceNode> leashWinSurfaceNode)115 void Session::SetLeashWinSurfaceNode(std::shared_ptr<RSSurfaceNode> leashWinSurfaceNode)
116 {
117     if (g_enableForceUIFirst) {
118         auto rsTransaction = RSTransactionProxy::GetInstance();
119         if (rsTransaction) {
120             rsTransaction->Begin();
121         }
122         if (!leashWinSurfaceNode && leashWinSurfaceNode_) {
123             leashWinSurfaceNode_->SetForceUIFirst(false);
124         }
125         if (rsTransaction) {
126             rsTransaction->Commit();
127         }
128     }
129     leashWinSurfaceNode_ = leashWinSurfaceNode;
130 }
131 
GetLeashWinSurfaceNode() const132 std::shared_ptr<RSSurfaceNode> Session::GetLeashWinSurfaceNode() const
133 {
134     return leashWinSurfaceNode_;
135 }
136 
GetSnapshot() const137 std::shared_ptr<Media::PixelMap> Session::GetSnapshot() const
138 {
139     return snapshot_;
140 }
141 
SetSessionInfoAncoSceneState(int32_t ancoSceneState)142 void Session::SetSessionInfoAncoSceneState(int32_t ancoSceneState)
143 {
144     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
145     sessionInfo_.ancoSceneState = ancoSceneState;
146 }
147 
SetSessionInfoTime(const std::string & time)148 void Session::SetSessionInfoTime(const std::string& time)
149 {
150     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
151     sessionInfo_.time = time;
152 }
153 
SetSessionInfoAbilityInfo(const std::shared_ptr<AppExecFwk::AbilityInfo> & abilityInfo)154 void Session::SetSessionInfoAbilityInfo(const std::shared_ptr<AppExecFwk::AbilityInfo>& abilityInfo)
155 {
156     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
157     sessionInfo_.abilityInfo = abilityInfo;
158 }
159 
SetSessionInfoWant(const std::shared_ptr<AAFwk::Want> & want)160 void Session::SetSessionInfoWant(const std::shared_ptr<AAFwk::Want>& want)
161 {
162     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
163     sessionInfo_.want = want;
164 }
165 
SetSessionInfoPersistentId(int32_t persistentId)166 void Session::SetSessionInfoPersistentId(int32_t persistentId)
167 {
168     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
169     sessionInfo_.persistentId_ = persistentId;
170 }
171 
SetSessionInfoCallerPersistentId(int32_t callerPersistentId)172 void Session::SetSessionInfoCallerPersistentId(int32_t callerPersistentId)
173 {
174     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
175     sessionInfo_.callerPersistentId_ = callerPersistentId;
176 }
177 
SetSessionInfoContinueState(ContinueState state)178 void Session::SetSessionInfoContinueState(ContinueState state)
179 {
180     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
181     sessionInfo_.continueState = state;
182 }
183 
SetSessionInfoLockedState(bool lockedState)184 void Session::SetSessionInfoLockedState(bool lockedState)
185 {
186     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
187     sessionInfo_.lockedState = lockedState;
188     NotifySessionInfoLockedStateChange(lockedState);
189 }
190 
SetSessionInfoIsClearSession(bool isClearSession)191 void Session::SetSessionInfoIsClearSession(bool isClearSession)
192 {
193     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
194     sessionInfo_.isClearSession = isClearSession;
195 }
196 
SetSessionInfoAffinity(std::string affinity)197 void Session::SetSessionInfoAffinity(std::string affinity)
198 {
199     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
200     sessionInfo_.sessionAffinity = affinity;
201 }
202 
GetCloseAbilityWantAndClean(AAFwk::Want & outWant)203 void Session::GetCloseAbilityWantAndClean(AAFwk::Want& outWant)
204 {
205     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
206     if (sessionInfo_.closeAbilityWant != nullptr) {
207         outWant = *sessionInfo_.closeAbilityWant;
208         sessionInfo_.closeAbilityWant = nullptr;
209     }
210 }
211 
SetSessionInfo(const SessionInfo & info)212 void Session::SetSessionInfo(const SessionInfo& info)
213 {
214     std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
215     sessionInfo_.want = info.want;
216     sessionInfo_.callerToken_ = info.callerToken_;
217     sessionInfo_.requestCode = info.requestCode;
218     sessionInfo_.callerPersistentId_ = info.callerPersistentId_;
219     sessionInfo_.callingTokenId_ = info.callingTokenId_;
220     sessionInfo_.uiAbilityId_ = info.uiAbilityId_;
221     sessionInfo_.startSetting = info.startSetting;
222 }
223 
SetScreenId(uint64_t screenId)224 void Session::SetScreenId(uint64_t screenId)
225 {
226     sessionInfo_.screenId_ = screenId;
227 }
228 
GetSessionInfo() const229 const SessionInfo& Session::GetSessionInfo() const
230 {
231     return sessionInfo_;
232 }
233 
RegisterLifecycleListener(const std::shared_ptr<ILifecycleListener> & listener)234 bool Session::RegisterLifecycleListener(const std::shared_ptr<ILifecycleListener>& listener)
235 {
236     return RegisterListenerLocked(lifecycleListeners_, listener);
237 }
238 
UnregisterLifecycleListener(const std::shared_ptr<ILifecycleListener> & listener)239 bool Session::UnregisterLifecycleListener(const std::shared_ptr<ILifecycleListener>& listener)
240 {
241     return UnregisterListenerLocked(lifecycleListeners_, listener);
242 }
243 
244 template<typename T>
RegisterListenerLocked(std::vector<std::shared_ptr<T>> & holder,const std::shared_ptr<T> & listener)245 bool Session::RegisterListenerLocked(std::vector<std::shared_ptr<T>>& holder, const std::shared_ptr<T>& listener)
246 {
247     if (listener == nullptr) {
248         WLOGFE("listener is nullptr");
249         return false;
250     }
251     std::lock_guard<std::recursive_mutex> lock(lifecycleListenersMutex_);
252     if (std::find(holder.begin(), holder.end(), listener) != holder.end()) {
253         WLOGFE("Listener already registered");
254         return false;
255     }
256     holder.emplace_back(listener);
257     return true;
258 }
259 
260 template<typename T>
UnregisterListenerLocked(std::vector<std::shared_ptr<T>> & holder,const std::shared_ptr<T> & listener)261 bool Session::UnregisterListenerLocked(std::vector<std::shared_ptr<T>>& holder, const std::shared_ptr<T>& listener)
262 {
263     if (listener == nullptr) {
264         WLOGFE("listener could not be null");
265         return false;
266     }
267     std::lock_guard<std::recursive_mutex> lock(lifecycleListenersMutex_);
268     holder.erase(std::remove_if(holder.begin(), holder.end(),
269         [listener](std::shared_ptr<T> registeredListener) { return registeredListener == listener; }),
270         holder.end());
271     return true;
272 }
273 
NotifyActivation()274 void Session::NotifyActivation()
275 {
276     auto lifecycleListeners = GetListeners<ILifecycleListener>();
277     std::lock_guard<std::recursive_mutex> lock(lifecycleListenersMutex_);
278     for (auto& listener : lifecycleListeners) {
279         if (!listener.expired()) {
280             listener.lock()->OnActivation();
281         }
282     }
283 }
284 
NotifyConnect()285 void Session::NotifyConnect()
286 {
287     auto lifecycleListeners = GetListeners<ILifecycleListener>();
288     std::lock_guard<std::recursive_mutex> lock(lifecycleListenersMutex_);
289     for (auto& listener : lifecycleListeners) {
290         if (!listener.expired()) {
291             listener.lock()->OnConnect();
292         }
293     }
294 }
295 
NotifyForeground()296 void Session::NotifyForeground()
297 {
298     auto lifecycleListeners = GetListeners<ILifecycleListener>();
299     std::lock_guard<std::recursive_mutex> lock(lifecycleListenersMutex_);
300     for (auto& listener : lifecycleListeners) {
301         if (!listener.expired()) {
302             listener.lock()->OnForeground();
303         }
304     }
305 }
306 
NotifyBackground()307 void Session::NotifyBackground()
308 {
309     auto lifecycleListeners = GetListeners<ILifecycleListener>();
310     std::lock_guard<std::recursive_mutex> lock(lifecycleListenersMutex_);
311     for (auto& listener : lifecycleListeners) {
312         if (!listener.expired()) {
313             listener.lock()->OnBackground();
314         }
315     }
316 }
317 
NotifyDisconnect()318 void Session::NotifyDisconnect()
319 {
320     auto lifecycleListeners = GetListeners<ILifecycleListener>();
321     std::lock_guard<std::recursive_mutex> lock(lifecycleListenersMutex_);
322     for (auto& listener : lifecycleListeners) {
323         if (!listener.expired()) {
324             listener.lock()->OnDisconnect();
325         }
326     }
327 }
328 
NotifyExtensionDied()329 void Session::NotifyExtensionDied()
330 {
331     auto lifecycleListeners = GetListeners<ILifecycleListener>();
332     std::lock_guard<std::recursive_mutex> lock(lifecycleListenersMutex_);
333     for (auto& listener : lifecycleListeners) {
334         if (!listener.expired()) {
335             listener.lock()->OnExtensionDied();
336         }
337     }
338 }
339 
NotifyTransferAccessibilityEvent(const Accessibility::AccessibilityEventInfo & info,int64_t uiExtensionIdLevel)340 void Session::NotifyTransferAccessibilityEvent(const Accessibility::AccessibilityEventInfo& info,
341     int64_t uiExtensionIdLevel)
342 {
343     auto lifecycleListeners = GetListeners<ILifecycleListener>();
344     std::lock_guard<std::recursive_mutex> lock(lifecycleListenersMutex_);
345     for (auto& listener : lifecycleListeners) {
346         if (!listener.expired()) {
347             listener.lock()->OnAccessibilityEvent(info, uiExtensionIdLevel);
348         }
349     }
350 }
351 
GetAspectRatio() const352 float Session::GetAspectRatio() const
353 {
354     return aspectRatio_;
355 }
356 
SetAspectRatio(float ratio)357 WSError Session::SetAspectRatio(float ratio)
358 {
359     aspectRatio_ = ratio;
360     return WSError::WS_OK;
361 }
362 
GetSessionState() const363 SessionState Session::GetSessionState() const
364 {
365     return state_;
366 }
367 
SetSessionState(SessionState state)368 void Session::SetSessionState(SessionState state)
369 {
370     if (state < SessionState::STATE_DISCONNECT || state > SessionState::STATE_END) {
371         WLOGFD("Invalid session state: %{public}u", state);
372         return;
373     }
374     state_ = state;
375 }
376 
UpdateSessionState(SessionState state)377 void Session::UpdateSessionState(SessionState state)
378 {
379     state_ = state;
380     NotifySessionStateChange(state);
381 }
382 
UpdateSessionTouchable(bool touchable)383 void Session::UpdateSessionTouchable(bool touchable)
384 {
385     GetSessionProperty()->SetTouchable(touchable);
386     NotifySessionTouchableChange(touchable);
387 }
388 
SetFocusable(bool isFocusable)389 WSError Session::SetFocusable(bool isFocusable)
390 {
391     WLOGFI("SetFocusable id: %{public}d, focusable: %{public}d", GetPersistentId(), isFocusable);
392     GetSessionProperty()->SetFocusable(isFocusable);
393     if (isFocused_ && !GetFocusable()) {
394         NotifyRequestFocusStatusNotifyManager(false);
395     }
396     return WSError::WS_OK;
397 }
398 
GetFocusable() const399 bool Session::GetFocusable() const
400 {
401     auto property = GetSessionProperty();
402     if (property) {
403         return property->GetFocusable();
404     }
405     WLOGFD("property is null");
406     return true;
407 }
408 
SetNeedNotify(bool needNotify)409 void Session::SetNeedNotify(bool needNotify)
410 {
411     needNotify_ = needNotify;
412 }
413 
NeedNotify() const414 bool Session::NeedNotify() const
415 {
416     return needNotify_;
417 }
418 
SetTouchable(bool touchable)419 WSError Session::SetTouchable(bool touchable)
420 {
421     SetSystemTouchable(touchable);
422     if (!IsSessionValid()) {
423         return WSError::WS_ERROR_INVALID_SESSION;
424     }
425     UpdateSessionTouchable(touchable);
426     return WSError::WS_OK;
427 }
428 
GetTouchable() const429 bool Session::GetTouchable() const
430 {
431     return GetSessionProperty()->GetTouchable();
432 }
433 
SetSystemTouchable(bool touchable)434 void Session::SetSystemTouchable(bool touchable)
435 {
436     WLOGFD("SetSystemTouchable id: %{public}d, systemtouchable: %{public}d, propertytouchable: %{public}d",
437         GetPersistentId(), touchable, GetTouchable());
438     systemTouchable_ = touchable;
439     NotifySessionInfoChange();
440 }
441 
GetSystemTouchable() const442 bool Session::GetSystemTouchable() const
443 {
444     return systemTouchable_ && GetTouchable();
445 }
446 
SetVisible(bool isVisible)447 WSError Session::SetVisible(bool isVisible)
448 {
449     isRSVisible_ = isVisible;
450     return WSError::WS_OK;
451 }
452 
GetVisible() const453 bool Session::GetVisible() const
454 {
455     return isRSVisible_;
456 }
457 
SetVisibilityState(WindowVisibilityState state)458 WSError Session::SetVisibilityState(WindowVisibilityState state)
459 {
460     visibilityState_ = state;
461     return WSError::WS_OK;
462 }
463 
GetVisibilityState() const464 WindowVisibilityState Session::GetVisibilityState() const
465 {
466     return visibilityState_;
467 }
468 
SetDrawingContentState(bool isRSDrawing)469 WSError Session::SetDrawingContentState(bool isRSDrawing)
470 {
471     isRSDrawing_ = isRSDrawing;
472     return WSError::WS_OK;
473 }
474 
GetDrawingContentState() const475 bool Session::GetDrawingContentState() const
476 {
477     return isRSDrawing_;
478 }
479 
GetWindowId() const480 int32_t Session::GetWindowId() const
481 {
482     return GetPersistentId();
483 }
484 
SetCallingPid(int32_t id)485 void Session::SetCallingPid(int32_t id)
486 {
487     callingPid_ = id;
488 }
489 
SetCallingUid(int32_t id)490 void Session::SetCallingUid(int32_t id)
491 {
492     callingUid_ = id;
493 }
494 
GetCallingPid() const495 int32_t Session::GetCallingPid() const
496 {
497     return callingPid_;
498 }
499 
GetCallingUid() const500 int32_t Session::GetCallingUid() const
501 {
502     return callingUid_;
503 }
504 
SetAbilityToken(sptr<IRemoteObject> token)505 void Session::SetAbilityToken(sptr<IRemoteObject> token)
506 {
507     abilityToken_ = token;
508 }
509 
GetAbilityToken() const510 sptr<IRemoteObject> Session::GetAbilityToken() const
511 {
512     return abilityToken_;
513 }
514 
SetBrightness(float brightness)515 WSError Session::SetBrightness(float brightness)
516 {
517     auto property = GetSessionProperty();
518     if (!property) {
519         return WSError::WS_ERROR_NULLPTR;
520     }
521     property->SetBrightness(brightness);
522     return WSError::WS_OK;
523 }
524 
GetBrightness() const525 float Session::GetBrightness() const
526 {
527     auto property = GetSessionProperty();
528     if (!property) {
529         return UNDEFINED_BRIGHTNESS;
530     }
531     return property->GetBrightness();
532 }
533 
IsSessionValid() const534 bool Session::IsSessionValid() const
535 {
536     if (sessionInfo_.isSystem_) {
537         WLOGFD("session is system, id: %{public}d, name: %{public}s, state: %{public}u",
538             GetPersistentId(), sessionInfo_.bundleName_.c_str(), state_);
539         return false;
540     }
541     bool res = state_ > SessionState::STATE_DISCONNECT && state_ < SessionState::STATE_END;
542     if (!res) {
543         if (state_ == SessionState::STATE_DISCONNECT && sessionStage_) {
544             WLOGFI("session is already destroyed or not created! id: %{public}d state: %{public}u",
545                 GetPersistentId(), state_);
546         }
547     }
548     return res;
549 }
550 
IsActive() const551 bool Session::IsActive() const
552 {
553     return isActive_;
554 }
555 
IsSystemSession() const556 bool Session::IsSystemSession() const
557 {
558     return sessionInfo_.isSystem_;
559 }
560 
IsSystemActive() const561 bool Session::IsSystemActive() const
562 {
563     return isSystemActive_;
564 }
565 
SetSystemActive(bool systemActive)566 void Session::SetSystemActive(bool systemActive)
567 {
568     isSystemActive_ = systemActive;
569     NotifySessionInfoChange();
570 }
571 
IsTerminated() const572 bool Session::IsTerminated() const
573 {
574     return (GetSessionState() == SessionState::STATE_DISCONNECT || isTerminating);
575 }
576 
IsSessionForeground() const577 bool Session::IsSessionForeground() const
578 {
579     return state_ == SessionState::STATE_FOREGROUND || state_ == SessionState::STATE_ACTIVE;
580 }
581 
SetPointerStyle(MMI::WindowArea area)582 WSError Session::SetPointerStyle(MMI::WindowArea area)
583 {
584     WLOGFI("Information to be set: pid:%{public}d, windowId:%{public}d, MMI::WindowArea:%{public}s",
585         callingPid_, persistentId_, DumpPointerWindowArea(area));
586     MMI::InputManager::GetInstance()->SetWindowPointerStyle(area, callingPid_, persistentId_);
587     return WSError::WS_OK;
588 }
589 
UpdateTopBottomArea(const WSRectF & rect,MMI::WindowArea area)590 WSRectF Session::UpdateTopBottomArea(const WSRectF& rect, MMI::WindowArea area)
591 {
592     const float innerBorder = INNER_BORDER_VP * vpr_;
593     const float outsideBorder = OUTSIDE_BORDER_VP * vpr_;
594     const float innerAngle = INNER_ANGLE_VP * vpr_;
595     const float horizontalBorderLength = outsideBorder + innerAngle;
596     const float verticalBorderLength = outsideBorder + innerBorder;
597     const size_t innerAngleCount = 2;
598     WSRectF tbRect;
599     tbRect.posX_ = rect.posX_ + horizontalBorderLength;
600     tbRect.width_ = rect.width_ - horizontalBorderLength * innerAngleCount;
601     tbRect.height_ = verticalBorderLength;
602     if (area == MMI::WindowArea::FOCUS_ON_TOP) {
603         tbRect.posY_ = rect.posY_;
604     } else if (area == MMI::WindowArea::FOCUS_ON_BOTTOM) {
605         tbRect.posY_ = rect.posY_ + rect.height_ - verticalBorderLength;
606     } else {
607         return WSRectF();
608     }
609     return tbRect;
610 }
611 
UpdateLeftRightArea(const WSRectF & rect,MMI::WindowArea area)612 WSRectF Session::UpdateLeftRightArea(const WSRectF& rect, MMI::WindowArea area)
613 {
614     const float innerBorder = INNER_BORDER_VP * vpr_;
615     const float outsideBorder = OUTSIDE_BORDER_VP * vpr_;
616     const float innerAngle = INNER_ANGLE_VP * vpr_;
617     const float verticalBorderLength = outsideBorder + innerAngle;
618     const float horizontalBorderLength = outsideBorder + innerBorder;
619     const size_t innerAngleCount = 2;
620     WSRectF lrRect;
621     lrRect.posY_ = rect.posY_ + verticalBorderLength;
622     lrRect.width_ = horizontalBorderLength;
623     lrRect.height_ = rect.height_ - verticalBorderLength * innerAngleCount;
624     if (area == MMI::WindowArea::FOCUS_ON_LEFT) {
625         lrRect.posX_ = rect.posX_;
626     } else if (area == MMI::WindowArea::FOCUS_ON_RIGHT) {
627         lrRect.posX_ = rect.posX_ + rect.width_ - horizontalBorderLength;
628     } else {
629         return WSRectF();
630     }
631     return lrRect;
632 }
633 
UpdateInnerAngleArea(const WSRectF & rect,MMI::WindowArea area)634 WSRectF Session::UpdateInnerAngleArea(const WSRectF& rect, MMI::WindowArea area)
635 {
636     const float outsideBorder = OUTSIDE_BORDER_VP * vpr_;
637     const float innerAngle = INNER_ANGLE_VP * vpr_;
638     WSRectF iaRect;
639     iaRect.width_ = outsideBorder + innerAngle;
640     iaRect.height_ = outsideBorder + innerAngle;
641     if (area == MMI::WindowArea::FOCUS_ON_TOP_LEFT) {
642         iaRect.posX_ = rect.posX_;
643         iaRect.posY_ = rect.posY_;
644     } else if (area == MMI::WindowArea::FOCUS_ON_TOP_RIGHT) {
645         iaRect.posX_ = rect.posX_ + rect.width_ - iaRect.width_;
646         iaRect.posY_ = rect.posY_;
647     } else if (area == MMI::WindowArea::FOCUS_ON_BOTTOM_LEFT) {
648         iaRect.posX_ = rect.posX_;
649         iaRect.posY_ = rect.posY_ + rect.height_ - iaRect.height_;
650     } else if (area == MMI::WindowArea::FOCUS_ON_BOTTOM_RIGHT) {
651         iaRect.posX_ = rect.posX_ + rect.width_ - iaRect.width_;
652         iaRect.posY_ = rect.posY_ + rect.height_ - iaRect.height_;
653     } else {
654         return WSRectF();
655     }
656     return iaRect;
657 }
658 
UpdateHotRect(const WSRect & rect)659 WSRectF Session::UpdateHotRect(const WSRect& rect)
660 {
661     WSRectF newRect;
662     const float outsideBorder = OUTSIDE_BORDER_VP * vpr_;
663     const size_t outsideBorderCount = 2;
664     newRect.posX_ = rect.posX_ - outsideBorder;
665     newRect.posY_ = rect.posY_ - outsideBorder;
666     newRect.width_ = rect.width_ + outsideBorder * outsideBorderCount;
667     newRect.height_ = rect.height_ + outsideBorder * outsideBorderCount;
668     return newRect;
669 }
670 
UpdatePointerArea(const WSRect & rect)671 void Session::UpdatePointerArea(const WSRect& rect)
672 {
673     if (IsSystemSession()) {
674         return;
675     }
676     if (!((GetWindowType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW ||
677             (WindowHelper::IsSubWindow(GetWindowType()) && property_->IsDecorEnable())) &&
678         GetWindowMode() == WindowMode::WINDOW_MODE_FLOATING)) {
679         return;
680     }
681     if (preRect_ == rect) {
682         WLOGFD("The window area does not change");
683         return;
684     }
685     WSRectF hotRect = UpdateHotRect(rect);
686     for (const auto &[area, _] : windowAreas_) {
687         if (area == MMI::WindowArea::FOCUS_ON_TOP || area == MMI::WindowArea::FOCUS_ON_BOTTOM) {
688             windowAreas_[area] = UpdateTopBottomArea(hotRect, area);
689         } else if (area == MMI::WindowArea::FOCUS_ON_RIGHT || area == MMI::WindowArea::FOCUS_ON_LEFT) {
690             windowAreas_[area] = UpdateLeftRightArea(hotRect, area);
691         } else if (area == MMI::WindowArea::FOCUS_ON_TOP_LEFT || area == MMI::WindowArea::FOCUS_ON_TOP_RIGHT ||
692             area == MMI::WindowArea::FOCUS_ON_BOTTOM_LEFT || area == MMI::WindowArea::FOCUS_ON_BOTTOM_RIGHT) {
693             windowAreas_[area] = UpdateInnerAngleArea(hotRect, area);
694         }
695     }
696     preRect_ = rect;
697 }
698 
UpdateRect(const WSRect & rect,SizeChangeReason reason,const std::shared_ptr<RSTransaction> & rsTransaction)699 WSError Session::UpdateRect(const WSRect& rect, SizeChangeReason reason,
700     const std::shared_ptr<RSTransaction>& rsTransaction)
701 {
702     WLOGFD("session update rect: id: %{public}d, rect[%{public}d, %{public}d, %{public}u, %{public}u], "\
703         "reason:%{public}u", GetPersistentId(), rect.posX_, rect.posY_, rect.width_, rect.height_, reason);
704     if (!IsSessionValid()) {
705         winRect_ = rect;
706         return WSError::WS_ERROR_INVALID_SESSION;
707     }
708     winRect_ = rect;
709     if (sessionStage_ != nullptr) {
710         sessionStage_->UpdateRect(rect, reason, rsTransaction);
711     } else {
712         WLOGFE("sessionStage_ is nullptr");
713     }
714     UpdatePointerArea(winRect_);
715     if (GetWindowType() == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT) {
716         NotifyCallingSessionUpdateRect();
717     }
718     return WSError::WS_OK;
719 }
720 
UpdateDensity()721 WSError Session::UpdateDensity()
722 {
723     WLOGFI("session update density: id: %{public}d.", GetPersistentId());
724     if (!IsSessionValid()) {
725         return WSError::WS_ERROR_INVALID_SESSION;
726     }
727     if (sessionStage_ != nullptr) {
728         sessionStage_->UpdateDensity();
729     } else {
730         WLOGFE("Session::UpdateDensity sessionStage_ is nullptr");
731         return WSError::WS_ERROR_NULLPTR;
732     }
733     return WSError::WS_OK;
734 }
735 
NotifyCallingSessionUpdateRect()736 void Session::NotifyCallingSessionUpdateRect()
737 {
738     if (notifyCallingSessionUpdateRectFunc_) {
739         WLOGFI("Notify calling window that input method update rect");
740         notifyCallingSessionUpdateRectFunc_(persistentId_);
741     }
742 }
743 
Connect(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)744 WSError Session::Connect(const sptr<ISessionStage>& sessionStage, const sptr<IWindowEventChannel>& eventChannel,
745     const std::shared_ptr<RSSurfaceNode>& surfaceNode, SystemSessionConfig& systemConfig,
746     sptr<WindowSessionProperty> property, sptr<IRemoteObject> token, int32_t pid, int32_t uid)
747 {
748     WLOGFI("[WMSLife] Connect session, id: %{public}d, state: %{public}u, isTerminating: %{public}d", GetPersistentId(),
749         static_cast<uint32_t>(GetSessionState()), isTerminating);
750     if (GetSessionState() != SessionState::STATE_DISCONNECT && !isTerminating) {
751         WLOGFE("[WMSLife]state is not disconnect state:%{public}u id:%{public}u!",
752             GetSessionState(), GetPersistentId());
753         return WSError::WS_ERROR_INVALID_SESSION;
754     }
755     if (sessionStage == nullptr || eventChannel == nullptr) {
756         WLOGFE("[WMSLife]session stage or eventChannel is nullptr");
757         return WSError::WS_ERROR_NULLPTR;
758     }
759     sessionStage_ = sessionStage;
760     windowEventChannel_ = eventChannel;
761     surfaceNode_ = surfaceNode;
762     abilityToken_ = token;
763     systemConfig = systemConfig_;
764     if (property_ && property_->GetIsNeedUpdateWindowMode() && property) {
765         property->SetIsNeedUpdateWindowMode(true);
766         property->SetWindowMode(property_->GetWindowMode());
767     }
768     if (SessionHelper::IsMainWindow(GetWindowType()) &&
769         GetSessionInfo().screenId_ != SCREEN_ID_INVALID && property) {
770         property->SetDisplayId(GetSessionInfo().screenId_);
771     }
772     SetSessionProperty(property);
773     if (property) {
774         property->SetPersistentId(GetPersistentId());
775     }
776     callingPid_ = pid;
777     callingUid_ = uid;
778 
779     UpdateSessionState(SessionState::STATE_CONNECT);
780     // once update rect before connect, update again when connect
781     if (WindowHelper::IsUIExtensionWindow(GetWindowType())) {
782         UpdateRect(winRect_, SizeChangeReason::UNDEFINED);
783     } else {
784         NotifyClientToUpdateRect(nullptr);
785     }
786     NotifyConnect();
787     callingBundleName_ = DelayedSingleton<ANRManager>::GetInstance()->GetBundleName(callingPid_, callingUid_);
788     DelayedSingleton<ANRManager>::GetInstance()->SetApplicationInfo(persistentId_, callingPid_, callingBundleName_);
789     return WSError::WS_OK;
790 }
791 
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)792 WSError Session::Reconnect(const sptr<ISessionStage>& sessionStage, const sptr<IWindowEventChannel>& eventChannel,
793     const std::shared_ptr<RSSurfaceNode>& surfaceNode, sptr<WindowSessionProperty> property, sptr<IRemoteObject> token,
794     int32_t pid, int32_t uid)
795 {
796     if (property == nullptr) {
797         WLOGFE("[WMSRecover] property is nullptr");
798         return WSError::WS_ERROR_NULLPTR;
799     }
800     WLOGFI("[WMSRecover] Reconnect session with: persistentId=%{public}d, windowState=%{public}u",
801         property->GetPersistentId(), static_cast<uint32_t>(property->GetWindowState()));
802     if (sessionStage == nullptr || eventChannel == nullptr) {
803         WLOGFE("[WMSRecover] session stage or eventChannel is nullptr");
804         return WSError::WS_ERROR_NULLPTR;
805     }
806     sessionStage_ = sessionStage;
807     surfaceNode_ = surfaceNode;
808     windowEventChannel_ = eventChannel;
809     abilityToken_ = token;
810     SetSessionProperty(property);
811     persistentId_ = property->GetPersistentId();
812     callingPid_ = pid;
813     callingUid_ = uid;
814     WindowState windowState = property->GetWindowState();
815     auto type = property->GetWindowType();
816     if (windowState == WindowState::STATE_SHOWN || SessionHelper::IsSubWindow(type)) {
817         isActive_ = true;
818         if (SessionHelper::IsMainWindow(type) || type == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT) {
819             UpdateSessionState(SessionState::STATE_ACTIVE);
820         } else {
821             UpdateSessionState(SessionState::STATE_FOREGROUND);
822         }
823     } else {
824         isActive_ = false;
825         UpdateSessionState(SessionState::STATE_BACKGROUND);
826     }
827     bufferAvailable_ = true;
828     return WSError::WS_OK;
829 }
830 
Foreground(sptr<WindowSessionProperty> property)831 WSError Session::Foreground(sptr<WindowSessionProperty> property)
832 {
833     HandleDialogForeground();
834     SessionState state = GetSessionState();
835     WLOGFI("[WMSLife] Foreground session, id: %{public}d, state: %{public}" PRIu32"", GetPersistentId(),
836         static_cast<uint32_t>(state));
837     if (state != SessionState::STATE_CONNECT && state != SessionState::STATE_BACKGROUND &&
838         state != SessionState::STATE_INACTIVE) {
839         WLOGFE("[WMSLife] Foreground state invalid! state:%{public}u", state);
840         return WSError::WS_ERROR_INVALID_SESSION;
841     }
842 
843     UpdateSessionState(SessionState::STATE_FOREGROUND);
844     if (!isActive_) {
845         SetActive(true);
846     }
847 
848     if (GetWindowType() == WindowType::WINDOW_TYPE_DIALOG && GetParentSession() &&
849         !GetParentSession()->IsSessionForeground()) {
850         WLOGFD("[WMSDialog] parent is not foreground");
851         SetSessionState(SessionState::STATE_BACKGROUND);
852     }
853 
854     if (GetWindowType() == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT) {
855         NotifyCallingSessionForeground();
856     }
857     NotifyForeground();
858     return WSError::WS_OK;
859 }
860 
NotifyCallingSessionForeground()861 void Session::NotifyCallingSessionForeground()
862 {
863     if (notifyCallingSessionForegroundFunc_) {
864         WLOGFI("[WMSInput] Notify calling window that input method shown");
865         notifyCallingSessionForegroundFunc_(persistentId_);
866     }
867 }
868 
HandleDialogBackground()869 void Session::HandleDialogBackground()
870 {
871     const auto& type = GetWindowType();
872     if (type < WindowType::APP_MAIN_WINDOW_BASE || type >= WindowType::APP_MAIN_WINDOW_END) {
873         WLOGFD("[WMSDialog] Current session is not main window, id: %{public}d, type: %{public}d",
874             GetPersistentId(), type);
875         return;
876     }
877 
878     std::vector<sptr<Session>> dialogVec;
879     {
880         std::unique_lock<std::mutex> lock(dialogVecMutex_);
881         dialogVec = dialogVec_;
882     }
883     for (const auto& dialog : dialogVec) {
884         if (dialog == nullptr) {
885             continue;
886         }
887         WLOGFI("[WMSDialog] Background dialog, id: %{public}d, dialogId: %{public}d",
888             GetPersistentId(), dialog->GetPersistentId());
889         dialog->SetSessionState(SessionState::STATE_BACKGROUND);
890         if (!dialog->sessionStage_) {
891             WLOGD("[WMSDialog] dialog session stage is nullptr");
892             return;
893         }
894         dialog->sessionStage_->NotifyDialogStateChange(false);
895     }
896 }
897 
HandleDialogForeground()898 void Session::HandleDialogForeground()
899 {
900     const auto& type = GetWindowType();
901     if (type < WindowType::APP_MAIN_WINDOW_BASE || type >= WindowType::APP_MAIN_WINDOW_END) {
902         WLOGFD("[WMSDialog] Current session is not main window, id: %{public}d, type: %{public}d",
903             GetPersistentId(), type);
904         return;
905     }
906 
907     std::vector<sptr<Session>> dialogVec;
908     {
909         std::unique_lock<std::mutex> lock(dialogVecMutex_);
910         dialogVec = dialogVec_;
911     }
912     for (const auto& dialog : dialogVec) {
913         if (dialog == nullptr) {
914             continue;
915         }
916         WLOGFI("[WMSDialog] Foreground dialog, id: %{public}d, dialogId: %{public}d",
917             GetPersistentId(), dialog->GetPersistentId());
918         dialog->SetSessionState(SessionState::STATE_ACTIVE);
919         if (!dialog->sessionStage_) {
920             WLOGD("[WMSDialog] dialog session stage is nullptr");
921             return;
922         }
923         dialog->sessionStage_->NotifyDialogStateChange(true);
924     }
925 }
926 
Background()927 WSError Session::Background()
928 {
929     HandleDialogBackground();
930     SessionState state = GetSessionState();
931     WLOGFI("[WMSLife] Background session, id: %{public}d, state: %{public}" PRIu32"", GetPersistentId(),
932         static_cast<uint32_t>(state));
933     if ((state == SessionState::STATE_ACTIVE || state == SessionState::STATE_FOREGROUND) &&
934         GetWindowType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW) {
935         UpdateSessionState(SessionState::STATE_INACTIVE);
936         state = SessionState::STATE_INACTIVE;
937         isActive_ = false;
938     }
939     if (state != SessionState::STATE_INACTIVE) {
940         WLOGFW("[WMSLife] Background state invalid! state:%{public}u", state);
941         return WSError::WS_ERROR_INVALID_SESSION;
942     }
943     UpdateSessionState(SessionState::STATE_BACKGROUND);
944     if (GetWindowType() == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT) {
945         NotifyCallingSessionBackground();
946         if (property_) {
947             WLOGFI("[WMSInput] When the soft keyboard is hidden, set the callingWindowId to 0.");
948             property_->SetCallingWindow(INVALID_WINDOW_ID);
949         }
950     }
951     NotifyBackground();
952     DelayedSingleton<ANRManager>::GetInstance()->OnBackground(persistentId_);
953     return WSError::WS_OK;
954 }
955 
NotifyCallingSessionBackground()956 void Session::NotifyCallingSessionBackground()
957 {
958     if (notifyCallingSessionBackgroundFunc_) {
959         WLOGFI("[WMSInput] Notify calling window that input method hide");
960         notifyCallingSessionBackgroundFunc_();
961     }
962 }
963 
Disconnect(bool isFromClient)964 WSError Session::Disconnect(bool isFromClient)
965 {
966     auto state = GetSessionState();
967     WLOGFI("[WMSLife] Disconnect session, id: %{public}d, state: %{public}u", GetPersistentId(), state);
968     isActive_ = false;
969     if (mainHandler_) {
970         mainHandler_->PostTask([surfaceNode = std::move(surfaceNode_)]() mutable {
971             surfaceNode.reset();
972         });
973     }
974     UpdateSessionState(SessionState::STATE_BACKGROUND);
975     UpdateSessionState(SessionState::STATE_DISCONNECT);
976     NotifyDisconnect();
977     DelayedSingleton<ANRManager>::GetInstance()->OnSessionLost(persistentId_);
978     return WSError::WS_OK;
979 }
980 
Show(sptr<WindowSessionProperty> property)981 WSError Session::Show(sptr<WindowSessionProperty> property)
982 {
983     WLOGFD("[WMSLife] Show session, id: %{public}d", GetPersistentId());
984     return WSError::WS_OK;
985 }
986 
Hide()987 WSError Session::Hide()
988 {
989     WLOGFD("[WMSLife] Hide session, id: %{public}d", GetPersistentId());
990     return WSError::WS_OK;
991 }
992 
SetActive(bool active)993 WSError Session::SetActive(bool active)
994 {
995     SessionState state = GetSessionState();
996     WLOGFI("[WMSLife] isActive: %{public}d, id: %{public}d, state: %{public}" PRIu32"",
997         active, GetPersistentId(), static_cast<uint32_t>(state));
998     if (!IsSessionValid()) {
999         return WSError::WS_ERROR_INVALID_SESSION;
1000     }
1001     if (active == isActive_) {
1002         WLOGFD("[WMSLife] Session active do not change: [%{public}d]", active);
1003         return WSError::WS_DO_NOTHING;
1004     }
1005     if (active && GetSessionState() == SessionState::STATE_FOREGROUND) {
1006         sessionStage_->SetActive(true);
1007         UpdateSessionState(SessionState::STATE_ACTIVE);
1008         isActive_ = active;
1009     }
1010     if (!active && GetSessionState() == SessionState::STATE_ACTIVE) {
1011         sessionStage_->SetActive(false);
1012         UpdateSessionState(SessionState::STATE_INACTIVE);
1013         isActive_ = active;
1014     }
1015     return WSError::WS_OK;
1016 }
1017 
NotifyForegroundInteractiveStatus(bool interactive)1018 void Session::NotifyForegroundInteractiveStatus(bool interactive)
1019 {
1020     SetForegroundInteractiveStatus(interactive);
1021     if (!IsSessionValid() || !sessionStage_) {
1022         return;
1023     }
1024     const auto& state = GetSessionState();
1025     if (WindowHelper::IsMainWindow(GetWindowType()) &&
1026         (isVisible_ || state == SessionState::STATE_ACTIVE || state == SessionState::STATE_FOREGROUND)) {
1027         WLOGFI("NotifyForegroundInteractiveStatus %{public}d", interactive);
1028         sessionStage_->NotifyForegroundInteractiveStatus(interactive);
1029     }
1030 }
1031 
SetForegroundInteractiveStatus(bool interactive)1032 void Session::SetForegroundInteractiveStatus(bool interactive)
1033 {
1034     foregroundInteractiveStatus_.store(interactive);
1035     NotifySessionInfoChange();
1036 }
1037 
GetForegroundInteractiveStatus() const1038 bool Session::GetForegroundInteractiveStatus() const
1039 {
1040     return foregroundInteractiveStatus_.load();
1041 }
1042 
SetPendingSessionActivationEventListener(const NotifyPendingSessionActivationFunc & func)1043 void Session::SetPendingSessionActivationEventListener(const NotifyPendingSessionActivationFunc& func)
1044 {
1045     pendingSessionActivationFunc_ = func;
1046 }
1047 
SetBackPressedListenser(const NotifyBackPressedFunc & func)1048 void Session::SetBackPressedListenser(const NotifyBackPressedFunc& func)
1049 {
1050     backPressedFunc_ = func;
1051 }
1052 
SetTerminateSessionListener(const NotifyTerminateSessionFunc & func)1053 void Session::SetTerminateSessionListener(const NotifyTerminateSessionFunc& func)
1054 {
1055     terminateSessionFunc_ = func;
1056 }
1057 
RemoveLifeCycleTask(const LifeCycleTaskType & taskType)1058 void Session::RemoveLifeCycleTask(const LifeCycleTaskType &taskType)
1059 {
1060     std::lock_guard<std::mutex> lock(lifeCycleTaskQueueMutex_);
1061     if (lifeCycleTaskQueue_.empty()) {
1062         return;
1063     }
1064     sptr<SessionLifeCycleTask> currLifeCycleTask = lifeCycleTaskQueue_.front();
1065     if (currLifeCycleTask->type != taskType) {
1066         WLOGFW("[WMSLife] current removed task type does not match. Current running taskName=%{public}s, "
1067                "PersistentId=%{public}d",
1068             currLifeCycleTask->name.c_str(), persistentId_);
1069         return;
1070     }
1071     WLOGFI("[WMSLife] Removed lifeCyleTask %{public}s. PersistentId=%{public}d",
1072         currLifeCycleTask->name.c_str(), persistentId_);
1073     lifeCycleTaskQueue_.pop_front();
1074     if (lifeCycleTaskQueue_.empty()) {
1075         return;
1076     }
1077     StartLifeCycleTask(lifeCycleTaskQueue_.front());
1078 }
1079 
PostLifeCycleTask(Task && task,const std::string & name,const LifeCycleTaskType & taskType)1080 void Session::PostLifeCycleTask(Task&& task, const std::string& name, const LifeCycleTaskType& taskType)
1081 {
1082     std::lock_guard<std::mutex> lock(lifeCycleTaskQueueMutex_);
1083     if (lifeCycleTaskQueue_.size() == MAX_LIFE_CYCLE_TASK_IN_QUEUE) {
1084         WLOGFE("[WMSLife] Failed to add task %{public}s to life cycle queue", name.c_str());
1085         return;
1086     }
1087     sptr<SessionLifeCycleTask> lifeCycleTask = new SessionLifeCycleTask(std::move(task), name, taskType);
1088     lifeCycleTaskQueue_.push_back(lifeCycleTask);
1089     WLOGFI("[WMSLife] Add task %{public}s to life cycle queue, PersistentId=%{public}d", name.c_str(), persistentId_);
1090     if (lifeCycleTaskQueue_.size() == 1) {
1091         StartLifeCycleTask(lifeCycleTask);
1092         return;
1093     }
1094 
1095     // remove current running task if expired
1096     sptr<SessionLifeCycleTask> currLifeCycleTask = lifeCycleTaskQueue_.front();
1097     std::chrono::steady_clock::time_point currentTime = std::chrono::steady_clock::now();
1098     bool isCurrentTaskExpired =
1099         std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - currLifeCycleTask->startTime).count() >
1100         LIFE_CYCLE_TASK_EXPIRED_TIME_MILLI;
1101     if (isCurrentTaskExpired) {
1102         WLOGFE(
1103             "[WMSLife] Remove expired LifeCycleTask %{public}s. PersistentId=%{public}d", name.c_str(), persistentId_);
1104         lifeCycleTaskQueue_.pop_front();
1105         StartLifeCycleTask(lifeCycleTaskQueue_.front());
1106     }
1107 }
1108 
StartLifeCycleTask(sptr<SessionLifeCycleTask> lifeCycleTask)1109 void Session::StartLifeCycleTask(sptr<SessionLifeCycleTask> lifeCycleTask)
1110 {
1111     WLOGFI("[WMSLife] Execute LifeCycleTask %{public}s. PersistentId: %{public}d",
1112         lifeCycleTask->name.c_str(), persistentId_);
1113     lifeCycleTask->running = true;
1114     lifeCycleTask->startTime = std::chrono::steady_clock::now();
1115     PostTask(std::move(lifeCycleTask->task), lifeCycleTask->name);
1116 }
1117 
TerminateSessionNew(const sptr<AAFwk::SessionInfo> abilitySessionInfo,bool needStartCaller)1118 WSError Session::TerminateSessionNew(const sptr<AAFwk::SessionInfo> abilitySessionInfo, bool needStartCaller)
1119 {
1120     if (abilitySessionInfo == nullptr) {
1121         WLOGFE("[WMSLife] abilitySessionInfo is null");
1122         return WSError::WS_ERROR_INVALID_SESSION;
1123     }
1124     auto task = [this, abilitySessionInfo, needStartCaller]() {
1125         isTerminating = true;
1126         SessionInfo info;
1127         info.abilityName_ = abilitySessionInfo->want.GetElement().GetAbilityName();
1128         info.bundleName_ = abilitySessionInfo->want.GetElement().GetBundleName();
1129         info.callerToken_ = abilitySessionInfo->callerToken;
1130         info.persistentId_ = static_cast<int32_t>(abilitySessionInfo->persistentId);
1131         {
1132             std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
1133             sessionInfo_.closeAbilityWant = std::make_shared<AAFwk::Want>(abilitySessionInfo->want);
1134             sessionInfo_.resultCode = abilitySessionInfo->resultCode;
1135         }
1136         if (terminateSessionFuncNew_) {
1137             terminateSessionFuncNew_(info, needStartCaller);
1138         }
1139         WLOGFI("[WMSLife] TerminateSessionNew, id: %{public}d, needStartCaller: %{public}d",
1140             GetPersistentId(), needStartCaller);
1141     };
1142     PostLifeCycleTask(task, "TerminateSessionNew", LifeCycleTaskType::STOP);
1143     return WSError::WS_OK;
1144 }
1145 
SetTerminateSessionListenerNew(const NotifyTerminateSessionFuncNew & func)1146 void Session::SetTerminateSessionListenerNew(const NotifyTerminateSessionFuncNew& func)
1147 {
1148     terminateSessionFuncNew_ = func;
1149 }
1150 
TerminateSessionTotal(const sptr<AAFwk::SessionInfo> abilitySessionInfo,TerminateType terminateType)1151 WSError Session::TerminateSessionTotal(const sptr<AAFwk::SessionInfo> abilitySessionInfo, TerminateType terminateType)
1152 {
1153     if (abilitySessionInfo == nullptr) {
1154         WLOGFE("abilitySessionInfo is null");
1155         return WSError::WS_ERROR_INVALID_SESSION;
1156     }
1157     if (isTerminating) {
1158         WLOGFE("TerminateSessionTotal isTerminating, return!");
1159         return WSError::WS_ERROR_INVALID_OPERATION;
1160     }
1161     isTerminating = true;
1162     SessionInfo info;
1163     info.abilityName_ = abilitySessionInfo->want.GetElement().GetAbilityName();
1164     info.bundleName_ = abilitySessionInfo->want.GetElement().GetBundleName();
1165     info.callerToken_ = abilitySessionInfo->callerToken;
1166     info.persistentId_ = static_cast<int32_t>(abilitySessionInfo->persistentId);
1167     {
1168         std::lock_guard<std::recursive_mutex> lock(sessionInfoMutex_);
1169         sessionInfo_.closeAbilityWant = std::make_shared<AAFwk::Want>(abilitySessionInfo->want);
1170         sessionInfo_.resultCode = abilitySessionInfo->resultCode;
1171     }
1172     if (terminateSessionFuncTotal_) {
1173         terminateSessionFuncTotal_(info, terminateType);
1174     }
1175     return WSError::WS_OK;
1176 }
1177 
SetTerminateSessionListenerTotal(const NotifyTerminateSessionFuncTotal & func)1178 void Session::SetTerminateSessionListenerTotal(const NotifyTerminateSessionFuncTotal& func)
1179 {
1180     terminateSessionFuncTotal_ = func;
1181 }
1182 
SetSessionLabel(const std::string & label)1183 WSError Session::SetSessionLabel(const std::string &label)
1184 {
1185     WLOGFI("run Session::SetSessionLabel");
1186     if (updateSessionLabelFunc_) {
1187         updateSessionLabelFunc_(label);
1188     }
1189     return WSError::WS_OK;
1190 }
1191 
SetUpdateSessionLabelListener(const NofitySessionLabelUpdatedFunc & func)1192 void Session::SetUpdateSessionLabelListener(const NofitySessionLabelUpdatedFunc &func)
1193 {
1194     updateSessionLabelFunc_ = func;
1195 }
1196 
SetSessionIcon(const std::shared_ptr<Media::PixelMap> & icon)1197 WSError Session::SetSessionIcon(const std::shared_ptr<Media::PixelMap> &icon)
1198 {
1199     WLOGFD("run Session::SetSessionIcon, id: %{public}d", GetPersistentId());
1200     if (scenePersistence_ == nullptr) {
1201         WLOGFE("scenePersistence_ is nullptr.");
1202         return WSError::WS_ERROR_INVALID_OPERATION;
1203     }
1204     scenePersistence_->SaveUpdatedIcon(icon);
1205     std::string updatedIconPath = scenePersistence_->GetUpdatedIconPath();
1206     if (updateSessionIconFunc_) {
1207         updateSessionIconFunc_(updatedIconPath);
1208     }
1209     return WSError::WS_OK;
1210 }
1211 
SetUpdateSessionIconListener(const NofitySessionIconUpdatedFunc & func)1212 void Session::SetUpdateSessionIconListener(const NofitySessionIconUpdatedFunc &func)
1213 {
1214     updateSessionIconFunc_ = func;
1215 }
1216 
Clear()1217 WSError Session::Clear()
1218 {
1219     WLOGFI("Clear, id: %{public}d", GetPersistentId());
1220     auto task = [this]() {
1221         isTerminating = true;
1222         SessionInfo info = GetSessionInfo();
1223         if (terminateSessionFuncNew_) {
1224             terminateSessionFuncNew_(info, false);
1225         }
1226     };
1227     PostLifeCycleTask(task, "Clear", LifeCycleTaskType::STOP);
1228     return WSError::WS_OK;
1229 }
1230 
SetSessionExceptionListener(const NotifySessionExceptionFunc & func,bool fromJsScene)1231 void Session::SetSessionExceptionListener(const NotifySessionExceptionFunc& func, bool fromJsScene)
1232 {
1233     if (func == nullptr) {
1234         WLOGFE("func is nullptr");
1235         return;
1236     }
1237     std::shared_ptr<NotifySessionExceptionFunc> funcSptr = std::make_shared<NotifySessionExceptionFunc>(func);
1238     if (fromJsScene) {
1239         jsSceneSessionExceptionFunc_ = funcSptr;
1240     } else {
1241         sessionExceptionFunc_ = funcSptr;
1242     }
1243 }
1244 
SetSessionSnapshotListener(const NotifySessionSnapshotFunc & func)1245 void Session::SetSessionSnapshotListener(const NotifySessionSnapshotFunc& func)
1246 {
1247     if (func == nullptr) {
1248         WLOGFE("func is nullptr");
1249         return;
1250     }
1251     notifySessionSnapshotFunc_ = func;
1252 }
1253 
SetPendingSessionToForegroundListener(const NotifyPendingSessionToForegroundFunc & func)1254 void Session::SetPendingSessionToForegroundListener(const NotifyPendingSessionToForegroundFunc& func)
1255 {
1256     pendingSessionToForegroundFunc_ = func;
1257 }
1258 
PendingSessionToForeground()1259 WSError Session::PendingSessionToForeground()
1260 {
1261     WLOGFI("id: %{public}d", GetPersistentId());
1262     SessionInfo info = GetSessionInfo();
1263     if (pendingSessionActivationFunc_) {
1264         pendingSessionActivationFunc_(info);
1265     }
1266     return WSError::WS_OK;
1267 }
1268 
SetPendingSessionToBackgroundForDelegatorListener(const NotifyPendingSessionToBackgroundForDelegatorFunc & func)1269 void Session::SetPendingSessionToBackgroundForDelegatorListener(
1270     const NotifyPendingSessionToBackgroundForDelegatorFunc& func)
1271 {
1272     pendingSessionToBackgroundForDelegatorFunc_ = func;
1273 }
1274 
PendingSessionToBackgroundForDelegator()1275 WSError Session::PendingSessionToBackgroundForDelegator()
1276 {
1277     WLOGFD("run PendingSessionToBackgroundForDelegator");
1278     SessionInfo info = GetSessionInfo();
1279     if (pendingSessionToBackgroundForDelegatorFunc_) {
1280         pendingSessionToBackgroundForDelegatorFunc_(info);
1281     }
1282     return WSError::WS_OK;
1283 }
1284 
SetNotifyCallingSessionUpdateRectFunc(const NotifyCallingSessionUpdateRectFunc & func)1285 void Session::SetNotifyCallingSessionUpdateRectFunc(const NotifyCallingSessionUpdateRectFunc& func)
1286 {
1287     notifyCallingSessionUpdateRectFunc_ = func;
1288 }
1289 
SetNotifyCallingSessionForegroundFunc(const NotifyCallingSessionForegroundFunc & func)1290 void Session::SetNotifyCallingSessionForegroundFunc(const NotifyCallingSessionForegroundFunc& func)
1291 {
1292     notifyCallingSessionForegroundFunc_ = func;
1293 }
1294 
SetNotifyCallingSessionBackgroundFunc(const NotifyCallingSessionBackgroundFunc & func)1295 void Session::SetNotifyCallingSessionBackgroundFunc(const NotifyCallingSessionBackgroundFunc& func)
1296 {
1297     notifyCallingSessionBackgroundFunc_ = func;
1298 }
1299 
SetRaiseToAppTopForPointDownFunc(const NotifyRaiseToTopForPointDownFunc & func)1300 void Session::SetRaiseToAppTopForPointDownFunc(const NotifyRaiseToTopForPointDownFunc& func)
1301 {
1302     raiseToTopForPointDownFunc_ = func;
1303 }
1304 
NotifyScreenshot()1305 void Session::NotifyScreenshot()
1306 {
1307     if (!sessionStage_) {
1308         return;
1309     }
1310     sessionStage_->NotifyScreenshot();
1311 }
1312 
NotifyCloseExistPipWindow()1313 WSError Session::NotifyCloseExistPipWindow()
1314 {
1315     if (!sessionStage_) {
1316         return WSError::WS_ERROR_NULLPTR;
1317     }
1318     return sessionStage_->NotifyCloseExistPipWindow();
1319 }
1320 
NotifyDestroy()1321 WSError Session::NotifyDestroy()
1322 {
1323     if (!sessionStage_) {
1324         return WSError::WS_ERROR_NULLPTR;
1325     }
1326     return sessionStage_->NotifyDestroy();
1327 }
1328 
SetParentSession(const sptr<Session> & session)1329 void Session::SetParentSession(const sptr<Session>& session)
1330 {
1331     if (session == nullptr) {
1332         WLOGFW("Session is nullptr");
1333         return;
1334     }
1335     parentSession_ = session;
1336     WLOGFD("[WMSSystem][WMSSub] Set parent success, parentId: %{public}d, id: %{public}d",
1337         session->GetPersistentId(), GetPersistentId());
1338 }
1339 
GetParentSession() const1340 sptr<Session> Session::GetParentSession() const
1341 {
1342     return parentSession_;
1343 }
1344 
BindDialogToParentSession(const sptr<Session> & session)1345 void Session::BindDialogToParentSession(const sptr<Session>& session)
1346 {
1347     std::unique_lock<std::mutex> lock(dialogVecMutex_);
1348     auto iter = std::find(dialogVec_.begin(), dialogVec_.end(), session);
1349     if (iter != dialogVec_.end()) {
1350         WLOGFW("[WMSDialog] Dialog is existed in parentVec, id: %{public}d, parentId: %{public}d",
1351             session->GetPersistentId(), GetPersistentId());
1352         return;
1353     }
1354     dialogVec_.push_back(session);
1355     WLOGFD("[WMSDialog] Bind dialog success, id: %{public}d, parentId: %{public}d",
1356         session->GetPersistentId(), GetPersistentId());
1357 }
1358 
RemoveDialogToParentSession(const sptr<Session> & session)1359 void Session::RemoveDialogToParentSession(const sptr<Session>& session)
1360 {
1361     std::unique_lock<std::mutex> lock(dialogVecMutex_);
1362     auto iter = std::find(dialogVec_.begin(), dialogVec_.end(), session);
1363     if (iter != dialogVec_.end()) {
1364         WLOGFD("[WMSDialog] Remove dialog success, id: %{public}d, parentId: %{public}d",
1365             session->GetPersistentId(), GetPersistentId());
1366         dialogVec_.erase(iter);
1367     }
1368     WLOGFW("[WMSDialog] Remove dialog failed, id: %{public}d, parentId: %{public}d",
1369         session->GetPersistentId(), GetPersistentId());
1370 }
1371 
GetDialogVector() const1372 std::vector<sptr<Session>> Session::GetDialogVector() const
1373 {
1374     std::unique_lock<std::mutex> lock(dialogVecMutex_);
1375     return dialogVec_;
1376 }
1377 
ClearDialogVector()1378 void Session::ClearDialogVector()
1379 {
1380     std::unique_lock<std::mutex> lock(dialogVecMutex_);
1381     dialogVec_.clear();
1382     WLOGFD("[WMSDialog] parentId: %{public}d", GetPersistentId());
1383     return;
1384 }
1385 
CheckDialogOnForeground()1386 bool Session::CheckDialogOnForeground()
1387 {
1388     std::unique_lock<std::mutex> lock(dialogVecMutex_);
1389     if (dialogVec_.empty()) {
1390         WLOGFD("[WMSDialog] Dialog is empty, id: %{public}d", GetPersistentId());
1391         return false;
1392     }
1393     for (auto iter = dialogVec_.rbegin(); iter != dialogVec_.rend(); iter++) {
1394         auto dialogSession = *iter;
1395         if (dialogSession && (dialogSession->GetSessionState() == SessionState::STATE_ACTIVE ||
1396             dialogSession->GetSessionState() == SessionState::STATE_FOREGROUND)) {
1397             WLOGFD("[WMSDialog] Notify touch dialog window, id: %{public}d", GetPersistentId());
1398             return true;
1399         }
1400     }
1401     return false;
1402 }
1403 
CheckPointerEventDispatch(const std::shared_ptr<MMI::PointerEvent> & pointerEvent) const1404 bool Session::CheckPointerEventDispatch(const std::shared_ptr<MMI::PointerEvent>& pointerEvent) const
1405 {
1406     auto windowType = GetWindowType();
1407     bool isSystemWindow = GetSessionInfo().isSystem_;
1408     auto sessionState = GetSessionState();
1409     int32_t action = pointerEvent->GetPointerAction();
1410     auto isPC = system::GetParameter("const.product.devicetype", "unknown") == "2in1";
1411     if (!isSystemWindow &&
1412         (WindowHelper::IsMainWindow(windowType) || (WindowHelper::IsSubWindow(windowType) && isPC)) &&
1413         sessionState != SessionState::STATE_FOREGROUND &&
1414         sessionState != SessionState::STATE_ACTIVE &&
1415         action != MMI::PointerEvent::POINTER_ACTION_LEAVE_WINDOW) {
1416         WLOGFW("Current Session Info: [persistentId: %{public}d, isSystemWindow: %{public}d,"
1417             "state: %{public}d, action:%{public}d]", GetPersistentId(), isSystemWindow, state_, action);
1418         return false;
1419     }
1420     return true;
1421 }
1422 
CheckKeyEventDispatch(const std::shared_ptr<MMI::KeyEvent> & keyEvent) const1423 bool Session::CheckKeyEventDispatch(const std::shared_ptr<MMI::KeyEvent>& keyEvent) const
1424 {
1425     if (GetWindowType() != WindowType::WINDOW_TYPE_DIALOG) {
1426         return true;
1427     }
1428 
1429     auto currentRect = winRect_;
1430     if (!isRSVisible_ || currentRect.width_ == 0 || currentRect.height_ == 0) {
1431         WLOGE("Error size: [width: %{public}d, height: %{public}d], isRSVisible_: %{public}d,"
1432             " persistentId: %{public}d",
1433             currentRect.width_, currentRect.height_, isRSVisible_, GetPersistentId());
1434         return false;
1435     }
1436 
1437     auto parentSession = GetParentSession();
1438     if (parentSession == nullptr) {
1439         WLOGFW("Dialog parent is null");
1440         return false;
1441     }
1442     auto parentSessionState = parentSession->GetSessionState();
1443     if ((parentSessionState != SessionState::STATE_FOREGROUND &&
1444         parentSessionState != SessionState::STATE_ACTIVE) ||
1445         (state_ != SessionState::STATE_FOREGROUND &&
1446         state_ != SessionState::STATE_ACTIVE)) {
1447         WLOGFE("[WMSDialog] Dialog's parent info : [persistentId: %{publicd}d, state:%{public}d];"
1448             "Dialog info:[persistentId: %{publicd}d, state:%{public}d]",
1449             parentSession->GetPersistentId(), parentSessionState, GetPersistentId(), state_);
1450         return false;
1451     }
1452     return true;
1453 }
1454 
IsTopDialog() const1455 bool Session::IsTopDialog() const
1456 {
1457     int32_t currentPersistentId = GetPersistentId();
1458     auto parentSession = GetParentSession();
1459     if (parentSession == nullptr) {
1460         WLOGFW("[WMSDialog] Dialog's Parent is NULL. id: %{public}d", currentPersistentId);
1461         return false;
1462     }
1463     std::unique_lock<std::mutex> lock(parentSession->dialogVecMutex_);
1464     if (parentSession->dialogVec_.size() <= 1) {
1465         return true;
1466     }
1467     auto parentDialogVec = parentSession->dialogVec_;
1468     for (auto iter = parentDialogVec.rbegin(); iter != parentDialogVec.rend(); iter++) {
1469         auto dialogSession = *iter;
1470         if (dialogSession && (dialogSession->GetSessionState() == SessionState::STATE_ACTIVE ||
1471             dialogSession->GetSessionState() == SessionState::STATE_FOREGROUND)) {
1472             return dialogSession->GetPersistentId() == currentPersistentId;
1473         }
1474     }
1475     return false;
1476 }
1477 
DumpPointerWindowArea(MMI::WindowArea area) const1478 const char* Session::DumpPointerWindowArea(MMI::WindowArea area) const
1479 {
1480     const std::map<MMI::WindowArea, const char*> areaMap = {
1481         { MMI::WindowArea::FOCUS_ON_INNER, "FOCUS_ON_INNER" },
1482         { MMI::WindowArea::FOCUS_ON_TOP, "FOCUS_ON_TOP" },
1483         { MMI::WindowArea::FOCUS_ON_BOTTOM, "FOCUS_ON_BOTTOM" },
1484         { MMI::WindowArea::FOCUS_ON_LEFT, "FOCUS_ON_LEFT" },
1485         { MMI::WindowArea::FOCUS_ON_RIGHT, "FOCUS_ON_RIGHT" },
1486         { MMI::WindowArea::FOCUS_ON_BOTTOM_LEFT, "FOCUS_ON_BOTTOM_LEFT" },
1487         { MMI::WindowArea::FOCUS_ON_BOTTOM_RIGHT, "FOCUS_ON_BOTTOM_RIGHT" },
1488         { MMI::WindowArea::FOCUS_ON_TOP_LEFT, "FOCUS_ON_TOP_LEFT" },
1489         { MMI::WindowArea::FOCUS_ON_TOP_RIGHT, "FOCUS_ON_TOP_RIGHT" },
1490         { MMI::WindowArea::EXIT, "EXIT" }
1491     };
1492     auto iter = areaMap.find(area);
1493     if (iter == areaMap.end()) {
1494         return "UNKNOW";
1495     }
1496     return iter->second;
1497 }
1498 
RaiseToAppTopForPointDown()1499 WSError Session::RaiseToAppTopForPointDown()
1500 {
1501     if (raiseToTopForPointDownFunc_) {
1502         raiseToTopForPointDownFunc_();
1503         WLOGFD("RaiseToAppTopForPointDown, id: %{public}d, type: %{public}d", GetPersistentId(), GetWindowType());
1504     }
1505     return WSError::WS_OK;
1506 }
1507 
PresentFocusIfPointDown()1508 void Session::PresentFocusIfPointDown()
1509 {
1510     WLOGFI("PresentFocusIfPointDown, id: %{public}d, type: %{public}d", GetPersistentId(), GetWindowType());
1511     if (!isFocused_ && GetFocusable()) {
1512         NotifyRequestFocusStatusNotifyManager(true, false);
1513     }
1514     if (!sessionInfo_.isSystem_ || (!isFocused_ && GetFocusable())) {
1515         NotifyClick();
1516     }
1517 }
1518 
HandlePointDownDialog()1519 void Session::HandlePointDownDialog()
1520 {
1521     for (auto dialog : dialogVec_) {
1522         if (dialog && (dialog->GetSessionState() == SessionState::STATE_FOREGROUND ||
1523             dialog->GetSessionState() == SessionState::STATE_ACTIVE)) {
1524             dialog->RaiseToAppTopForPointDown();
1525             dialog->PresentFocusIfPointDown();
1526             WLOGFD("[WMSDialog] Point main window, raise to top and dialog need focus, "
1527                 "id: %{public}d, dialogId: %{public}d", GetPersistentId(), dialog->GetPersistentId());
1528         }
1529     }
1530 }
1531 
NotifyPointerEventToRs(int32_t pointAction)1532 void Session::NotifyPointerEventToRs(int32_t pointAction)
1533 {
1534     if ((pointAction == MMI::PointerEvent::POINTER_ACTION_UP) |
1535         (pointAction == MMI::PointerEvent::POINTER_ACTION_DOWN)) {
1536         // RSInterfaces::GetInstance().NotifyTouchEvent(pointAction);
1537     }
1538 }
1539 
HandleSubWindowClick(int32_t action)1540 WSError Session::HandleSubWindowClick(int32_t action)
1541 {
1542     if (parentSession_ && parentSession_->CheckDialogOnForeground()) {
1543         WLOGFD("[WMSDialog] Its main window has dialog on foreground, id: %{public}d", GetPersistentId());
1544         return WSError::WS_ERROR_INVALID_PERMISSION;
1545     }
1546 
1547     bool raiseEnabled = property_->GetRaiseEnabled() &&
1548         (action == MMI::PointerEvent::POINTER_ACTION_DOWN || action == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN);
1549     if (raiseEnabled) {
1550         RaiseToAppTopForPointDown();
1551     }
1552     return WSError::WS_OK;
1553 }
1554 
TransferPointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent,bool needNotifyClient)1555 WSError Session::TransferPointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent, bool needNotifyClient)
1556 {
1557     WLOGFD("Session TransferPointEvent, id: %{public}d", GetPersistentId());
1558     if (!IsSystemSession() && !IsSessionValid()) {
1559         return WSError::WS_ERROR_INVALID_SESSION;
1560     }
1561     if (pointerEvent == nullptr) {
1562         WLOGFE("PointerEvent is nullptr");
1563         return WSError::WS_ERROR_NULLPTR;
1564     }
1565     auto pointerAction = pointerEvent->GetPointerAction();
1566     NotifyPointerEventToRs(pointerAction);
1567     bool isPointDown = (pointerAction == MMI::PointerEvent::POINTER_ACTION_DOWN) ||
1568         (pointerAction == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN);
1569     if (GetWindowType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW) {
1570         if (CheckDialogOnForeground() && isPointDown) {
1571             HandlePointDownDialog();
1572             return WSError::WS_ERROR_INVALID_PERMISSION;
1573         }
1574     } else if (GetWindowType() == WindowType::WINDOW_TYPE_APP_SUB_WINDOW) {
1575         WSError ret = HandleSubWindowClick(pointerAction);
1576         if (ret != WSError::WS_OK) {
1577             return ret;
1578         }
1579     } else if (GetWindowType() == WindowType::WINDOW_TYPE_DIALOG) {
1580         if (parentSession_ && parentSession_->CheckDialogOnForeground() && isPointDown) {
1581             parentSession_->HandlePointDownDialog();
1582             if (!IsTopDialog()) {
1583                 WLOGFI("[WMSDialog] There is at least one active dialog upon this dialog, id: %{public}d",
1584                     GetPersistentId());
1585                 return WSError::WS_ERROR_INVALID_PERMISSION;
1586             }
1587         }
1588     }
1589     if (DelayedSingleton<ANRManager>::GetInstance()->IsANRTriggered(persistentId_)) {
1590         WLOGFW("InputTracking id:%{public}d, The pointerEvent does not report normally,"
1591             "bundleName:%{public}s not reponse, pid:%{public}d, persistentId:%{public}d",
1592             pointerEvent->GetId(), callingBundleName_.c_str(), callingPid_, persistentId_);
1593         return WSError::WS_DO_NOTHING;
1594     }
1595     PresentFoucusIfNeed(pointerAction);
1596     if (!windowEventChannel_) {
1597         if (!IsSystemSession()) {
1598             WLOGFE("windowEventChannel_ is null");
1599         }
1600         return WSError::WS_ERROR_NULLPTR;
1601     }
1602 
1603     if (needNotifyClient) {
1604         WSError ret = windowEventChannel_->TransferPointerEvent(pointerEvent);
1605         if (ret != WSError::WS_OK) {
1606             WLOGFE("InputTracking id:%{public}d, TransferPointer failed, ret:%{public}d ",
1607                 pointerEvent->GetId(), ret);
1608         }
1609         return ret;
1610     } else {
1611         pointerEvent->MarkProcessed();
1612     }
1613 
1614     if (pointerAction == MMI::PointerEvent::POINTER_ACTION_MOVE ||
1615         pointerAction == MMI::PointerEvent::POINTER_ACTION_PULL_MOVE) {
1616         WLOGFD("Session TransferPointEvent, eventId:%{public}d, action:%{public}s, persistentId:%{public}d, "
1617             "bundleName:%{public}s, pid:%{public}d", pointerEvent->GetId(), pointerEvent->DumpPointerAction(),
1618             persistentId_, callingBundleName_.c_str(), callingPid_);
1619     } else {
1620         WLOGFI("Session TransferPointEvent, eventId:%{public}d, action:%{public}s, persistentId:%{public}d, "
1621             "bundleName:%{public}s, pid:%{public}d", pointerEvent->GetId(), pointerEvent->DumpPointerAction(),
1622             persistentId_, callingBundleName_.c_str(), callingPid_);
1623     }
1624     if (pointerAction == MMI::PointerEvent::POINTER_ACTION_ENTER_WINDOW ||
1625         pointerAction == MMI::PointerEvent::POINTER_ACTION_LEAVE_WINDOW ||
1626         pointerAction == MMI::PointerEvent::POINTER_ACTION_PULL_IN_WINDOW ||
1627         pointerAction == MMI::PointerEvent::POINTER_ACTION_PULL_OUT_WINDOW) {
1628         WLOGFD("Action:%{public}s, eventId:%{public}d, report without timer",
1629             pointerEvent->DumpPointerAction(), pointerEvent->GetId());
1630     }
1631     return WSError::WS_OK;
1632 }
1633 
TransferKeyEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent)1634 WSError Session::TransferKeyEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
1635 {
1636     if (!IsSystemSession() && !IsSessionValid()) {
1637         return WSError::WS_ERROR_INVALID_SESSION;
1638     }
1639     if (keyEvent == nullptr) {
1640         WLOGFE("KeyEvent is nullptr");
1641         return WSError::WS_ERROR_NULLPTR;
1642     }
1643     if (GetWindowType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW) {
1644         if (CheckDialogOnForeground()) {
1645             WLOGFD("[WMSDialog] Has dialog on foreground, not transfer pointer event");
1646             return WSError::WS_ERROR_INVALID_PERMISSION;
1647         }
1648     } else if (GetWindowType() == WindowType::WINDOW_TYPE_APP_SUB_WINDOW) {
1649         if (parentSession_ && parentSession_->CheckDialogOnForeground()) {
1650             WLOGFD("[WMSDialog] Its main window has dialog on foreground, not transfer pointer event");
1651             return WSError::WS_ERROR_INVALID_PERMISSION;
1652         }
1653     } else if (GetWindowType() == WindowType::WINDOW_TYPE_DIALOG) {
1654         if (keyEvent->GetKeyCode() == MMI::KeyEvent::KEYCODE_BACK) {
1655             return WSError::WS_ERROR_INVALID_PERMISSION;
1656         }
1657         if (parentSession_ && parentSession_->CheckDialogOnForeground() &&
1658             !IsTopDialog()) {
1659             return WSError::WS_ERROR_INVALID_PERMISSION;
1660         }
1661     }
1662 
1663     if (!CheckKeyEventDispatch(keyEvent)) {
1664         WLOGFW("Do not dispatch the key event.");
1665         return WSError::WS_DO_NOTHING;
1666     }
1667 
1668     WLOGFD("Session TransferKeyEvent eventId:%{public}d persistentId:%{public}d bundleName:%{public}s pid:%{public}d",
1669         keyEvent->GetId(), persistentId_, callingBundleName_.c_str(), callingPid_);
1670     if (DelayedSingleton<ANRManager>::GetInstance()->IsANRTriggered(persistentId_)) {
1671         WLOGFD("The keyEvent does not report normally, "
1672             "bundleName:%{public}s not response, pid:%{public}d, persistentId:%{public}d",
1673             callingBundleName_.c_str(), callingPid_, persistentId_);
1674         return WSError::WS_DO_NOTHING;
1675     }
1676     if (!windowEventChannel_) {
1677         WLOGFE("windowEventChannel_ is null");
1678         return WSError::WS_ERROR_NULLPTR;
1679     }
1680     WLOGD("TransferKeyEvent, id: %{public}d", persistentId_);
1681     WSError ret = windowEventChannel_->TransferKeyEvent(keyEvent);
1682     if (ret != WSError::WS_OK) {
1683         WLOGFE("TransferKeyEvent failed, ret:%{public}d", ret);
1684         return ret;
1685     }
1686     return WSError::WS_OK;
1687 }
1688 
TransferBackPressedEventForConsumed(bool & isConsumed)1689 WSError Session::TransferBackPressedEventForConsumed(bool& isConsumed)
1690 {
1691     if (!windowEventChannel_) {
1692         WLOGFE("windowEventChannel_ is null");
1693         return WSError::WS_ERROR_NULLPTR;
1694     }
1695     return windowEventChannel_->TransferBackpressedEventForConsumed(isConsumed);
1696 }
1697 
TransferKeyEventForConsumed(const std::shared_ptr<MMI::KeyEvent> & keyEvent,bool & isConsumed)1698 WSError Session::TransferKeyEventForConsumed(const std::shared_ptr<MMI::KeyEvent>& keyEvent, bool& isConsumed)
1699 {
1700     if (!windowEventChannel_) {
1701         WLOGFE("windowEventChannel_ is null");
1702         return WSError::WS_ERROR_NULLPTR;
1703     }
1704     if (keyEvent == nullptr) {
1705         WLOGFE("KeyEvent is nullptr");
1706         return WSError::WS_ERROR_NULLPTR;
1707     }
1708     return windowEventChannel_->TransferKeyEventForConsumed(keyEvent, isConsumed);
1709 }
1710 
TransferFocusActiveEvent(bool isFocusActive)1711 WSError Session::TransferFocusActiveEvent(bool isFocusActive)
1712 {
1713     if (!windowEventChannel_) {
1714         WLOGFE("windowEventChannel_ is null");
1715         return WSError::WS_ERROR_NULLPTR;
1716     }
1717     return windowEventChannel_->TransferFocusActiveEvent(isFocusActive);
1718 }
1719 
TransferFocusStateEvent(bool focusState)1720 WSError Session::TransferFocusStateEvent(bool focusState)
1721 {
1722     if (!windowEventChannel_) {
1723         if (!IsSystemSession()) {
1724             WLOGFW("windowEventChannel_ is null");
1725         }
1726         return WSError::WS_ERROR_NULLPTR;
1727     }
1728     return windowEventChannel_->TransferFocusState(focusState);
1729 }
1730 
Snapshot(const float scaleParam) const1731 std::shared_ptr<Media::PixelMap> Session::Snapshot(const float scaleParam) const
1732 {
1733     if (!surfaceNode_ || (!surfaceNode_->IsBufferAvailable() && !bufferAvailable_)) {
1734         return nullptr;
1735     }
1736     auto callback = std::make_shared<SurfaceCaptureFuture>();
1737     auto scaleValue = scaleParam == 0.0f ? snapshotScale_ : scaleParam;
1738     bool ret = RSInterfaces::GetInstance().TakeSurfaceCapture(surfaceNode_, callback, scaleValue, scaleValue);
1739     if (!ret) {
1740         WLOGFE("TakeSurfaceCapture failed");
1741         return nullptr;
1742     }
1743     auto pixelMap = callback->GetResult(SNAPSHOT_TIMEOUT_MS);
1744     if (pixelMap != nullptr) {
1745         WLOGFD("Save pixelMap WxH = %{public}dx%{public}d", pixelMap->GetWidth(), pixelMap->GetHeight());
1746         if (notifySessionSnapshotFunc_) {
1747             notifySessionSnapshotFunc_(persistentId_);
1748         }
1749     } else {
1750         WLOGFE("Failed to get pixelMap, return nullptr");
1751     }
1752     return pixelMap;
1753 }
1754 
SetSessionStateChangeListenser(const NotifySessionStateChangeFunc & func)1755 void Session::SetSessionStateChangeListenser(const NotifySessionStateChangeFunc& func)
1756 {
1757     sessionStateChangeFunc_ = func;
1758     auto changedState = state_;
1759     if (changedState == SessionState::STATE_ACTIVE) {
1760         changedState = SessionState::STATE_FOREGROUND;
1761     } else if (changedState == SessionState::STATE_INACTIVE) {
1762         changedState = SessionState::STATE_BACKGROUND;
1763     } else if (changedState == SessionState::STATE_DISCONNECT) {
1764         return;
1765     }
1766     NotifySessionStateChange(changedState);
1767     WLOGFD("SetSessionStateChangeListenser, id: %{public}d, state_: %{public}d, changedState: %{public}d",
1768         GetPersistentId(), state_, changedState);
1769 }
1770 
SetBufferAvailableChangeListener(const NotifyBufferAvailableChangeFunc & func)1771 void Session::SetBufferAvailableChangeListener(const NotifyBufferAvailableChangeFunc& func)
1772 {
1773     bufferAvailableChangeFunc_ = func;
1774     if (bufferAvailable_ && bufferAvailableChangeFunc_ != nullptr) {
1775         bufferAvailableChangeFunc_(bufferAvailable_);
1776     }
1777     WLOGFD("SetBufferAvailableChangeListener, id: %{public}d", GetPersistentId());
1778 }
1779 
UnregisterSessionChangeListeners()1780 void Session::UnregisterSessionChangeListeners()
1781 {
1782     auto task = [weakThis = wptr(this)]() {
1783         auto session = weakThis.promote();
1784         if (session == nullptr) {
1785             WLOGFE("session is null");
1786             return;
1787         }
1788         session->sessionStateChangeFunc_ = nullptr;
1789         session->sessionFocusableChangeFunc_ = nullptr;
1790         session->sessionTouchableChangeFunc_ = nullptr;
1791         session->clickFunc_ = nullptr;
1792         session->jsSceneSessionExceptionFunc_ = nullptr;
1793         session->sessionExceptionFunc_ = nullptr;
1794         WLOGFD("UnregisterSessionChangeListenser, id: %{public}d", session->GetPersistentId());
1795     };
1796     PostTask(task, "UnregisterSessionChangeListeners");
1797 }
1798 
SetSessionStateChangeNotifyManagerListener(const NotifySessionStateChangeNotifyManagerFunc & func)1799 void Session::SetSessionStateChangeNotifyManagerListener(const NotifySessionStateChangeNotifyManagerFunc& func)
1800 {
1801     sessionStateChangeNotifyManagerFunc_ = func;
1802     if (state_ == SessionState::STATE_DISCONNECT) {
1803         return;
1804     }
1805     NotifySessionStateChange(state_);
1806 }
1807 
SetSessionInfoChangeNotifyManagerListener(const NotifySessionInfoChangeNotifyManagerFunc & func)1808 void Session::SetSessionInfoChangeNotifyManagerListener(const NotifySessionInfoChangeNotifyManagerFunc& func)
1809 {
1810     sessionInfoChangeNotifyManagerFunc_ = func;
1811 }
1812 
SetRequestFocusStatusNotifyManagerListener(const NotifyRequestFocusStatusNotifyManagerFunc & func)1813 void Session::SetRequestFocusStatusNotifyManagerListener(const NotifyRequestFocusStatusNotifyManagerFunc& func)
1814 {
1815     requestFocusStatusNotifyManagerFunc_ = func;
1816 }
1817 
SetNotifyUIRequestFocusFunc(const NotifyUIRequestFocusFunc & func)1818 void Session::SetNotifyUIRequestFocusFunc(const NotifyUIRequestFocusFunc& func)
1819 {
1820     requestFocusFunc_ = func;
1821 }
1822 
SetNotifyUILostFocusFunc(const NotifyUILostFocusFunc & func)1823 void Session::SetNotifyUILostFocusFunc(const NotifyUILostFocusFunc& func)
1824 {
1825     lostFocusFunc_ = func;
1826 }
1827 
SetGetStateFromManagerListener(const GetStateFromManagerFunc & func)1828 void Session::SetGetStateFromManagerListener(const GetStateFromManagerFunc& func)
1829 {
1830     getStateFromManagerFunc_ = func;
1831 }
1832 
NotifySessionStateChange(const SessionState & state)1833 void Session::NotifySessionStateChange(const SessionState& state)
1834 {
1835     auto task = [weakThis = wptr(this), state]() {
1836         auto session = weakThis.promote();
1837         if (session == nullptr) {
1838             WLOGFE("session is null");
1839             return;
1840         }
1841         WLOGI("[WMSLife] NotifySessionStateChange, [state: %{public}u, persistent: %{public}d]",
1842             static_cast<uint32_t>(state), session->GetPersistentId());
1843         if (session->sessionStateChangeFunc_) {
1844             session->sessionStateChangeFunc_(state);
1845         }
1846 
1847         if (session->sessionStateChangeNotifyManagerFunc_) {
1848             session->sessionStateChangeNotifyManagerFunc_(session->GetPersistentId(), state);
1849         }
1850     };
1851     PostTask(task, "NotifySessionStateChange");
1852 }
1853 
SetSessionFocusableChangeListener(const NotifySessionFocusableChangeFunc & func)1854 void Session::SetSessionFocusableChangeListener(const NotifySessionFocusableChangeFunc& func)
1855 {
1856     sessionFocusableChangeFunc_ = func;
1857     sessionFocusableChangeFunc_(GetFocusable());
1858 }
1859 
SetSessionTouchableChangeListener(const NotifySessionTouchableChangeFunc & func)1860 void Session::SetSessionTouchableChangeListener(const NotifySessionTouchableChangeFunc& func)
1861 {
1862     sessionTouchableChangeFunc_ = func;
1863     sessionTouchableChangeFunc_(GetTouchable());
1864 }
1865 
SetClickListener(const NotifyClickFunc & func)1866 void Session::SetClickListener(const NotifyClickFunc& func)
1867 {
1868     clickFunc_ = func;
1869 }
1870 
NotifySessionFocusableChange(bool isFocusable)1871 void Session::NotifySessionFocusableChange(bool isFocusable)
1872 {
1873     WLOGFI("Notify session focusable change, id: %{public}d, focusable: %{public}u", GetPersistentId(), isFocusable);
1874     if (sessionFocusableChangeFunc_) {
1875         sessionFocusableChangeFunc_(isFocusable);
1876     }
1877 }
1878 
NotifySessionTouchableChange(bool touchable)1879 void Session::NotifySessionTouchableChange(bool touchable)
1880 {
1881     WLOGFD("Notify session touchable change: %{public}d", touchable);
1882     if (sessionTouchableChangeFunc_) {
1883         sessionTouchableChangeFunc_(touchable);
1884     }
1885 }
1886 
NotifyClick()1887 void Session::NotifyClick()
1888 {
1889     WLOGFD("Notify click");
1890     if (clickFunc_) {
1891         clickFunc_();
1892     }
1893 }
1894 
NotifyRequestFocusStatusNotifyManager(bool isFocused,bool byForeground)1895 void Session::NotifyRequestFocusStatusNotifyManager(bool isFocused, bool byForeground)
1896 {
1897     WLOGFD("NotifyRequestFocusStatusNotifyManager id: %{public}d, focused: %{public}d", GetPersistentId(), isFocused);
1898     if (requestFocusStatusNotifyManagerFunc_) {
1899         requestFocusStatusNotifyManagerFunc_(GetPersistentId(), isFocused, byForeground);
1900     }
1901 }
1902 
GetStateFromManager(const ManagerState key)1903 bool Session::GetStateFromManager(const ManagerState key)
1904 {
1905     if (getStateFromManagerFunc_) {
1906         return getStateFromManagerFunc_(key);
1907     }
1908     switch (key)
1909     {
1910     case ManagerState::MANAGER_STATE_SCREEN_LOCKED:
1911         return false;
1912         break;
1913     default:
1914         return false;
1915     }
1916 }
1917 
NotifyUIRequestFocus()1918 void Session::NotifyUIRequestFocus()
1919 {
1920     WLOGFD("NotifyUIRequestFocus id: %{public}d", GetPersistentId());
1921     if (requestFocusFunc_) {
1922         requestFocusFunc_();
1923     }
1924 }
1925 
NotifyUILostFocus()1926 void Session::NotifyUILostFocus()
1927 {
1928     WLOGFD("NotifyUILostFocus id: %{public}d", GetPersistentId());
1929     if (lostFocusFunc_) {
1930         lostFocusFunc_();
1931     }
1932 }
1933 
PresentFoucusIfNeed(int32_t pointerAction)1934 void Session::PresentFoucusIfNeed(int32_t pointerAction)
1935 {
1936     WLOGFD("OnClick down, id: %{public}d", GetPersistentId());
1937     if (pointerAction == MMI::PointerEvent::POINTER_ACTION_DOWN ||
1938         pointerAction == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN) {
1939         if (!isFocused_ && GetFocusable()) {
1940             NotifyRequestFocusStatusNotifyManager(true, false);
1941         }
1942         if (!sessionInfo_.isSystem_ || (!isFocused_ && GetFocusable())) {
1943             NotifyClick();
1944         }
1945     }
1946 }
1947 
UpdateFocus(bool isFocused)1948 WSError Session::UpdateFocus(bool isFocused)
1949 {
1950     WLOGFD("[WMSFocus]Update focus id: %{public}d, status: %{public}d", GetPersistentId(), isFocused);
1951     if (isFocused_ == isFocused) {
1952         WLOGFD("[WMSFocus]Session focus do not change");
1953         return WSError::WS_DO_NOTHING;
1954     }
1955     isFocused_ = isFocused;
1956     // notify scb arkui focus
1957     if (isFocused) {
1958         if (sessionInfo_.isSystem_) {
1959             NotifyUIRequestFocus();
1960         }
1961     } else {
1962          NotifyUILostFocus();
1963     }
1964     return WSError::WS_OK;
1965 }
1966 
NotifyFocusStatus(bool isFocused)1967 WSError Session::NotifyFocusStatus(bool isFocused)
1968 {
1969     WLOGFD("[WMSFocus]Notify focus, id: %{public}d, status: %{public}d", GetPersistentId(), isFocused);
1970     if (!IsSessionValid()) {
1971         return WSError::WS_ERROR_INVALID_SESSION;
1972     }
1973     sessionStage_->UpdateFocus(isFocused);
1974 
1975     return WSError::WS_OK;
1976 }
1977 
UpdateWindowMode(WindowMode mode)1978 WSError Session::UpdateWindowMode(WindowMode mode)
1979 {
1980     WLOGFD("Session update window mode, id: %{public}d, mode: %{public}d", GetPersistentId(),
1981         static_cast<int32_t>(mode));
1982     if (sessionInfo_.isSystem_) {
1983         WLOGFD("session is system, id: %{public}d, name: %{public}s, state: %{public}u",
1984             GetPersistentId(), sessionInfo_.bundleName_.c_str(), state_);
1985         return WSError::WS_ERROR_INVALID_SESSION;
1986     }
1987 
1988     if (property_ == nullptr) {
1989         WLOGFD("id: %{public}d property is nullptr", persistentId_);
1990         return WSError::WS_ERROR_NULLPTR;
1991     }
1992 
1993     if (state_ == SessionState::STATE_END) {
1994         WLOGFI("session is already destroyed or property is nullptr! id: %{public}d state: %{public}u",
1995             GetPersistentId(), state_);
1996         return WSError::WS_ERROR_INVALID_SESSION;
1997     } else if (state_ == SessionState::STATE_DISCONNECT) {
1998         property_->SetWindowMode(mode);
1999         property_->SetIsNeedUpdateWindowMode(true);
2000     } else {
2001         property_->SetWindowMode(mode);
2002         if (mode == WindowMode::WINDOW_MODE_SPLIT_PRIMARY || mode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY) {
2003             property_->SetMaximizeMode(MaximizeMode::MODE_RECOVER);
2004         }
2005         return sessionStage_->UpdateWindowMode(mode);
2006     }
2007     return WSError::WS_OK;
2008 }
2009 
SetSystemSceneBlockingFocus(bool blocking)2010 WSError Session::SetSystemSceneBlockingFocus(bool blocking)
2011 {
2012     WLOGFD("[WMSFocus]Session set blocking focus of lower session, id: %{public}d, mode: %{public}d", GetPersistentId(),
2013         blocking);
2014     if (!sessionInfo_.isSystem_) {
2015         WLOGFW("[WMSFocus]Session is not system.");
2016         return WSError::WS_ERROR_INVALID_SESSION;
2017     }
2018     blockingFocus_ = blocking;
2019     return WSError::WS_OK;
2020 }
2021 
GetBlockingFocus() const2022 bool Session::GetBlockingFocus() const
2023 {
2024     return blockingFocus_;
2025 }
2026 
SetSessionProperty(const sptr<WindowSessionProperty> & property)2027 WSError Session::SetSessionProperty(const sptr<WindowSessionProperty>& property)
2028 {
2029     std::unique_lock<std::shared_mutex> lock(propertyMutex_);
2030     property_ = property;
2031     NotifySessionInfoChange();
2032     if (property_ == nullptr) {
2033         return WSError::WS_OK;
2034     }
2035 
2036     auto hotAreasChangeCallback = [weakThis = wptr(this)]() {
2037         auto session = weakThis.promote();
2038         if (session == nullptr) {
2039             WLOGFE("session is nullptr");
2040             return;
2041         }
2042         session->NotifySessionInfoChange();
2043     };
2044     property_->SetSessionPropertyChangeCallback(hotAreasChangeCallback);
2045     return WSError::WS_OK;
2046 }
2047 
GetSessionProperty() const2048 sptr<WindowSessionProperty> Session::GetSessionProperty() const
2049 {
2050     std::shared_lock<std::shared_mutex> lock(propertyMutex_);
2051     return property_;
2052 }
2053 
SetSessionRect(const WSRect & rect)2054 void Session::SetSessionRect(const WSRect& rect)
2055 {
2056     if (winRect_ == rect) {
2057         WLOGFW("id: %{public}d skip same rect", persistentId_);
2058         return;
2059     }
2060     winRect_ = rect;
2061     isDirty_ = true;
2062 }
2063 
GetSessionRect() const2064 WSRect Session::GetSessionRect() const
2065 {
2066     return winRect_;
2067 }
2068 
SetSessionRequestRect(const WSRect & rect)2069 void Session::SetSessionRequestRect(const WSRect& rect)
2070 {
2071     auto property = GetSessionProperty();
2072     if (property == nullptr) {
2073         WLOGFD("id: %{public}d property is nullptr", persistentId_);
2074         return;
2075     }
2076     property->SetRequestRect(SessionHelper::TransferToRect(rect));
2077     WLOGFD("is: %{public}d, rect: [%{public}d, %{public}d, %{public}u, %{public}u]", persistentId_,
2078         rect.posX_, rect.posY_, rect.width_, rect.height_);
2079 }
2080 
GetSessionRequestRect() const2081 WSRect Session::GetSessionRequestRect() const
2082 {
2083     WSRect rect;
2084     auto property = GetSessionProperty();
2085     if (property == nullptr) {
2086         WLOGFD("id: %{public}d property is nullptr", persistentId_);
2087         return rect;
2088     }
2089     rect = SessionHelper::TransferToWSRect(property->GetRequestRect());
2090     WLOGFD("id: %{public}d, rect: %{public}s", persistentId_, rect.ToString().c_str());
2091     return rect;
2092 }
2093 
GetWindowType() const2094 WindowType Session::GetWindowType() const
2095 {
2096     auto property = GetSessionProperty();
2097     if (property) {
2098         return property->GetWindowType();
2099     }
2100     return WindowType::WINDOW_TYPE_APP_MAIN_WINDOW;
2101 }
2102 
SetSystemConfig(const SystemSessionConfig & systemConfig)2103 void Session::SetSystemConfig(const SystemSessionConfig& systemConfig)
2104 {
2105     systemConfig_ = systemConfig;
2106 }
2107 
SetSnapshotScale(const float snapshotScale)2108 void Session::SetSnapshotScale(const float snapshotScale)
2109 {
2110     snapshotScale_ = snapshotScale;
2111 }
2112 
ProcessBackEvent()2113 WSError Session::ProcessBackEvent()
2114 {
2115     if (!IsSessionValid()) {
2116         return WSError::WS_ERROR_INVALID_SESSION;
2117     }
2118     if (GetWindowType() == WindowType::WINDOW_TYPE_DIALOG) {
2119         WLOGFI("[WMSDialog] this is dialog, id: %{public}d", GetPersistentId());
2120         return WSError::WS_OK;
2121     }
2122     return sessionStage_->HandleBackEvent();
2123 }
2124 
MarkProcessed(int32_t eventId)2125 WSError Session::MarkProcessed(int32_t eventId)
2126 {
2127     int32_t persistentId = GetPersistentId();
2128     WLOGFI("InputTracking persistentId:%{public}d, eventId:%{public}d", persistentId, eventId);
2129     DelayedSingleton<ANRManager>::GetInstance()->MarkProcessed(eventId, persistentId);
2130     return WSError::WS_OK;
2131 }
2132 
GeneratePersistentId(bool isExtension,int32_t persistentId)2133 void Session::GeneratePersistentId(bool isExtension, int32_t persistentId)
2134 {
2135     if (persistentId != INVALID_SESSION_ID  && !g_persistentIdSet.count(g_persistentId)) {
2136         g_persistentIdSet.insert(persistentId);
2137         persistentId_ = persistentId;
2138         return;
2139     }
2140 
2141     if (g_persistentId == INVALID_SESSION_ID) {
2142         g_persistentId++; // init non system session id from 2
2143     }
2144 
2145     g_persistentId++;
2146     while (g_persistentIdSet.count(g_persistentId)) {
2147         g_persistentId++;
2148     }
2149     persistentId_ = isExtension ? static_cast<uint32_t>(
2150         g_persistentId.load()) | 0x40000000 : static_cast<uint32_t>(g_persistentId.load()) & 0x3fffffff;
2151     g_persistentIdSet.insert(g_persistentId);
2152     WLOGFI("GeneratePersistentId, persistentId: %{public}d, persistentId_: %{public}d", persistentId, persistentId_);
2153 }
2154 
GetScenePersistence() const2155 sptr<ScenePersistence> Session::GetScenePersistence() const
2156 {
2157     return scenePersistence_;
2158 }
2159 
NotifyOccupiedAreaChangeInfo(sptr<OccupiedAreaChangeInfo> info)2160 void Session::NotifyOccupiedAreaChangeInfo(sptr<OccupiedAreaChangeInfo> info)
2161 {
2162     if (!sessionStage_) {
2163         WLOGFD("session stage is nullptr");
2164         return;
2165     }
2166     sessionStage_->NotifyOccupiedAreaChangeInfo(info);
2167 }
2168 
GetWindowMode()2169 WindowMode Session::GetWindowMode()
2170 {
2171     auto property = GetSessionProperty();
2172     if (property == nullptr) {
2173         WLOGFW("null property.");
2174         return WindowMode::WINDOW_MODE_UNDEFINED;
2175     }
2176     return property->GetWindowMode();
2177 }
2178 
UpdateMaximizeMode(bool isMaximize)2179 WSError Session::UpdateMaximizeMode(bool isMaximize)
2180 {
2181     WLOGFD("Session update maximize mode, isMaximize: %{public}d", isMaximize);
2182     if (!IsSessionValid()) {
2183         return WSError::WS_ERROR_INVALID_SESSION;
2184     }
2185     MaximizeMode mode = MaximizeMode::MODE_RECOVER;
2186     if (isMaximize) {
2187         mode = MaximizeMode::MODE_AVOID_SYSTEM_BAR;
2188     } else if (GetWindowMode() == WindowMode::WINDOW_MODE_FULLSCREEN) {
2189         mode = MaximizeMode::MODE_FULL_FILL;
2190     }
2191     property_->SetMaximizeMode(mode);
2192     return sessionStage_->UpdateMaximizeMode(mode);
2193 }
2194 
SetZOrder(uint32_t zOrder)2195 void Session::SetZOrder(uint32_t zOrder)
2196 {
2197     zOrder_ = zOrder;
2198     NotifySessionInfoChange();
2199 }
2200 
GetZOrder() const2201 uint32_t Session::GetZOrder() const
2202 {
2203     return zOrder_;
2204 }
2205 
SetUINodeId(uint32_t uiNodeId)2206 void Session::SetUINodeId(uint32_t uiNodeId)
2207 {
2208     if (uiNodeId_ != 0 && uiNodeId != 0 && !IsSystemSession()) {
2209         int32_t eventRet = HiSysEventWrite(
2210             OHOS::HiviewDFX::HiSysEvent::Domain::WINDOW_MANAGER,
2211             "REPEAT_SET_UI_NODE_ID",
2212             OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC,
2213             "PID", getpid(),
2214             "UID", getuid());
2215         WLOGE("[WMSLife] SetUINodeId: Repeat set UINodeId ret:%{public}d", eventRet);
2216         return;
2217     }
2218     uiNodeId_ = uiNodeId;
2219 }
2220 
GetUINodeId() const2221 uint32_t Session::GetUINodeId() const
2222 {
2223     return uiNodeId_;
2224 }
2225 
SetShowRecent(bool showRecent)2226 void Session::SetShowRecent(bool showRecent)
2227 {
2228     showRecent_ = showRecent;
2229 }
2230 
GetShowRecent() const2231 bool Session::GetShowRecent() const
2232 {
2233     return showRecent_;
2234 }
2235 
SetBufferAvailable(bool bufferAvailable)2236 void Session::SetBufferAvailable(bool bufferAvailable)
2237 {
2238     WLOGFI("SetBufferAvailable: %{public}d", bufferAvailable);
2239     if (bufferAvailableChangeFunc_) {
2240         bufferAvailableChangeFunc_(bufferAvailable);
2241     }
2242     bufferAvailable_ = bufferAvailable;
2243 }
2244 
GetBufferAvailable() const2245 bool Session::GetBufferAvailable() const
2246 {
2247     return bufferAvailable_;
2248 }
2249 
SetNeedSnapshot(bool needSnapshot)2250 void Session::SetNeedSnapshot(bool needSnapshot)
2251 {
2252     needSnapshot_ = needSnapshot;
2253 }
2254 
SetFloatingScale(float floatingScale)2255 void Session::SetFloatingScale(float floatingScale)
2256 {
2257     floatingScale_ = floatingScale;
2258 }
2259 
GetFloatingScale() const2260 float Session::GetFloatingScale() const
2261 {
2262     return floatingScale_;
2263 }
2264 
SetScale(float scaleX,float scaleY,float pivotX,float pivotY)2265 void Session::SetScale(float scaleX, float scaleY, float pivotX, float pivotY)
2266 {
2267     scaleX_ = scaleX;
2268     scaleY_ = scaleY;
2269     pivotX_ = pivotX;
2270     pivotY_ = pivotY;
2271 }
2272 
GetScaleX() const2273 float Session::GetScaleX() const
2274 {
2275     return scaleX_;
2276 }
2277 
GetScaleY() const2278 float Session::GetScaleY() const
2279 {
2280     return scaleY_;
2281 }
2282 
GetPivotX() const2283 float Session::GetPivotX() const
2284 {
2285     return pivotX_;
2286 }
2287 
GetPivotY() const2288 float Session::GetPivotY() const
2289 {
2290     return pivotY_;
2291 }
2292 
SetSCBKeepKeyboard(bool scbKeepKeyboardFlag)2293 void Session::SetSCBKeepKeyboard(bool scbKeepKeyboardFlag)
2294 {
2295     scbKeepKeyboardFlag_ = scbKeepKeyboardFlag;
2296 }
2297 
GetSCBKeepKeyboardFlag() const2298 bool Session::GetSCBKeepKeyboardFlag() const
2299 {
2300     return scbKeepKeyboardFlag_;
2301 }
2302 
SetOffset(float x,float y)2303 void Session::SetOffset(float x, float y)
2304 {
2305     offsetX_ = x;
2306     offsetY_ = y;
2307     WSRect newRect {
2308         .posX_ = std::round(bounds_.posX_ + x),
2309         .posY_ = std::round(bounds_.posY_ + y),
2310         .width_ = std::round(bounds_.width_),
2311         .height_ = std::round(bounds_.height_),
2312     };
2313     if (newRect != winRect_) {
2314         UpdateRect(newRect, SizeChangeReason::UNDEFINED);
2315     }
2316 }
2317 
GetOffsetX() const2318 float Session::GetOffsetX() const
2319 {
2320     return offsetX_;
2321 }
2322 
GetOffsetY() const2323 float Session::GetOffsetY() const
2324 {
2325     return offsetY_;
2326 }
2327 
SetBounds(const WSRectF & bounds)2328 void Session::SetBounds(const WSRectF& bounds)
2329 {
2330     bounds_ = bounds;
2331 }
2332 
GetBounds()2333 WSRectF Session::GetBounds()
2334 {
2335     return bounds_;
2336 }
2337 
TransferSearchElementInfo(int64_t elementId,int32_t mode,int64_t baseParent,std::list<Accessibility::AccessibilityElementInfo> & infos)2338 WSError Session::TransferSearchElementInfo(int64_t elementId, int32_t mode, int64_t baseParent,
2339     std::list<Accessibility::AccessibilityElementInfo>& infos)
2340 {
2341     if (!windowEventChannel_) {
2342         WLOGFE("windowEventChannel_ is null");
2343         return WSError::WS_ERROR_NULLPTR;
2344     }
2345     return windowEventChannel_->TransferSearchElementInfo(elementId, mode, baseParent, infos);
2346 }
2347 
TransferSearchElementInfosByText(int64_t elementId,const std::string & text,int64_t baseParent,std::list<Accessibility::AccessibilityElementInfo> & infos)2348 WSError Session::TransferSearchElementInfosByText(int64_t elementId, const std::string& text, int64_t baseParent,
2349     std::list<Accessibility::AccessibilityElementInfo>& infos)
2350 {
2351     if (!windowEventChannel_) {
2352         WLOGFE("windowEventChannel_ is null");
2353         return WSError::WS_ERROR_NULLPTR;
2354     }
2355     return windowEventChannel_->TransferSearchElementInfosByText(elementId, text, baseParent, infos);
2356 }
2357 
TransferFindFocusedElementInfo(int64_t elementId,int32_t focusType,int64_t baseParent,Accessibility::AccessibilityElementInfo & info)2358 WSError Session::TransferFindFocusedElementInfo(int64_t elementId, int32_t focusType, int64_t baseParent,
2359     Accessibility::AccessibilityElementInfo& info)
2360 {
2361     if (!windowEventChannel_) {
2362         WLOGFE("windowEventChannel_ is null");
2363         return WSError::WS_ERROR_NULLPTR;
2364     }
2365     return windowEventChannel_->TransferFindFocusedElementInfo(elementId, focusType, baseParent, info);
2366 }
2367 
TransferFocusMoveSearch(int64_t elementId,int32_t direction,int64_t baseParent,Accessibility::AccessibilityElementInfo & info)2368 WSError Session::TransferFocusMoveSearch(int64_t elementId, int32_t direction, int64_t baseParent,
2369     Accessibility::AccessibilityElementInfo& info)
2370 {
2371     if (!windowEventChannel_) {
2372         WLOGFE("windowEventChannel_ is null");
2373         return WSError::WS_ERROR_NULLPTR;
2374     }
2375     return windowEventChannel_->TransferFocusMoveSearch(elementId, direction, baseParent, info);
2376 }
2377 
TransferExecuteAction(int64_t elementId,const std::map<std::string,std::string> & actionArguments,int32_t action,int64_t baseParent)2378 WSError Session::TransferExecuteAction(int64_t elementId, const std::map<std::string, std::string>& actionArguments,
2379     int32_t action, int64_t baseParent)
2380 {
2381     if (!windowEventChannel_) {
2382         WLOGFE("windowEventChannel_ is null");
2383         return WSError::WS_ERROR_NULLPTR;
2384     }
2385     return windowEventChannel_->TransferExecuteAction(elementId, actionArguments, action, baseParent);
2386 }
2387 
SetSessionInfoLockedStateChangeListener(const NotifySessionInfoLockedStateChangeFunc & func)2388 void Session::SetSessionInfoLockedStateChangeListener(const NotifySessionInfoLockedStateChangeFunc& func)
2389 {
2390     sessionInfoLockedStateChangeFunc_ = func;
2391 }
2392 
NotifySessionInfoLockedStateChange(bool lockedState)2393 void Session::NotifySessionInfoLockedStateChange(bool lockedState)
2394 {
2395     WLOGFD("Notify sessioninfo lockedstate change: %{public}u", lockedState);
2396     if (sessionInfoLockedStateChangeFunc_) {
2397         sessionInfoLockedStateChangeFunc_(lockedState);
2398     }
2399 }
2400 
UpdateTitleInTargetPos(bool isShow,int32_t height)2401 WSError Session::UpdateTitleInTargetPos(bool isShow, int32_t height)
2402 {
2403     WLOGFD("Session update title in target position, id: %{public}d, isShow: %{public}d, height: %{public}d",
2404         GetPersistentId(), isShow, height);
2405     if (!IsSessionValid()) {
2406         return WSError::WS_ERROR_INVALID_SESSION;
2407     }
2408     return sessionStage_->UpdateTitleInTargetPos(isShow, height);
2409 }
2410 
NeedSystemPermission(WindowType type)2411 bool Session::NeedSystemPermission(WindowType type)
2412 {
2413     return !(WindowHelper::IsAppWindow(type) || type == WindowType::WINDOW_TYPE_UI_EXTENSION ||
2414         type == WindowType::WINDOW_TYPE_SCENE_BOARD || type == WindowType::WINDOW_TYPE_SYSTEM_FLOAT ||
2415         type == WindowType::WINDOW_TYPE_SYSTEM_SUB_WINDOW || type == WindowType::WINDOW_TYPE_TOAST ||
2416         type == WindowType::WINDOW_TYPE_DRAGGING_EFFECT || type == WindowType::WINDOW_TYPE_APP_LAUNCHING ||
2417         type == WindowType::WINDOW_TYPE_PIP);
2418 }
2419 
SetNotifySystemSessionPointerEventFunc(const NotifySystemSessionPointerEventFunc & func)2420 void Session::SetNotifySystemSessionPointerEventFunc(const NotifySystemSessionPointerEventFunc& func)
2421 {
2422     std::lock_guard<std::mutex> lock(pointerEventMutex_);
2423     systemSessionPointerEventFunc_ = func;
2424 }
2425 
SetNotifySystemSessionKeyEventFunc(const NotifySystemSessionKeyEventFunc & func)2426 void Session::SetNotifySystemSessionKeyEventFunc(const NotifySystemSessionKeyEventFunc& func)
2427 {
2428     std::lock_guard<std::mutex> lock(keyEventMutex_);
2429     systemSessionKeyEventFunc_ = func;
2430 }
2431 
NotifySessionInfoChange()2432 void Session::NotifySessionInfoChange()
2433 {
2434     if (sessionInfoChangeNotifyManagerFunc_) {
2435         sessionInfoChangeNotifyManagerFunc_(GetPersistentId());
2436     }
2437 }
2438 
IsSystemInput()2439 bool Session::IsSystemInput()
2440 {
2441     return sessionInfo_.isSystemInput_;
2442 }
2443 
SetTouchHotAreas(const std::vector<Rect> & touchHotAreas)2444 void Session::SetTouchHotAreas(const std::vector<Rect>& touchHotAreas)
2445 {
2446     auto property = GetSessionProperty();
2447     if (property == nullptr) {
2448         return;
2449     }
2450 
2451     property->SetTouchHotAreas(touchHotAreas);
2452 }
2453 
ResetSnapshot()2454 void Session::ResetSnapshot()
2455 {
2456     snapshot_.reset();
2457 }
2458 
GetSnapshotPixelMap(const float oriScale,const float newScale)2459 std::shared_ptr<Media::PixelMap> Session::GetSnapshotPixelMap(const float oriScale, const float newScale)
2460 {
2461     WLOGFI("GetSnapshotPixelMap id %{public}d", GetPersistentId());
2462     if (scenePersistence_ != nullptr && scenePersistence_->IsSavingSnapshot()) {
2463         return snapshot_;
2464     } else if (scenePersistence_ != nullptr && !scenePersistence_->IsSavingSnapshot()) {
2465         return scenePersistence_->GetLocalSnapshotPixelMap(oriScale, newScale);
2466     }
2467     return nullptr;
2468 }
2469 } // namespace OHOS::Rosen
2470