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 #ifndef OHOS_ROSEN_WINDOW_SCENE_SESSION_H
17 #define OHOS_ROSEN_WINDOW_SCENE_SESSION_H
18 #include <list>
19 #include <mutex>
20 #include <shared_mutex>
21 #include <vector>
22 
23 #include <event_handler.h>
24 
25 #include "accessibility_element_info.h"
26 #include "interfaces/include/ws_common.h"
27 #include "session/container/include/zidl/session_stage_interface.h"
28 #include "session/host/include/zidl/session_stub.h"
29 #include "session/host/include/scene_persistence.h"
30 #include "wm_common.h"
31 #include "occupied_area_change_info.h"
32 #include "window_visibility_info.h"
33 #include "pattern_detach_callback_interface.h"
34 
35 namespace OHOS::MMI {
36 class PointerEvent;
37 class KeyEvent;
38 class AxisEvent;
39 enum class WindowArea;
40 } // namespace OHOS::MMI
41 
42 namespace OHOS::Media {
43 class PixelMap;
44 } // namespace OHOS::Media
45 
46 namespace OHOS::Rosen {
47 class RSSurfaceNode;
48 class RSTransaction;
49 class RSSyncTransactionController;
50 using NotifySessionRectChangeFunc = std::function<void(const WSRect& rect, const SizeChangeReason& reason)>;
51 using NotifyPendingSessionActivationFunc = std::function<void(SessionInfo& info)>;
52 using NotifyChangeSessionVisibilityWithStatusBarFunc = std::function<void(SessionInfo& info, const bool visible)>;
53 using NotifySessionStateChangeFunc = std::function<void(const SessionState& state)>;
54 using NotifyBufferAvailableChangeFunc = std::function<void(const bool isAvailable)>;
55 using NotifySessionStateChangeNotifyManagerFunc = std::function<void(int32_t persistentId, const SessionState& state)>;
56 using NotifyRequestFocusStatusNotifyManagerFunc =
57     std::function<void(int32_t persistentId, const bool isFocused, const bool byForeground, FocusChangeReason reason)>;
58 using NotifyBackPressedFunc = std::function<void(const bool needMoveToBackground)>;
59 using NotifySessionFocusableChangeFunc = std::function<void(const bool isFocusable)>;
60 using NotifySessionTouchableChangeFunc = std::function<void(const bool touchable)>;
61 using NotifyClickFunc = std::function<void()>;
62 using NotifyTerminateSessionFunc = std::function<void(const SessionInfo& info)>;
63 using NotifyTerminateSessionFuncNew =
64     std::function<void(const SessionInfo& info, bool needStartCaller, bool isFromBroker)>;
65 using NotifyTerminateSessionFuncTotal = std::function<void(const SessionInfo& info, TerminateType terminateType)>;
66 using NofitySessionLabelUpdatedFunc = std::function<void(const std::string& label)>;
67 using NofitySessionIconUpdatedFunc = std::function<void(const std::string& iconPath)>;
68 using NotifySessionExceptionFunc = std::function<void(const SessionInfo& info, bool needRemoveSession, bool startFail)>;
69 using NotifySessionSnapshotFunc = std::function<void(const int32_t& persistentId)>;
70 using NotifyPendingSessionToForegroundFunc = std::function<void(const SessionInfo& info)>;
71 using NotifyPendingSessionToBackgroundForDelegatorFunc = std::function<void(const SessionInfo& info,
72     bool shouldBackToCaller)>;
73 using NotifyRaiseToTopForPointDownFunc = std::function<void()>;
74 using NotifyUIRequestFocusFunc = std::function<void()>;
75 using NotifyUILostFocusFunc = std::function<void()>;
76 using NotifySessionInfoLockedStateChangeFunc = std::function<void(const bool lockedState)>;
77 using GetStateFromManagerFunc = std::function<bool(const ManagerState key)>;
78 using NotifySystemSessionPointerEventFunc = std::function<void(std::shared_ptr<MMI::PointerEvent> pointerEvent)>;
79 using NotifySessionInfoChangeNotifyManagerFunc = std::function<void(int32_t persistentid)>;
80 using NotifySystemSessionKeyEventFunc = std::function<bool(std::shared_ptr<MMI::KeyEvent> keyEvent,
81     bool isPreImeEvent)>;
82 using NotifyContextTransparentFunc = std::function<void()>;
83 using NotifyFrameLayoutFinishFunc = std::function<void()>;
84 using AcquireRotateAnimationConfigFunc = std::function<void(RotateAnimationConfig& config)>;
85 
86 class ILifecycleListener {
87 public:
OnActivation()88     virtual void OnActivation() {}
OnConnect()89     virtual void OnConnect() {}
OnForeground()90     virtual void OnForeground() {}
OnBackground()91     virtual void OnBackground() {}
OnDisconnect()92     virtual void OnDisconnect() {}
OnLayoutFinished()93     virtual void OnLayoutFinished() {}
OnRemoveBlank()94     virtual void OnRemoveBlank() {}
OnDrawingCompleted()95     virtual void OnDrawingCompleted() {}
OnExtensionDied()96     virtual void OnExtensionDied() {}
OnExtensionDetachToDisplay()97     virtual void OnExtensionDetachToDisplay() {}
OnExtensionTimeout(int32_t errorCode)98     virtual void OnExtensionTimeout(int32_t errorCode) {}
OnAccessibilityEvent(const Accessibility::AccessibilityEventInfo & info,int64_t uiExtensionIdLevel)99     virtual void OnAccessibilityEvent(const Accessibility::AccessibilityEventInfo& info,
100         int64_t uiExtensionIdLevel) {}
OnAppRemoveStartingWindow()101     virtual void OnAppRemoveStartingWindow() {}
102 };
103 
104 enum class LifeCycleTaskType : uint32_t {
105     START,
106     STOP
107 };
108 
109 enum class DetectTaskState : uint32_t {
110     NO_TASK,
111     ATTACH_TASK,
112     DETACH_TASK
113 };
114 
115 struct DetectTaskInfo {
116     WindowMode taskWindowMode = WindowMode::WINDOW_MODE_UNDEFINED;
117     DetectTaskState taskState = DetectTaskState::NO_TASK;
118 };
119 
120 class Session : public SessionStub {
121 public:
122     using Task = std::function<void()>;
123     explicit Session(const SessionInfo& info);
124     virtual ~Session();
125     bool isKeyboardPanelEnabled_ = false;
126     void SetEventHandler(const std::shared_ptr<AppExecFwk::EventHandler>& handler,
127         const std::shared_ptr<AppExecFwk::EventHandler>& exportHandler = nullptr);
128 
129     /**
130      * Window LifeCycle
131      */
132     virtual WSError ConnectInner(const sptr<ISessionStage>& sessionStage, const sptr<IWindowEventChannel>& eventChannel,
133         const std::shared_ptr<RSSurfaceNode>& surfaceNode, SystemSessionConfig& systemConfig,
134         sptr<WindowSessionProperty> property = nullptr, sptr<IRemoteObject> token = nullptr,
135         int32_t pid = -1, int32_t uid = -1, const std::string& identityToken = "");
136     WSError Reconnect(const sptr<ISessionStage>& sessionStage, const sptr<IWindowEventChannel>& eventChannel,
137         const std::shared_ptr<RSSurfaceNode>& surfaceNode, sptr<WindowSessionProperty> property = nullptr,
138         sptr<IRemoteObject> token = nullptr, int32_t pid = -1, int32_t uid = -1);
139     WSError Foreground(sptr<WindowSessionProperty> property, bool isFromClient = false,
140         const std::string& identityToken = "") override;
141     WSError Background(bool isFromClient = false, const std::string& identityToken = "") override;
142     WSError Disconnect(bool isFromClient = false, const std::string& identityToken = "") override;
143     WSError Show(sptr<WindowSessionProperty> property) override;
144     WSError Hide() override;
145     WSError DrawingCompleted() override;
146     void ResetSessionConnectState();
147     void ResetIsActive();
148     WSError PendingSessionToForeground();
149     WSError PendingSessionToBackgroundForDelegator(bool shouldBackToCaller);
150     bool RegisterLifecycleListener(const std::shared_ptr<ILifecycleListener>& listener);
151     bool UnregisterLifecycleListener(const std::shared_ptr<ILifecycleListener>& listener);
152     void SetPendingSessionActivationEventListener(NotifyPendingSessionActivationFunc&& func);
153     void SetTerminateSessionListener(NotifyTerminateSessionFunc&& func);
154     void SetTerminateSessionListenerNew(NotifyTerminateSessionFuncNew&& func);
155     void SetSessionExceptionListener(NotifySessionExceptionFunc&& func, bool fromJsScene);
156     void SetTerminateSessionListenerTotal(NotifyTerminateSessionFuncTotal&& func);
157     void SetBackPressedListenser(NotifyBackPressedFunc&& func);
158     void SetPendingSessionToForegroundListener(NotifyPendingSessionToForegroundFunc&& func);
159     void SetPendingSessionToBackgroundForDelegatorListener(NotifyPendingSessionToBackgroundForDelegatorFunc&& func);
160     void SetSessionSnapshotListener(const NotifySessionSnapshotFunc& func);
161     WSError TerminateSessionNew(const sptr<AAFwk::SessionInfo> info, bool needStartCaller, bool isFromBroker);
162     WSError TerminateSessionTotal(const sptr<AAFwk::SessionInfo> info, TerminateType terminateType);
163 
164     /*
165      * Callbacks for ILifecycleListener
166      */
167     void NotifyActivation();
168     void NotifyConnect();
169     void NotifyForeground();
170     void NotifyBackground();
171     void NotifyDisconnect();
172     void NotifyLayoutFinished();
173     void NotifyRemoveBlank();
174     void NotifyExtensionDied() override;
175     void NotifyExtensionTimeout(int32_t errorCode) override;
176     void NotifyTransferAccessibilityEvent(const Accessibility::AccessibilityEventInfo& info,
177         int64_t uiExtensionIdLevel) override;
178     void NotifyExtensionDetachToDisplay() override;
179 
180     virtual WSError TransferPointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent,
181         bool needNotifyClient = true);
182     virtual WSError TransferKeyEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent);
183 
NotifyClientToUpdateRect(const std::string & updateReason,std::shared_ptr<RSTransaction> rsTransaction)184     virtual WSError NotifyClientToUpdateRect(const std::string& updateReason,
185         std::shared_ptr<RSTransaction> rsTransaction) { return WSError::WS_OK; }
186     WSError TransferBackPressedEventForConsumed(bool& isConsumed);
187     WSError TransferKeyEventForConsumed(const std::shared_ptr<MMI::KeyEvent>& keyEvent, bool& isConsumed,
188         bool isPreImeEvent = false);
189     WSError TransferFocusActiveEvent(bool isFocusActive);
190     WSError TransferFocusStateEvent(bool focusState);
UpdateAvoidArea(const sptr<AvoidArea> & avoidArea,AvoidAreaType type)191     virtual WSError UpdateAvoidArea(const sptr<AvoidArea>& avoidArea, AvoidAreaType type) { return WSError::WS_OK; }
192 
193     int32_t GetPersistentId() const;
194     std::shared_ptr<RSSurfaceNode> GetSurfaceNode() const;
195     void SetLeashWinSurfaceNode(std::shared_ptr<RSSurfaceNode> leashWinSurfaceNode);
196     std::shared_ptr<RSSurfaceNode> GetLeashWinSurfaceNode() const;
197     std::shared_ptr<Media::PixelMap> GetSnapshot() const;
198     std::shared_ptr<Media::PixelMap> Snapshot(bool runInFfrt = false, const float scaleParam = 0.0f) const;
199     void SaveSnapshot(bool useFfrt);
200     SessionState GetSessionState() const;
201     virtual void SetSessionState(SessionState state);
202     void SetSessionInfoAncoSceneState(int32_t ancoSceneState);
203     void SetSessionInfoTime(const std::string& time);
204     void SetSessionInfoAbilityInfo(const std::shared_ptr<AppExecFwk::AbilityInfo>& abilityInfo);
205     void SetSessionInfoWant(const std::shared_ptr<AAFwk::Want>& want);
206     void SetSessionInfoProcessOptions(const std::shared_ptr<AAFwk::ProcessOptions>& processOptions);
207     void ResetSessionInfoResultCode();
208     void SetSessionInfoPersistentId(int32_t persistentId);
209     void SetSessionInfoCallerPersistentId(int32_t callerPersistentId);
210     void SetSessionInfoContinueState(ContinueState state);
211     void SetSessionInfoLockedState(bool lockedState);
212     void SetSessionInfoIsClearSession(bool isClearSession);
213     void SetSessionInfoAffinity(std::string affinity);
214     void GetCloseAbilityWantAndClean(AAFwk::Want& outWant);
215     void SetSessionInfo(const SessionInfo& info);
216     const SessionInfo& GetSessionInfo() const;
217     DisplayId GetScreenId() const;
218     void SetScreenId(uint64_t screenId);
219     void SetScreenIdOnServer(uint64_t screenId);
220     WindowType GetWindowType() const;
221     float GetAspectRatio() const;
222     WSError SetAspectRatio(float ratio) override;
223     WSError SetSessionProperty(const sptr<WindowSessionProperty>& property);
224     sptr<WindowSessionProperty> GetSessionProperty() const;
225     void SetSessionRect(const WSRect& rect);
226     WSRect GetSessionRect() const;
227     WSRect GetSessionGlobalRect() const;
228     WMError GetGlobalScaledRect(Rect& globalScaledRect) override;
229     void SetSessionGlobalRect(const WSRect& rect);
230     void SetSessionRequestRect(const WSRect& rect);
231     WSRect GetSessionRequestRect() const;
232     std::string GetWindowName() const;
233     WSRect GetLastLayoutRect() const;
234     WSRect GetLayoutRect() const;
235 
236     virtual WSError SetActive(bool active);
237     virtual WSError UpdateSizeChangeReason(SizeChangeReason reason);
GetSizeChangeReason()238     SizeChangeReason GetSizeChangeReason() const { return reason_; }
239     virtual WSError UpdateRect(const WSRect& rect, SizeChangeReason reason,
240         const std::string& updateReason, const std::shared_ptr<RSTransaction>& rsTransaction = nullptr);
241     WSError UpdateDensity();
242     WSError UpdateOrientation();
243 
244     void SetShowRecent(bool showRecent);
245     void SetSystemActive(bool systemActive);
246     bool GetShowRecent() const;
247     void SetOffset(float x, float y);
248     float GetOffsetX() const;
249     float GetOffsetY() const;
250     void SetBounds(const WSRectF& bounds);
251     WSRectF GetBounds();
252     void SetRotation(Rotation rotation);
253     Rotation GetRotation() const;
254     void SetBufferAvailable(bool bufferAvailable);
255     bool GetBufferAvailable() const;
256     void SetNeedSnapshot(bool needSnapshot);
257     virtual void SetExitSplitOnBackground(bool isExitSplitOnBackground);
258     virtual bool IsExitSplitOnBackground() const;
NeedStartingWindowExitAnimation()259     virtual bool NeedStartingWindowExitAnimation() const { return true; }
260 
261     void SetChangeSessionVisibilityWithStatusBarEventListener(
262         const NotifyChangeSessionVisibilityWithStatusBarFunc& func);
263     WSError Clear(bool needStartCaller = false);
264     WSError SetSessionLabel(const std::string &label);
265     void SetUpdateSessionLabelListener(const NofitySessionLabelUpdatedFunc& func);
266     WSError SetSessionIcon(const std::shared_ptr<Media::PixelMap>& icon);
267     void SetUpdateSessionIconListener(const NofitySessionIconUpdatedFunc& func);
268     void SetSessionStateChangeListenser(const NotifySessionStateChangeFunc& func);
269     void SetBufferAvailableChangeListener(const NotifyBufferAvailableChangeFunc& func);
270     virtual void UnregisterSessionChangeListeners();
271     void SetSessionStateChangeNotifyManagerListener(const NotifySessionStateChangeNotifyManagerFunc& func);
272     void SetSessionInfoChangeNotifyManagerListener(const NotifySessionInfoChangeNotifyManagerFunc& func);
273     void SetRequestFocusStatusNotifyManagerListener(const NotifyRequestFocusStatusNotifyManagerFunc& func);
274     void SetNotifyUIRequestFocusFunc(const NotifyUIRequestFocusFunc& func);
275     void SetNotifyUILostFocusFunc(const NotifyUILostFocusFunc& func);
276     void SetGetStateFromManagerListener(const GetStateFromManagerFunc& func);
277 
278     void SetSystemConfig(const SystemSessionConfig& systemConfig);
279     void SetSnapshotScale(const float snapshotScale);
280     virtual WSError ProcessBackEvent(); // send back event to session_stage
281     WSError MarkProcessed(int32_t eventId) override;
282 
283     sptr<ScenePersistence> GetScenePersistence() const;
284     void SetParentSession(const sptr<Session>& session);
285     sptr<Session> GetParentSession() const;
286     sptr<Session> GetMainSession();
287     void BindDialogToParentSession(const sptr<Session>& session);
288     void RemoveDialogToParentSession(const sptr<Session>& session);
289     std::vector<sptr<Session>> GetDialogVector() const;
290     void ClearDialogVector();
291     WSError NotifyDestroy();
292     WSError NotifyCloseExistPipWindow();
293 
294     void SetSessionFocusableChangeListener(const NotifySessionFocusableChangeFunc& func);
295     void SetSessionTouchableChangeListener(const NotifySessionTouchableChangeFunc& func);
296     void SetClickListener(const NotifyClickFunc& func);
297     void NotifySessionFocusableChange(bool isFocusable);
298     void NotifySessionTouchableChange(bool touchable);
299     void NotifyClick();
300     bool GetStateFromManager(const ManagerState key);
301     virtual void PresentFoucusIfNeed(int32_t pointerAcrion);
302     virtual WSError UpdateWindowMode(WindowMode mode);
303     WSError SetCompatibleModeInPc(bool enable, bool isSupportDragInPcCompatibleMode);
304     WSError SetIsPcAppInPad(bool enable);
305     WSError SetCompatibleWindowSizeInPc(int32_t portraitWidth, int32_t portraitHeight,
306         int32_t landscapeWidth, int32_t landscapeHeight);
307     WSError SetAppSupportPhoneInPc(bool isSupportPhone);
308     WSError SetCompatibleModeEnableInPad(bool enable);
309     bool NeedNotify() const;
310     void SetNeedNotify(bool needNotify);
311     void SetStartingBeforeVisible(bool isStartingBeforeVisible);
312     bool GetStartingBeforeVisible() const;
313     WSError SetTouchable(bool touchable);
314     bool GetTouchable() const;
315     void SetForceTouchable(bool touchable);
316     virtual void SetSystemTouchable(bool touchable);
317     bool GetSystemTouchable() const;
318     virtual WSError SetRSVisible(bool isVisible);
319     bool GetRSVisible() const;
320     WSError SetVisibilityState(WindowVisibilityState state);
321     WindowVisibilityState GetVisibilityState() const;
322     WSError SetDrawingContentState(bool isRSDrawing);
323     bool GetDrawingContentState() const;
324     WSError SetBrightness(float brightness);
325     float GetBrightness() const;
326     void NotifyOccupiedAreaChangeInfo(sptr<OccupiedAreaChangeInfo> info,
327                                       const std::shared_ptr<RSTransaction>& rsTransaction = nullptr);
328     void SetSessionInfoLockedStateChangeListener(const NotifySessionInfoLockedStateChangeFunc& func);
329     void NotifySessionInfoLockedStateChange(bool lockedState);
330     void SetContextTransparentFunc(const NotifyContextTransparentFunc& func);
331     void NotifyContextTransparent();
332     bool NeedCheckContextTransparent() const;
333     void SetAcquireRotateAnimationConfigFunc(const AcquireRotateAnimationConfigFunc& func);
334 
335     /*
336      * Window Focus
337      */
338     virtual WSError SetSystemSceneBlockingFocus(bool blocking);
339     bool GetBlockingFocus() const;
340     WSError SetFocusable(bool isFocusable);
341     bool GetFocusable() const;
342     void SetFocusedOnShow(bool focusedOnShow); // Used when creating ability
343     bool IsFocusedOnShow() const;
344     WSError SetFocusableOnShow(bool isFocusableOnShow); // Used when showing window
345     bool IsFocusableOnShow() const;
346     bool IsFocused() const;
347     bool GetFocused() const;
348     virtual WSError UpdateFocus(bool isFocused);
349     virtual void PresentFocusIfPointDown();
350     WSError RequestFocus(bool isFocused) override;
351     void NotifyRequestFocusStatusNotifyManager(bool isFocused, bool byForeground = true,
352         FocusChangeReason reason = FocusChangeReason::DEFAULT);
353     void NotifyUIRequestFocus();
354     virtual void NotifyUILostFocus();
355     WSError NotifyFocusStatus(bool isFocused);
356 
357     /*
358      * Multi Window
359      */
360     void SetIsMidScene(bool isMidScene);
361     bool GetIsMidScene() const;
362 
363     /*
364      * Keyboard Window
365      */
366     bool CheckEmptyKeyboardAvoidAreaIfNeeded() const;
367 
368     bool IsSessionValid() const;
369     bool IsActive() const;
370     bool IsSystemActive() const;
371     bool IsSystemSession() const;
372     bool IsTerminated() const;
373     bool IsSessionForeground() const;
IsAnco()374     virtual bool IsAnco() const { return false; }
SetBlankFlag(bool isAddBlank)375     virtual void SetBlankFlag(bool isAddBlank) {};
GetBlankFlag()376     virtual bool GetBlankFlag() const { return false; }
GetBufferAvailableCallbackEnable()377     virtual bool GetBufferAvailableCallbackEnable() const { return false; }
378 
379     sptr<IRemoteObject> dialogTargetToken_ = nullptr;
380     int32_t GetWindowId() const;
381     void SetAppIndex(const int32_t appIndex);
382     int32_t GetAppIndex() const;
383     void SetCallingPid(int32_t id);
384     void SetCallingUid(int32_t id);
385     int32_t GetCallingPid() const;
386     int32_t GetCallingUid() const;
387     void SetAbilityToken(sptr<IRemoteObject> token);
388     sptr<IRemoteObject> GetAbilityToken() const;
389     WindowMode GetWindowMode() const;
390 
391     /*
392      * Window ZOrder
393      */
394     virtual void SetZOrder(uint32_t zOrder);
395     uint32_t GetZOrder() const;
396     uint32_t GetLastZOrder() const;
397 
398     void SetUINodeId(uint32_t uiNodeId);
399     uint32_t GetUINodeId() const;
400     virtual void SetFloatingScale(float floatingScale);
401     float GetFloatingScale() const;
402     virtual void SetScale(float scaleX, float scaleY, float pivotX, float pivotY);
403     float GetScaleX() const;
404     float GetScaleY() const;
405     float GetPivotX() const;
406     float GetPivotY() const;
407     void SetSCBKeepKeyboard(bool scbKeepKeyboardFlag);
408     bool GetSCBKeepKeyboardFlag() const;
409 
410     void SetRaiseToAppTopForPointDownFunc(const NotifyRaiseToTopForPointDownFunc& func);
411     void SetFrameLayoutFinishListener(const NotifyFrameLayoutFinishFunc& func);
412     void NotifyScreenshot();
413     void RemoveLifeCycleTask(const LifeCycleTaskType& taskType);
414     void PostLifeCycleTask(Task &&task, const std::string& name, const LifeCycleTaskType& taskType);
415     WSError UpdateMaximizeMode(bool isMaximize);
416     void NotifySessionForeground(uint32_t reason, bool withAnimation);
417     void NotifySessionBackground(uint32_t reason, bool withAnimation, bool isFromInnerkits);
418     void HandlePointDownDialog();
419     bool CheckDialogOnForeground();
420     std::shared_ptr<Media::PixelMap> GetSnapshotPixelMap(const float oriScale = 1.0f, const float newScale = 1.0f);
GetTouchHotAreas()421     virtual std::vector<Rect> GetTouchHotAreas() const
422     {
423         return std::vector<Rect>();
424     }
425 
426     virtual void SetTouchHotAreas(const std::vector<Rect>& touchHotAreas);
427 
SetVpr(float vpr)428     void SetVpr(float vpr)
429     {
430         vpr_ = vpr;
431     }
432 
433     bool operator==(const Session* session) const
434     {
435         if (session == nullptr) {
436             return false;
437         }
438         return (persistentId_ == session->persistentId_ && callingPid_ == session->callingPid_);
439     }
440 
441     bool operator!=(const Session* session) const
442     {
443         return !this->operator==(session);
444     }
445 
HandleStyleEvent(MMI::WindowArea area)446     virtual void HandleStyleEvent(MMI::WindowArea area) {};
447     WSError SetPointerStyle(MMI::WindowArea area);
448     const char* DumpPointerWindowArea(MMI::WindowArea area) const;
449     WSRectF UpdateHotRect(const WSRect& rect);
450     WSError RaiseToAppTopForPointDown();
451 
452     virtual void NotifyForegroundInteractiveStatus(bool interactive);
453     WSError UpdateTitleInTargetPos(bool isShow, int32_t height);
454     void SetNotifySystemSessionPointerEventFunc(const NotifySystemSessionPointerEventFunc& func);
455     void SetNotifySystemSessionKeyEventFunc(const NotifySystemSessionKeyEventFunc& func);
456     bool IsSystemInput();
457     // ForegroundInteractiveStatus interface only for event use
458     bool GetForegroundInteractiveStatus() const;
459     virtual void SetForegroundInteractiveStatus(bool interactive);
460 
461     /*
462      * Window Lifecycle
463      */
464     bool IsActivatedAfterScreenLocked() const;
465     void SetIsActivatedAfterScreenLocked(bool isActivatedAfterScreenLocked);
466     void SetAttachState(bool isAttach, WindowMode windowMode = WindowMode::WINDOW_MODE_UNDEFINED);
467     bool GetAttachState() const;
468     void RegisterDetachCallback(const sptr<IPatternDetachCallback>& callback);
469 
470     SystemSessionConfig GetSystemConfig() const;
471     void RectCheckProcess();
RectCheck(uint32_t curWidth,uint32_t curHeight)472     virtual void RectCheck(uint32_t curWidth, uint32_t curHeight) {};
473     void RectSizeCheckProcess(uint32_t curWidth, uint32_t curHeight, uint32_t minWidth,
474         uint32_t minHeight, uint32_t maxFloatingWindowSize);
475     DetectTaskInfo GetDetectTaskInfo() const;
476     void SetDetectTaskInfo(const DetectTaskInfo& detectTaskInfo);
477     WSError GetUIContentRemoteObj(sptr<IRemoteObject>& uiContentRemoteObj);
478     void CreateWindowStateDetectTask(bool isAttach, WindowMode windowMode);
479     void RegisterIsScreenLockedCallback(const std::function<bool()>& callback);
480     std::string GetWindowDetectTaskName() const;
481     void RemoveWindowDetectTask();
482     WSError SwitchFreeMultiWindow(bool enable);
GetCustomDecorHeight()483     virtual int32_t GetCustomDecorHeight()
484     {
485         return 0;
486     };
CheckGetAvoidAreaAvailable(AvoidAreaType type)487     virtual bool CheckGetAvoidAreaAvailable(AvoidAreaType type) { return true; }
488 
489     virtual bool IsVisibleForeground() const;
490     void SetIsStarting(bool isStarting);
491     void SetUIStateDirty(bool dirty);
492     void SetMainSessionUIStateDirty(bool dirty);
493     bool GetUIStateDirty() const;
494     void ResetDirtyFlags();
495     static bool IsScbCoreEnabled();
496     static void SetScbCoreEnabled(bool enabled);
IsNeedSyncScenePanelGlobalPosition()497     virtual bool IsNeedSyncScenePanelGlobalPosition() { return true; }
498 
499     /*
500      * Window Layout
501      */
502     void SetClientRect(const WSRect& rect);
503     WSRect GetClientRect() const;
504     void SetClientDragEnable(bool dragEnable);
505     std::optional<bool> GetClientDragEnable() const;
506 
507     /*
508      * Starting Window
509      */
510     WSError RemoveStartingWindow() override;
511     void SetEnableRemoveStartingWindow(bool enableRemoveStartingWindow);
512     bool GetEnableRemoveStartingWindow() const;
513     void SetAppBufferReady(bool appBufferReady);
514     bool GetAppBufferReady() const;
515     void SetUseStartingWindowAboveLocked(bool useStartingWindowAboveLocked);
516     bool UseStartingWindowAboveLocked() const;
517 
518     /**
519      * Free Multi Window
520      */
521     std::shared_ptr<Media::PixelMap> SetFreezeImmediately(float scaleParam, bool isFreeze) const;
522 
523     /*
524      * Screen Lock
525      */
526     bool IsScreenLockWindow() const;
527 
528 protected:
529     class SessionLifeCycleTask : public virtual RefBase {
530     public:
SessionLifeCycleTask(const Task & task,const std::string & name,const LifeCycleTaskType & type)531         SessionLifeCycleTask(const Task& task, const std::string& name, const LifeCycleTaskType& type)
532             : task(task), name(name), type(type) {}
533         Task task;
534         const std::string name;
535         LifeCycleTaskType type;
536         std::chrono::steady_clock::time_point startTime = std::chrono::steady_clock::now();
537         bool running = false;
538     };
539     void StartLifeCycleTask(sptr<SessionLifeCycleTask> lifeCycleTask);
540     void GeneratePersistentId(bool isExtension, int32_t persistentId);
541     virtual void UpdateSessionState(SessionState state);
542     void NotifySessionStateChange(const SessionState& state);
543     void UpdateSessionTouchable(bool touchable);
UpdateActiveStatus(bool isActive)544     virtual WSError UpdateActiveStatus(bool isActive) { return WSError::WS_OK; }
545 
546     /*
547      * Gesture Back
548      */
UpdateGestureBackEnabled()549     virtual void UpdateGestureBackEnabled() {}
550 
551     WSRectF UpdateTopBottomArea(const WSRectF& rect, MMI::WindowArea area);
552     WSRectF UpdateLeftRightArea(const WSRectF& rect, MMI::WindowArea area);
553     WSRectF UpdateInnerAngleArea(const WSRectF& rect, MMI::WindowArea area);
554     virtual void UpdatePointerArea(const WSRect& rect);
555     virtual bool CheckPointerEventDispatch(const std::shared_ptr<MMI::PointerEvent>& pointerEvent) const;
556     bool IsTopDialog() const;
557     void HandlePointDownDialog(int32_t pointAction);
558     void NotifySessionInfoChange();
559 
560     std::shared_ptr<AppExecFwk::EventHandler> GetEventHandler() const;
561     void PostTask(Task&& task, const std::string& name = "sessionTask", int64_t delayTime = 0);
562     void PostExportTask(Task&& task, const std::string& name = "sessionExportTask", int64_t delayTime = 0);
563     template<typename SyncTask, typename Return = std::invoke_result_t<SyncTask>>
564     Return PostSyncTask(SyncTask&& task, const std::string& name = "sessionTask")
565     {
566         Return ret;
567         if (!handler_ || handler_->GetEventRunner()->IsCurrentRunnerThread()) {
568             StartTraceForSyncTask(name);
569             ret = task();
570             FinishTraceForSyncTask();
571             return ret;
572         }
573         auto syncTask = [&ret, &task, name]() {
574             StartTraceForSyncTask(name);
575             ret = task();
576             FinishTraceForSyncTask();
577         };
578         handler_->PostSyncTask(std::move(syncTask), name, AppExecFwk::EventQueue::Priority::IMMEDIATE);
579         return ret;
580     }
581 
582     static std::shared_ptr<AppExecFwk::EventHandler> mainHandler_;
583     int32_t persistentId_ = INVALID_SESSION_ID;
584     std::atomic<SessionState> state_ = SessionState::STATE_DISCONNECT;
585     SessionInfo sessionInfo_;
586     std::recursive_mutex sessionInfoMutex_;
587     std::shared_ptr<RSSurfaceNode> surfaceNode_;
588     mutable std::mutex snapshotMutex_;
589     std::shared_ptr<Media::PixelMap> snapshot_;
590     sptr<ISessionStage> sessionStage_;
591     std::mutex lifeCycleTaskQueueMutex_;
592     std::list<sptr<SessionLifeCycleTask>> lifeCycleTaskQueue_;
593     bool isActive_ = false;
594     bool isSystemActive_ = false;
595     WSRectF bounds_;
596     Rotation rotation_;
597     float offsetX_ = 0.0f;
598     float offsetY_ = 0.0f;
599     std::atomic_bool isExitSplitOnBackground_ = false;
600     bool isVisible_ = false;
601 
602     NotifyChangeSessionVisibilityWithStatusBarFunc changeSessionVisibilityWithStatusBarFunc_;
603     NotifySessionStateChangeFunc sessionStateChangeFunc_;
604     NotifyBufferAvailableChangeFunc bufferAvailableChangeFunc_;
605     NotifySessionInfoChangeNotifyManagerFunc sessionInfoChangeNotifyManagerFunc_;
606     NotifySessionStateChangeNotifyManagerFunc sessionStateChangeNotifyManagerFunc_;
607     NotifyRequestFocusStatusNotifyManagerFunc requestFocusStatusNotifyManagerFunc_;
608     NotifyUIRequestFocusFunc requestFocusFunc_;
609     NotifyUILostFocusFunc lostFocusFunc_;
610     GetStateFromManagerFunc getStateFromManagerFunc_;
611     NotifySessionFocusableChangeFunc sessionFocusableChangeFunc_;
612     NotifySessionTouchableChangeFunc sessionTouchableChangeFunc_;
613     NotifyClickFunc clickFunc_;
614     NofitySessionLabelUpdatedFunc updateSessionLabelFunc_;
615     NofitySessionIconUpdatedFunc updateSessionIconFunc_;
616     NotifySessionSnapshotFunc notifySessionSnapshotFunc_;
617     NotifyRaiseToTopForPointDownFunc raiseToTopForPointDownFunc_;
618     NotifySessionInfoLockedStateChangeFunc sessionInfoLockedStateChangeFunc_;
619     NotifySystemSessionPointerEventFunc systemSessionPointerEventFunc_;
620     NotifySystemSessionKeyEventFunc systemSessionKeyEventFunc_;
621     NotifyContextTransparentFunc contextTransparentFunc_;
622     NotifyFrameLayoutFinishFunc frameLayoutFinishFunc_;
623 
624     /**
625      * Window LifeCycle
626      */
627     NotifyPendingSessionActivationFunc pendingSessionActivationFunc_;
628     NotifyPendingSessionToForegroundFunc pendingSessionToForegroundFunc_;
629     NotifyPendingSessionToBackgroundForDelegatorFunc pendingSessionToBackgroundForDelegatorFunc_;
630     NotifyBackPressedFunc backPressedFunc_;
631     NotifyTerminateSessionFunc terminateSessionFunc_;
632     NotifyTerminateSessionFuncNew terminateSessionFuncNew_;
633     NotifyTerminateSessionFuncTotal terminateSessionFuncTotal_;
634     NotifySessionExceptionFunc sessionExceptionFunc_;
635     NotifySessionExceptionFunc jsSceneSessionExceptionFunc_;
636 
637     AcquireRotateAnimationConfigFunc acquireRotateAnimationConfigFunc_;
638     SystemSessionConfig systemConfig_;
639     bool needSnapshot_ = false;
640     float snapshotScale_ = 0.5;
641     sptr<ScenePersistence> scenePersistence_ = nullptr;
642 
643     /*
644      * Window Layout
645      */
646     WSRect winRect_;
647     WSRect clientRect_; // rect saved when prelayout or notify client to update rect
648     WSRect lastLayoutRect_; // rect saved when go background
649     WSRect layoutRect_; // rect of root view
650     WSRect globalRect_; // globalRect include translate
651     mutable std::mutex globalRectMutex_;
652     SizeChangeReason reason_ = SizeChangeReason::UNDEFINED;
653     NotifySessionRectChangeFunc sessionRectChangeFunc_;
654     float clientScaleX_ = 1.0f;
655     float clientScaleY_ = 1.0f;
656     float clientPivotX_ = 0.0f;
657     float clientPivotY_ = 0.0f;
658     void SetClientScale(float scaleX, float scaleY, float pivotX, float pivotY);
659 
660     /*
661      * Window ZOrder
662      */
663     uint32_t zOrder_ = 0;
664     uint32_t lastZOrder_ = 0;
665 
666     /*
667      * Window Focus
668      */
669     bool isFocused_ = false;
670     bool blockingFocus_ {false};
671 
672     uint32_t uiNodeId_ = 0;
673     float aspectRatio_ = 0.0f;
674     std::map<MMI::WindowArea, WSRectF> windowAreas_;
675     bool isTerminating_ = false;
676     float floatingScale_ = 1.0f;
677     bool isDirty_ = false;
678     std::recursive_mutex sizeChangeMutex_;
679     float scaleX_ = 1.0f;
680     float scaleY_ = 1.0f;
681     float pivotX_ = 0.0f;
682     float pivotY_ = 0.0f;
683     bool scbKeepKeyboardFlag_ = false;
684     mutable std::shared_mutex dialogVecMutex_;
685     std::vector<sptr<Session>> dialogVec_;
686     mutable std::shared_mutex parentSessionMutex_;
687     sptr<Session> parentSession_;
688     sptr<IWindowEventChannel> windowEventChannel_;
689 
690     mutable std::mutex pointerEventMutex_;
691     mutable std::shared_mutex keyEventMutex_;
692     bool rectChangeListenerRegistered_ = false;
693 
694     /*
695      * Window Pipeline
696      */
697     uint32_t dirtyFlags_ = 0; // only accessed on SSM thread
698     bool isNeedSyncSessionRect_ { true }; // where need sync to session rect, currently use in split drag
699     bool isStarting_ = false;   // when start app, session is starting state until foreground
700     std::atomic_bool mainUIStateDirty_ = false;
701     static bool isScbCoreEnabled_;
702 
703 private:
704     void HandleDialogForeground();
705     void HandleDialogBackground();
706     WSError HandleSubWindowClick(int32_t action);
707     void NotifyPointerEventToRs(int32_t pointAction);
708 
709     template<typename T>
710     bool RegisterListenerLocked(std::vector<std::shared_ptr<T>>& holder, const std::shared_ptr<T>& listener);
711     template<typename T>
712     bool UnregisterListenerLocked(std::vector<std::shared_ptr<T>>& holder, const std::shared_ptr<T>& listener);
713     bool IsStateMatch(bool isAttach) const;
714     bool IsSupportDetectWindow(bool isAttach);
715     bool ShouldCreateDetectTask(bool isAttach, WindowMode windowMode) const;
716     bool ShouldCreateDetectTaskInRecent(bool newShowRecent, bool oldShowRecent, bool isAttach) const;
717     void CreateDetectStateTask(bool isAttach, WindowMode windowMode);
718     int32_t GetRotateAnimationDuration();
719 
720     /*
721      * Window Property
722      */
723     void InitSessionPropertyWhenConnect(const sptr<WindowSessionProperty>& property);
724     void InitSystemSessionDragEnable(const sptr<WindowSessionProperty>& property);
725 
726     /*
727      * Window Layout
728      */
729     void UpdateGravityWhenUpdateWindowMode(WindowMode mode);
730 
731     template<typename T1, typename T2, typename Ret>
732     using EnableIfSame = typename std::enable_if<std::is_same_v<T1, T2>, Ret>::type;
733     template<typename T>
GetListeners()734     inline EnableIfSame<T, ILifecycleListener, std::vector<std::weak_ptr<ILifecycleListener>>> GetListeners()
735     {
736         std::vector<std::weak_ptr<ILifecycleListener>> lifecycleListeners;
737         {
738             std::lock_guard<std::recursive_mutex> lock(lifecycleListenersMutex_);
739             for (auto& listener : lifecycleListeners_) {
740                 lifecycleListeners.push_back(listener);
741             }
742         }
743         return lifecycleListeners;
744     }
745 
746     std::recursive_mutex lifecycleListenersMutex_;
747     std::vector<std::shared_ptr<ILifecycleListener>> lifecycleListeners_;
748     std::shared_ptr<AppExecFwk::EventHandler> handler_;
749     std::shared_ptr<AppExecFwk::EventHandler> exportHandler_;
750     std::function<bool()> isScreenLockedCallback_;
751 
752     mutable std::shared_mutex propertyMutex_;
753     sptr<WindowSessionProperty> property_;
754 
755     /*
756      * Window Focus
757      */
758     mutable std::shared_mutex uiRequestFocusMutex_;
759     mutable std::shared_mutex uiLostFocusMutex_;
760     bool focusedOnShow_ = true;
761     bool focusableOnShow_ = true; // if false, ignore request focus when session onAttach
762     bool isStartingBeforeVisible_ = false;
763 
764     bool showRecent_ = false;
765     bool bufferAvailable_ = false;
766 
767     /*
768      * Multi Window
769      */
770     bool isMidScene_ = false;
771 
772     WSRect preRect_;
773     int32_t callingPid_ = -1;
774     int32_t callingUid_ = -1;
775     int32_t appIndex_ = { 0 };
776     std::string callingBundleName_ { "unknown" };
777     bool isRSVisible_ {false};
778     WindowVisibilityState visibilityState_ { WINDOW_LAYER_STATE_MAX};
779     bool needNotify_ {true};
780     bool isRSDrawing_ {false};
781     sptr<IRemoteObject> abilityToken_ = nullptr;
782     float vpr_ { 1.5f };
783     bool forceTouchable_ { true };
784     bool systemTouchable_ { true };
785     std::atomic_bool foregroundInteractiveStatus_ { true };
786 
787     /*
788      * Window Lifecycle
789      */
790     std::atomic<bool> isActivatedAfterScreenLocked_ { true };
791     std::atomic<bool> isAttach_{ false };
792     sptr<IPatternDetachCallback> detachCallback_ = nullptr;
793 
794     std::shared_ptr<RSSurfaceNode> leashWinSurfaceNode_;
795     mutable std::mutex leashWinSurfaceNodeMutex_;
796     DetectTaskInfo detectTaskInfo_;
797     mutable std::shared_mutex detectTaskInfoMutex_;
798 
799     /*
800      * Starting Window
801      */
802     bool enableRemoveStartingWindow_ { false };
803     bool appBufferReady_ { false };
804     bool useStartingWindowAboveLocked_ { false };
805 
806     /*
807      * Window Layout
808      */
809     std::optional<bool> clientDragEnable_;
810 
811     /*
812      * Screen Lock
813      */
814     bool isScreenLockWindow_ { false };
815 };
816 } // namespace OHOS::Rosen
817 
818 #endif // OHOS_ROSEN_WINDOW_SCENE_SESSION_H
819