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