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