• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "session/host/include/scene_session.h"
17 #include <parameters.h>
18 
19 #include <ability_manager_client.h>
20 #include <algorithm>
21 #include <climits>
22 #include <hitrace_meter.h>
23 #include <type_traits>
24 #ifdef IMF_ENABLE
25 #include <input_method_controller.h>
26 #endif // IMF_ENABLE
27 #include <ipc_skeleton.h>
28 #include <pointer_event.h>
29 #include <transaction/rs_sync_transaction_controller.h>
30 #include <transaction/rs_transaction.h>
31 #include <ui/rs_surface_node.h>
32 
33 #include "proxy/include/window_info.h"
34 
35 #include "common/include/session_permission.h"
36 #ifdef DEVICE_STATUS_ENABLE
37 #include "interaction_manager.h"
38 #endif // DEVICE_STATUS_ENABLE
39 #include "interfaces/include/ws_common.h"
40 #include "pixel_map.h"
41 #include "session/screen/include/screen_session.h"
42 #include "screen_session_manager/include/screen_session_manager_client.h"
43 #include "session/host/include/scene_persistent_storage.h"
44 #include "session/host/include/session_utils.h"
45 #include "display_manager.h"
46 #include "session_helper.h"
47 #include "window_helper.h"
48 #include "window_manager_hilog.h"
49 #include "wm_math.h"
50 #include <running_lock.h>
51 #include "screen_manager.h"
52 #include "screen.h"
53 #include "singleton_container.h"
54 #include "screen_session_manager/include/screen_session_manager_client.h"
55 #include "fold_screen_state_internel.h"
56 #include "session/host/include/ability_info_manager.h"
57 
58 #ifdef POWER_MANAGER_ENABLE
59 #include <power_mgr_client.h>
60 #endif
61 
62 namespace OHOS::Rosen {
63 namespace {
64 constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, HILOG_DOMAIN_WINDOW, "SceneSession" };
65 const std::string DLP_INDEX = "ohos.dlp.params.index";
66 constexpr const char* APP_CLONE_INDEX = "ohos.extra.param.key.appCloneIndex";
67 
CheckIfRectElementIsTooLarge(const WSRect & rect)68 bool CheckIfRectElementIsTooLarge(const WSRect& rect)
69 {
70     int32_t largeNumber = static_cast<int32_t>(SHRT_MAX);
71     if (rect.posX_ >= largeNumber || rect.posY_ >= largeNumber ||
72         rect.width_ >= largeNumber || rect.height_ >= largeNumber) {
73         return true;
74     }
75     return false;
76 }
77 } // namespace
78 
79 MaximizeMode SceneSession::maximizeMode_ = MaximizeMode::MODE_RECOVER;
80 wptr<SceneSession> SceneSession::enterSession_ = nullptr;
81 std::mutex SceneSession::enterSessionMutex_;
82 std::shared_mutex SceneSession::windowDragHotAreaMutex_;
83 std::map<uint32_t, WSRect> SceneSession::windowDragHotAreaMap_;
84 static bool g_enableForceUIFirst = system::GetParameter("window.forceUIFirst.enabled", "1") == "1";
85 GetConstrainedModalExtWindowInfoFunc SceneSession::onGetConstrainedModalExtWindowInfoFunc_;
86 
SceneSession(const SessionInfo & info,const sptr<SpecificSessionCallback> & specificCallback)87 SceneSession::SceneSession(const SessionInfo& info, const sptr<SpecificSessionCallback>& specificCallback)
88     : Session(info)
89 {
90     GeneratePersistentId(false, info.persistentId_);
91     specificCallback_ = specificCallback;
92     SetCollaboratorType(info.collaboratorType_);
93     TLOGI(WmsLogTag::WMS_LIFE, "Create session, id: %{public}d", GetPersistentId());
94 }
95 
~SceneSession()96 SceneSession::~SceneSession()
97 {
98     TLOGI(WmsLogTag::WMS_LIFE, "~SceneSession, id: %{public}d", GetPersistentId());
99 }
100 
ConnectInner(const sptr<ISessionStage> & sessionStage,const sptr<IWindowEventChannel> & eventChannel,const std::shared_ptr<RSSurfaceNode> & surfaceNode,SystemSessionConfig & systemConfig,sptr<WindowSessionProperty> property,sptr<IRemoteObject> token,int32_t pid,int32_t uid,const std::string & identityToken)101 WSError SceneSession::ConnectInner(const sptr<ISessionStage>& sessionStage,
102     const sptr<IWindowEventChannel>& eventChannel,
103     const std::shared_ptr<RSSurfaceNode>& surfaceNode, SystemSessionConfig& systemConfig,
104     sptr<WindowSessionProperty> property, sptr<IRemoteObject> token, int32_t pid, int32_t uid,
105     const std::string& identityToken)
106 {
107     auto task = [weakThis = wptr(this), sessionStage, eventChannel, surfaceNode, &systemConfig, property, token, pid,
108         uid, identityToken]() {
109         auto session = weakThis.promote();
110         if (!session) {
111             TLOGE(WmsLogTag::WMS_LIFE, "session is null");
112             return WSError::WS_ERROR_DESTROYED_OBJECT;
113         }
114 
115         if (SessionHelper::IsMainWindow(session->GetWindowType())) {
116             if (!session->CheckIdentityTokenIfMatched(identityToken)) {
117                 TLOGNW(WmsLogTag::WMS_LIFE, "check failed");
118                 return WSError::WS_OK;
119             }
120         }
121         if (property) {
122             property->SetCollaboratorType(session->GetCollaboratorType());
123         }
124         session->RetrieveStatusBarDefaultVisibility();
125         auto ret = session->Session::ConnectInner(
126             sessionStage, eventChannel, surfaceNode, systemConfig, property, token, pid, uid);
127         if (ret != WSError::WS_OK) {
128             return ret;
129         }
130         session->NotifySingleHandTransformChange(session->GetSingleHandTransform());
131         session->NotifyPropertyWhenConnect();
132         return ret;
133     };
134     return PostSyncTask(task, "ConnectInner");
135 }
136 
Connect(const sptr<ISessionStage> & sessionStage,const sptr<IWindowEventChannel> & eventChannel,const std::shared_ptr<RSSurfaceNode> & surfaceNode,SystemSessionConfig & systemConfig,sptr<WindowSessionProperty> property,sptr<IRemoteObject> token,const std::string & identityToken)137 WSError SceneSession::Connect(const sptr<ISessionStage>& sessionStage, const sptr<IWindowEventChannel>& eventChannel,
138     const std::shared_ptr<RSSurfaceNode>& surfaceNode, SystemSessionConfig& systemConfig,
139     sptr<WindowSessionProperty> property, sptr<IRemoteObject> token,
140     const std::string& identityToken)
141 {
142     // Get pid and uid before posting task.
143     int32_t pid = IPCSkeleton::GetCallingRealPid();
144     int32_t uid = IPCSkeleton::GetCallingUid();
145     return ConnectInner(sessionStage, eventChannel, surfaceNode, systemConfig,
146         property, token, pid, uid, identityToken);
147 }
148 
Reconnect(const sptr<ISessionStage> & sessionStage,const sptr<IWindowEventChannel> & eventChannel,const std::shared_ptr<RSSurfaceNode> & surfaceNode,sptr<WindowSessionProperty> property,sptr<IRemoteObject> token,int32_t pid,int32_t uid)149 WSError SceneSession::Reconnect(const sptr<ISessionStage>& sessionStage, const sptr<IWindowEventChannel>& eventChannel,
150     const std::shared_ptr<RSSurfaceNode>& surfaceNode, sptr<WindowSessionProperty> property, sptr<IRemoteObject> token,
151     int32_t pid, int32_t uid)
152 {
153     return PostSyncTask([weakThis = wptr(this), sessionStage, eventChannel, surfaceNode, property, token, pid, uid]() {
154         auto session = weakThis.promote();
155         if (!session) {
156             WLOGFE("session is null");
157             return WSError::WS_ERROR_DESTROYED_OBJECT;
158         }
159         WSError ret = session->Session::Reconnect(sessionStage, eventChannel, surfaceNode, property, token, pid, uid);
160         if (ret != WSError::WS_OK) {
161             return ret;
162         }
163         return session->ReconnectInner(property);
164     });
165 }
166 
ReconnectInner(sptr<WindowSessionProperty> property)167 WSError SceneSession::ReconnectInner(sptr<WindowSessionProperty> property)
168 {
169     if (property == nullptr) {
170         TLOGE(WmsLogTag::WMS_RECOVER, "property is nullptr");
171         return WSError::WS_ERROR_NULLPTR;
172     }
173     WindowState windowState = property->GetWindowState();
174     TLOGI(WmsLogTag::WMS_RECOVER, "persistentId: %{public}d, windowState: %{public}d ", GetPersistentId(), windowState);
175     WSError ret = WSError::WS_OK;
176     switch (windowState) {
177         case WindowState::STATE_INITIAL: {
178             TLOGE(WmsLogTag::WMS_RECOVER, "persistentId: %{public}d, invalid window state: STATE_INITIAL",
179                 GetPersistentId());
180             ret = WSError::WS_ERROR_INVALID_PARAM;
181             break;
182         }
183         case WindowState::STATE_CREATED:
184             break;
185         case WindowState::STATE_SHOWN: {
186             UpdateSessionState(SessionState::STATE_FOREGROUND);
187             UpdateActiveStatus(true);
188             break;
189         }
190         case WindowState::STATE_HIDDEN: {
191             UpdateSessionState(SessionState::STATE_BACKGROUND);
192             break;
193         }
194         default:
195             TLOGE(WmsLogTag::WMS_RECOVER, "persistentId: %{public}d, invalid window state: %{public}u",
196                 GetPersistentId(), windowState);
197             ret = WSError::WS_ERROR_INVALID_PARAM;
198             break;
199     }
200     if (ret != WSError::WS_OK) {
201         Session::Disconnect(false);
202     }
203     return ret;
204 }
205 
IsShowOnLockScreen(uint32_t lockScreenZOrder)206 bool SceneSession::IsShowOnLockScreen(uint32_t lockScreenZOrder)
207 {
208     TLOGD(WmsLogTag::WMS_UIEXT, "UIExtOnLock: lockScreenZOrder: %{public}d, zOrder_: %{public}d", lockScreenZOrder,
209         zOrder_);
210     // must be default screen
211     ScreenId defaultScreenId = ScreenSessionManagerClient::GetInstance().GetDefaultScreenId();
212     auto sessionProperty = GetSessionProperty();
213     if (sessionProperty != nullptr && defaultScreenId != sessionProperty->GetDisplayId()) {
214         TLOGD(WmsLogTag::WMS_UIEXT, "UIExtOnLock: not default display");
215         return false;
216     }
217     // current window on lock screen jurded by zorder
218     if (zOrder_ >= lockScreenZOrder) {
219         TLOGI(WmsLogTag::WMS_UIEXT, "UIExtOnLock: zOrder_ is no more than lockScreenZOrder");
220         return true;
221     }
222     return false;
223 }
224 
AddExtensionTokenInfo(const UIExtensionTokenInfo & tokenInfo)225 void SceneSession::AddExtensionTokenInfo(const UIExtensionTokenInfo& tokenInfo)
226 {
227     extensionTokenInfos_.push_back(tokenInfo);
228     TLOGI(WmsLogTag::WMS_UIEXT, "UIExtOnLock: canShowOnLockScreen: %{public}u, persistentId: %{public}d",
229         tokenInfo.canShowOnLockScreen, GetPersistentId());
230 }
231 
RemoveExtensionTokenInfo(const sptr<IRemoteObject> & abilityToken)232 void SceneSession::RemoveExtensionTokenInfo(const sptr<IRemoteObject>& abilityToken)
233 {
234     auto persistentId = GetPersistentId();
235     auto itr = std::remove_if(
236         extensionTokenInfos_.begin(), extensionTokenInfos_.end(), [&abilityToken, persistentId](const auto& tokenInfo) {
237             TLOGNI(WmsLogTag::WMS_UIEXT, "UIExtOnLock: need remove, token: %{public}u, persistentId: %{public}d",
238                 tokenInfo.callingTokenId, persistentId);
239             return tokenInfo.abilityToken == abilityToken;
240         });
241     extensionTokenInfos_.erase(itr, extensionTokenInfos_.end());
242 }
243 
OnNotifyAboveLockScreen()244 void SceneSession::OnNotifyAboveLockScreen()
245 {
246     CheckExtensionOnLockScreenToClose();
247 }
248 
CheckExtensionOnLockScreenToClose()249 void SceneSession::CheckExtensionOnLockScreenToClose()
250 {
251     TLOGD(WmsLogTag::WMS_UIEXT, "UIExtOnLock: %{public}d", GetPersistentId());
252     // 1. check sub session
253     for (auto& session : GetSubSession()) {
254         if (!session) {
255             TLOGE(WmsLogTag::WMS_UIEXT, "UIExtOnLock: session is null");
256             continue;
257         }
258         session->CheckExtensionOnLockScreenToClose();
259     }
260     // 2. check self permission
261     std::vector<UIExtensionTokenInfo> tokenInfosToClose;
262     for (auto& tokenInfo : extensionTokenInfos_) {
263         if (tokenInfo.canShowOnLockScreen) {
264             continue;
265         }
266         tokenInfosToClose.push_back(tokenInfo);
267     }
268     // 3. close ui extension without lock screen permisson
269     std::for_each(tokenInfosToClose.rbegin(), tokenInfosToClose.rend(),
270         [this](const UIExtensionTokenInfo& tokenInfo) { CloseExtensionSync(tokenInfo); });
271 }
272 
CloseExtensionSync(const UIExtensionTokenInfo & tokenInfo)273 void SceneSession::CloseExtensionSync(const UIExtensionTokenInfo& tokenInfo)
274 {
275     TLOGD(WmsLogTag::WMS_UIEXT, "UIExtOnLock");
276     // hide sub window
277     auto subSceneSessions = GetSubSession();
278     for (auto& session : subSceneSessions) {
279         if (!session) {
280             TLOGE(WmsLogTag::WMS_UIEXT, "UIExtOnLock: session is null");
281             continue;
282         }
283         // hide sub window of ui extension
284         if (session->GetAbilityToken() == tokenInfo.abilityToken) {
285             TLOGI(WmsLogTag::WMS_UIEXT, "UIExtOnLock: hide sub window %{public}u", session->GetWindowId());
286             session->HideSync();
287         }
288     }
289     TLOGI(WmsLogTag::WMS_UIEXT, "UIExtOnLock: close ui extension, callerToken: %{public}u, persistent id %{public}d",
290         tokenInfo.callingTokenId, GetPersistentId());
291     // kill ui extension ability
292     AAFwk::AbilityManagerClient::GetInstance()->CloseUIExtensionAbilityBySCB(tokenInfo.abilityToken);
293 }
294 
Foreground(sptr<WindowSessionProperty> property,bool isFromClient,const std::string & identityToken)295 WSError SceneSession::Foreground(
296     sptr<WindowSessionProperty> property, bool isFromClient, const std::string& identityToken)
297 {
298     if (!CheckPermissionWithPropertyAnimation(property)) {
299         return WSError::WS_ERROR_NOT_SYSTEM_APP;
300     }
301     if (isFromClient && SessionHelper::IsMainWindow(GetWindowType())) {
302         if (!CheckPidIfMatched() || !CheckIdentityTokenIfMatched(identityToken)) {
303             TLOGW(WmsLogTag::WMS_LIFE, "check failed");
304             return WSError::WS_OK;
305         }
306     }
307     return ForegroundTask(property);
308 }
309 
ForegroundTask(const sptr<WindowSessionProperty> & property)310 WSError SceneSession::ForegroundTask(const sptr<WindowSessionProperty>& property)
311 {
312     auto task = [weakThis = wptr(this), property]() {
313         auto session = weakThis.promote();
314         if (!session) {
315             TLOGE(WmsLogTag::WMS_LIFE, "session is null");
316             return WSError::WS_ERROR_DESTROYED_OBJECT;
317         }
318         auto sessionProperty = session->GetSessionProperty();
319         if (property && sessionProperty) {
320             sessionProperty->SetWindowMode(property->GetWindowMode());
321             sessionProperty->SetDecorEnable(property->IsDecorEnable());
322             session->SetFocusableOnShow(property->GetFocusableOnShow());
323         }
324         int32_t persistentId = session->GetPersistentId();
325         auto ret = session->Session::Foreground(property);
326         if (ret != WSError::WS_OK) {
327             TLOGE(WmsLogTag::WMS_LIFE, "session foreground failed, ret=%{public}d persistentId=%{public}d",
328                 ret, persistentId);
329             return ret;
330         }
331         session->NotifySingleHandTransformChange(session->GetSingleHandTransform());
332         auto leashWinSurfaceNode = session->GetLeashWinSurfaceNode();
333         if (leashWinSurfaceNode && sessionProperty) {
334             bool lastPrivacyMode = sessionProperty->GetPrivacyMode() || sessionProperty->GetSystemPrivacyMode();
335             leashWinSurfaceNode->SetSecurityLayer(lastPrivacyMode);
336         }
337         if (session->specificCallback_ != nullptr) {
338             if (Session::IsScbCoreEnabled()) {
339                 session->MarkAvoidAreaAsDirty();
340             } else {
341                 session->specificCallback_->onUpdateAvoidArea_(persistentId);
342             }
343             session->specificCallback_->onWindowInfoUpdate_(
344                 persistentId, WindowUpdateType::WINDOW_UPDATE_ADDED);
345             session->specificCallback_->onHandleSecureSessionShouldHide_(session);
346             session->UpdateGestureBackEnabled();
347         } else {
348             TLOGI(WmsLogTag::WMS_LIFE, "foreground specific callback does not take effect, callback function null");
349         }
350         return WSError::WS_OK;
351     };
352     PostTask(task, "Foreground");
353     return WSError::WS_OK;
354 }
355 
Background(bool isFromClient,const std::string & identityToken)356 WSError SceneSession::Background(bool isFromClient, const std::string& identityToken)
357 {
358     if (!CheckPermissionWithPropertyAnimation(GetSessionProperty())) {
359         return WSError::WS_ERROR_NOT_SYSTEM_APP;
360     }
361 
362     if (isFromClient && SessionHelper::IsMainWindow(GetWindowType())) {
363         if (!CheckPidIfMatched() || !CheckIdentityTokenIfMatched(identityToken)) {
364             TLOGW(WmsLogTag::WMS_LIFE, "check failed");
365             return WSError::WS_OK;
366         }
367     }
368 
369     return BackgroundTask(true);
370 }
371 
NotifyFrameLayoutFinishFromApp(bool notifyListener,const WSRect & rect)372 WSError SceneSession::NotifyFrameLayoutFinishFromApp(bool notifyListener, const WSRect& rect)
373 {
374     TLOGI(WmsLogTag::WMS_LAYOUT, "%{public}d, %{public}s", notifyListener, rect.ToString().c_str());
375     auto task = [weakThis = wptr(this), notifyListener, rect]() {
376         auto session = weakThis.promote();
377         if (!session) {
378             TLOGE(WmsLogTag::WMS_MULTI_WINDOW, "session is null");
379             return WSError::WS_ERROR_DESTROYED_OBJECT;
380         }
381         session->layoutRect_ = rect;
382         session->NotifyLayoutFinished();
383         if (notifyListener && session->frameLayoutFinishFunc_) {
384             TLOGD(WmsLogTag::WMS_MULTI_WINDOW, "id: %{public}d", session->GetPersistentId());
385             session->frameLayoutFinishFunc_();
386         }
387         return WSError::WS_OK;
388     };
389     PostTask(task, "NotifyFrameLayoutFinishFromApp");
390     return WSError::WS_OK;
391 }
392 
BackgroundTask(const bool isSaveSnapshot)393 WSError SceneSession::BackgroundTask(const bool isSaveSnapshot)
394 {
395     auto task = [weakThis = wptr(this), isSaveSnapshot]() {
396         auto session = weakThis.promote();
397         if (!session) {
398             TLOGE(WmsLogTag::WMS_LIFE, "session is null");
399             return WSError::WS_ERROR_DESTROYED_OBJECT;
400         }
401         auto state = session->GetSessionState();
402         if (state == SessionState::STATE_BACKGROUND) {
403             return WSError::WS_OK;
404         }
405         auto ret = session->Session::Background();
406         if (ret != WSError::WS_OK) {
407             return ret;
408         }
409         if (WindowHelper::IsMainWindow(session->GetWindowType()) && isSaveSnapshot) {
410             session->SaveSnapshot(true);
411         }
412         if (session->specificCallback_ != nullptr) {
413             if (Session::IsScbCoreEnabled()) {
414                 session->MarkAvoidAreaAsDirty();
415             } else {
416                 session->specificCallback_->onUpdateAvoidArea_(session->GetPersistentId());
417             }
418             session->specificCallback_->onWindowInfoUpdate_(
419                 session->GetPersistentId(), WindowUpdateType::WINDOW_UPDATE_REMOVED);
420             session->specificCallback_->onHandleSecureSessionShouldHide_(session);
421             session->UpdateGestureBackEnabled();
422         }
423         return WSError::WS_OK;
424     };
425     PostTask(task, "Background");
426     return WSError::WS_OK;
427 }
428 
ClearSpecificSessionCbMap()429 void SceneSession::ClearSpecificSessionCbMap()
430 {
431     auto task = [weakThis = wptr(this)]() {
432         auto session = weakThis.promote();
433         if (!session) {
434             TLOGE(WmsLogTag::WMS_SYSTEM, "session is null");
435             return;
436         }
437         if (session->clearCallbackMapFunc_) {
438             session->clearCallbackMapFunc_(true, session->GetPersistentId());
439             TLOGD(WmsLogTag::WMS_SYSTEM, "ClearCallbackMap, id: %{public}d", session->GetPersistentId());
440         } else {
441             TLOGE(WmsLogTag::WMS_SYSTEM, "get callback failed, id: %{public}d", session->GetPersistentId());
442         }
443     };
444     PostTask(task, "ClearSpecificSessionCbMap");
445 }
446 
RegisterShowWhenLockedCallback(NotifyShowWhenLockedFunc && callback)447 void SceneSession::RegisterShowWhenLockedCallback(NotifyShowWhenLockedFunc&& callback)
448 {
449     const char* const where = __func__;
450     auto task = [weakThis = wptr(this), callback = std::move(callback), where] {
451         auto session = weakThis.promote();
452         if (!session) {
453             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session is nullptr", where);
454             return;
455         }
456         session->onShowWhenLockedFunc_ = std::move(callback);
457         session->onShowWhenLockedFunc_(session->GetShowWhenLockedFlagValue());
458     };
459     PostTask(task, where);
460 }
461 
RegisterForceHideChangeCallback(NotifyForceHideChangeFunc && callback)462 void SceneSession::RegisterForceHideChangeCallback(NotifyForceHideChangeFunc&& callback)
463 {
464     const char* const where = __func__;
465     auto task = [weakThis = wptr(this), callback = std::move(callback), where] {
466         auto session = weakThis.promote();
467         if (!session) {
468             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session is nullptr", where);
469             return;
470         }
471         session->onForceHideChangeFunc_ = std::move(callback);
472     };
473     PostTask(task, where);
474 }
475 
RegisterClearCallbackMapCallback(ClearCallbackMapFunc && callback)476 void SceneSession::RegisterClearCallbackMapCallback(ClearCallbackMapFunc&& callback)
477 {
478     const char* const where = __func__;
479     auto task = [weakThis = wptr(this), callback = std::move(callback), where] {
480         auto session = weakThis.promote();
481         if (!session) {
482             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session is nullptr", where);
483             return;
484         }
485         session->clearCallbackMapFunc_ = std::move(callback);
486     };
487     PostTask(task, where);
488 }
489 
Disconnect(bool isFromClient,const std::string & identityToken)490 WSError SceneSession::Disconnect(bool isFromClient, const std::string& identityToken)
491 {
492     if (isFromClient && SessionHelper::IsMainWindow(GetWindowType())) {
493         if (!CheckPidIfMatched() || !CheckIdentityTokenIfMatched(identityToken)) {
494             TLOGW(WmsLogTag::WMS_LIFE, "check failed");
495             return WSError::WS_OK;
496         }
497     }
498 
499     return DisconnectTask(isFromClient, true);
500 }
501 
DisconnectTask(bool isFromClient,bool isSaveSnapshot)502 WSError SceneSession::DisconnectTask(bool isFromClient, bool isSaveSnapshot)
503 {
504     PostTask([weakThis = wptr(this), isFromClient, isSaveSnapshot]() {
505         auto session = weakThis.promote();
506         if (!session) {
507             TLOGE(WmsLogTag::WMS_LIFE, "session is null");
508             return WSError::WS_ERROR_DESTROYED_OBJECT;
509         }
510         if (isFromClient) {
511             TLOGI(WmsLogTag::WMS_LIFE, "Client need notify destroy session, id: %{public}d",
512                 session->GetPersistentId());
513             session->SetSessionState(SessionState::STATE_DISCONNECT);
514             return WSError::WS_OK;
515         }
516         auto state = session->GetSessionState();
517         auto isMainWindow = SessionHelper::IsMainWindow(session->GetWindowType());
518         if ((session->needSnapshot_ || (state == SessionState::STATE_ACTIVE && isMainWindow)) && isSaveSnapshot) {
519             session->SaveSnapshot(false);
520         }
521         session->Session::Disconnect(isFromClient);
522         session->isTerminating_ = false;
523         if (session->specificCallback_ != nullptr) {
524             session->specificCallback_->onHandleSecureSessionShouldHide_(session);
525             session->isEnableGestureBack_ = true;
526             session->UpdateGestureBackEnabled();
527             session->isEnableGestureBackHadSet_ = false;
528         }
529         return WSError::WS_OK;
530     },
531         "Disconnect");
532     return WSError::WS_OK;
533 }
534 
UpdateActiveStatus(bool isActive)535 WSError SceneSession::UpdateActiveStatus(bool isActive)
536 {
537     auto task = [weakThis = wptr(this), isActive]() {
538         auto session = weakThis.promote();
539         if (!session) {
540             WLOGFE("[WMSCom] session is null");
541             return WSError::WS_ERROR_DESTROYED_OBJECT;
542         }
543         if (!session->IsSessionValid()) {
544             TLOGW(WmsLogTag::WMS_MAIN, "Session is invalid, id: %{public}d state: %{public}u",
545                 session->GetPersistentId(), session->GetSessionState());
546             return WSError::WS_ERROR_INVALID_SESSION;
547         }
548         if (isActive == session->isActive_) {
549             WLOGFD("[WMSCom] Session active do not change: %{public}d", isActive);
550             return WSError::WS_DO_NOTHING;
551         }
552 
553         WSError ret = WSError::WS_DO_NOTHING;
554         if (isActive && session->GetSessionState() == SessionState::STATE_FOREGROUND) {
555             session->UpdateSessionState(SessionState::STATE_ACTIVE);
556             session->isActive_ = isActive;
557             ret = WSError::WS_OK;
558         }
559         if (!isActive && session->GetSessionState() == SessionState::STATE_ACTIVE) {
560             session->UpdateSessionState(SessionState::STATE_INACTIVE);
561             session->isActive_ = isActive;
562             ret = WSError::WS_OK;
563         }
564         WLOGFI("[WMSCom] UpdateActiveStatus, isActive: %{public}d, state: %{public}u",
565             session->isActive_, session->GetSessionState());
566         return ret;
567     };
568     PostTask(task, "UpdateActiveStatus:" + std::to_string(isActive));
569     return WSError::WS_OK;
570 }
571 
CalcRectForStatusBar()572 DMRect SceneSession::CalcRectForStatusBar()
573 {
574     DMRect statusBarRect = {0, 0, 0, 0};
575     if (specificCallback_ == nullptr || specificCallback_->onGetSceneSessionVectorByTypeAndDisplayId_ == nullptr) {
576         TLOGE(WmsLogTag::WMS_KEYBOARD, "specificCallback is null");
577         return statusBarRect;
578     }
579     const auto& statusBarVector = specificCallback_->onGetSceneSessionVectorByTypeAndDisplayId_(
580         WindowType::WINDOW_TYPE_STATUS_BAR, GetSessionProperty()->GetDisplayId());
581     for (auto& statusBar : statusBarVector) {
582         if (statusBar == nullptr) {
583             continue;
584         }
585         if (statusBar->IsVisible() &&
586             static_cast<uint32_t>(statusBar->GetSessionRect().height_) > statusBarRect.height_) {
587             statusBarRect.height_ = static_cast<uint32_t>(statusBar->GetSessionRect().height_);
588         }
589         if (static_cast<uint32_t>(statusBar->GetSessionRect().width_) > statusBarRect.width_) {
590             statusBarRect.width_ = static_cast<uint32_t>(statusBar->GetSessionRect().width_);
591         }
592     }
593     TLOGD(
594         WmsLogTag::WMS_KEYBOARD, "width: %{public}d, height: %{public}d", statusBarRect.width_, statusBarRect.height_);
595     return statusBarRect;
596 }
597 
SetMoveAvailableArea(DisplayId displayId)598 WSError SceneSession::SetMoveAvailableArea(DisplayId displayId)
599 {
600     sptr<Display> display = DisplayManager::GetInstance().GetDisplayById(displayId);
601     if (display == nullptr) {
602         TLOGE(WmsLogTag::WMS_KEYBOARD, "fail to get display");
603         return WSError::WS_ERROR_INVALID_DISPLAY;
604     }
605 
606     DMRect availableArea;
607     DMError ret = display->GetAvailableArea(availableArea);
608     if (ret != DMError::DM_OK) {
609         TLOGE(WmsLogTag::WMS_KEYBOARD, "Failed to get available area, ret: %{public}d", ret);
610         return WSError::WS_ERROR_INVALID_DISPLAY;
611     }
612 
613     DMRect statusBarRect = CalcRectForStatusBar();
614     if (systemConfig_.uiType_ == UI_TYPE_PAD || systemConfig_.uiType_ == UI_TYPE_PHONE) {
615         uint32_t statusBarHeight = statusBarRect.height_;
616         if (static_cast<int32_t>(statusBarHeight) > availableArea.posY_) {
617             availableArea.posY_ = static_cast<int32_t>(statusBarHeight);
618         }
619 
620         sptr<ScreenSession> currentScreenSession =
621             ScreenSessionManagerClient::GetInstance().GetScreenSessionById(GetSessionProperty()->GetDisplayId());
622         if (currentScreenSession == nullptr) {
623             TLOGW(WmsLogTag::WMS_KEYBOARD, "Screen session is null");
624             return WSError::WS_ERROR_INVALID_DISPLAY;
625         }
626         uint32_t currentScreenHeight = currentScreenSession->GetScreenProperty().GetBounds().rect_.height_;
627         availableArea.height_ = currentScreenHeight - static_cast<uint32_t>(availableArea.posY_);
628     }
629 
630     bool isFoldable = ScreenSessionManagerClient::GetInstance().IsFoldable();
631     if (systemConfig_.uiType_ == UI_TYPE_PHONE && isFoldable && statusBarRect.width_) {
632         availableArea.width_ = statusBarRect.width_;
633     }
634     TLOGD(WmsLogTag::WMS_KEYBOARD,
635           "the available area x is: %{public}d, y is: %{public}d, width is: %{public}d, height is: %{public}d",
636           availableArea.posX_, availableArea.posY_, availableArea.width_, availableArea.height_);
637     moveDragController_->SetMoveAvailableArea(availableArea);
638     return WSError::WS_OK;
639 }
640 
InitializeMoveInputBar()641 WSError SceneSession::InitializeMoveInputBar()
642 {
643     auto property = GetSessionProperty();
644     WindowType windowType = property->GetWindowType();
645     if (WindowHelper::IsInputWindow(windowType)) {
646         TLOGD(WmsLogTag::WMS_KEYBOARD, "Start init move input bar param");
647         DisplayId displayId = property->GetDisplayId();
648 
649         WSError ret = SetMoveAvailableArea(displayId);
650         if (ret != WSError::WS_OK) {
651             TLOGD(WmsLogTag::WMS_KEYBOARD, "set move availableArea error");
652             return WSError::WS_ERROR_INVALID_OPERATION;
653         }
654         moveDragController_->SetMoveInputBarStartDisplayId(displayId);
655     }
656     return WSError::WS_OK;
657 }
658 
OnSessionEvent(SessionEvent event)659 WSError SceneSession::OnSessionEvent(SessionEvent event)
660 {
661     auto task = [weakThis = wptr(this), event]() {
662         auto session = weakThis.promote();
663         if (!session) {
664             WLOGFE("[WMSCom] session is null");
665             return WSError::WS_ERROR_DESTROYED_OBJECT;
666         }
667         WLOGFI("[WMSCom] SceneSession OnSessionEvent event: %{public}d", static_cast<int32_t>(event));
668         if (event == SessionEvent::EVENT_START_MOVE) {
669             if (!session->IsMovable()) {
670                 TLOGW(WmsLogTag::WMS_LAYOUT, "Window is not movable, id: %{public}d", session->GetPersistentId());
671                 return WSError::WS_OK;
672             }
673             HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "SceneSession::StartMove");
674             WSError ret = session->InitializeMoveInputBar();
675             if (ret != WSError::WS_OK) {
676                 return ret;
677             }
678             session->moveDragController_->InitMoveDragProperty();
679             if (session->IsFullScreenMovable()) {
680                 WSRect rect = session->moveDragController_->GetFullScreenToFloatingRect(session->winRect_,
681                     session->GetSessionRequestRect());
682                 session->Session::UpdateRect(rect, SizeChangeReason::RECOVER, "OnSessionEvent", nullptr);
683                 session->moveDragController_->SetStartMoveFlag(true);
684                 session->moveDragController_->CalcFirstMoveTargetRect(rect, true);
685             } else {
686                 session->moveDragController_->SetStartMoveFlag(true);
687                 session->moveDragController_->CalcFirstMoveTargetRect(session->winRect_, false);
688             }
689             session->SetSessionEventParam({session->moveDragController_->GetOriginalPointerPosX(),
690                 session->moveDragController_->GetOriginalPointerPosY()});
691         }
692         session->HandleSessionDragEvent(event);
693         if (session->sessionChangeCallback_ && session->sessionChangeCallback_->OnSessionEvent_) {
694             session->sessionChangeCallback_->OnSessionEvent_(static_cast<uint32_t>(event),
695                 session->sessionEventParam_);
696         }
697         return WSError::WS_OK;
698     };
699     PostTask(task, "OnSessionEvent:" + std::to_string(static_cast<int>(event)));
700     return WSError::WS_OK;
701 }
702 
HandleSessionDragEvent(SessionEvent event)703 void SceneSession::HandleSessionDragEvent(SessionEvent event)
704 {
705     if (moveDragController_ &&
706         (event == SessionEvent::EVENT_DRAG || event == SessionEvent::EVENT_DRAG_START)) {
707         WSRect rect = moveDragController_->GetTargetRect();
708         DragResizeType dragResizeType = DragResizeType::RESIZE_TYPE_UNDEFINED;
709         if (event == SessionEvent::EVENT_DRAG_START) {
710             dragResizeType = GetAppDragResizeType();
711             SetDragResizeTypeDuringDrag(dragResizeType);
712         }
713         SetSessionEventParam({rect.posX_, rect.posY_, rect.width_, rect.height_,
714             static_cast<uint32_t>(dragResizeType)});
715     }
716 }
717 
SyncSessionEvent(SessionEvent event)718 WSError SceneSession::SyncSessionEvent(SessionEvent event)
719 {
720     if (event != SessionEvent::EVENT_START_MOVE && event != SessionEvent::EVENT_END_MOVE) {
721         TLOGE(WmsLogTag::WMS_LAYOUT, "This is not start move event or end move event, "
722             "eventId=%{public}u windowId=%{public}d", event, GetPersistentId());
723         return WSError::WS_ERROR_NULLPTR;
724     }
725     const char* const funcName = __func__;
726     return PostSyncTask([weakThis = wptr(this), event, funcName] {
727         auto session = weakThis.promote();
728         if (!session || !session->moveDragController_) {
729             TLOGNW(WmsLogTag::WMS_LAYOUT, "%{public}s: session or moveDragController is null", funcName);
730             return WSError::WS_ERROR_NULLPTR;
731         }
732         if (event == SessionEvent::EVENT_END_MOVE) {
733             if (!session->moveDragController_->GetStartMoveFlag()) {
734                 TLOGNW(WmsLogTag::WMS_LAYOUT_PC, "Repeat operation, window is not moving");
735                 return WSError::WS_OK;
736             }
737             session->moveDragController_->StopMoving();
738             return WSError::WS_OK;
739         }
740         if (session->moveDragController_->GetStartMoveFlag()) {
741             TLOGNW(WmsLogTag::WMS_LAYOUT, "%{public}s: Repeat operation, system window is moving", funcName);
742             return WSError::WS_ERROR_REPEAT_OPERATION;
743         }
744         session->OnSessionEvent(event);
745         return WSError::WS_OK;
746     }, funcName);
747 }
748 
StartMovingWithCoordinate(int32_t offsetX,int32_t offsetY,int32_t pointerPosX,int32_t pointerPosY)749 WSError SceneSession::StartMovingWithCoordinate(int32_t offsetX, int32_t offsetY,
750     int32_t pointerPosX, int32_t pointerPosY)
751 {
752     return PostSyncTask([weakThis = wptr(this), offsetX, offsetY, pointerPosX, pointerPosY, where = __func__] {
753         auto session = weakThis.promote();
754         if (!session || !session->moveDragController_) {
755             TLOGNW(WmsLogTag::WMS_LAYOUT_PC, "%{public}s: session or moveDragController is null", where);
756             return WSError::WS_ERROR_NULLPTR;
757         }
758         if (session->moveDragController_->GetStartMoveFlag()) {
759             TLOGNW(WmsLogTag::WMS_LAYOUT_PC, "%{public}s: Repeat operation, window is moving", where);
760             return WSError::WS_ERROR_REPEAT_OPERATION;
761         }
762         TLOGND(WmsLogTag::WMS_LAYOUT_PC, "%{public}s: offsetX:%{public}d offsetY:%{public}d pointerPosX:%{public}d"
763             " pointerPosY:%{public}d", where, offsetX, offsetY, pointerPosX, pointerPosY);
764         WSRect winRect = {
765             pointerPosX - offsetX,
766             pointerPosY - offsetY,
767             session->winRect_.width_,
768             session->winRect_.height_
769         };
770         session->moveDragController_->HandleStartMovingWithCoordinate(offsetX,
771             offsetY, pointerPosX, pointerPosY, winRect);
772         session->OnSessionEvent(SessionEvent::EVENT_START_MOVE);
773         return WSError::WS_OK;
774     }, __func__);
775 }
776 
GetWindowDragHotAreaType(uint32_t type,int32_t pointerX,int32_t pointerY)777 uint32_t SceneSession::GetWindowDragHotAreaType(uint32_t type, int32_t pointerX, int32_t pointerY)
778 {
779     std::shared_lock<std::shared_mutex> lock(windowDragHotAreaMutex_);
780     for (auto it = windowDragHotAreaMap_.begin(); it != windowDragHotAreaMap_.end(); ++it) {
781         uint32_t key = it->first;
782         WSRect rect = it->second;
783         if (rect.IsInRegion(pointerX, pointerY)) {
784             type |= key;
785         }
786     }
787     return type;
788 }
789 
AddOrUpdateWindowDragHotArea(uint32_t type,const WSRect & area)790 void SceneSession::AddOrUpdateWindowDragHotArea(uint32_t type, const WSRect& area)
791 {
792     std::unique_lock<std::shared_mutex> lock(windowDragHotAreaMutex_);
793     auto const result = windowDragHotAreaMap_.insert({type, area});
794     if (!result.second) {
795         result.first->second = area;
796     }
797 }
798 
NotifySubModalTypeChange(SubWindowModalType subWindowModalType)799 WSError SceneSession::NotifySubModalTypeChange(SubWindowModalType subWindowModalType)
800 {
801     const char* const where = __func__;
802     PostTask([weakThis = wptr(this), subWindowModalType, where] {
803         auto session = weakThis.promote();
804         if (!session) {
805             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session is null", where);
806             return;
807         }
808         TLOGNI(WmsLogTag::WMS_HIERARCHY, "%{public}s subWindowModalType: %{public}u",
809             where, static_cast<uint32_t>(subWindowModalType));
810         if (session->onSubModalTypeChange_) {
811             session->onSubModalTypeChange_(subWindowModalType);
812         }
813     }, __func__);
814     return WSError::WS_OK;
815 }
816 
RegisterSubModalTypeChangeCallback(NotifySubModalTypeChangeFunc && func)817 void SceneSession::RegisterSubModalTypeChangeCallback(NotifySubModalTypeChangeFunc&& func)
818 {
819     const char* const where = __func__;
820     PostTask([weakThis = wptr(this), func = std::move(func), where] {
821         auto session = weakThis.promote();
822         if (!session || !func) {
823             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s session or SessionModalTypeChangeFunc is null", where);
824             return;
825         }
826         session->onSubModalTypeChange_ = std::move(func);
827         TLOGNI(WmsLogTag::WMS_HIERARCHY, "%{public}s id: %{public}d",
828             where, session->GetPersistentId());
829     }, __func__);
830 }
831 
RegisterMainModalTypeChangeCallback(NotifyMainModalTypeChangeFunc && func)832 void SceneSession::RegisterMainModalTypeChangeCallback(NotifyMainModalTypeChangeFunc&& func)
833 {
834     const char* const where = __func__;
835     PostTask([weakThis = wptr(this), func = std::move(func), where] {
836         auto session = weakThis.promote();
837         if (!session || !func) {
838             TLOGNE(WmsLogTag::WMS_MAIN, "%{public}s session or func is null", where);
839             return;
840         }
841         session->onMainModalTypeChange_ = std::move(func);
842         TLOGNI(WmsLogTag::WMS_MAIN, "%{public}s id: %{public}d", where, session->GetPersistentId());
843     }, __func__);
844 }
845 
IsDialogWindow() const846 bool SceneSession::IsDialogWindow() const
847 {
848     return WindowHelper::IsDialogWindow(GetSessionProperty()->GetWindowType());
849 }
850 
GetSubWindowModalType() const851 SubWindowModalType SceneSession::GetSubWindowModalType() const
852 {
853     SubWindowModalType modalType = SubWindowModalType::TYPE_UNDEFINED;
854     auto property = GetSessionProperty();
855     if (property == nullptr) {
856         TLOGE(WmsLogTag::DEFAULT, "property is nullptr");
857         return modalType;
858     }
859     auto windowType = property->GetWindowType();
860     if (WindowHelper::IsToastSubWindow(windowType, property->GetWindowFlags())) {
861         return SubWindowModalType::TYPE_TOAST;
862     }
863     if (WindowHelper::IsDialogWindow(windowType)) {
864         modalType = SubWindowModalType::TYPE_DIALOG;
865     } else if (WindowHelper::IsModalSubWindow(windowType, property->GetWindowFlags())) {
866         if (WindowHelper::IsApplicationModalSubWindow(windowType, property->GetWindowFlags())) {
867             modalType = SubWindowModalType::TYPE_APPLICATION_MODALITY;
868         } else {
869             modalType = SubWindowModalType::TYPE_WINDOW_MODALITY;
870         }
871     } else if (WindowHelper::IsSubWindow(windowType)) {
872         modalType = SubWindowModalType::TYPE_NORMAL;
873     }
874     return modalType;
875 }
876 
SetSessionEventParam(SessionEventParam param)877 void SceneSession::SetSessionEventParam(SessionEventParam param)
878 {
879     sessionEventParam_ = param;
880 }
881 
RegisterSessionChangeCallback(const sptr<SceneSession::SessionChangeCallback> & sessionChangeCallback)882 void SceneSession::RegisterSessionChangeCallback(const sptr<SceneSession::SessionChangeCallback>&
883     sessionChangeCallback)
884 {
885     std::lock_guard<std::mutex> guard(sessionChangeCbMutex_);
886     sessionChangeCallback_ = sessionChangeCallback;
887 }
888 
RegisterUpdateAppUseControlCallback(UpdateAppUseControlFunc && callback)889 void SceneSession::RegisterUpdateAppUseControlCallback(UpdateAppUseControlFunc&& callback)
890 {
891     auto task = [weakThis = wptr(this), callback = std::move(callback)] {
892         auto session = weakThis.promote();
893         if (!session) {
894             TLOGNE(WmsLogTag::WMS_LIFE, "session is null");
895             return;
896         }
897         session->onUpdateAppUseControlFunc_ = std::move(callback);
898         for (const auto& [type, isNeedControl] : session->appUseControlMap_) {
899             session->onUpdateAppUseControlFunc_(type, isNeedControl);
900         }
901     };
902     PostTask(task, __func__);
903 }
904 
NotifyUpdateAppUseControl(ControlAppType type,bool isNeedControl)905 void SceneSession::NotifyUpdateAppUseControl(ControlAppType type, bool isNeedControl)
906 {
907     auto task = [weakThis = wptr(this), type, isNeedControl] {
908         auto session = weakThis.promote();
909         if (!session) {
910             TLOGNE(WmsLogTag::WMS_LIFE, "session is null");
911             return;
912         }
913         session->appUseControlMap_[type] = isNeedControl;
914         if (session->onUpdateAppUseControlFunc_) {
915             session->onUpdateAppUseControlFunc_(type, isNeedControl);
916         }
917     };
918     PostTask(task, __func__);
919 }
920 
RegisterDefaultAnimationFlagChangeCallback(NotifyWindowAnimationFlagChangeFunc && callback)921 void SceneSession::RegisterDefaultAnimationFlagChangeCallback(NotifyWindowAnimationFlagChangeFunc&& callback)
922 {
923     auto task = [weakThis = wptr(this), callback = std::move(callback)] {
924         auto session = weakThis.promote();
925         if (!session) {
926             TLOGNE(WmsLogTag::WMS_LIFE, "session is null");
927             return;
928         }
929         session->onWindowAnimationFlagChange_ = std::move(callback);
930         session->onWindowAnimationFlagChange_(session->IsNeedDefaultAnimation());
931     };
932     PostTask(task, __func__);
933 }
934 
RegisterDefaultDensityEnabledCallback(NotifyDefaultDensityEnabledFunc && callback)935 void SceneSession::RegisterDefaultDensityEnabledCallback(NotifyDefaultDensityEnabledFunc&& callback)
936 {
937     auto task = [weakThis = wptr(this), callback = std::move(callback)] {
938         auto session = weakThis.promote();
939         if (!session) {
940             TLOGNE(WmsLogTag::WMS_LIFE, "session is null");
941             return;
942         }
943         session->onDefaultDensityEnabledFunc_ = std::move(callback);
944     };
945     PostTask(task, __func__);
946 }
947 
RegisterNeedAvoidCallback(NotifyNeedAvoidFunc && callback)948 void SceneSession::RegisterNeedAvoidCallback(NotifyNeedAvoidFunc&& callback)
949 {
950     auto task = [weakThis = wptr(this), callback = std::move(callback)] {
951         auto session = weakThis.promote();
952         if (!session) {
953             TLOGNE(WmsLogTag::WMS_IMMS, "session is null");
954             return;
955         }
956         session->onNeedAvoid_ = std::move(callback);
957     };
958     PostTask(task, __func__);
959 }
960 
RegisterSystemBarPropertyChangeCallback(NotifySystemBarPropertyChangeFunc && callback)961 void SceneSession::RegisterSystemBarPropertyChangeCallback(NotifySystemBarPropertyChangeFunc&& callback)
962 {
963     PostTask([weakThis = wptr(this), callback = std::move(callback)] {
964         auto session = weakThis.promote();
965         if (!session) {
966             TLOGNE(WmsLogTag::WMS_LIFE, "session is null");
967             return;
968         }
969         session->onSystemBarPropertyChange_ = std::move(callback);
970     }, __func__);
971 }
972 
RegisterTouchOutsideCallback(NotifyTouchOutsideFunc && callback)973 void SceneSession::RegisterTouchOutsideCallback(NotifyTouchOutsideFunc&& callback)
974 {
975     PostTask([weakThis = wptr(this), callback = std::move(callback)] {
976         auto session = weakThis.promote();
977         if (!session) {
978             TLOGNE(WmsLogTag::WMS_LIFE, "session is null");
979             return;
980         }
981         session->onTouchOutside_ = std::move(callback);
982     }, __func__);
983 }
984 
SetGlobalMaximizeMode(MaximizeMode mode)985 WSError SceneSession::SetGlobalMaximizeMode(MaximizeMode mode)
986 {
987     auto task = [weakThis = wptr(this), mode]() {
988         auto session = weakThis.promote();
989         if (!session) {
990             WLOGFE("[WMSCom] session is null");
991             return WSError::WS_ERROR_DESTROYED_OBJECT;
992         }
993         WLOGFD("[WMSCom] mode: %{public}u", static_cast<uint32_t>(mode));
994         session->maximizeMode_ = mode;
995         ScenePersistentStorage::Insert("maximize_state", static_cast<int32_t>(session->maximizeMode_),
996             ScenePersistentStorageType::MAXIMIZE_STATE);
997         return WSError::WS_OK;
998     };
999     return PostSyncTask(task, "SetGlobalMaximizeMode");
1000 }
1001 
GetGlobalMaximizeMode(MaximizeMode & mode)1002 WSError SceneSession::GetGlobalMaximizeMode(MaximizeMode& mode)
1003 {
1004     auto task = [weakThis = wptr(this), &mode]() {
1005         auto session = weakThis.promote();
1006         if (!session) {
1007             WLOGFE("[WMSCom] session is null");
1008             return WSError::WS_ERROR_DESTROYED_OBJECT;
1009         }
1010         mode = maximizeMode_;
1011         WLOGFD("[WMSCom] mode: %{public}u", static_cast<uint32_t>(mode));
1012         return WSError::WS_OK;
1013     };
1014     return PostSyncTask(task, "GetGlobalMaximizeMode");
1015 }
1016 
CheckAspectRatioValid(const sptr<SceneSession> & session,float ratio,float vpr)1017 static WSError CheckAspectRatioValid(const sptr<SceneSession>& session, float ratio, float vpr)
1018 {
1019     if (MathHelper::NearZero(ratio)) {
1020         return WSError::WS_OK;
1021     }
1022     if (!session) {
1023         return WSError::WS_ERROR_INVALID_PARAM;
1024     }
1025     auto sessionProperty = session->GetSessionProperty();
1026     if (!sessionProperty) {
1027         return WSError::WS_ERROR_INVALID_PARAM;
1028     }
1029     auto limits = sessionProperty->GetWindowLimits();
1030     if (session->IsDecorEnable()) {
1031         if (limits.minWidth_ && limits.maxHeight_ &&
1032             MathHelper::LessNotEqual(ratio, SessionUtils::ToLayoutWidth(limits.minWidth_, vpr) /
1033             SessionUtils::ToLayoutHeight(limits.maxHeight_, vpr))) {
1034             WLOGE("Failed, because aspectRatio is smaller than minWidth/maxHeight");
1035             return WSError::WS_ERROR_INVALID_PARAM;
1036         } else if (limits.minHeight_ && limits.maxWidth_ &&
1037             MathHelper::GreatNotEqual(ratio, SessionUtils::ToLayoutWidth(limits.maxWidth_, vpr) /
1038             SessionUtils::ToLayoutHeight(limits.minHeight_, vpr))) {
1039             WLOGE("Failed, because aspectRatio is bigger than maxWidth/minHeight");
1040             return WSError::WS_ERROR_INVALID_PARAM;
1041         }
1042     } else {
1043         if (limits.minWidth_ && limits.maxHeight_ && MathHelper::LessNotEqual(ratio,
1044             static_cast<float>(limits.minWidth_) / limits.maxHeight_)) {
1045             WLOGE("Failed, because aspectRatio is smaller than minWidth/maxHeight");
1046             return WSError::WS_ERROR_INVALID_PARAM;
1047         } else if (limits.minHeight_ && limits.maxWidth_ && MathHelper::GreatNotEqual(ratio,
1048             static_cast<float>(limits.maxWidth_) / limits.minHeight_)) {
1049             WLOGE("Failed, because aspectRatio is bigger than maxWidth/minHeight");
1050             return WSError::WS_ERROR_INVALID_PARAM;
1051         }
1052     }
1053     return WSError::WS_OK;
1054 }
1055 
SetAspectRatio(float ratio)1056 WSError SceneSession::SetAspectRatio(float ratio)
1057 {
1058     auto task = [weakThis = wptr(this), ratio]() {
1059         auto session = weakThis.promote();
1060         if (!session) {
1061             TLOGE(WmsLogTag::WMS_LAYOUT, "session is null");
1062             return WSError::WS_ERROR_DESTROYED_OBJECT;
1063         }
1064         if (!session->GetSessionProperty()) {
1065             TLOGE(WmsLogTag::WMS_LAYOUT, "SetAspectRatio failed because property is null");
1066             return WSError::WS_ERROR_NULLPTR;
1067         }
1068         float vpr = 1.5f; // 1.5f: default virtual pixel ratio
1069         auto display = DisplayManager::GetInstance().GetDefaultDisplay();
1070         if (display) {
1071             vpr = display->GetVirtualPixelRatio();
1072             WLOGD("vpr = %{public}f", vpr);
1073         }
1074         WSError ret = CheckAspectRatioValid(session, ratio, vpr);
1075         if (ret != WSError::WS_OK) {
1076             return ret;
1077         }
1078         session->aspectRatio_ = ratio;
1079         if (session->moveDragController_) {
1080             session->moveDragController_->SetAspectRatio(ratio);
1081         }
1082         session->SaveAspectRatio(session->aspectRatio_);
1083         WSRect fixedRect = session->winRect_;
1084         TLOGI(WmsLogTag::WMS_LAYOUT, "Before fixing, the id:%{public}d, the current rect: %{public}s, "
1085             "ratio: %{public}f", session->GetPersistentId(), fixedRect.ToString().c_str(), ratio);
1086         if (session->FixRectByAspectRatio(fixedRect)) {
1087             TLOGI(WmsLogTag::WMS_LAYOUT, "After fixing, the id:%{public}d, the fixed rect: %{public}s",
1088                 session->GetPersistentId(), fixedRect.ToString().c_str());
1089             session->NotifySessionRectChange(fixedRect, SizeChangeReason::RESIZE);
1090         }
1091         return WSError::WS_OK;
1092     };
1093     return PostSyncTask(task, "SetAspectRatio");
1094 }
1095 
UpdateRect(const WSRect & rect,SizeChangeReason reason,const std::string & updateReason,const std::shared_ptr<RSTransaction> & rsTransaction)1096 WSError SceneSession::UpdateRect(const WSRect& rect, SizeChangeReason reason,
1097     const std::string& updateReason, const std::shared_ptr<RSTransaction>& rsTransaction)
1098 {
1099     const char* const funcName = __func__;
1100     auto task = [weakThis = wptr(this), rect, reason, rsTransaction, updateReason, funcName]() {
1101         auto session = weakThis.promote();
1102         if (!session) {
1103             TLOGNE(WmsLogTag::WMS_LAYOUT, "%{public}s: session is null", funcName);
1104             return WSError::WS_ERROR_DESTROYED_OBJECT;
1105         }
1106         if (session->winRect_ == rect && session->reason_ != SizeChangeReason::DRAG_END &&
1107             (session->GetWindowType() != WindowType::WINDOW_TYPE_KEYBOARD_PANEL &&
1108              session->GetWindowType() != WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT)) {
1109             if (!session->sessionStage_) {
1110                 TLOGND(WmsLogTag::WMS_LAYOUT, "%{public}s: skip same rect update id:%{public}d rect:%{public}s",
1111                     funcName, session->GetPersistentId(), rect.ToString().c_str());
1112                 return WSError::WS_OK;
1113             } else if (session->GetClientRect() == rect) {
1114                 TLOGND(WmsLogTag::WMS_LAYOUT, "%{public}s: skip same rect update id:%{public}d rect:%{public}s "
1115                     "clientRect:%{public}s", funcName, session->GetPersistentId(), rect.ToString().c_str(),
1116                     session->GetClientRect().ToString().c_str());
1117                 return WSError::WS_OK;
1118             }
1119         }
1120         if (rect.IsInvalid()) {
1121             TLOGNE(WmsLogTag::WMS_LAYOUT, "%{public}s: id:%{public}d rect:%{public}s is invalid",
1122                 funcName, session->GetPersistentId(), rect.ToString().c_str());
1123             return WSError::WS_ERROR_INVALID_PARAM;
1124         }
1125         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER,
1126             "SceneSession::UpdateRect%d [%d, %d, %u, %u]",
1127             session->GetPersistentId(), rect.posX_, rect.posY_, rect.width_, rect.height_);
1128         // position change no need to notify client, since frame layout finish will notify
1129         if (NearEqual(rect.width_, session->winRect_.width_) && NearEqual(rect.height_, session->winRect_.height_) &&
1130             (session->reason_ != SizeChangeReason::DRAG_MOVE || !session->rectChangeListenerRegistered_)) {
1131             TLOGNI(WmsLogTag::WMS_LAYOUT, "%{public}s: position change no need notify client id:%{public}d, "
1132                 "rect:%{public}s, preRect: %{public}s", funcName,
1133                 session->GetPersistentId(), rect.ToString().c_str(), session->winRect_.ToString().c_str());
1134             session->SetWinRectWhenUpdateRect(rect);
1135         } else {
1136             session->SetWinRectWhenUpdateRect(rect);
1137             session->NotifyClientToUpdateRect(updateReason, rsTransaction);
1138         }
1139         session->dirtyFlags_ |= static_cast<uint32_t>(SessionUIDirtyFlag::RECT);
1140         TLOGNI(WmsLogTag::WMS_LAYOUT, "%{public}s: id:%{public}d, reason:%{public}d %{public}s, "
1141             "rect:%{public}s, clientRect:%{public}s",
1142             funcName, session->GetPersistentId(), session->reason_, updateReason.c_str(),
1143             rect.ToString().c_str(), session->GetClientRect().ToString().c_str());
1144 
1145         return WSError::WS_OK;
1146     };
1147     PostTask(task, "UpdateRect" + GetRectInfo(rect));
1148     return WSError::WS_OK;
1149 }
1150 
1151 /** @note @window.layout */
SetWinRectWhenUpdateRect(const WSRect & rect)1152 void SceneSession::SetWinRectWhenUpdateRect(const WSRect& rect)
1153 {
1154     if (GetIsMidScene() && rect.posX_ == 0 && rect.posY_ == 0) {
1155         winRect_.width_ = rect.width_;
1156         winRect_.height_ = rect.height_;
1157     } else {
1158         winRect_ = rect;
1159     }
1160 }
1161 
IsKeyboardNeedLeftOffset(bool isPhone,const sptr<WindowSessionProperty> & sessionProperty)1162 bool SceneSession::IsKeyboardNeedLeftOffset(bool isPhone, const sptr<WindowSessionProperty>& sessionProperty)
1163 {
1164     static bool isFoldable = ScreenSessionManagerClient::GetInstance().IsFoldable();
1165     bool isFolded = ScreenSessionManagerClient::GetInstance().GetFoldStatus() == OHOS::Rosen::FoldStatus::FOLDED;
1166     bool isDualDevice = FoldScreenStateInternel::IsDualDisplayFoldDevice();
1167     uint32_t screenWidth = 0;
1168     uint32_t screenHeight = 0;
1169     if (!GetScreenWidthAndHeightFromServer(sessionProperty, screenWidth, screenHeight)) {
1170         return false;
1171     }
1172     bool isLandscape = screenWidth > screenHeight ? true : false;
1173     bool result = isPhone && (!isFoldable || isFolded || isDualDevice) && isLandscape;
1174     TLOGI(WmsLogTag::WMS_LAYOUT, "isPhone:%{public}d, isFoldable:%{public}d, isFolded:%{public}d, "
1175         "isDualDevice:%{public}d, isLandscape:%{public}d, screenWidth:%{public}u, screenHeight:%{public}u, "
1176         "isKeyboardNeedLeftOffset:%{public}d", isPhone, isFoldable, isFolded, isDualDevice, isLandscape,
1177         screenWidth, screenHeight, result);
1178     return result;
1179 }
1180 
FixKeyboardPositionByKeyboardPanel(sptr<SceneSession> panelSession,sptr<SceneSession> keyboardSession)1181 void SceneSession::FixKeyboardPositionByKeyboardPanel(sptr<SceneSession> panelSession,
1182     sptr<SceneSession> keyboardSession)
1183 {
1184     if (panelSession == nullptr || keyboardSession == nullptr) {
1185         TLOGE(WmsLogTag::WMS_LAYOUT, "keyboard or panel session is null");
1186         return;
1187     }
1188 
1189     SessionGravity gravity = keyboardSession->GetKeyboardGravity();
1190     if (gravity == SessionGravity::SESSION_GRAVITY_FLOAT) {
1191         keyboardSession->winRect_.posX_ = panelSession->winRect_.posX_;
1192     } else {
1193         auto sessionProperty = keyboardSession->GetSessionProperty();
1194         if (sessionProperty == nullptr) {
1195             TLOGE(WmsLogTag::WMS_LAYOUT, "keyboard property is null");
1196             return;
1197         }
1198         static bool isPhone = systemConfig_.uiType_ == UI_TYPE_PHONE;
1199         if (!IsKeyboardNeedLeftOffset(isPhone, sessionProperty) || panelSession->winRect_.posX_ != 0) {
1200             keyboardSession->winRect_.posX_ = panelSession->winRect_.posX_;
1201         }
1202     }
1203     keyboardSession->winRect_.posY_ = panelSession->winRect_.posY_;
1204     TLOGI(WmsLogTag::WMS_LAYOUT, "panelId:%{public}d, keyboardId:%{public}d, panelRect:%{public}s, "
1205         "keyboardRect:%{public}s, gravity:%{public}d", panelSession->GetPersistentId(),
1206         keyboardSession->GetPersistentId(), panelSession->winRect_.ToString().c_str(),
1207         keyboardSession->winRect_.ToString().c_str(), gravity);
1208 }
1209 
NotifyClientToUpdateRectTask(const std::string & updateReason,std::shared_ptr<RSTransaction> rsTransaction)1210 WSError SceneSession::NotifyClientToUpdateRectTask(const std::string& updateReason,
1211     std::shared_ptr<RSTransaction> rsTransaction)
1212 {
1213     TLOGD(WmsLogTag::WMS_LAYOUT, "id:%{public}d, reason:%{public}d, rect:%{public}s",
1214         GetPersistentId(), reason_, winRect_.ToString().c_str());
1215     bool isMoveOrDrag = moveDragController_ &&
1216         (moveDragController_->GetStartDragFlag() || moveDragController_->GetStartMoveFlag());
1217     if (isMoveOrDrag && reason_ == SizeChangeReason::UNDEFINED) {
1218         TLOGD(WmsLogTag::WMS_LAYOUT, "skip redundant rect update!");
1219         return WSError::WS_ERROR_REPEAT_OPERATION;
1220     }
1221     WSError ret = WSError::WS_OK;
1222     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER,
1223         "SceneSession::NotifyClientToUpdateRect%d [%d, %d, %u, %u] reason:%u",
1224         GetPersistentId(), winRect_.posX_, winRect_.posY_, winRect_.width_, winRect_.height_, reason_);
1225 
1226     std::map<AvoidAreaType, AvoidArea> avoidAreas;
1227     if (GetForegroundInteractiveStatus()) {
1228         GetAllAvoidAreas(avoidAreas);
1229     } else {
1230         TLOGD(WmsLogTag::WMS_IMMS, "win [%{public}d] avoid area update rejected by recent", GetPersistentId());
1231     }
1232     if (!Session::IsScbCoreEnabled() && isKeyboardPanelEnabled_) {
1233         sptr<SceneSession> self(this);
1234         if (GetWindowType() == WindowType::WINDOW_TYPE_KEYBOARD_PANEL) {
1235             const auto& keyboardSession = GetKeyboardSession();
1236             FixKeyboardPositionByKeyboardPanel(self, keyboardSession);
1237             if (keyboardSession != nullptr) {
1238                 ret = keyboardSession->Session::UpdateRect(keyboardSession->winRect_, reason_, updateReason, nullptr);
1239             }
1240             return ret;
1241         }
1242         if (GetWindowType() == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT) {
1243             FixKeyboardPositionByKeyboardPanel(GetKeyboardPanelSession(), self);
1244         }
1245     }
1246 
1247     // once reason is undefined, not use rsTransaction
1248     // when rotation, sync cnt++ in marshalling. Although reason is undefined caused by resize
1249     if (reason_ == SizeChangeReason::UNDEFINED || reason_ == SizeChangeReason::RESIZE || IsMoveToOrDragMove(reason_)) {
1250         ret = Session::UpdateRectWithLayoutInfo(winRect_, reason_, updateReason, nullptr, avoidAreas);
1251     } else {
1252         ret = Session::UpdateRectWithLayoutInfo(winRect_, reason_, updateReason, rsTransaction, avoidAreas);
1253 #ifdef DEVICE_STATUS_ENABLE
1254         // When the drag is in progress, the drag window needs to be notified to rotate.
1255         if (rsTransaction != nullptr) {
1256             RotateDragWindow(rsTransaction);
1257         }
1258 #endif // DEVICE_STATUS_ENABLE
1259     }
1260 
1261     return ret;
1262 }
1263 
NotifyClientToUpdateRect(const std::string & updateReason,std::shared_ptr<RSTransaction> rsTransaction)1264 WSError SceneSession::NotifyClientToUpdateRect(const std::string& updateReason,
1265     std::shared_ptr<RSTransaction> rsTransaction)
1266 {
1267     auto task = [weakThis = wptr(this), rsTransaction, updateReason]() {
1268         auto session = weakThis.promote();
1269         if (!session) {
1270             TLOGE(WmsLogTag::WMS_LAYOUT, "session is null");
1271             return WSError::WS_ERROR_DESTROYED_OBJECT;
1272         }
1273         WSError ret = session->NotifyClientToUpdateRectTask(updateReason, rsTransaction);
1274         if (ret != WSError::WS_OK) {
1275             return ret;
1276         }
1277         if (session->specificCallback_ && session->specificCallback_->onUpdateOccupiedAreaIfNeed_) {
1278             session->specificCallback_->onUpdateOccupiedAreaIfNeed_(session->GetPersistentId());
1279         }
1280         return ret;
1281     };
1282     PostTask(task, "NotifyClientToUpdateRect");
1283     return WSError::WS_OK;
1284 }
1285 
GetScreenWidthAndHeightFromServer(const sptr<WindowSessionProperty> & sessionProperty,uint32_t & screenWidth,uint32_t & screenHeight)1286 bool SceneSession::GetScreenWidthAndHeightFromServer(const sptr<WindowSessionProperty>& sessionProperty,
1287     uint32_t& screenWidth, uint32_t& screenHeight)
1288 {
1289     if (isScreenAngleMismatch_) {
1290         screenWidth = targetScreenWidth_;
1291         screenHeight = targetScreenHeight_;
1292         TLOGI(WmsLogTag::WMS_KEYBOARD, "screenWidth: %{public}d, screenHeight: %{public}d", screenWidth, screenHeight);
1293         return true;
1294     }
1295 
1296     const auto& screenSession = sessionProperty == nullptr ? nullptr :
1297         ScreenSessionManagerClient::GetInstance().GetScreenSession(sessionProperty->GetDisplayId());
1298     if (screenSession != nullptr) {
1299         screenWidth = screenSession->GetScreenProperty().GetBounds().rect_.width_;
1300         screenHeight = screenSession->GetScreenProperty().GetBounds().rect_.height_;
1301     } else {
1302         TLOGI(WmsLogTag::WMS_KEYBOARD, "sessionProperty or screenSession is nullptr, use defaultDisplayInfo");
1303         auto defaultDisplayInfo = DisplayManager::GetInstance().GetDefaultDisplay();
1304         if (defaultDisplayInfo != nullptr) {
1305             screenWidth = static_cast<uint32_t>(defaultDisplayInfo->GetWidth());
1306             screenHeight = static_cast<uint32_t>(defaultDisplayInfo->GetHeight());
1307         } else {
1308             TLOGE(WmsLogTag::WMS_KEYBOARD, "defaultDisplayInfo is null, get screenWidthAndHeight failed");
1309             return false;
1310         }
1311     }
1312     TLOGI(WmsLogTag::WMS_KEYBOARD, "screenWidth: %{public}d, screenHeight: %{public}d", screenWidth, screenHeight);
1313     return true;
1314 }
1315 
GetScreenWidthAndHeightFromClient(const sptr<WindowSessionProperty> & sessionProperty,uint32_t & screenWidth,uint32_t & screenHeight)1316 bool SceneSession::GetScreenWidthAndHeightFromClient(const sptr<WindowSessionProperty>& sessionProperty,
1317     uint32_t& screenWidth, uint32_t& screenHeight)
1318 {
1319     if (isScreenAngleMismatch_) {
1320         screenWidth = targetScreenWidth_;
1321         screenHeight = targetScreenHeight_;
1322         TLOGI(WmsLogTag::WMS_KEYBOARD, "screenWidth: %{public}d, screenHeight: %{public}d", screenWidth, screenHeight);
1323         return true;
1324     }
1325 
1326     auto defaultDisplayInfo = DisplayManager::GetInstance().GetDefaultDisplay();
1327     if (defaultDisplayInfo != nullptr) {
1328         screenWidth = static_cast<uint32_t>(defaultDisplayInfo->GetWidth());
1329         screenHeight = static_cast<uint32_t>(defaultDisplayInfo->GetHeight());
1330     } else {
1331         TLOGE(WmsLogTag::WMS_KEYBOARD, "defaultDisplayInfo is null, get screenWidthAndHeight failed");
1332         return false;
1333     }
1334     TLOGI(WmsLogTag::WMS_KEYBOARD, "screenWidth: %{public}d, screenHeight: %{public}d", screenWidth, screenHeight);
1335     return true;
1336 }
1337 
NotifyTargetScreenWidthAndHeight(bool isScreenAngleMismatch,uint32_t screenWidth,uint32_t screenHeight)1338 void SceneSession::NotifyTargetScreenWidthAndHeight(bool isScreenAngleMismatch, uint32_t screenWidth,
1339     uint32_t screenHeight)
1340 {
1341     auto task = [weakThis = wptr(this), isScreenAngleMismatch, screenWidth, screenHeight]() {
1342         auto session = weakThis.promote();
1343         if (!session) {
1344             TLOGE(WmsLogTag::WMS_KEYBOARD, "keyboard session is null");
1345             return;
1346         }
1347         session->isScreenAngleMismatch_ = isScreenAngleMismatch;
1348         session->targetScreenWidth_ = screenWidth;
1349         session->targetScreenHeight_ = screenHeight;
1350         TLOGI(WmsLogTag::WMS_KEYBOARD, "target isMismatch: %{public}d, width_: %{public}d, height_: %{public}d",
1351             isScreenAngleMismatch, screenWidth, screenHeight);
1352         return;
1353     };
1354     PostTask(task, "NotifyTargetScreenWidthAndHeight");
1355 }
1356 
UpdateInputMethodSessionRect(const WSRect & rect,WSRect & newWinRect,WSRect & newRequestRect)1357 bool SceneSession::UpdateInputMethodSessionRect(const WSRect& rect, WSRect& newWinRect, WSRect& newRequestRect)
1358 {
1359     uint32_t screenWidth = 0;
1360     uint32_t screenHeight = 0;
1361     auto sessionProperty = GetSessionProperty();
1362     if (!sessionProperty) {
1363         TLOGE(WmsLogTag::WMS_KEYBOARD, "sessionProperty is null");
1364         return false;
1365     }
1366     SessionGravity gravity = GetKeyboardGravity();
1367     if (GetWindowType() == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT &&
1368         (gravity == SessionGravity::SESSION_GRAVITY_BOTTOM || gravity == SessionGravity::SESSION_GRAVITY_DEFAULT)) {
1369         if (!GetScreenWidthAndHeightFromServer(sessionProperty, screenWidth, screenHeight)) {
1370             return false;
1371         }
1372         newWinRect.width_ = (gravity == SessionGravity::SESSION_GRAVITY_BOTTOM) ?
1373             static_cast<int32_t>(screenWidth) : rect.width_;
1374         newRequestRect.width_ = newWinRect.width_;
1375         newWinRect.height_ = rect.height_;
1376         newRequestRect.height_ = newWinRect.height_;
1377         newWinRect.posX_ = (gravity == SessionGravity::SESSION_GRAVITY_BOTTOM) ? 0 : rect.posX_;
1378         newRequestRect.posX_ = newWinRect.posX_;
1379         newWinRect.posY_ = static_cast<int32_t>(screenHeight) - newWinRect.height_;
1380         newRequestRect.posY_ = newWinRect.posY_;
1381         TLOGI(WmsLogTag::WMS_KEYBOARD, "rect: %{public}s, newRequestRect: %{public}s, newWinRect: %{public}s",
1382             rect.ToString().c_str(), newRequestRect.ToString().c_str(), newWinRect.ToString().c_str());
1383         return true;
1384     }
1385     TLOGD(WmsLogTag::WMS_KEYBOARD, "There is no need to update input rect");
1386     return false;
1387 }
1388 
SetSessionRectChangeCallback(const NotifySessionRectChangeFunc & func)1389 void SceneSession::SetSessionRectChangeCallback(const NotifySessionRectChangeFunc& func)
1390 {
1391     auto task = [weakThis = wptr(this), func]() {
1392         auto session = weakThis.promote();
1393         if (!session) {
1394             WLOGFE("session is null");
1395             return WSError::WS_ERROR_DESTROYED_OBJECT;
1396         }
1397         session->sessionRectChangeFunc_ = func;
1398         if (session->sessionRectChangeFunc_ && session->GetWindowType() != WindowType::WINDOW_TYPE_APP_MAIN_WINDOW) {
1399             auto reason = SizeChangeReason::UNDEFINED;
1400             auto rect = session->GetSessionRequestRect();
1401             if (rect.width_ == 0 && rect.height_ == 0) {
1402                 reason = SizeChangeReason::MOVE;
1403             }
1404             session->sessionRectChangeFunc_(session->GetSessionRequestRect(), reason);
1405         }
1406         return WSError::WS_OK;
1407     };
1408     PostTask(task, "SetSessionRectChangeCallback");
1409 }
1410 
SetMainWindowTopmostChangeCallback(NotifyMainWindowTopmostChangeFunc && func)1411 void SceneSession::SetMainWindowTopmostChangeCallback(NotifyMainWindowTopmostChangeFunc&& func)
1412 {
1413     const char* const where = __func__;
1414     PostTask([weakThis = wptr(this), func = std::move(func), where] {
1415         auto session = weakThis.promote();
1416         if (!session || !func) {
1417             TLOGNE(WmsLogTag::WMS_HIERARCHY, "%{public}s session or func is null", where);
1418             return;
1419         }
1420         session->mainWindowTopmostChangeFunc_ = std::move(func);
1421     }, __func__);
1422 }
1423 
SetTitleAndDockHoverShowChangeCallback(NotifyTitleAndDockHoverShowChangeFunc && func)1424 void SceneSession::SetTitleAndDockHoverShowChangeCallback(NotifyTitleAndDockHoverShowChangeFunc&& func)
1425 {
1426     const char* const funcName = __func__;
1427     PostTask([weakThis = wptr(this), func = std::move(func), funcName] {
1428         auto session = weakThis.promote();
1429         if (!session || !func) {
1430             TLOGNE(WmsLogTag::WMS_IMMS, "session or TitleAndDockHoverShowChangeFunc is null");
1431             return;
1432         }
1433         session->onTitleAndDockHoverShowChangeFunc_ = std::move(func);
1434         TLOGNI(WmsLogTag::WMS_IMMS, "%{public}s id: %{public}d",
1435             funcName, session->GetPersistentId());
1436     }, funcName);
1437 }
1438 
SetRestoreMainWindowCallback(NotifyRestoreMainWindowFunc && func)1439 void SceneSession::SetRestoreMainWindowCallback(NotifyRestoreMainWindowFunc&& func)
1440 {
1441     const char* const funcName = __func__;
1442     auto task = [weakThis = wptr(this), func = std::move(func), funcName] {
1443         auto session = weakThis.promote();
1444         if (!session || !func) {
1445             TLOGNE(WmsLogTag::WMS_LIFE, "session or RestoreMainWindowFunc is null");
1446             return;
1447         }
1448         session->onRestoreMainWindowFunc_ = std::move(func);
1449         TLOGNI(WmsLogTag::WMS_LIFE, "%{public}s id: %{public}d",
1450             funcName, session->GetPersistentId());
1451     };
1452     PostTask(task, funcName);
1453 }
1454 
SetKeyboardGravityChangeCallback(const NotifyKeyboardGravityChangeFunc & func)1455 void SceneSession::SetKeyboardGravityChangeCallback(const NotifyKeyboardGravityChangeFunc& func)
1456 {
1457     auto task = [weakThis = wptr(this), func]() {
1458         auto session = weakThis.promote();
1459         if (!session || !func) {
1460             WLOGFE("session or gravityChangeFunc is null");
1461             return WSError::WS_ERROR_DESTROYED_OBJECT;
1462         }
1463         session->keyboardGravityChangeFunc_ = func;
1464         session->keyboardGravityChangeFunc_(session->GetKeyboardGravity());
1465         TLOGI(WmsLogTag::WMS_KEYBOARD, "Notify gravity change when register, id: %{public}d gravity: %{public}d",
1466             session->GetPersistentId(), session->GetKeyboardGravity());
1467         return WSError::WS_OK;
1468     };
1469     PostTask(task, "SetKeyboardGravityChangeCallback");
1470 }
1471 
SetAdjustKeyboardLayoutCallback(const NotifyKeyboardLayoutAdjustFunc & func)1472 void SceneSession::SetAdjustKeyboardLayoutCallback(const NotifyKeyboardLayoutAdjustFunc& func)
1473 {
1474     auto task = [weakThis = wptr(this), func]() {
1475         auto session = weakThis.promote();
1476         if (!session || !func) {
1477             TLOGE(WmsLogTag::WMS_KEYBOARD, "session or keyboardLayoutFunc is null");
1478             return WSError::WS_ERROR_DESTROYED_OBJECT;
1479         }
1480         session->adjustKeyboardLayoutFunc_ = func;
1481         auto property = session->GetSessionProperty();
1482         if (property == nullptr) {
1483             TLOGE(WmsLogTag::WMS_KEYBOARD, "property is null");
1484             return WSError::WS_ERROR_DESTROYED_OBJECT;
1485         }
1486         KeyboardLayoutParams params = property->GetKeyboardLayoutParams();
1487         session->adjustKeyboardLayoutFunc_(params);
1488         TLOGI(WmsLogTag::WMS_KEYBOARD, "Notify adjust keyboard layout when register, keyboardId: %{public}d, "
1489             "gravity: %{public}u, landscapeAvoidHeight: %{public}d, portraitAvoidHeight: %{public}d, "
1490             "LandscapeKeyboardRect: %{public}s, PortraitKeyboardRect: %{public}s, "
1491             "LandscapePanelRect: %{public}s, PortraitPanelRect: %{public}s", session->GetPersistentId(),
1492             static_cast<uint32_t>(params.gravity_), params.landscapeAvoidHeight_, params.portraitAvoidHeight_,
1493             params.LandscapeKeyboardRect_.ToString().c_str(), params.PortraitKeyboardRect_.ToString().c_str(),
1494             params.LandscapePanelRect_.ToString().c_str(), params.PortraitPanelRect_.ToString().c_str());
1495         return WSError::WS_OK;
1496     };
1497     PostTask(task, "SetAdjustKeyboardLayoutCallback");
1498 }
1499 
SetSessionPiPControlStatusChangeCallback(const NotifySessionPiPControlStatusChangeFunc & func)1500 void SceneSession::SetSessionPiPControlStatusChangeCallback(const NotifySessionPiPControlStatusChangeFunc& func)
1501 {
1502     auto task = [weakThis = wptr(this), func]() {
1503         auto session = weakThis.promote();
1504         if (!session) {
1505             TLOGE(WmsLogTag::WMS_PIP, "session is null");
1506             return WSError::WS_ERROR_DESTROYED_OBJECT;
1507         }
1508         session->sessionPiPControlStatusChangeFunc_ = func;
1509         return WSError::WS_OK;
1510     };
1511     PostTask(task, __func__);
1512 }
1513 
SetAutoStartPiPStatusChangeCallback(const NotifyAutoStartPiPStatusChangeFunc & func)1514 void SceneSession::SetAutoStartPiPStatusChangeCallback(const NotifyAutoStartPiPStatusChangeFunc& func)
1515 {
1516     auto task = [weakThis = wptr(this), func] {
1517         auto session = weakThis.promote();
1518         if (!session) {
1519             TLOGNE(WmsLogTag::WMS_PIP, "session is null");
1520             return;
1521         }
1522         session->autoStartPiPStatusChangeFunc_ = func;
1523     };
1524     PostTask(task, __func__);
1525 }
1526 
UpdateSessionRectInner(const WSRect & rect,const SizeChangeReason & reason)1527 void SceneSession::UpdateSessionRectInner(const WSRect& rect, const SizeChangeReason& reason)
1528 {
1529     auto newWinRect = winRect_;
1530     auto newRequestRect = GetSessionRequestRect();
1531     SizeChangeReason newReason = reason;
1532     if (reason == SizeChangeReason::MOVE) {
1533         newWinRect.posX_ = rect.posX_;
1534         newWinRect.posY_ = rect.posY_;
1535         newRequestRect.posX_ = rect.posX_;
1536         newRequestRect.posY_ = rect.posY_;
1537         if (!Session::IsScbCoreEnabled() && !WindowHelper::IsMainWindow(GetWindowType())) {
1538             SetSessionRect(newWinRect);
1539         }
1540         SetSessionRequestRect(newRequestRect);
1541         NotifySessionRectChange(newRequestRect, reason);
1542     } else if (reason == SizeChangeReason::RESIZE) {
1543         bool needUpdateInputMethod = UpdateInputMethodSessionRect(rect, newWinRect, newRequestRect);
1544         if (needUpdateInputMethod) {
1545             newReason = SizeChangeReason::UNDEFINED;
1546             TLOGD(WmsLogTag::WMS_KEYBOARD, "Input rect has totally changed, need to modify reason, id: %{public}d",
1547                 GetPersistentId());
1548         } else if (rect.width_ > 0 && rect.height_ > 0) {
1549             newWinRect.width_ = rect.width_;
1550             newWinRect.height_ = rect.height_;
1551             newRequestRect.width_ = rect.width_;
1552             newRequestRect.height_ = rect.height_;
1553         }
1554         if (!Session::IsScbCoreEnabled() && GetWindowType() != WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT) {
1555             SetSessionRect(newWinRect);
1556         }
1557         SetSessionRequestRect(newRequestRect);
1558         NotifySessionRectChange(newRequestRect, newReason);
1559     } else {
1560         if (!Session::IsScbCoreEnabled()) {
1561             SetSessionRect(rect);
1562         }
1563         NotifySessionRectChange(rect, reason);
1564     }
1565     TLOGI(WmsLogTag::WMS_LAYOUT, "Id:%{public}d reason:%{public}d newReason:%{public}d rect:%{public}s "
1566         "newRequestRect:%{public}s newWinRect:%{public}s", GetPersistentId(), reason,
1567         newReason, rect.ToString().c_str(), newRequestRect.ToString().c_str(), newWinRect.ToString().c_str());
1568 }
1569 
UpdateSessionRect(const WSRect & rect,const SizeChangeReason reason,bool isGlobal,bool isFromMoveToGlobal)1570 WSError SceneSession::UpdateSessionRect(
1571     const WSRect &rect, const SizeChangeReason reason, bool isGlobal, bool isFromMoveToGlobal)
1572 {
1573     if ((reason == SizeChangeReason::MOVE || reason == SizeChangeReason::RESIZE) &&
1574         GetWindowType() == WindowType::WINDOW_TYPE_PIP) {
1575         return WSError::WS_DO_NOTHING;
1576     }
1577     WSRect newRect = rect;
1578     if (isGlobal && WindowHelper::IsSubWindow(Session::GetWindowType()) &&
1579         (systemConfig_.uiType_ == UI_TYPE_PHONE ||
1580          (systemConfig_.uiType_ == UI_TYPE_PAD && !IsFreeMultiWindowMode()))) {
1581         auto parentSession = GetParentSession();
1582         if (parentSession) {
1583             auto parentRect = parentSession->GetSessionRect();
1584             if (!CheckIfRectElementIsTooLarge(parentRect)) {
1585                 newRect.posX_ -= parentRect.posX_;
1586                 newRect.posY_ -= parentRect.posY_;
1587             }
1588         }
1589     }
1590     if (isFromMoveToGlobal && WindowHelper::IsSubWindow(Session::GetWindowType()) &&
1591         (systemConfig_.uiType_ == UI_TYPE_PHONE ||
1592          (systemConfig_.uiType_ == UI_TYPE_PAD && !IsFreeMultiWindowMode()))) {
1593         auto parentSession = GetParentSession();
1594         if (parentSession && parentSession->GetFloatingScale() != 0) {
1595             Rect parentGlobalRect;
1596             WMError errorCode = parentSession->GetGlobalScaledRect(parentGlobalRect);
1597             newRect.posX_ = (newRect.posX_ - parentGlobalRect.posX_) / parentSession->GetFloatingScale();
1598             newRect.posY_ = (newRect.posY_ - parentGlobalRect.posY_) / parentSession->GetFloatingScale();
1599         }
1600     }
1601     Session::RectCheckProcess();
1602     auto task = [weakThis = wptr(this), newRect, reason]() {
1603         auto session = weakThis.promote();
1604         if (!session) {
1605             TLOGE(WmsLogTag::WMS_LAYOUT, "session is null");
1606             return WSError::WS_ERROR_DESTROYED_OBJECT;
1607         }
1608         session->UpdateSessionRectInner(newRect, reason);
1609         return WSError::WS_OK;
1610     };
1611     PostTask(task, "UpdateSessionRect" + GetRectInfo(rect));
1612     return WSError::WS_OK;
1613 }
1614 
1615 /** @note @window.layout */
UpdateClientRect(const WSRect & rect)1616 WSError SceneSession::UpdateClientRect(const WSRect& rect)
1617 {
1618     const char* const funcName = __func__;
1619     auto task = [weakThis = wptr(this), rect, funcName] {
1620         auto session = weakThis.promote();
1621         if (!session) {
1622             TLOGNE(WmsLogTag::WMS_LAYOUT, "%{public}s: session is null", funcName);
1623             return;
1624         }
1625         if (rect.IsInvalid()) {
1626             TLOGNE(WmsLogTag::WMS_LAYOUT, "%{public}s: id:%{public}d rect:%{public}s is invalid",
1627                 funcName, session->GetPersistentId(), rect.ToString().c_str());
1628             return;
1629         }
1630         if (rect == session->GetClientRect()) {
1631             TLOGND(WmsLogTag::WMS_LAYOUT, "%{public}s: id:%{public}d skip same rect",
1632                 funcName, session->GetPersistentId());
1633             return;
1634         }
1635         session->SetClientRect(rect);
1636     };
1637     PostTask(task, "UpdateClientRect" + GetRectInfo(rect));
1638     return WSError::WS_OK;
1639 }
1640 
NotifySingleHandTransformChange(const SingleHandTransform & singleHandTransform)1641 void SceneSession::NotifySingleHandTransformChange(const SingleHandTransform& singleHandTransform)
1642 {
1643     if (!IsSessionForeground() && !IsVisible()) {
1644         TLOGD(WmsLogTag::WMS_LAYOUT, "id:%{public}d, session is not foreground and not visible!", GetPersistentId());
1645         return;
1646     }
1647     if (sessionStage_ != nullptr) {
1648         sessionStage_->NotifySingleHandTransformChange(singleHandTransform);
1649     }
1650 }
1651 
1652 /** @note @window.hierarchy */
RaiseToAppTop()1653 WSError SceneSession::RaiseToAppTop()
1654 {
1655     auto task = [weakThis = wptr(this)]() {
1656         auto session = weakThis.promote();
1657         if (!session) {
1658             WLOGFE("session is null");
1659             return WSError::WS_ERROR_DESTROYED_OBJECT;
1660         }
1661         if (session->sessionChangeCallback_ && session->sessionChangeCallback_->onRaiseToTop_) {
1662             TLOGI(WmsLogTag::WMS_SUB, "id: %{public}d", session->GetPersistentId());
1663             session->sessionChangeCallback_->onRaiseToTop_();
1664             session->SetMainSessionUIStateDirty(true);
1665         }
1666         return WSError::WS_OK;
1667     };
1668     return PostSyncTask(task, "RaiseToAppTop");
1669 }
1670 
1671 /** @note @window.hierarchy */
RaiseAboveTarget(int32_t subWindowId)1672 WSError SceneSession::RaiseAboveTarget(int32_t subWindowId)
1673 {
1674     if (!SessionPermission::IsSystemCalling() && !SessionPermission::IsStartByHdcd()) {
1675         WLOGFE("RaiseAboveTarget permission denied!");
1676         return WSError::WS_ERROR_NOT_SYSTEM_APP;
1677     }
1678     auto subSession = std::find_if(subSession_.begin(), subSession_.end(), [subWindowId](sptr<SceneSession> session) {
1679         bool res = (session != nullptr && session->GetWindowId() == subWindowId) ? true : false;
1680         return res;
1681     });
1682     int32_t callingPid = IPCSkeleton::GetCallingPid();
1683     if (subSession != subSession_.end() && callingPid != (*subSession)->GetCallingPid()) {
1684         TLOGE(WmsLogTag::WMS_LAYOUT, "permission denied! id: %{public}d", subWindowId);
1685         return WSError::WS_ERROR_INVALID_CALLING;
1686     }
1687     auto task = [weakThis = wptr(this), subWindowId]() {
1688         auto session = weakThis.promote();
1689         if (!session) {
1690             WLOGFE("session is null");
1691             return WSError::WS_ERROR_DESTROYED_OBJECT;
1692         }
1693         if (session->sessionChangeCallback_ && session->sessionChangeCallback_->onRaiseAboveTarget_) {
1694             session->sessionChangeCallback_->onRaiseAboveTarget_(subWindowId);
1695         }
1696         return WSError::WS_OK;
1697     };
1698     return PostSyncTask(task, "RaiseAboveTarget");
1699 }
1700 
BindDialogSessionTarget(const sptr<SceneSession> & sceneSession)1701 WSError SceneSession::BindDialogSessionTarget(const sptr<SceneSession>& sceneSession)
1702 {
1703     if (sceneSession == nullptr) {
1704         TLOGE(WmsLogTag::WMS_DIALOG, "dialog session is null");
1705         return WSError::WS_ERROR_NULLPTR;
1706     }
1707     if (sessionChangeCallback_ != nullptr && sessionChangeCallback_->onBindDialogTarget_) {
1708         TLOGI(WmsLogTag::WMS_DIALOG, "id: %{public}d", sceneSession->GetPersistentId());
1709         sessionChangeCallback_->onBindDialogTarget_(sceneSession);
1710     }
1711     return WSError::WS_OK;
1712 }
1713 
SetSystemBarProperty(WindowType type,SystemBarProperty systemBarProperty)1714 WSError SceneSession::SetSystemBarProperty(WindowType type, SystemBarProperty systemBarProperty)
1715 {
1716     TLOGD(WmsLogTag::WMS_IMMS, "persistentId():%{public}u type:%{public}u"
1717         "enable:%{public}u bgColor:%{public}x Color:%{public}x enableAnimation:%{public}u settingFlag:%{public}u",
1718         GetPersistentId(), static_cast<uint32_t>(type),
1719         systemBarProperty.enable_, systemBarProperty.backgroundColor_, systemBarProperty.contentColor_,
1720         systemBarProperty.enableAnimation_, systemBarProperty.settingFlag_);
1721     auto property = GetSessionProperty();
1722     if (property == nullptr) {
1723         TLOGE(WmsLogTag::WMS_DIALOG, "property is null");
1724         return WSError::WS_ERROR_NULLPTR;
1725     }
1726     property->SetSystemBarProperty(type, systemBarProperty);
1727     if (onSystemBarPropertyChange_) {
1728         onSystemBarPropertyChange_(property->GetSystemBarProperty());
1729     }
1730     return WSError::WS_OK;
1731 }
1732 
SetIsStatusBarVisible(bool isVisible)1733 void SceneSession::SetIsStatusBarVisible(bool isVisible)
1734 {
1735     auto task = [weakThis = wptr(this), isVisible] {
1736         sptr<SceneSession> sceneSession = weakThis.promote();
1737         if (sceneSession == nullptr) {
1738             TLOGNE(WmsLogTag::WMS_IMMS, "session is null");
1739             return;
1740         }
1741         sceneSession->SetIsStatusBarVisibleInner(isVisible);
1742     };
1743     PostTask(task, __func__);
1744 }
1745 
SetIsStatusBarVisibleInner(bool isVisible)1746 WSError SceneSession::SetIsStatusBarVisibleInner(bool isVisible)
1747 {
1748     bool isNeedNotify = isStatusBarVisible_ != isVisible;
1749     TLOGI(WmsLogTag::WMS_IMMS, "Window [%{public}d, %{public}s] status bar visible %{public}u, "
1750         "need notify %{public}u", GetPersistentId(), GetWindowName().c_str(), isVisible, isNeedNotify);
1751     isStatusBarVisible_ = isVisible;
1752     if (!isNeedNotify) {
1753         return WSError::WS_OK;
1754     }
1755     if (isLastFrameLayoutFinishedFunc_ == nullptr) {
1756         TLOGE(WmsLogTag::WMS_IMMS, "isLastFrameLayoutFinishedFunc is null, id: %{public}d", GetPersistentId());
1757         return WSError::WS_ERROR_NULLPTR;
1758     }
1759     bool isLayoutFinished = false;
1760     WSError ret = isLastFrameLayoutFinishedFunc_(isLayoutFinished);
1761     if (ret != WSError::WS_OK) {
1762         TLOGE(WmsLogTag::WMS_IMMS, "isLastFrameLayoutFinishedFunc failed: %{public}d", ret);
1763         return ret;
1764     }
1765     if (isLayoutFinished) {
1766         UpdateAvoidArea(new AvoidArea(GetAvoidAreaByType(AvoidAreaType::TYPE_SYSTEM)), AvoidAreaType::TYPE_SYSTEM);
1767     } else {
1768         MarkAvoidAreaAsDirty();
1769     }
1770     return WSError::WS_OK;
1771 }
1772 
NotifyPropertyWhenConnect()1773 void SceneSession::NotifyPropertyWhenConnect()
1774 {
1775     WLOGFI("Notify property when connect.");
1776     auto property = GetSessionProperty();
1777     if (property == nullptr) {
1778         WLOGFD("id: %{public}d property is nullptr", persistentId_);
1779         return;
1780     }
1781     NotifySessionFocusableChange(property->GetFocusable());
1782     NotifySessionTouchableChange(property->GetTouchable());
1783     OnShowWhenLocked(GetShowWhenLockedFlagValue());
1784 }
1785 
1786 /** @note @window.hierarchy */
RaiseAppMainWindowToTop()1787 WSError SceneSession::RaiseAppMainWindowToTop()
1788 {
1789     auto task = [weakThis = wptr(this)]() {
1790         auto session = weakThis.promote();
1791         if (!session) {
1792             WLOGFE("session is null");
1793             return WSError::WS_ERROR_DESTROYED_OBJECT;
1794         }
1795         if (session->IsFocusedOnShow()) {
1796             FocusChangeReason reason = FocusChangeReason::MOVE_UP;
1797             session->NotifyRequestFocusStatusNotifyManager(true, true, reason);
1798             session->NotifyClick();
1799         } else {
1800             session->SetFocusedOnShow(true);
1801         }
1802         return WSError::WS_OK;
1803     };
1804     PostTask(task, "RaiseAppMainWindowToTop");
1805     return WSError::WS_OK;
1806 }
1807 
OnNeedAvoid(bool status)1808 WSError SceneSession::OnNeedAvoid(bool status)
1809 {
1810     auto task = [weakThis = wptr(this), status]() {
1811         auto session = weakThis.promote();
1812         if (!session) {
1813             TLOGE(WmsLogTag::WMS_IMMS, "session is null");
1814             return WSError::WS_ERROR_DESTROYED_OBJECT;
1815         }
1816         TLOGI(WmsLogTag::WMS_IMMS, "SceneSession OnNeedAvoid status:%{public}d, id:%{public}d",
1817             static_cast<int32_t>(status), session->GetPersistentId());
1818         if (session->onNeedAvoid_) {
1819             session->onNeedAvoid_(status);
1820         }
1821         return WSError::WS_OK;
1822     };
1823     PostTask(task, "OnNeedAvoid");
1824     return WSError::WS_OK;
1825 }
1826 
OnShowWhenLocked(bool showWhenLocked)1827 WSError SceneSession::OnShowWhenLocked(bool showWhenLocked)
1828 {
1829     WLOGFD("SceneSession ShowWhenLocked status:%{public}d", static_cast<int32_t>(showWhenLocked));
1830     if (onShowWhenLockedFunc_) {
1831         onShowWhenLockedFunc_(showWhenLocked);
1832     }
1833     return WSError::WS_OK;
1834 }
1835 
IsShowWhenLocked() const1836 bool SceneSession::IsShowWhenLocked() const
1837 {
1838     return (GetSessionProperty()->GetWindowFlags() &
1839         static_cast<uint32_t>(WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED)) || IsTemporarilyShowWhenLocked();
1840 }
1841 
GetShowWhenLockedFlagValue() const1842 bool SceneSession::GetShowWhenLockedFlagValue() const
1843 {
1844     return GetSessionProperty()->GetWindowFlags() & static_cast<uint32_t>(WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED);
1845 }
1846 
CalculateAvoidAreaRect(WSRect & rect,WSRect & avoidRect,AvoidArea & avoidArea) const1847 void SceneSession::CalculateAvoidAreaRect(WSRect& rect, WSRect& avoidRect, AvoidArea& avoidArea) const
1848 {
1849     if (SessionHelper::IsEmptyRect(rect) || SessionHelper::IsEmptyRect(avoidRect)) {
1850         return;
1851     }
1852     Rect avoidAreaRect = SessionHelper::TransferToRect(
1853         SessionHelper::GetOverlap(rect, avoidRect, rect.posX_, rect.posY_));
1854     if (WindowHelper::IsEmptyRect(avoidAreaRect)) {
1855         return;
1856     }
1857 
1858     uint32_t avoidAreaCenterX = static_cast<uint32_t>(avoidAreaRect.posX_) + (avoidAreaRect.width_ >> 1);
1859     uint32_t avoidAreaCenterY = static_cast<uint32_t>(avoidAreaRect.posY_) + (avoidAreaRect.height_ >> 1);
1860     float res1 = float(avoidAreaCenterY) - float(rect.height_) / float(rect.width_) *
1861         float(avoidAreaCenterX);
1862     float res2 = float(avoidAreaCenterY) + float(rect.height_) / float(rect.width_) *
1863         float(avoidAreaCenterX) - float(rect.height_);
1864     if (res1 < 0) {
1865         if (res2 < 0) {
1866             avoidArea.topRect_ = avoidAreaRect;
1867         } else {
1868             avoidArea.rightRect_ = avoidAreaRect;
1869         }
1870     } else {
1871         if (res2 < 0) {
1872             avoidArea.leftRect_ = avoidAreaRect;
1873         } else {
1874             avoidArea.bottomRect_ = avoidAreaRect;
1875         }
1876     }
1877 }
1878 
GetSystemAvoidArea(WSRect & rect,AvoidArea & avoidArea)1879 void SceneSession::GetSystemAvoidArea(WSRect& rect, AvoidArea& avoidArea)
1880 {
1881     auto sessionProperty = GetSessionProperty();
1882     if (sessionProperty == nullptr ||
1883         (sessionProperty->GetWindowFlags() & static_cast<uint32_t>(WindowFlag::WINDOW_FLAG_NEED_AVOID))) {
1884         return;
1885     }
1886     uint64_t displayId = sessionProperty->GetDisplayId();
1887     auto screenSession = ScreenSessionManagerClient::GetInstance().GetScreenSession(displayId);
1888     if ((Session::GetWindowMode() == WindowMode::WINDOW_MODE_FLOATING ||
1889          Session::GetWindowMode() == WindowMode::WINDOW_MODE_SPLIT_PRIMARY ||
1890          Session::GetWindowMode() == WindowMode::WINDOW_MODE_SPLIT_SECONDARY) &&
1891         WindowHelper::IsMainWindow(Session::GetWindowType()) &&
1892         (systemConfig_.uiType_ == UI_TYPE_PHONE ||
1893          (systemConfig_.uiType_ == UI_TYPE_PAD && !IsFreeMultiWindowMode())) &&
1894         (!screenSession || screenSession->GetName() != "HiCar")) {
1895         float miniScale = 0.316f; // Pressed mini floating Scale with 0.001 precision
1896         if (Session::GetFloatingScale() <= miniScale) {
1897             return;
1898         }
1899         float vpr = 3.5f; // 3.5f: default pixel ratio
1900         auto display = DisplayManager::GetInstance().GetDefaultDisplay();
1901         if (display == nullptr) {
1902             WLOGFE("display is null");
1903             return;
1904         }
1905         vpr = display->GetVirtualPixelRatio();
1906         int32_t floatingBarHeight = 32; // 32: floating windowBar Height
1907         avoidArea.topRect_.height_ = vpr * floatingBarHeight;
1908         avoidArea.topRect_.width_ = static_cast<uint32_t>(display->GetWidth());
1909         return;
1910     }
1911     std::vector<sptr<SceneSession>> statusBarVector;
1912     if (specificCallback_ != nullptr && specificCallback_->onGetSceneSessionVectorByTypeAndDisplayId_) {
1913         statusBarVector = specificCallback_->onGetSceneSessionVectorByTypeAndDisplayId_(
1914             WindowType::WINDOW_TYPE_STATUS_BAR, sessionProperty->GetDisplayId());
1915     }
1916     for (auto& statusBar : statusBarVector) {
1917         WSRect statusBarRect = statusBar->GetSessionRect();
1918         bool isStatusBarVisible = WindowHelper::IsMainWindow(Session::GetWindowType()) ?
1919             isStatusBarVisible_ : statusBar->isVisible_;
1920         if (!isStatusBarVisible) {
1921             TLOGI(WmsLogTag::WMS_IMMS, "win %{public}d status bar not visible", GetPersistentId());
1922             continue;
1923         }
1924         TLOGI(WmsLogTag::WMS_IMMS, "window %{public}s status bar %{public}s",
1925               rect.ToString().c_str(), statusBarRect.ToString().c_str());
1926         CalculateAvoidAreaRect(rect, statusBarRect, avoidArea);
1927     }
1928     return;
1929 }
1930 
GetKeyboardAvoidArea(WSRect & rect,AvoidArea & avoidArea)1931 void SceneSession::GetKeyboardAvoidArea(WSRect& rect, AvoidArea& avoidArea)
1932 {
1933     if (Session::CheckEmptyKeyboardAvoidAreaIfNeeded()) {
1934         TLOGI(WmsLogTag::WMS_IMMS, "Keyboard avoid area needs to be empty when in floating mode");
1935         return;
1936     }
1937     auto sessionProperty = GetSessionProperty();
1938     if (!sessionProperty) {
1939         TLOGE(WmsLogTag::WMS_IMMS, "Failed to get session property");
1940         return;
1941     }
1942     std::vector<sptr<SceneSession>> inputMethodVector;
1943     if (specificCallback_ != nullptr && specificCallback_->onGetSceneSessionVectorByType_) {
1944         inputMethodVector = specificCallback_->onGetSceneSessionVectorByType_(
1945             WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT);
1946     }
1947     for (auto& inputMethod : inputMethodVector) {
1948         if (inputMethod->GetSessionState() != SessionState::STATE_FOREGROUND &&
1949             inputMethod->GetSessionState() != SessionState::STATE_ACTIVE) {
1950             continue;
1951         }
1952         SessionGravity gravity = inputMethod->GetKeyboardGravity();
1953         if (gravity == SessionGravity::SESSION_GRAVITY_FLOAT) {
1954             continue;
1955         }
1956         if (isKeyboardPanelEnabled_) {
1957             WSRect keyboardRect = {0, 0, 0, 0};
1958             if (inputMethod && inputMethod->GetKeyboardPanelSession()) {
1959                 keyboardRect = inputMethod->GetKeyboardPanelSession()->GetSessionRect();
1960                 inputMethod->RecalculatePanelRectForAvoidArea(keyboardRect);
1961             }
1962             TLOGI(WmsLogTag::WMS_IMMS, "window %{public}s keyboard %{public}s",
1963                   rect.ToString().c_str(), keyboardRect.ToString().c_str());
1964             CalculateAvoidAreaRect(rect, keyboardRect, avoidArea);
1965         } else {
1966             WSRect inputMethodRect = inputMethod->GetSessionRect();
1967             TLOGI(WmsLogTag::WMS_IMMS, "window %{public}s input method %{public}s",
1968                   rect.ToString().c_str(), inputMethodRect.ToString().c_str());
1969             CalculateAvoidAreaRect(rect, inputMethodRect, avoidArea);
1970         }
1971     }
1972     return;
1973 }
1974 
GetCutoutAvoidArea(WSRect & rect,AvoidArea & avoidArea)1975 void SceneSession::GetCutoutAvoidArea(WSRect& rect, AvoidArea& avoidArea)
1976 {
1977     auto display = DisplayManager::GetInstance().GetDisplayById(GetSessionProperty()->GetDisplayId());
1978     if (display == nullptr) {
1979         TLOGE(WmsLogTag::WMS_IMMS, "Failed to get display");
1980         return;
1981     }
1982     sptr<CutoutInfo> cutoutInfo = display->GetCutoutInfo();
1983     if (cutoutInfo == nullptr) {
1984         TLOGI(WmsLogTag::WMS_IMMS, "There is no CutoutInfo");
1985         return;
1986     }
1987     std::vector<DMRect> cutoutAreas = cutoutInfo->GetBoundingRects();
1988     if (cutoutAreas.empty()) {
1989         TLOGI(WmsLogTag::WMS_IMMS, "There is no cutoutAreas");
1990         return;
1991     }
1992     for (auto& cutoutArea : cutoutAreas) {
1993         WSRect cutoutAreaRect = {
1994             cutoutArea.posX_,
1995             cutoutArea.posY_,
1996             cutoutArea.width_,
1997             cutoutArea.height_
1998         };
1999         TLOGI(WmsLogTag::WMS_IMMS, "window %{public}s cutout %{public}s",
2000               rect.ToString().c_str(), cutoutAreaRect.ToString().c_str());
2001         CalculateAvoidAreaRect(rect, cutoutAreaRect, avoidArea);
2002     }
2003 
2004     return;
2005 }
2006 
GetAINavigationBarArea(WSRect rect,AvoidArea & avoidArea) const2007 void SceneSession::GetAINavigationBarArea(WSRect rect, AvoidArea& avoidArea) const
2008 {
2009     if (isDisplayStatusBarTemporarily_.load()) {
2010         TLOGI(WmsLogTag::WMS_IMMS, "temporary show navigation bar, no need to avoid");
2011         return;
2012     }
2013     if (Session::GetWindowMode() == WindowMode::WINDOW_MODE_PIP) {
2014         TLOGI(WmsLogTag::WMS_IMMS, "window mode pip return");
2015         return;
2016     }
2017     auto sessionProperty = GetSessionProperty();
2018     if (!sessionProperty) {
2019         TLOGE(WmsLogTag::WMS_IMMS, "Failed to get session property");
2020         return;
2021     }
2022     WSRect barArea;
2023     if (specificCallback_ != nullptr && specificCallback_->onGetAINavigationBarArea_) {
2024         barArea = specificCallback_->onGetAINavigationBarArea_(sessionProperty->GetDisplayId());
2025     }
2026     TLOGI(WmsLogTag::WMS_IMMS, "window %{public}s AI bar %{public}s",
2027           rect.ToString().c_str(), barArea.ToString().c_str());
2028     CalculateAvoidAreaRect(rect, barArea, avoidArea);
2029 }
2030 
CheckGetAvoidAreaAvailable(AvoidAreaType type)2031 bool SceneSession::CheckGetAvoidAreaAvailable(AvoidAreaType type)
2032 {
2033     if (type == AvoidAreaType::TYPE_KEYBOARD) {
2034         return true;
2035     }
2036     WindowMode mode = GetWindowMode();
2037     WindowType winType = GetWindowType();
2038     std::string uiType = systemConfig_.uiType_;
2039     if (WindowHelper::IsMainWindow(winType)) {
2040         if (mode == WindowMode::WINDOW_MODE_FLOATING && type != AvoidAreaType::TYPE_SYSTEM) {
2041             return false;
2042         }
2043 
2044         if (mode != WindowMode::WINDOW_MODE_FLOATING ||
2045             uiType == UI_TYPE_PHONE || uiType == UI_TYPE_PAD) {
2046             return true;
2047         }
2048     }
2049     if (WindowHelper::IsSubWindow(winType)) {
2050         auto parentSession = GetParentSession();
2051         if (parentSession != nullptr && parentSession->GetSessionRect() == GetSessionRect()) {
2052             return parentSession->CheckGetAvoidAreaAvailable(type);
2053         }
2054     }
2055     TLOGD(WmsLogTag::WMS_IMMS, "win %{public}d type %{public}u "
2056         "avoidAreaType %{public}u windowMode %{public}u, return default avoid area.",
2057         GetPersistentId(), static_cast<uint32_t>(winType), static_cast<uint32_t>(type), static_cast<uint32_t>(mode));
2058     return false;
2059 }
2060 
AddNormalModalUIExtension(const ExtensionWindowEventInfo & extensionInfo)2061 void SceneSession::AddNormalModalUIExtension(const ExtensionWindowEventInfo& extensionInfo)
2062 {
2063     TLOGD(WmsLogTag::WMS_UIEXT, "parentId=%{public}d, persistentId=%{public}d, pid=%{public}d", GetPersistentId(),
2064         extensionInfo.persistentId, extensionInfo.pid);
2065     {
2066         std::unique_lock<std::shared_mutex> lock(modalUIExtensionInfoListMutex_);
2067         modalUIExtensionInfoList_.push_back(extensionInfo);
2068     }
2069     NotifySessionInfoChange();
2070 }
2071 
UpdateNormalModalUIExtension(const ExtensionWindowEventInfo & extensionInfo)2072 void SceneSession::UpdateNormalModalUIExtension(const ExtensionWindowEventInfo& extensionInfo)
2073 {
2074     TLOGD(WmsLogTag::WMS_UIEXT, "persistentId=%{public}d,pid=%{public}d,"
2075         "Rect:[%{public}d %{public}d %{public}d %{public}d]",
2076         extensionInfo.persistentId, extensionInfo.pid, extensionInfo.windowRect.posX_,
2077         extensionInfo.windowRect.posY_, extensionInfo.windowRect.width_, extensionInfo.windowRect.height_);
2078     {
2079         std::unique_lock<std::shared_mutex> lock(modalUIExtensionInfoListMutex_);
2080         auto iter = std::find_if(modalUIExtensionInfoList_.begin(), modalUIExtensionInfoList_.end(),
2081             [extensionInfo](const ExtensionWindowEventInfo& eventInfo) {
2082             return extensionInfo.persistentId == eventInfo.persistentId && extensionInfo.pid == eventInfo.pid;
2083         });
2084         if (iter == modalUIExtensionInfoList_.end()) {
2085             return;
2086         }
2087         iter->windowRect = extensionInfo.windowRect;
2088         iter->uiExtRect = extensionInfo.uiExtRect;
2089         iter->hasUpdatedRect = extensionInfo.hasUpdatedRect;
2090     }
2091     NotifySessionInfoChange();
2092 }
2093 
RemoveNormalModalUIExtension(int32_t persistentId)2094 void SceneSession::RemoveNormalModalUIExtension(int32_t persistentId)
2095 {
2096     TLOGI(WmsLogTag::WMS_UIEXT, "parentId=%{public}d, persistentId=%{public}d", GetPersistentId(), persistentId);
2097     {
2098         std::unique_lock<std::shared_mutex> lock(modalUIExtensionInfoListMutex_);
2099         auto iter = std::find_if(modalUIExtensionInfoList_.begin(), modalUIExtensionInfoList_.end(),
2100             [persistentId](const ExtensionWindowEventInfo& extensionInfo) {
2101             return extensionInfo.persistentId == persistentId;
2102         });
2103         if (iter == modalUIExtensionInfoList_.end()) {
2104             return;
2105         }
2106         modalUIExtensionInfoList_.erase(iter);
2107     }
2108     NotifySessionInfoChange();
2109 }
2110 
RegisterGetConstrainedModalExtWindowInfo(GetConstrainedModalExtWindowInfoFunc && callback)2111 void SceneSession::RegisterGetConstrainedModalExtWindowInfo(GetConstrainedModalExtWindowInfoFunc&& callback)
2112 {
2113     onGetConstrainedModalExtWindowInfoFunc_ = std::move(callback);
2114 }
2115 
GetLastModalUIExtensionEventInfo()2116 std::optional<ExtensionWindowEventInfo> SceneSession::GetLastModalUIExtensionEventInfo()
2117 {
2118     // Priority query constrained modal UIExt, if unavailable, then query normal modal UIExt
2119     if (onGetConstrainedModalExtWindowInfoFunc_) {
2120         if (auto constrainedExtEventInfo = onGetConstrainedModalExtWindowInfoFunc_(this)) {
2121             TLOGD(WmsLogTag::WMS_UIEXT, "get constrained UIExt eventInfo, id: %{public}d",
2122                 constrainedExtEventInfo->persistentId);
2123             return constrainedExtEventInfo;
2124         }
2125     }
2126     std::shared_lock<std::shared_mutex> lock(modalUIExtensionInfoListMutex_);
2127     return modalUIExtensionInfoList_.empty() ? std::nullopt :
2128         std::make_optional<ExtensionWindowEventInfo>(modalUIExtensionInfoList_.back());
2129 }
2130 
GetSessionGlobalPosition(bool useUIExtension)2131 Vector2f SceneSession::GetSessionGlobalPosition(bool useUIExtension)
2132 {
2133     WSRect windowRect = GetSessionGlobalRect();
2134     if (useUIExtension) {
2135         if (auto modalUIExtensionEventInfo = GetLastModalUIExtensionEventInfo()) {
2136             const auto& rect = modalUIExtensionEventInfo.value().windowRect;
2137             windowRect.posX_ = rect.posX_;
2138             windowRect.posY_ = rect.posY_;
2139         }
2140     }
2141     Vector2f position(windowRect.posX_, windowRect.posY_);
2142     return position;
2143 }
2144 
GetSessionGlobalRectWithSingleHandScale()2145 WSRect SceneSession::GetSessionGlobalRectWithSingleHandScale()
2146 {
2147     WSRect rectWithTransform = GetSessionGlobalRect();
2148     const SingleHandTransform& transform = GetSingleHandTransform();
2149     if (transform.posX == 0 && transform.posY == 0) {
2150         return rectWithTransform;
2151     }
2152     rectWithTransform.posX_ =
2153         static_cast<int32_t>(static_cast<float>(rectWithTransform.posX_) * transform.scaleX) + transform.posX;
2154     rectWithTransform.posY_ =
2155         static_cast<int32_t>(static_cast<float>(rectWithTransform.posY_) * transform.scaleY) + transform.posY;
2156     rectWithTransform.width_ =
2157         static_cast<int32_t>(static_cast<float>(rectWithTransform.width_) * transform.scaleX);
2158     rectWithTransform.height_ =
2159         static_cast<int32_t>(static_cast<float>(rectWithTransform.height_) * transform.scaleY);
2160     return rectWithTransform;
2161 }
2162 
AddUIExtSurfaceNodeId(uint64_t surfaceNodeId,int32_t persistentId)2163 void SceneSession::AddUIExtSurfaceNodeId(uint64_t surfaceNodeId, int32_t persistentId)
2164 {
2165     std::unique_lock<std::shared_mutex> lock(uiExtNodeIdToPersistentIdMapMutex_);
2166     TLOGI(WmsLogTag::WMS_UIEXT, "Add uiExtension pair surfaceNodeId=%{public}" PRIu64 ", persistentId=%{public}d",
2167         surfaceNodeId, persistentId);
2168     uiExtNodeIdToPersistentIdMap_.insert(std::make_pair(surfaceNodeId, persistentId));
2169 }
2170 
RemoveUIExtSurfaceNodeId(int32_t persistentId)2171 void SceneSession::RemoveUIExtSurfaceNodeId(int32_t persistentId)
2172 {
2173     std::unique_lock<std::shared_mutex> lock(uiExtNodeIdToPersistentIdMapMutex_);
2174     TLOGI(WmsLogTag::WMS_UIEXT, "Remove uiExtension by persistentId=%{public}d", persistentId);
2175     auto pairIter = std::find_if(uiExtNodeIdToPersistentIdMap_.begin(), uiExtNodeIdToPersistentIdMap_.end(),
2176         [persistentId](const auto& entry) { return entry.second == persistentId; });
2177     if (pairIter != uiExtNodeIdToPersistentIdMap_.end()) {
2178         TLOGI(WmsLogTag::WMS_UIEXT,
2179             "Successfully removed uiExtension pair surfaceNodeId=%{public}" PRIu64 ", persistentId=%{public}d",
2180             pairIter->first, persistentId);
2181         uiExtNodeIdToPersistentIdMap_.erase(pairIter);
2182         return;
2183     }
2184     TLOGE(WmsLogTag::WMS_UIEXT, "Failed to remove uiExtension by persistentId=%{public}d", persistentId);
2185 }
2186 
GetUIExtPersistentIdBySurfaceNodeId(uint64_t surfaceNodeId) const2187 int32_t SceneSession::GetUIExtPersistentIdBySurfaceNodeId(uint64_t surfaceNodeId) const
2188 {
2189     std::shared_lock<std::shared_mutex> lock(uiExtNodeIdToPersistentIdMapMutex_);
2190     auto ret = uiExtNodeIdToPersistentIdMap_.find(surfaceNodeId);
2191     if (ret == uiExtNodeIdToPersistentIdMap_.end()) {
2192         TLOGE(WmsLogTag::WMS_UIEXT, "Failed to find uiExtension by surfaceNodeId=%{public}" PRIu64 "", surfaceNodeId);
2193         return 0;
2194     }
2195     return ret->second;
2196 }
2197 
GetAvoidAreaByTypeInner(AvoidAreaType type)2198 AvoidArea SceneSession::GetAvoidAreaByTypeInner(AvoidAreaType type)
2199 {
2200     if (!CheckGetAvoidAreaAvailable(type)) {
2201         return {};
2202     }
2203 
2204     AvoidArea avoidArea;
2205     WSRect rect = GetSessionRect();
2206     switch (type) {
2207         case AvoidAreaType::TYPE_SYSTEM: {
2208             GetSystemAvoidArea(rect, avoidArea);
2209             return avoidArea;
2210         }
2211         case AvoidAreaType::TYPE_CUTOUT: {
2212             GetCutoutAvoidArea(rect, avoidArea);
2213             return avoidArea;
2214         }
2215         case AvoidAreaType::TYPE_SYSTEM_GESTURE: {
2216             return avoidArea;
2217         }
2218         case AvoidAreaType::TYPE_KEYBOARD: {
2219             GetKeyboardAvoidArea(rect, avoidArea);
2220             return avoidArea;
2221         }
2222         case AvoidAreaType::TYPE_NAVIGATION_INDICATOR: {
2223             GetAINavigationBarArea(rect, avoidArea);
2224             return avoidArea;
2225         }
2226         default: {
2227             TLOGE(WmsLogTag::WMS_IMMS, "cannot find type %{public}u, id %{public}d",
2228                 type, GetPersistentId());
2229             return avoidArea;
2230         }
2231     }
2232 }
2233 
GetAvoidAreaByType(AvoidAreaType type)2234 AvoidArea SceneSession::GetAvoidAreaByType(AvoidAreaType type)
2235 {
2236     auto task = [weakThis = wptr(this), type]() -> AvoidArea {
2237         auto session = weakThis.promote();
2238         if (!session) {
2239             TLOGE(WmsLogTag::WMS_IMMS, "session is null");
2240             return {};
2241         }
2242         return session->GetAvoidAreaByTypeInner(type);
2243     };
2244     return PostSyncTask(task, "GetAvoidAreaByType");
2245 }
2246 
GetAllAvoidAreas(std::map<AvoidAreaType,AvoidArea> & avoidAreas)2247 WSError SceneSession::GetAllAvoidAreas(std::map<AvoidAreaType, AvoidArea>& avoidAreas)
2248 {
2249     auto task = [weakThis = wptr(this), &avoidAreas] {
2250         auto session = weakThis.promote();
2251         if (!session) {
2252             TLOGE(WmsLogTag::WMS_IMMS, "session is null");
2253             return WSError::WS_ERROR_NULLPTR;
2254         }
2255 
2256         using T = std::underlying_type_t<AvoidAreaType>;
2257         for (T avoidType = static_cast<T>(AvoidAreaType::TYPE_SYSTEM);
2258             avoidType <= static_cast<T>(AvoidAreaType::TYPE_NAVIGATION_INDICATOR); avoidType++) {
2259             auto type = static_cast<AvoidAreaType>(avoidType);
2260             auto area = session->GetAvoidAreaByTypeInner(type);
2261             // code below aims to check if ai bar avoid area reaches window rect's bottom
2262             // it should not be removed until unexpected window rect update issues were solved
2263             if (type == AvoidAreaType::TYPE_NAVIGATION_INDICATOR) {
2264                 if (session->isAINavigationBarAvoidAreaValid_ &&
2265                     !session->isAINavigationBarAvoidAreaValid_(area, session->GetSessionRect().height_)) {
2266                     continue;
2267                 }
2268             }
2269             avoidAreas[type] = area;
2270         }
2271         return WSError::WS_OK;
2272     };
2273     return PostSyncTask(task, "GetAllAvoidAreas");
2274 }
2275 
UpdateAvoidArea(const sptr<AvoidArea> & avoidArea,AvoidAreaType type)2276 WSError SceneSession::UpdateAvoidArea(const sptr<AvoidArea>& avoidArea, AvoidAreaType type)
2277 {
2278     if (!sessionStage_) {
2279         return WSError::WS_ERROR_NULLPTR;
2280     }
2281     if (!GetForegroundInteractiveStatus()) {
2282         TLOGD(WmsLogTag::WMS_IMMS, "win [%{public}d] avoid area update rejected by recent", GetPersistentId());
2283         return WSError::WS_DO_NOTHING;
2284     }
2285     return sessionStage_->UpdateAvoidArea(avoidArea, type);
2286 }
2287 
SetPipActionEvent(const std::string & action,int32_t status)2288 WSError SceneSession::SetPipActionEvent(const std::string& action, int32_t status)
2289 {
2290     TLOGI(WmsLogTag::WMS_PIP, "action: %{public}s, status: %{public}d", action.c_str(), status);
2291     if (!sessionStage_) {
2292         return WSError::WS_ERROR_NULLPTR;
2293     }
2294     return sessionStage_->SetPipActionEvent(action, status);
2295 }
2296 
SetPiPControlEvent(WsPiPControlType controlType,WsPiPControlStatus status)2297 WSError SceneSession::SetPiPControlEvent(WsPiPControlType controlType, WsPiPControlStatus status)
2298 {
2299     TLOGI(WmsLogTag::WMS_PIP, "controlType: %{public}u, status: %{public}u", controlType, status);
2300     if (GetWindowType() != WindowType::WINDOW_TYPE_PIP || GetWindowMode() != WindowMode::WINDOW_MODE_PIP) {
2301         return WSError::WS_ERROR_INVALID_TYPE;
2302     }
2303     if (!sessionStage_) {
2304         return WSError::WS_ERROR_NULLPTR;
2305     }
2306     return sessionStage_->SetPiPControlEvent(controlType, status);
2307 }
2308 
NotifyPipWindowSizeChange(uint32_t width,uint32_t height,double scale)2309 WSError SceneSession::NotifyPipWindowSizeChange(uint32_t width, uint32_t height, double scale)
2310 {
2311     TLOGI(WmsLogTag::WMS_PIP, "width: %{public}u, height: %{public}u scale: %{public}f", width, height, scale);
2312     if (!sessionStage_) {
2313         return WSError::WS_ERROR_NULLPTR;
2314     }
2315     return sessionStage_->NotifyPipWindowSizeChange(width, height, scale);
2316 }
2317 
RegisterProcessPrepareClosePiPCallback(NotifyPrepareClosePiPSessionFunc && callback)2318 void SceneSession::RegisterProcessPrepareClosePiPCallback(NotifyPrepareClosePiPSessionFunc&& callback)
2319 {
2320     auto task = [weakThis = wptr(this), callback = std::move(callback)] {
2321         auto session = weakThis.promote();
2322         if (!session) {
2323             TLOGNE(WmsLogTag::WMS_PIP, "session is null");
2324             return;
2325         }
2326         session->onPrepareClosePiPSession_ = std::move(callback);
2327     };
2328     PostTask(task, __func__);
2329 }
2330 
HandleStyleEvent(MMI::WindowArea area)2331 void SceneSession::HandleStyleEvent(MMI::WindowArea area)
2332 {
2333     static std::pair<int32_t, MMI::WindowArea> preWindowArea =
2334         std::make_pair(INVALID_WINDOW_ID, MMI::WindowArea::EXIT);
2335     if (preWindowArea.first == Session::GetWindowId() && preWindowArea.second == area) {
2336         return;
2337     }
2338     if (area != MMI::WindowArea::EXIT) {
2339         if (Session::SetPointerStyle(area) != WSError::WS_OK) {
2340             WLOGFE("Failed to set the cursor style");
2341         }
2342     }
2343     preWindowArea = { Session::GetWindowId(), area };
2344 }
2345 
HandleEnterWinwdowArea(int32_t displayX,int32_t displayY)2346 WSError SceneSession::HandleEnterWinwdowArea(int32_t displayX, int32_t displayY)
2347 {
2348     if (displayX < 0 || displayY < 0) {
2349         TLOGE(WmsLogTag::WMS_EVENT, "Illegal parameter, displayX:%{private}d, displayY:%{private}d",
2350             displayX, displayY);
2351         return WSError::WS_ERROR_INVALID_PARAM;
2352     }
2353 
2354     auto windowType = Session::GetWindowType();
2355     auto iter = Session::windowAreas_.cend();
2356     if (!IsSystemSession() &&
2357         Session::GetWindowMode() == WindowMode::WINDOW_MODE_FLOATING &&
2358         (windowType == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW || WindowHelper::IsSubWindow(windowType))) {
2359         iter = Session::windowAreas_.cbegin();
2360         for (;iter != Session::windowAreas_.cend(); ++iter) {
2361             WSRectF rect = iter->second;
2362             if (rect.IsInRegion(displayX, displayY)) {
2363                 break;
2364             }
2365         }
2366     }
2367 
2368     MMI::WindowArea area = MMI::WindowArea::EXIT;
2369     if (iter == Session::windowAreas_.cend()) {
2370         bool isInRegion = false;
2371         WSRect rect = Session::winRect_;
2372         if (Session::GetWindowMode() == WindowMode::WINDOW_MODE_FLOATING &&
2373             (windowType == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW || WindowHelper::IsSubWindow(windowType))) {
2374             WSRectF rectF = Session::UpdateHotRect(rect);
2375             isInRegion = rectF.IsInRegion(displayX, displayY);
2376         } else {
2377             isInRegion = rect.IsInRegion(displayX, displayY);
2378         }
2379         if (!isInRegion) {
2380             WLOGFE("The wrong event(%{public}d, %{public}d) could not be matched to the region:"
2381                 "[%{public}d, %{public}d, %{public}d, %{public}d]",
2382                 displayX, displayY, rect.posX_, rect.posY_, rect.width_, rect.height_);
2383             return WSError::WS_ERROR_INVALID_TYPE;
2384         }
2385         area = MMI::WindowArea::FOCUS_ON_INNER;
2386     } else {
2387         area = iter->first;
2388     }
2389     HandleStyleEvent(area);
2390     return WSError::WS_OK;
2391 }
2392 
ProcessPointDownSession(int32_t posX,int32_t posY)2393 WSError SceneSession::ProcessPointDownSession(int32_t posX, int32_t posY)
2394 {
2395     const auto& id = GetPersistentId();
2396     WLOGFI("id: %{public}d, type: %{public}d", id, GetWindowType());
2397 
2398     // notify touch outside
2399     if (specificCallback_ != nullptr && specificCallback_->onSessionTouchOutside_ &&
2400         sessionInfo_.bundleName_.find("SCBGestureBack") == std::string::npos) {
2401         specificCallback_->onSessionTouchOutside_(id);
2402     }
2403 
2404     // notify outside down event
2405     if (specificCallback_ != nullptr && specificCallback_->onOutsideDownEvent_) {
2406         specificCallback_->onOutsideDownEvent_(posX, posY);
2407     }
2408     return WSError::WS_OK;
2409 }
2410 
SendPointEventForMoveDrag(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)2411 WSError SceneSession::SendPointEventForMoveDrag(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
2412 {
2413     NotifyOutsideDownEvent(pointerEvent);
2414     TransferPointerEvent(pointerEvent, false);
2415     return WSError::WS_OK;
2416 }
2417 
NotifyOutsideDownEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)2418 void SceneSession::NotifyOutsideDownEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
2419 {
2420     // notify touchOutside and touchDown event
2421     int32_t action = pointerEvent->GetPointerAction();
2422     if (action != MMI::PointerEvent::POINTER_ACTION_DOWN &&
2423         action != MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN) {
2424         return;
2425     }
2426 
2427     MMI::PointerEvent::PointerItem pointerItem;
2428     if (!pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
2429         return;
2430     }
2431 
2432     // notify touch outside
2433     if (specificCallback_ != nullptr && specificCallback_->onSessionTouchOutside_ &&
2434         sessionInfo_.bundleName_.find("SCBGestureBack") == std::string::npos) {
2435         specificCallback_->onSessionTouchOutside_(GetPersistentId());
2436     }
2437 
2438     // notify outside down event
2439     if (specificCallback_ != nullptr && specificCallback_->onOutsideDownEvent_) {
2440         specificCallback_->onOutsideDownEvent_(pointerItem.GetDisplayX(), pointerItem.GetDisplayY());
2441     }
2442 }
2443 
TransferPointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent,bool needNotifyClient)2444 WSError SceneSession::TransferPointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent,
2445     bool needNotifyClient)
2446 {
2447     WLOGFD("[WMSCom] TransferPointEvent, id: %{public}d, type: %{public}d, needNotifyClient: %{public}d",
2448         GetPersistentId(), GetWindowType(), needNotifyClient);
2449     if (pointerEvent == nullptr) {
2450         WLOGFE("pointerEvent is null");
2451         return WSError::WS_ERROR_NULLPTR;
2452     }
2453 
2454     int32_t action = pointerEvent->GetPointerAction();
2455     {
2456         bool isSystemWindow = GetSessionInfo().isSystem_;
2457         std::lock_guard<std::mutex> guard(enterSessionMutex_);
2458         if (action == MMI::PointerEvent::POINTER_ACTION_ENTER_WINDOW) {
2459             WLOGFD("Set enter session, persistentId:%{public}d", GetPersistentId());
2460             enterSession_ = wptr<SceneSession>(this);
2461         }
2462         if ((enterSession_ != nullptr) &&
2463             (isSystemWindow && (action != MMI::PointerEvent::POINTER_ACTION_ENTER_WINDOW))) {
2464             WLOGFD("Remove enter session, persistentId:%{public}d", GetPersistentId());
2465             enterSession_ = nullptr;
2466         }
2467     }
2468 
2469     if (!CheckPointerEventDispatch(pointerEvent)) {
2470         WLOGFI("Do not dispatch this pointer event");
2471         return WSError::WS_DO_NOTHING;
2472     }
2473 
2474     bool isPointDown = (action == MMI::PointerEvent::POINTER_ACTION_DOWN ||
2475         action == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN);
2476 
2477     auto property = GetSessionProperty();
2478     if (property == nullptr) {
2479         return Session::TransferPointerEvent(pointerEvent, needNotifyClient);
2480     }
2481     auto windowType = property->GetWindowType();
2482     bool isMovableWindowType = IsMovableWindowType();
2483     bool isMainWindow = WindowHelper::IsMainWindow(windowType);
2484     bool isSubWindow = WindowHelper::IsSubWindow(windowType);
2485     bool isDialog = WindowHelper::IsDialogWindow(windowType);
2486     bool isMaxModeAvoidSysBar = property->GetMaximizeMode() == MaximizeMode::MODE_AVOID_SYSTEM_BAR;
2487     bool isDragAccessibleSystemWindow = WindowHelper::IsSystemWindow(windowType) && IsDragAccessible() &&
2488         !isDialog;
2489     bool isMovableSystemWindow = WindowHelper::IsSystemWindow(windowType) && !isDialog;
2490     TLOGD(WmsLogTag::WMS_EVENT, "%{public}s: %{public}d && %{public}d", property->GetWindowName().c_str(),
2491         WindowHelper::IsSystemWindow(windowType), IsDragAccessible());
2492     if (isMovableWindowType && !isMaxModeAvoidSysBar &&
2493         (isMainWindow || isSubWindow || isDialog || isDragAccessibleSystemWindow || isMovableSystemWindow)) {
2494         if (CheckDialogOnForeground() && isPointDown) {
2495             HandlePointDownDialog();
2496             pointerEvent->MarkProcessed();
2497             TLOGI(WmsLogTag::WMS_DIALOG, "There is dialog window foreground");
2498             return WSError::WS_OK;
2499         }
2500         if (!moveDragController_) {
2501             WLOGE("moveDragController_ is null");
2502             return Session::TransferPointerEvent(pointerEvent, needNotifyClient);
2503         }
2504         if ((property->GetWindowMode() == WindowMode::WINDOW_MODE_FLOATING && IsDragAccessible()) ||
2505             isDragAccessibleSystemWindow) {
2506             auto isPC = systemConfig_.uiType_ == UI_TYPE_PC;
2507             if ((isPC || IsFreeMultiWindowMode() || (property->GetIsPcAppInPad() && !isMainWindow)) &&
2508                 moveDragController_->ConsumeDragEvent(pointerEvent, winRect_, property, systemConfig_)) {
2509                 auto surfaceNode = GetSurfaceNode();
2510                 moveDragController_->UpdateGravityWhenDrag(pointerEvent, surfaceNode);
2511                 PresentFoucusIfNeed(pointerEvent->GetPointerAction());
2512                 pointerEvent->MarkProcessed();
2513                 return WSError::WS_OK;
2514             }
2515         }
2516         if ((WindowHelper::IsMainWindow(windowType) ||
2517              WindowHelper::IsSubWindow(windowType) ||
2518              WindowHelper::IsSystemWindow(windowType)) &&
2519             moveDragController_->ConsumeMoveEvent(pointerEvent, winRect_)) {
2520             PresentFoucusIfNeed(pointerEvent->GetPointerAction());
2521             pointerEvent->MarkProcessed();
2522             Session::TransferPointerEvent(pointerEvent, needNotifyClient);
2523             return WSError::WS_OK;
2524         }
2525     }
2526 
2527     bool raiseEnabled = property->GetWindowType() == WindowType::WINDOW_TYPE_DIALOG && property->GetRaiseEnabled() &&
2528         (action == MMI::PointerEvent::POINTER_ACTION_DOWN || action == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN);
2529     if (raiseEnabled) {
2530         RaiseToAppTopForPointDown();
2531     }
2532     // modify the window coordinates when move end
2533     MMI::PointerEvent::PointerItem pointerItem;
2534     if ((action == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP || action == MMI::PointerEvent::POINTER_ACTION_MOVE) &&
2535         needNotifyClient && pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
2536         int32_t windowX = pointerItem.GetDisplayX() - winRect_.posX_;
2537         int32_t windowY = pointerItem.GetDisplayY() - winRect_.posY_;
2538         TLOGD(WmsLogTag::WMS_EVENT, "move end position: windowX:%{private}d windowY:%{private}d action:%{public}d",
2539             windowX, windowY, action);
2540         pointerItem.SetWindowX(windowX);
2541         pointerItem.SetWindowY(windowY);
2542         pointerEvent->AddPointerItem(pointerItem);
2543     }
2544     return Session::TransferPointerEvent(pointerEvent, needNotifyClient);
2545 }
2546 
IsMovableWindowType()2547 bool SceneSession::IsMovableWindowType()
2548 {
2549     auto property = GetSessionProperty();
2550     if (property == nullptr) {
2551         TLOGE(WmsLogTag::WMS_LAYOUT, "property is null");
2552         return false;
2553     }
2554 
2555     return property->GetWindowMode() == WindowMode::WINDOW_MODE_FLOATING ||
2556         property->GetWindowMode() == WindowMode::WINDOW_MODE_SPLIT_PRIMARY ||
2557         property->GetWindowMode() == WindowMode::WINDOW_MODE_SPLIT_SECONDARY ||
2558         IsFullScreenMovable();
2559 }
2560 
IsFullScreenMovable()2561 bool SceneSession::IsFullScreenMovable()
2562 {
2563     auto property = GetSessionProperty();
2564     if (property == nullptr) {
2565         TLOGE(WmsLogTag::WMS_LAYOUT, "property is null");
2566         return false;
2567     }
2568     return property->GetWindowMode() == WindowMode::WINDOW_MODE_FULLSCREEN &&
2569         WindowHelper::IsWindowModeSupported(property->GetWindowModeSupportType(), WindowMode::WINDOW_MODE_FLOATING);
2570 }
2571 
IsMovable()2572 bool SceneSession::IsMovable()
2573 {
2574     if (!moveDragController_) {
2575         TLOGW(WmsLogTag::WMS_LAYOUT, "moveDragController_ is null, id: %{public}d", GetPersistentId());
2576         return false;
2577     }
2578 
2579     bool windowIsMovable = moveDragController_ && !moveDragController_->GetStartDragFlag() &&
2580                            IsMovableWindowType() && moveDragController_->HasPointDown();
2581     auto property = GetSessionProperty();
2582     if (property->GetWindowType() != WindowType::WINDOW_TYPE_INPUT_METHOD_STATUS_BAR &&
2583         property->GetWindowType() != WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT) {
2584         windowIsMovable = windowIsMovable && IsFocused();
2585     }
2586     if (!windowIsMovable) {
2587         TLOGW(WmsLogTag::WMS_LAYOUT, "Window is not movable, id: %{public}d, startDragFlag: %{public}d, "
2588             "isFocused: %{public}d, movableWindowType: %{public}d, hasPointDown: %{public}d",
2589             GetPersistentId(), moveDragController_->GetStartDragFlag(), IsFocused(), IsMovableWindowType(),
2590             moveDragController_->HasPointDown());
2591         return false;
2592     }
2593     return true;
2594 }
2595 
RequestSessionBack(bool needMoveToBackground)2596 WSError SceneSession::RequestSessionBack(bool needMoveToBackground)
2597 {
2598     auto task = [weakThis = wptr(this), needMoveToBackground]() {
2599         auto session = weakThis.promote();
2600         if (!session) {
2601             WLOGFE("session is null");
2602             return WSError::WS_ERROR_DESTROYED_OBJECT;
2603         }
2604         if (!session->backPressedFunc_) {
2605             WLOGFW("Session didn't register back event consumer!");
2606             return WSError::WS_DO_NOTHING;
2607         }
2608         if (g_enableForceUIFirst) {
2609             auto rsTransaction = RSTransactionProxy::GetInstance();
2610             if (rsTransaction) {
2611                 rsTransaction->Begin();
2612             }
2613             auto leashWinSurfaceNode = session->GetLeashWinSurfaceNode();
2614             if (leashWinSurfaceNode) {
2615                 leashWinSurfaceNode->SetForceUIFirst(true);
2616                 WLOGFI("leashWinSurfaceNode_ SetForceUIFirst id:%{public}u!", session->GetPersistentId());
2617             } else {
2618                 WLOGFI("failed, leashWinSurfaceNode_ null id:%{public}u", session->GetPersistentId());
2619             }
2620             if (rsTransaction) {
2621                 rsTransaction->Commit();
2622             }
2623         }
2624         session->backPressedFunc_(needMoveToBackground);
2625         return WSError::WS_OK;
2626     };
2627     PostTask(task, "RequestSessionBack:" + std::to_string(needMoveToBackground));
2628     return WSError::WS_OK;
2629 }
2630 
GetEnterWindow()2631 const wptr<SceneSession> SceneSession::GetEnterWindow()
2632 {
2633     std::lock_guard<std::mutex> guard(enterSessionMutex_);
2634     return enterSession_;
2635 }
2636 
ClearEnterWindow()2637 void SceneSession::ClearEnterWindow()
2638 {
2639     std::lock_guard<std::mutex> guard(enterSessionMutex_);
2640     enterSession_ = nullptr;
2641 }
2642 
2643 #ifdef DEVICE_STATUS_ENABLE
RotateDragWindow(std::shared_ptr<RSTransaction> rsTransaction)2644 void SceneSession::RotateDragWindow(std::shared_ptr<RSTransaction> rsTransaction)
2645 {
2646     Msdp::DeviceStatus::DragState state = Msdp::DeviceStatus::DragState::STOP;
2647     Msdp::DeviceStatus::InteractionManager::GetInstance()->GetDragState(state);
2648     if (state == Msdp::DeviceStatus::DragState::START) {
2649         Msdp::DeviceStatus::InteractionManager::GetInstance()->RotateDragWindowSync(rsTransaction);
2650     }
2651 }
2652 #endif // DEVICE_STATUS_ENABLE
2653 
NotifySessionRectChange(const WSRect & rect,const SizeChangeReason & reason)2654 void SceneSession::NotifySessionRectChange(const WSRect& rect, const SizeChangeReason& reason)
2655 {
2656     auto task = [weakThis = wptr(this), rect, reason]() {
2657         auto session = weakThis.promote();
2658         if (!session) {
2659             WLOGFE("session is null");
2660             return;
2661         }
2662         if (session->sessionRectChangeFunc_) {
2663             HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "SceneSession::NotifySessionRectChange");
2664             session->sessionRectChangeFunc_(rect, reason);
2665         }
2666     };
2667     PostTask(task, "NotifySessionRectChange" + GetRectInfo(rect));
2668 }
2669 
IsDecorEnable() const2670 bool SceneSession::IsDecorEnable() const
2671 {
2672     auto property = GetSessionProperty();
2673     if (property == nullptr) {
2674         WLOGE("property is nullptr");
2675         return false;
2676     }
2677     auto windowType = property->GetWindowType();
2678     bool isMainWindow = WindowHelper::IsMainWindow(windowType);
2679     bool isSubWindow = WindowHelper::IsSubWindow(windowType);
2680     bool isDialogWindow = WindowHelper::IsDialogWindow(windowType);
2681     bool isValidWindow = isMainWindow ||
2682         ((isSubWindow || isDialogWindow) && property->IsDecorEnable());
2683     bool isWindowModeSupported = WindowHelper::IsWindowModeSupported(
2684         systemConfig_.decorWindowModeSupportType_, property->GetWindowMode());
2685     bool enable = isValidWindow && systemConfig_.isSystemDecorEnable_ && isWindowModeSupported;
2686     return enable;
2687 }
2688 
GetRatioPreferenceKey()2689 std::string SceneSession::GetRatioPreferenceKey()
2690 {
2691     std::string key = sessionInfo_.bundleName_ + sessionInfo_.moduleName_ + sessionInfo_.abilityName_;
2692     if (key.length() > ScenePersistentStorage::MAX_KEY_LEN) {
2693         return key.substr(key.length() - ScenePersistentStorage::MAX_KEY_LEN);
2694     }
2695     return key;
2696 }
2697 
SaveAspectRatio(float ratio)2698 bool SceneSession::SaveAspectRatio(float ratio)
2699 {
2700     std::string key = GetRatioPreferenceKey();
2701     if (!key.empty()) {
2702         ScenePersistentStorage::Insert(key, ratio, ScenePersistentStorageType::ASPECT_RATIO);
2703         WLOGD("SceneSession save aspectRatio , key %{public}s, value: %{public}f", key.c_str(), aspectRatio_);
2704         return true;
2705     }
2706     return false;
2707 }
2708 
FixRectByLimits(WindowLimits limits,WSRect & rect,float ratio,bool isDecor,float vpr)2709 void SceneSession::FixRectByLimits(WindowLimits limits, WSRect& rect, float ratio, bool isDecor, float vpr)
2710 {
2711     if (isDecor) {
2712         rect.width_ = SessionUtils::ToLayoutWidth(rect.width_, vpr);
2713         rect.height_ = SessionUtils::ToLayoutHeight(rect.height_, vpr);
2714         limits.minWidth_ = SessionUtils::ToLayoutWidth(limits.minWidth_, vpr);
2715         limits.maxWidth_ = SessionUtils::ToLayoutWidth(limits.maxWidth_, vpr);
2716         limits.minHeight_ = SessionUtils::ToLayoutHeight(limits.minHeight_, vpr);
2717         limits.maxHeight_ = SessionUtils::ToLayoutHeight(limits.maxHeight_, vpr);
2718     }
2719     if (static_cast<uint32_t>(rect.height_) > limits.maxHeight_) {
2720         rect.height_ = static_cast<int32_t>(limits.maxHeight_);
2721         rect.width_ = floor(rect.height_ * ratio);
2722     } else if (static_cast<uint32_t>(rect.width_) > limits.maxWidth_) {
2723         rect.width_ = static_cast<int32_t>(limits.maxWidth_);
2724         rect.height_ = floor(rect.width_ / ratio);
2725     } else if (static_cast<uint32_t>(rect.width_) < limits.minWidth_) {
2726         rect.width_ = static_cast<int32_t>(limits.minWidth_);
2727         rect.height_ = ceil(rect.width_ / ratio);
2728     } else if (static_cast<uint32_t>(rect.height_) < limits.minHeight_) {
2729         rect.height_ = static_cast<int32_t>(limits.minHeight_);
2730         rect.width_ = ceil(rect.height_ * ratio);
2731     }
2732     if (isDecor) {
2733         rect.height_ = SessionUtils::ToWinHeight(rect.height_, vpr) ;
2734         rect.width_ = SessionUtils::ToWinWidth(rect.width_, vpr);
2735     }
2736 }
FixRectByAspectRatio(WSRect & rect)2737 bool SceneSession::FixRectByAspectRatio(WSRect& rect)
2738 {
2739     const int tolerancePx = 2; // 2: tolerance delta pixel value, unit: px
2740     WSRect originalRect = rect;
2741     auto property = GetSessionProperty();
2742     if (!property || property->GetWindowMode() != WindowMode::WINDOW_MODE_FLOATING ||
2743         !WindowHelper::IsMainWindow(GetWindowType())) {
2744         return false;
2745     }
2746 
2747     if (MathHelper::NearZero(aspectRatio_)) {
2748         return false;
2749     }
2750     float vpr = 1.5f; // 1.5f: default virtual pixel ratio
2751     auto display = DisplayManager::GetInstance().GetDefaultDisplay();
2752     if (display) {
2753         vpr = display->GetVirtualPixelRatio();
2754     }
2755     int32_t minW;
2756     int32_t maxW;
2757     int32_t minH;
2758     int32_t maxH;
2759     SessionUtils::CalcFloatWindowRectLimits(property->GetWindowLimits(), systemConfig_.maxFloatingWindowSize_, vpr,
2760         minW, maxW, minH, maxH);
2761     rect.width_ = std::max(minW, static_cast<int32_t>(rect.width_));
2762     rect.width_ = std::min(maxW, static_cast<int32_t>(rect.width_));
2763     rect.height_ = std::max(minH, static_cast<int32_t>(rect.height_));
2764     rect.height_ = std::min(maxH, static_cast<int32_t>(rect.height_));
2765     if (IsDecorEnable()) {
2766         if (SessionUtils::ToLayoutWidth(rect.width_, vpr) >
2767                 SessionUtils::ToLayoutHeight(rect.height_, vpr) * aspectRatio_) {
2768             rect.width_ = SessionUtils::ToWinWidth(SessionUtils::ToLayoutHeight(rect.height_, vpr)* aspectRatio_, vpr);
2769         } else {
2770             rect.height_ = SessionUtils::ToWinHeight(SessionUtils::ToLayoutWidth(rect.width_, vpr) / aspectRatio_, vpr);
2771         }
2772     } else {
2773         if (rect.width_ > rect.height_ * aspectRatio_) {
2774             rect.width_ = rect.height_ * aspectRatio_;
2775         } else {
2776             rect.height_ = rect.width_ / aspectRatio_;
2777         }
2778     }
2779     FixRectByLimits(property->GetWindowLimits(), rect, aspectRatio_, IsDecorEnable(), vpr);
2780     if (std::abs(static_cast<int32_t>(originalRect.width_) - static_cast<int32_t>(rect.width_)) <= tolerancePx &&
2781         std::abs(static_cast<int32_t>(originalRect.height_) - static_cast<int32_t>(rect.height_)) <= tolerancePx) {
2782         rect = originalRect;
2783         return false;
2784     }
2785     return true;
2786 }
2787 
HandleCompatibleModeMoveDrag(WSRect & rect,const SizeChangeReason & reason,bool isSupportDragInPcCompatibleMode)2788 void SceneSession::HandleCompatibleModeMoveDrag(WSRect& rect, const SizeChangeReason& reason,
2789     bool isSupportDragInPcCompatibleMode)
2790 {
2791     auto sessionProperty = GetSessionProperty();
2792     if (!sessionProperty) {
2793         TLOGE(WmsLogTag::WMS_SCB, "sessionProperty is null");
2794         return;
2795     }
2796     WindowLimits windowLimits = sessionProperty->GetWindowLimits();
2797     const int32_t compatibleInPcPortraitWidth = sessionProperty->GetCompatibleInPcPortraitWidth();
2798     const int32_t compatibleInPcPortraitHeight = sessionProperty->GetCompatibleInPcPortraitHeight();
2799     const int32_t compatibleInPcLandscapeWidth = sessionProperty->GetCompatibleInPcLandscapeWidth();
2800     const int32_t compatibleInPcLandscapeHeight = sessionProperty->GetCompatibleInPcLandscapeHeight();
2801     const int32_t compatibleInPcDragLimit = compatibleInPcLandscapeWidth - compatibleInPcPortraitWidth;
2802     WSRect windowRect = GetSessionRect();
2803     auto windowWidth = windowRect.width_;
2804     auto windowHeight = windowRect.height_;
2805 
2806     if (reason != SizeChangeReason::DRAG_MOVE) {
2807         if (isSupportDragInPcCompatibleMode && windowWidth > windowHeight &&
2808             (rect.width_ < compatibleInPcLandscapeWidth - compatibleInPcDragLimit ||
2809              rect.width_ == static_cast<int32_t>(windowLimits.minWidth_))) {
2810             rect.width_ = compatibleInPcPortraitWidth;
2811             rect.height_ = compatibleInPcPortraitHeight;
2812             SetSurfaceBounds(rect);
2813             UpdateSizeChangeReason(reason);
2814             UpdateRect(rect, reason, "compatibleInPcPortrait");
2815         } else if (isSupportDragInPcCompatibleMode && windowWidth < windowHeight &&
2816             rect.width_ > compatibleInPcPortraitWidth + compatibleInPcDragLimit) {
2817             rect.width_ = compatibleInPcLandscapeWidth;
2818             rect.height_ = compatibleInPcLandscapeHeight;
2819             SetSurfaceBounds(rect);
2820             UpdateSizeChangeReason(reason);
2821             UpdateRect(rect, reason, "compatibleInPcLandscape");
2822         } else {
2823             if (windowWidth < windowHeight) {
2824                 rect.width_ = compatibleInPcPortraitWidth;
2825                 rect.height_ = compatibleInPcPortraitHeight;
2826             } else {
2827                 rect.width_ = compatibleInPcLandscapeWidth;
2828                 rect.height_ = compatibleInPcLandscapeHeight;
2829             }
2830             rect.posX_ = windowRect.posX_;
2831             rect.posY_ = windowRect.posY_;
2832             SetSurfaceBounds(rect);
2833             UpdateSizeChangeReason(reason);
2834         }
2835     } else {
2836         SetSurfaceBounds(rect);
2837         UpdateSizeChangeReason(reason);
2838     }
2839 }
2840 
SetMoveDragCallback()2841 void SceneSession::SetMoveDragCallback()
2842 {
2843     if (moveDragController_) {
2844         MoveDragCallback callBack = [this](const SizeChangeReason& reason) {
2845             this->OnMoveDragCallback(reason);
2846         };
2847         moveDragController_->RegisterMoveDragCallback(callBack);
2848     }
2849 }
2850 
OnMoveDragCallback(const SizeChangeReason & reason)2851 void SceneSession::OnMoveDragCallback(const SizeChangeReason& reason)
2852 {
2853     if (!moveDragController_) {
2854         WLOGE("moveDragController_ is null");
2855         return;
2856     }
2857 
2858     auto property = GetSessionProperty();
2859     if (property == nullptr) {
2860         TLOGE(WmsLogTag::WMS_SCB, "property is null");
2861         return;
2862     }
2863     bool isCompatibleModeInPc = property->GetCompatibleModeInPc();
2864     bool isSupportDragInPcCompatibleMode = property->GetIsSupportDragInPcCompatibleMode();
2865     bool isMainWindow = WindowHelper::IsMainWindow(property->GetWindowType());
2866     WSRect rect = moveDragController_->GetTargetRect();
2867     WLOGFD("OnMoveDragCallback rect: [%{public}d, %{public}d, %{public}u, %{public}u], reason : %{public}d "
2868         "isCompatibleMode: %{public}d, isSupportDragInPcCompatibleMode: %{public}d",
2869         rect.posX_, rect.posY_, rect.width_, rect.height_, reason, isCompatibleModeInPc,
2870         isSupportDragInPcCompatibleMode);
2871     if (reason == SizeChangeReason::DRAG || reason == SizeChangeReason::DRAG_END) {
2872         UpdateWinRectForSystemBar(rect);
2873     }
2874     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER,
2875         "SceneSession::OnMoveDragCallback [%d, %d, %u, %u]", rect.posX_, rect.posY_, rect.width_, rect.height_);
2876     if (isCompatibleModeInPc && !IsFreeMultiWindowMode()) {
2877         HandleCompatibleModeMoveDrag(rect, reason, isSupportDragInPcCompatibleMode);
2878     } else {
2879         if (IsDragResizeWhenEnd(reason)) {
2880             UpdateSizeChangeReason(reason);
2881             OnSessionEvent(SessionEvent::EVENT_DRAG);
2882             return;
2883         }
2884         SetSurfaceBounds(rect);
2885         UpdateSizeChangeReason(reason);
2886         if (reason != SizeChangeReason::MOVE) {
2887             UpdateRect(rect, reason, "OnMoveDragCallback");
2888         }
2889     }
2890 
2891     if (reason == SizeChangeReason::DRAG_END) {
2892         if (GetOriPosYBeforeRaisedByKeyboard() != 0) {
2893             TLOGI(WmsLogTag::WMS_KEYBOARD, "Calling session is moved and reset oriPosYBeforeRaisedByKeyboard");
2894             SetOriPosYBeforeRaisedByKeyboard(0);
2895         }
2896         NotifySessionRectChange(rect, reason);
2897         moveDragController_->SetMoveInputBarFlag(false);
2898         OnSessionEvent(SessionEvent::EVENT_END_MOVE);
2899     }
2900     if (reason == SizeChangeReason::DRAG_START) {
2901         OnSessionEvent(SessionEvent::EVENT_DRAG_START);
2902     }
2903 }
2904 
IsDragResizeWhenEnd(SizeChangeReason reason)2905 bool SceneSession::IsDragResizeWhenEnd(SizeChangeReason reason)
2906 {
2907     auto property = GetSessionProperty();
2908     if (property == nullptr) {
2909         TLOGE(WmsLogTag::WMS_LAYOUT, "property is null");
2910         return true;
2911     }
2912     bool isPcOrPcModeMainWindow = (systemConfig_.uiType_ == UI_TYPE_PC || IsFreeMultiWindowMode()) &&
2913         WindowHelper::IsMainWindow(property->GetWindowType());
2914     return reason == SizeChangeReason::DRAG && isPcOrPcModeMainWindow &&
2915         GetDragResizeTypeDuringDrag() == DragResizeType::RESIZE_WHEN_DRAG_END;
2916 }
2917 
UpdateWinRectForSystemBar(WSRect & rect)2918 void SceneSession::UpdateWinRectForSystemBar(WSRect& rect)
2919 {
2920     if (!specificCallback_) {
2921         WLOGFE("specificCallback_ is null!");
2922         return;
2923     }
2924     auto sessionProperty = GetSessionProperty();
2925     if (!sessionProperty) {
2926         WLOGFE("get session property is null!");
2927         return;
2928     }
2929     float tmpPosY = 0.0;
2930     std::vector<sptr<SceneSession>> statusBarVector;
2931     if (specificCallback_->onGetSceneSessionVectorByTypeAndDisplayId_) {
2932         statusBarVector = specificCallback_->onGetSceneSessionVectorByTypeAndDisplayId_(
2933             WindowType::WINDOW_TYPE_STATUS_BAR, sessionProperty->GetDisplayId());
2934     }
2935     for (auto& statusBar : statusBarVector) {
2936         if (!(statusBar->isVisible_)) {
2937             continue;
2938         }
2939         WSRect statusBarRect = statusBar->GetSessionRect();
2940         if ((rect.posY_ < statusBarRect.posY_ + static_cast<int32_t>(statusBarRect.height_)) &&
2941             (rect.height_ != winRect_.height_ || rect.width_ != winRect_.width_)) {
2942             tmpPosY = rect.posY_ + rect.height_;
2943             rect.posY_ = statusBarRect.posY_ + statusBarRect.height_;
2944             rect.height_ = tmpPosY - rect.posY_;
2945         }
2946     }
2947     WLOGFD("after UpdateWinRectForSystemBar rect: [%{public}d, %{public}d, %{public}u, %{public}u]",
2948         rect.posX_, rect.posY_, rect.width_, rect.height_);
2949 }
2950 
SetSurfaceBounds(const WSRect & rect)2951 void SceneSession::SetSurfaceBounds(const WSRect& rect)
2952 {
2953     auto rsTransaction = RSTransactionProxy::GetInstance();
2954     if (rsTransaction != nullptr) {
2955         rsTransaction->Begin();
2956     }
2957     auto surfaceNode = GetSurfaceNode();
2958     auto leashWinSurfaceNode = GetLeashWinSurfaceNode();
2959     if (surfaceNode && leashWinSurfaceNode) {
2960         leashWinSurfaceNode->SetBounds(rect.posX_, rect.posY_, rect.width_, rect.height_);
2961         leashWinSurfaceNode->SetFrame(rect.posX_, rect.posY_, rect.width_, rect.height_);
2962         surfaceNode->SetBounds(0, 0, rect.width_, rect.height_);
2963         surfaceNode->SetFrame(0, 0, rect.width_, rect.height_);
2964     } else if (WindowHelper::IsPipWindow(GetWindowType()) && surfaceNode) {
2965         TLOGD(WmsLogTag::WMS_PIP, "PipWindow setSurfaceBounds");
2966         surfaceNode->SetBounds(rect.posX_, rect.posY_, rect.width_, rect.height_);
2967         surfaceNode->SetFrame(rect.posX_, rect.posY_, rect.width_, rect.height_);
2968     } else if (WindowHelper::IsSubWindow(GetWindowType()) && surfaceNode) {
2969         WLOGFD("subwindow setSurfaceBounds");
2970         surfaceNode->SetBounds(rect.posX_, rect.posY_, rect.width_, rect.height_);
2971         surfaceNode->SetFrame(rect.posX_, rect.posY_, rect.width_, rect.height_);
2972     } else if (WindowHelper::IsDialogWindow(GetWindowType()) && surfaceNode) {
2973         TLOGD(WmsLogTag::WMS_DIALOG, "dialogWindow setSurfaceBounds");
2974         surfaceNode->SetBounds(rect.posX_, rect.posY_, rect.width_, rect.height_);
2975         surfaceNode->SetFrame(rect.posX_, rect.posY_, rect.width_, rect.height_);
2976     } else if (WindowHelper::IsSystemWindow(GetWindowType()) && surfaceNode) {
2977         TLOGD(WmsLogTag::WMS_SYSTEM, "system window setSurfaceBounds");
2978         surfaceNode->SetBounds(rect.posX_, rect.posY_, rect.width_, rect.height_);
2979         surfaceNode->SetFrame(rect.posX_, rect.posY_, rect.width_, rect.height_);
2980     } else {
2981         WLOGE("SetSurfaceBounds surfaceNode is null!");
2982     }
2983     if (rsTransaction != nullptr) {
2984         rsTransaction->Commit();
2985     }
2986 }
2987 
SetZOrder(uint32_t zOrder)2988 void SceneSession::SetZOrder(uint32_t zOrder)
2989 {
2990     auto task = [weakThis = wptr(this), zOrder]() {
2991         auto session = weakThis.promote();
2992         if (session == nullptr) {
2993             WLOGFE("session is null");
2994             return;
2995         }
2996         if (session->zOrder_ != zOrder) {
2997             session->Session::SetZOrder(zOrder);
2998             if (session->specificCallback_ != nullptr) {
2999                 session->specificCallback_->onWindowInfoUpdate_(session->GetPersistentId(),
3000                     WindowUpdateType::WINDOW_UPDATE_PROPERTY);
3001             }
3002         }
3003     };
3004     PostTask(task, "SetZOrder");
3005 }
3006 
SetFloatingScale(float floatingScale)3007 void SceneSession::SetFloatingScale(float floatingScale)
3008 {
3009     if (floatingScale_ != floatingScale) {
3010         Session::SetFloatingScale(floatingScale);
3011         if (specificCallback_ != nullptr) {
3012             specificCallback_->onWindowInfoUpdate_(GetPersistentId(), WindowUpdateType::WINDOW_UPDATE_PROPERTY);
3013             if (Session::IsScbCoreEnabled()) {
3014                 MarkAvoidAreaAsDirty();
3015             } else {
3016                 specificCallback_->onUpdateAvoidArea_(GetPersistentId());
3017             }
3018         }
3019     }
3020 }
3021 
SetParentPersistentId(int32_t parentId)3022 void SceneSession::SetParentPersistentId(int32_t parentId)
3023 {
3024     auto property = GetSessionProperty();
3025     if (property) {
3026         property->SetParentPersistentId(parentId);
3027     }
3028 }
3029 
GetParentPersistentId() const3030 int32_t SceneSession::GetParentPersistentId() const
3031 {
3032     auto property = GetSessionProperty();
3033     if (property) {
3034         return property->GetParentPersistentId();
3035     }
3036     return INVALID_SESSION_ID;
3037 }
3038 
GetMainSessionId()3039 int32_t SceneSession::GetMainSessionId()
3040 {
3041     const auto& mainSession = GetMainSession();
3042     if (mainSession) {
3043         return mainSession->GetPersistentId();
3044     }
3045     return INVALID_SESSION_ID;
3046 }
3047 
GetWindowNameAllType() const3048 std::string SceneSession::GetWindowNameAllType() const
3049 {
3050     if (GetSessionInfo().isSystem_) {
3051         return GetSessionInfo().abilityName_;
3052     } else {
3053         return GetWindowName();
3054     }
3055 }
3056 
SetTurnScreenOn(bool turnScreenOn)3057 WSError SceneSession::SetTurnScreenOn(bool turnScreenOn)
3058 {
3059     GetSessionProperty()->SetTurnScreenOn(turnScreenOn);
3060     return WSError::WS_OK;
3061 }
3062 
IsTurnScreenOn() const3063 bool SceneSession::IsTurnScreenOn() const
3064 {
3065     return GetSessionProperty()->IsTurnScreenOn();
3066 }
3067 
SetWindowEnableDragBySystem(bool enableDrag)3068 WMError SceneSession::SetWindowEnableDragBySystem(bool enableDrag)
3069 {
3070     TLOGI(WmsLogTag::WMS_LAYOUT, "enableDrag: %{public}d", enableDrag);
3071     auto task = [weakThis = wptr(this), enableDrag] {
3072         auto session = weakThis.promote();
3073         if (!session) {
3074             TLOGNE(WmsLogTag::WMS_LAYOUT, "session is null");
3075             return;
3076         }
3077         session->SetClientDragEnable(enableDrag);
3078         TLOGNI(WmsLogTag::WMS_LAYOUT, "id: %{public}d, enableDrag: %{public}d",
3079             session->GetPersistentId(), enableDrag);
3080         auto sessionProperty = session->GetSessionProperty();
3081         if (!sessionProperty) {
3082             TLOGNE(WmsLogTag::WMS_LAYOUT, "sessionProperty is null");
3083             return;
3084         }
3085         sessionProperty->SetDragEnabled(enableDrag);
3086         if (session->sessionStage_) {
3087             session->sessionStage_->SetEnableDragBySystem(enableDrag);
3088         }
3089     };
3090     PostTask(task, __func__);
3091     return WMError::WM_OK;
3092 }
3093 
SetKeepScreenOn(bool keepScreenOn)3094 WSError SceneSession::SetKeepScreenOn(bool keepScreenOn)
3095 {
3096     GetSessionProperty()->SetKeepScreenOn(keepScreenOn);
3097     return WSError::WS_OK;
3098 }
3099 
IsKeepScreenOn() const3100 bool SceneSession::IsKeepScreenOn() const
3101 {
3102     return GetSessionProperty()->IsKeepScreenOn();
3103 }
3104 
GetSessionSnapshotFilePath() const3105 std::string SceneSession::GetSessionSnapshotFilePath() const
3106 {
3107     WLOGFI("GetSessionSnapshotFilePath id %{public}d", GetPersistentId());
3108     if (Session::GetSessionState() < SessionState::STATE_BACKGROUND) {
3109         WLOGFI("GetSessionSnapshotFilePath UpdateSnapshot");
3110         auto snapshot = Snapshot();
3111         if (scenePersistence_ != nullptr) {
3112             scenePersistence_->SaveSnapshot(snapshot);
3113         }
3114     }
3115     if (scenePersistence_ != nullptr) {
3116         return scenePersistence_->GetSnapshotFilePath();
3117     }
3118     return "";
3119 }
3120 
SaveUpdatedIcon(const std::shared_ptr<Media::PixelMap> & icon)3121 void SceneSession::SaveUpdatedIcon(const std::shared_ptr<Media::PixelMap>& icon)
3122 {
3123     WLOGFI("run SaveUpdatedIcon");
3124     if (scenePersistence_ != nullptr) {
3125         scenePersistence_->SaveUpdatedIcon(icon);
3126     }
3127 }
3128 
GetUpdatedIconPath() const3129 std::string SceneSession::GetUpdatedIconPath() const
3130 {
3131     WLOGFI("run GetUpdatedIconPath");
3132     if (scenePersistence_ != nullptr) {
3133         return scenePersistence_->GetUpdatedIconPath();
3134     }
3135     return "";
3136 }
3137 
UpdateNativeVisibility(bool visible)3138 void SceneSession::UpdateNativeVisibility(bool visible)
3139 {
3140     auto task = [weakThis = wptr(this), visible]() {
3141         auto session = weakThis.promote();
3142         if (!session) {
3143             TLOGE(WmsLogTag::WMS_LIFE, "session is null");
3144             return;
3145         }
3146         int32_t persistentId = session->GetPersistentId();
3147         WLOGFI("[WMSSCB] name: %{public}s, id: %{public}u, visible: %{public}u",
3148             session->sessionInfo_.bundleName_.c_str(), persistentId, visible);
3149         session->isVisible_ = visible;
3150         if (session->specificCallback_ == nullptr) {
3151             WLOGFW("specific callback is null.");
3152             return;
3153         }
3154 
3155         if (visible) {
3156             session->specificCallback_->onWindowInfoUpdate_(persistentId, WindowUpdateType::WINDOW_UPDATE_ADDED);
3157         } else {
3158             session->specificCallback_->onWindowInfoUpdate_(persistentId, WindowUpdateType::WINDOW_UPDATE_REMOVED);
3159         }
3160         session->NotifyAccessibilityVisibilityChange();
3161         session->specificCallback_->onUpdateAvoidArea_(persistentId);
3162         // update private state
3163         if (!session->GetSessionProperty()) {
3164             WLOGFE("UpdateNativeVisibility property is null");
3165             return;
3166         }
3167         if (session->updatePrivateStateAndNotifyFunc_ != nullptr) {
3168             session->updatePrivateStateAndNotifyFunc_(persistentId);
3169         }
3170     };
3171     PostTask(task, "UpdateNativeVisibility");
3172 }
3173 
IsVisible() const3174 bool SceneSession::IsVisible() const
3175 {
3176     return isVisible_;
3177 }
3178 
UpdateRotationAvoidArea()3179 void SceneSession::UpdateRotationAvoidArea()
3180 {
3181     if (specificCallback_) {
3182         if (Session::IsScbCoreEnabled()) {
3183             MarkAvoidAreaAsDirty();
3184         } else {
3185             specificCallback_->onUpdateAvoidArea_(GetPersistentId());
3186         }
3187     }
3188 }
3189 
SetPrivacyMode(bool isPrivacy)3190 void SceneSession::SetPrivacyMode(bool isPrivacy)
3191 {
3192     auto property = GetSessionProperty();
3193     if (!property) {
3194         WLOGFE("SetPrivacyMode property is null");
3195         return;
3196     }
3197     auto surfaceNode = GetSurfaceNode();
3198     if (!surfaceNode) {
3199         WLOGFE("surfaceNode_ is null");
3200         return;
3201     }
3202     bool lastPrivacyMode = property->GetPrivacyMode() || property->GetSystemPrivacyMode();
3203     if (lastPrivacyMode == isPrivacy) {
3204         WLOGFW("privacy mode is not change, do nothing, isPrivacy:%{public}d", isPrivacy);
3205         return;
3206     }
3207     property->SetPrivacyMode(isPrivacy);
3208     property->SetSystemPrivacyMode(isPrivacy);
3209     auto rsTransaction = RSTransactionProxy::GetInstance();
3210     if (rsTransaction != nullptr) {
3211         rsTransaction->Begin();
3212     }
3213     surfaceNode->SetSecurityLayer(isPrivacy);
3214     auto leashWinSurfaceNode = GetLeashWinSurfaceNode();
3215     if (leashWinSurfaceNode != nullptr) {
3216         leashWinSurfaceNode->SetSecurityLayer(isPrivacy);
3217     }
3218     if (rsTransaction != nullptr) {
3219         rsTransaction->Commit();
3220     }
3221 }
3222 
SetSnapshotSkip(bool isSkip)3223 WMError SceneSession::SetSnapshotSkip(bool isSkip)
3224 {
3225     auto property = GetSessionProperty();
3226     if (!property) {
3227         TLOGE(WmsLogTag::DEFAULT, "property is null");
3228         return WMError::WM_ERROR_DESTROYED_OBJECT;
3229     }
3230     auto surfaceNode = GetSurfaceNode();
3231     if (!surfaceNode) {
3232         TLOGE(WmsLogTag::DEFAULT, "surfaceNode_ is null");
3233         return WMError::WM_ERROR_DESTROYED_OBJECT;
3234     }
3235     bool lastSnapshotSkip = property->GetSnapshotSkip();
3236     if (lastSnapshotSkip == isSkip) {
3237         TLOGW(WmsLogTag::DEFAULT, "Snapshot skip does not change, do nothing, isSkip: %{public}d, "
3238             "id: %{public}d", isSkip, GetPersistentId());
3239         return WMError::WM_OK;
3240     }
3241     property->SetSnapshotSkip(isSkip);
3242     auto rsTransaction = RSTransactionProxy::GetInstance();
3243     if (rsTransaction != nullptr) {
3244         rsTransaction->Begin();
3245     }
3246     surfaceNode->SetSkipLayer(isSkip);
3247     auto leashWinSurfaceNode = GetLeashWinSurfaceNode();
3248     if (leashWinSurfaceNode != nullptr) {
3249         leashWinSurfaceNode->SetSkipLayer(isSkip);
3250     }
3251     if (rsTransaction != nullptr) {
3252         rsTransaction->Commit();
3253     }
3254     return WMError::WM_OK;
3255 }
3256 
SetPiPTemplateInfo(const PiPTemplateInfo & pipTemplateInfo)3257 void SceneSession::SetPiPTemplateInfo(const PiPTemplateInfo& pipTemplateInfo)
3258 {
3259     pipTemplateInfo_ = pipTemplateInfo;
3260 }
3261 
SetSystemSceneOcclusionAlpha(double alpha)3262 void SceneSession::SetSystemSceneOcclusionAlpha(double alpha)
3263 {
3264     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "SceneSession::SetAbilityBGAlpha");
3265     if (alpha < 0 || alpha > 1.0) {
3266         WLOGFE("OnSetSystemSceneOcclusionAlpha property is null");
3267         return;
3268     }
3269     auto surfaceNode = GetSurfaceNode();
3270     if (!surfaceNode) {
3271         WLOGFE("surfaceNode_ is null");
3272         return;
3273     }
3274     uint8_t alpha8bit = static_cast<uint8_t>(alpha * 255);
3275     WLOGFI("SetAbilityBGAlpha alpha8bit=%{public}u.", alpha8bit);
3276     auto rsTransaction = RSTransactionProxy::GetInstance();
3277     if (rsTransaction != nullptr) {
3278         rsTransaction->Begin();
3279     }
3280     surfaceNode->SetAbilityBGAlpha(alpha8bit);
3281     auto leashWinSurfaceNode = GetLeashWinSurfaceNode();
3282     if (leashWinSurfaceNode != nullptr) {
3283         leashWinSurfaceNode->SetAbilityBGAlpha(alpha8bit);
3284     }
3285     if (rsTransaction != nullptr) {
3286         rsTransaction->Commit();
3287     }
3288 }
3289 
SetSystemSceneForceUIFirst(bool forceUIFirst)3290 void SceneSession::SetSystemSceneForceUIFirst(bool forceUIFirst)
3291 {
3292     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "SceneSession::SetForceUIFirst");
3293     auto leashWinSurfaceNode = GetLeashWinSurfaceNode();
3294     auto surfaceNode = GetSurfaceNode();
3295     if (leashWinSurfaceNode == nullptr && surfaceNode == nullptr) {
3296         TLOGE(WmsLogTag::DEFAULT, "leashWindow and surfaceNode are nullptr");
3297         return;
3298     }
3299     auto rsTransaction = RSTransactionProxy::GetInstance();
3300     if (rsTransaction != nullptr) {
3301         rsTransaction->Begin();
3302     }
3303     if (leashWinSurfaceNode != nullptr) {
3304         TLOGI(WmsLogTag::DEFAULT, "%{public}s %{public}" PRIu64 " forceUIFirst=%{public}d.",
3305             leashWinSurfaceNode->GetName().c_str(), leashWinSurfaceNode->GetId(), forceUIFirst);
3306         leashWinSurfaceNode->SetForceUIFirst(forceUIFirst);
3307     } else if (surfaceNode != nullptr) {
3308         TLOGI(WmsLogTag::DEFAULT, "%{public}s %{public}" PRIu64 " forceUIFirst=%{public}d.",
3309             surfaceNode->GetName().c_str(), surfaceNode->GetId(), forceUIFirst);
3310         surfaceNode->SetForceUIFirst(forceUIFirst);
3311     }
3312     if (rsTransaction != nullptr) {
3313         rsTransaction->Commit();
3314     }
3315 }
3316 
SetUIFirstSwitch(RSUIFirstSwitch uiFirstSwitch)3317 void SceneSession::SetUIFirstSwitch(RSUIFirstSwitch uiFirstSwitch)
3318 {
3319     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "SceneSession::SetUIFirstSwitch");
3320     auto rsTransaction = RSTransactionProxy::GetInstance();
3321     if (rsTransaction == nullptr) {
3322         TLOGE(WmsLogTag::DEFAULT, "rsTransaction is nullptr");
3323         return;
3324     }
3325     rsTransaction->Begin();
3326     auto leashWinSurfaceNode = GetLeashWinSurfaceNode();
3327     auto surfaceNode = GetSurfaceNode();
3328     if (leashWinSurfaceNode != nullptr) {
3329         TLOGI(WmsLogTag::DEFAULT, "%{public}s %{public}" PRIu64 " uiFirstSwitch=%{public}d",
3330             leashWinSurfaceNode->GetName().c_str(), leashWinSurfaceNode->GetId(), uiFirstSwitch);
3331         leashWinSurfaceNode->SetUIFirstSwitch(uiFirstSwitch);
3332     } else if (surfaceNode != nullptr) {
3333         TLOGI(WmsLogTag::DEFAULT, "%{public}s %{public}" PRIu64 " uiFirstSwitch=%{public}d",
3334             surfaceNode->GetName().c_str(), surfaceNode->GetId(), uiFirstSwitch);
3335         surfaceNode->SetUIFirstSwitch(uiFirstSwitch);
3336     } else {
3337         TLOGE(WmsLogTag::DEFAULT, "leashWindow and surfaceNode are nullptr");
3338     }
3339     rsTransaction->Commit();
3340 }
3341 
MarkSystemSceneUIFirst(bool isForced,bool isUIFirstEnabled)3342 void SceneSession::MarkSystemSceneUIFirst(bool isForced, bool isUIFirstEnabled)
3343 {
3344     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "SceneSession::MarkSystemSceneUIFirst");
3345     auto leashWinSurfaceNode = GetLeashWinSurfaceNode();
3346     auto surfaceNode = GetSurfaceNode();
3347     if (leashWinSurfaceNode == nullptr && surfaceNode == nullptr) {
3348         TLOGE(WmsLogTag::DEFAULT, "leashWindow and surfaceNode are nullptr");
3349         return;
3350     }
3351     if (leashWinSurfaceNode != nullptr) {
3352         TLOGI(WmsLogTag::DEFAULT, "%{public}s %{public}" PRIu64 " isForced=%{public}d. isUIFirstEnabled=%{public}d",
3353             leashWinSurfaceNode->GetName().c_str(), leashWinSurfaceNode->GetId(), isForced, isUIFirstEnabled);
3354         leashWinSurfaceNode->MarkUifirstNode(isForced, isUIFirstEnabled);
3355     } else {
3356         TLOGI(WmsLogTag::DEFAULT, "%{public}s %{public}" PRIu64 " isForced=%{public}d. isUIFirstEnabled=%{public}d",
3357             surfaceNode->GetName().c_str(), surfaceNode->GetId(), isForced, isUIFirstEnabled);
3358         surfaceNode->MarkUifirstNode(isForced, isUIFirstEnabled);
3359     }
3360 }
3361 
UpdateWindowAnimationFlag(bool needDefaultAnimationFlag)3362 WSError SceneSession::UpdateWindowAnimationFlag(bool needDefaultAnimationFlag)
3363 {
3364     auto task = [weakThis = wptr(this), needDefaultAnimationFlag] {
3365         auto session = weakThis.promote();
3366         if (!session) {
3367             TLOGNE(WmsLogTag::WMS_LIFE, "session is null");
3368             return WSError::WS_ERROR_DESTROYED_OBJECT;
3369         }
3370         session->needDefaultAnimationFlag_ = needDefaultAnimationFlag;
3371         if (session->onWindowAnimationFlagChange_) {
3372             session->onWindowAnimationFlagChange_(needDefaultAnimationFlag);
3373         }
3374         return WSError::WS_OK;
3375     };
3376     return PostSyncTask(task, __func__);
3377 }
3378 
SetWindowAnimationFlag(bool needDefaultAnimationFlag)3379 void SceneSession::SetWindowAnimationFlag(bool needDefaultAnimationFlag)
3380 {
3381     needDefaultAnimationFlag_ = needDefaultAnimationFlag;
3382     if (onWindowAnimationFlagChange_) {
3383         onWindowAnimationFlagChange_(needDefaultAnimationFlag);
3384     }
3385     return;
3386 }
3387 
IsNeedDefaultAnimation() const3388 bool SceneSession::IsNeedDefaultAnimation() const
3389 {
3390     return needDefaultAnimationFlag_;
3391 }
3392 
IsAppSession() const3393 bool SceneSession::IsAppSession() const
3394 {
3395     if (GetWindowType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW) {
3396         return true;
3397     }
3398     if (GetParentSession() && GetParentSession()->GetWindowType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW) {
3399         return true;
3400     }
3401     return false;
3402 }
3403 
3404 /** @note @window.focus */
IsAppOrLowerSystemSession() const3405 bool SceneSession::IsAppOrLowerSystemSession() const
3406 {
3407     WindowType windowType = GetWindowType();
3408     if (windowType == WindowType::WINDOW_TYPE_NEGATIVE_SCREEN ||
3409         windowType == WindowType::WINDOW_TYPE_GLOBAL_SEARCH ||
3410         windowType == WindowType::WINDOW_TYPE_DESKTOP) {
3411         return true;
3412     }
3413     return IsAppSession();
3414 }
3415 
3416 /** @note @window.focus */
IsSystemSessionAboveApp() const3417 bool SceneSession::IsSystemSessionAboveApp() const
3418 {
3419     WindowType windowType = GetWindowType();
3420     if (windowType == WindowType::WINDOW_TYPE_DIALOG || windowType == WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW) {
3421         return true;
3422     }
3423     if (windowType == WindowType::WINDOW_TYPE_PANEL &&
3424         sessionInfo_.bundleName_.find("SCBDropdownPanel") != std::string::npos) {
3425         return true;
3426     }
3427     return false;
3428 }
3429 
3430 /** @note @window.focus */
IsSameMainSession(const sptr<SceneSession> & prevSession)3431 bool SceneSession::IsSameMainSession(const sptr<SceneSession>& prevSession)
3432 {
3433     if (prevSession == nullptr) {
3434         TLOGE(WmsLogTag::WMS_FOCUS, "prevSession is nullptr");
3435         return false;
3436     }
3437     int32_t currSessionId = GetMainSessionId();
3438     int32_t prevSessionId = prevSession->GetMainSessionId();
3439     return currSessionId == prevSessionId && prevSessionId != INVALID_SESSION_ID;
3440 }
3441 
NotifyIsCustomAnimationPlaying(bool isPlaying)3442 void SceneSession::NotifyIsCustomAnimationPlaying(bool isPlaying)
3443 {
3444     WLOGFI("id %{public}d %{public}u", GetPersistentId(), isPlaying);
3445     if (onIsCustomAnimationPlaying_) {
3446         onIsCustomAnimationPlaying_(isPlaying);
3447     }
3448 }
3449 
UpdateWindowSceneAfterCustomAnimation(bool isAdd)3450 WSError SceneSession::UpdateWindowSceneAfterCustomAnimation(bool isAdd)
3451 {
3452     if (!SessionPermission::IsSystemCalling()) {
3453         TLOGE(WmsLogTag::WMS_SYSTEM, "failed to update with id:%{public}u!", GetPersistentId());
3454         return WSError::WS_ERROR_NOT_SYSTEM_APP;
3455     }
3456     auto task = [weakThis = wptr(this), isAdd]() {
3457         auto session = weakThis.promote();
3458         if (!session) {
3459             WLOGFE("session is null");
3460             return WSError::WS_ERROR_DESTROYED_OBJECT;
3461         }
3462         WLOGFI("UpdateWindowSceneAfterCustomAnimation, id %{public}d, isAdd: %{public}d",
3463             session->GetPersistentId(), isAdd);
3464         if (isAdd) {
3465             WLOGFE("SetOpacityFunc not register %{public}d", session->GetPersistentId());
3466             return WSError::WS_ERROR_INVALID_OPERATION;
3467         } else {
3468             WLOGFI("background after custom animation id %{public}d", session->GetPersistentId());
3469             // since background will remove surfaceNode
3470             session->Background();
3471             session->NotifyIsCustomAnimationPlaying(false);
3472         }
3473         return WSError::WS_OK;
3474     };
3475     PostTask(task, "UpdateWindowSceneAfterCustomAnimation:" + std::to_string(isAdd));
3476     return WSError::WS_OK;
3477 }
3478 
IsFloatingWindowAppType() const3479 bool SceneSession::IsFloatingWindowAppType() const
3480 {
3481     auto property = GetSessionProperty();
3482     if (property == nullptr) {
3483         return false;
3484     }
3485     return property->IsFloatingWindowAppType();
3486 }
3487 
GetTouchHotAreas() const3488 std::vector<Rect> SceneSession::GetTouchHotAreas() const
3489 {
3490     std::vector<Rect> touchHotAreas;
3491     auto property = GetSessionProperty();
3492     if (property) {
3493         property->GetTouchHotAreas(touchHotAreas);
3494     }
3495     return touchHotAreas;
3496 }
3497 
GetPiPTemplateInfo() const3498 PiPTemplateInfo SceneSession::GetPiPTemplateInfo() const
3499 {
3500     return pipTemplateInfo_;
3501 }
3502 
DumpSessionElementInfo(const std::vector<std::string> & params)3503 void SceneSession::DumpSessionElementInfo(const std::vector<std::string>& params)
3504 {
3505     if (!sessionStage_) {
3506         return;
3507     }
3508     return sessionStage_->DumpSessionElementInfo(params);
3509 }
3510 
NotifyTouchOutside()3511 void SceneSession::NotifyTouchOutside()
3512 {
3513     WLOGFI("id: %{public}d, type: %{public}d", GetPersistentId(), GetWindowType());
3514     if (sessionStage_) {
3515         WLOGFD("Notify sessionStage TouchOutside");
3516         sessionStage_->NotifyTouchOutside();
3517     }
3518     if (onTouchOutside_) {
3519         WLOGFD("Notify sessionChangeCallback TouchOutside");
3520         onTouchOutside_();
3521     }
3522 }
3523 
NotifyWindowVisibility()3524 void SceneSession::NotifyWindowVisibility()
3525 {
3526     if (sessionStage_) {
3527         sessionStage_->NotifyWindowVisibility(GetRSVisible());
3528     } else {
3529         WLOGFE("Notify window(id:%{public}d) visibility failed, for this session stage is nullptr", GetPersistentId());
3530     }
3531 }
3532 
CheckTouchOutsideCallbackRegistered()3533 bool SceneSession::CheckTouchOutsideCallbackRegistered()
3534 {
3535     return onTouchOutside_ != nullptr;
3536 }
3537 
SetRequestedOrientation(Orientation orientation)3538 void SceneSession::SetRequestedOrientation(Orientation orientation)
3539 {
3540     WLOGFI("id: %{public}d orientation: %{public}u", GetPersistentId(), static_cast<uint32_t>(orientation));
3541     GetSessionProperty()->SetRequestedOrientation(orientation);
3542     if (onRequestedOrientationChange_) {
3543         onRequestedOrientationChange_(static_cast<uint32_t>(orientation));
3544     }
3545 }
3546 
SetDefaultRequestedOrientation(Orientation orientation)3547 WSError SceneSession::SetDefaultRequestedOrientation(Orientation orientation)
3548 {
3549     auto task = [weakThis = wptr(this), orientation]() -> WSError {
3550         auto session = weakThis.promote();
3551         if (!session) {
3552             TLOGNE(WmsLogTag::DEFAULT, "session is null");
3553             return WSError::WS_ERROR_NULLPTR;
3554         }
3555         TLOGNI(WmsLogTag::DEFAULT, "id: %{public}d defaultRequestedOrientation: %{public}u",
3556             session->GetPersistentId(), static_cast<uint32_t>(orientation));
3557         auto property = session->GetSessionProperty();
3558         if (property == nullptr) {
3559             TLOGNE(WmsLogTag::DEFAULT, "get session property failed");
3560             return WSError::WS_ERROR_NULLPTR;
3561         }
3562         property->SetRequestedOrientation(orientation);
3563         property->SetDefaultRequestedOrientation(orientation);
3564         return WSError::WS_OK;
3565     };
3566     return PostSyncTask(task, __func__);
3567 }
3568 
NotifyForceHideChange(bool hide)3569 void SceneSession::NotifyForceHideChange(bool hide)
3570 {
3571     WLOGFI("id: %{public}d forceHide: %{public}u", persistentId_, hide);
3572     auto property = GetSessionProperty();
3573     if (property == nullptr) {
3574         WLOGFD("id: %{public}d property is nullptr", persistentId_);
3575         return;
3576     }
3577     property->SetForceHide(hide);
3578     if (onForceHideChangeFunc_) {
3579         onForceHideChangeFunc_(hide);
3580     }
3581     SetForceTouchable(!hide);
3582     if (hide) {
3583         if (isFocused_) {
3584             FocusChangeReason reason = FocusChangeReason::DEFAULT;
3585             NotifyRequestFocusStatusNotifyManager(false, true, reason);
3586             SetForceHideState(ForceHideState::HIDDEN_WHEN_FOCUSED);
3587         } else if (forceHideState_ == ForceHideState::NOT_HIDDEN) {
3588             SetForceHideState(ForceHideState::HIDDEN_WHEN_UNFOCUSED);
3589         }
3590     } else {
3591         if (forceHideState_ == ForceHideState::HIDDEN_WHEN_FOCUSED) {
3592             SetForceHideState(ForceHideState::NOT_HIDDEN);
3593             FocusChangeReason reason = FocusChangeReason::DEFAULT;
3594             NotifyRequestFocusStatusNotifyManager(true, true, reason);
3595         } else {
3596             SetForceHideState(ForceHideState::NOT_HIDDEN);
3597         }
3598     }
3599 }
3600 
GetRequestedOrientation() const3601 Orientation SceneSession::GetRequestedOrientation() const
3602 {
3603     return GetSessionProperty()->GetRequestedOrientation();
3604 }
3605 
IsAnco() const3606 bool SceneSession::IsAnco() const
3607 {
3608     return collaboratorType_ == static_cast<int32_t>(CollaboratorType::RESERVE_TYPE);
3609 }
3610 
SetBlankFlag(bool isAddBlank)3611 void SceneSession::SetBlankFlag(bool isAddBlank)
3612 {
3613     isAddBlank_ = isAddBlank;
3614 }
3615 
GetBlankFlag() const3616 bool SceneSession::GetBlankFlag() const
3617 {
3618     return isAddBlank_;
3619 }
3620 
SetBufferAvailableCallbackEnable(bool enable)3621 void SceneSession::SetBufferAvailableCallbackEnable(bool enable)
3622 {
3623     bufferAvailableCallbackEnable_ = enable;
3624 }
3625 
GetBufferAvailableCallbackEnable() const3626 bool SceneSession::GetBufferAvailableCallbackEnable() const
3627 {
3628     return bufferAvailableCallbackEnable_;
3629 }
3630 
GetCollaboratorType() const3631 int32_t SceneSession::GetCollaboratorType() const
3632 {
3633     return collaboratorType_;
3634 }
3635 
SetCollaboratorType(int32_t collaboratorType)3636 void SceneSession::SetCollaboratorType(int32_t collaboratorType)
3637 {
3638     collaboratorType_ = collaboratorType;
3639     sessionInfo_.collaboratorType_ = collaboratorType;
3640 }
3641 
GetClientIdentityToken() const3642 std::string SceneSession::GetClientIdentityToken() const
3643 {
3644     return clientIdentityToken_;
3645 }
3646 
SetClientIdentityToken(const std::string & clientIdentityToken)3647 void SceneSession::SetClientIdentityToken(const std::string& clientIdentityToken)
3648 {
3649     clientIdentityToken_ = clientIdentityToken;
3650 }
3651 
DumpSessionInfo(std::vector<std::string> & info) const3652 void SceneSession::DumpSessionInfo(std::vector<std::string>& info) const
3653 {
3654     std::string dumpInfo = "      Session ID #" + std::to_string(persistentId_);
3655     info.push_back(dumpInfo);
3656     dumpInfo = "        session name [" + SessionUtils::ConvertSessionName(sessionInfo_.bundleName_,
3657         sessionInfo_.abilityName_, sessionInfo_.moduleName_, sessionInfo_.appIndex_) + "]";
3658     info.push_back(dumpInfo);
3659     dumpInfo = "        runningState [" + std::string(isActive_ ? "FOREGROUND" : "BACKGROUND") + "]";
3660     info.push_back(dumpInfo);
3661     dumpInfo = "        lockedState [" + std::to_string(sessionInfo_.lockedState) + "]";
3662     info.push_back(dumpInfo);
3663     auto abilityInfo = sessionInfo_.abilityInfo;
3664     dumpInfo = "        continuable [" + (abilityInfo ? std::to_string(abilityInfo->continuable) : " ") + "]";
3665     info.push_back(dumpInfo);
3666     dumpInfo = "        timeStamp [" + sessionInfo_.time + "]";
3667     info.push_back(dumpInfo);
3668     dumpInfo = "        label [" + (abilityInfo ? abilityInfo->label : " ") + "]";
3669     info.push_back(dumpInfo);
3670     dumpInfo = "        iconPath [" + (abilityInfo ? abilityInfo->iconPath : " ") + "]";
3671     info.push_back(dumpInfo);
3672     dumpInfo = "        want [" + (sessionInfo_.want ? sessionInfo_.want->ToUri() : " ") + "]";
3673     info.push_back(dumpInfo);
3674 }
3675 
GetAbilityInfo() const3676 std::shared_ptr<AppExecFwk::AbilityInfo> SceneSession::GetAbilityInfo() const
3677 {
3678     const SessionInfo& sessionInfo = GetSessionInfo();
3679     return sessionInfo.abilityInfo;
3680 }
3681 
SetAbilitySessionInfo(std::shared_ptr<AppExecFwk::AbilityInfo> abilityInfo)3682 void SceneSession::SetAbilitySessionInfo(std::shared_ptr<AppExecFwk::AbilityInfo> abilityInfo)
3683 {
3684     SetSessionInfoAbilityInfo(abilityInfo);
3685 }
3686 
SetSessionState(SessionState state)3687 void SceneSession::SetSessionState(SessionState state)
3688 {
3689     Session::SetSessionState(state);
3690     NotifyAccessibilityVisibilityChange();
3691 }
3692 
UpdateSessionState(SessionState state)3693 void SceneSession::UpdateSessionState(SessionState state)
3694 {
3695     Session::UpdateSessionState(state);
3696     NotifyAccessibilityVisibilityChange();
3697 }
3698 
IsVisibleForAccessibility() const3699 bool SceneSession::IsVisibleForAccessibility() const
3700 {
3701     if (Session::IsScbCoreEnabled()) {
3702         return GetSystemTouchable() && GetForegroundInteractiveStatus() && IsVisibleForeground();
3703     }
3704     return GetSystemTouchable() && GetForegroundInteractiveStatus() &&
3705         (IsVisible() || state_ == SessionState::STATE_ACTIVE || state_ == SessionState::STATE_FOREGROUND);
3706 }
3707 
SetForegroundInteractiveStatus(bool interactive)3708 void SceneSession::SetForegroundInteractiveStatus(bool interactive)
3709 {
3710     Session::SetForegroundInteractiveStatus(interactive);
3711     NotifyAccessibilityVisibilityChange();
3712     if (interactive) {
3713         return;
3714     }
3715     for (auto toastSession : toastSession_) {
3716         if (toastSession == nullptr) {
3717             TLOGD(WmsLogTag::WMS_TOAST, "toastSession session is nullptr");
3718             continue;
3719         }
3720         auto state = toastSession->GetSessionState();
3721         if (state != SessionState::STATE_FOREGROUND && state != SessionState::STATE_ACTIVE) {
3722             continue;
3723         }
3724         toastSession->SetActive(false);
3725         toastSession->BackgroundTask();
3726     }
3727 }
3728 
NotifyAccessibilityVisibilityChange()3729 void SceneSession::NotifyAccessibilityVisibilityChange()
3730 {
3731     bool isVisibleForAccessibilityNew = IsVisibleForAccessibility();
3732     if (isVisibleForAccessibilityNew == isVisibleForAccessibility_.load()) {
3733         return;
3734     }
3735     WLOGFD("[WMSAccess] NotifyAccessibilityVisibilityChange id: %{public}d, access: %{public}d ",
3736         GetPersistentId(), isVisibleForAccessibilityNew);
3737     isVisibleForAccessibility_.store(isVisibleForAccessibilityNew);
3738     if (specificCallback_ && specificCallback_->onWindowInfoUpdate_) {
3739         if (isVisibleForAccessibilityNew) {
3740             specificCallback_->onWindowInfoUpdate_(GetPersistentId(), WindowUpdateType::WINDOW_UPDATE_ADDED);
3741         } else {
3742             specificCallback_->onWindowInfoUpdate_(GetPersistentId(), WindowUpdateType::WINDOW_UPDATE_REMOVED);
3743         }
3744     } else {
3745         WLOGFD("specificCallback_->onWindowInfoUpdate_ not exist, persistent id: %{public}d", GetPersistentId());
3746     }
3747 }
3748 
SetSystemTouchable(bool touchable)3749 void SceneSession::SetSystemTouchable(bool touchable)
3750 {
3751     Session::SetSystemTouchable(touchable);
3752     NotifyAccessibilityVisibilityChange();
3753 }
3754 
ChangeSessionVisibilityWithStatusBar(const sptr<AAFwk::SessionInfo> abilitySessionInfo,bool visible)3755 WSError SceneSession::ChangeSessionVisibilityWithStatusBar(
3756     const sptr<AAFwk::SessionInfo> abilitySessionInfo, bool visible)
3757 {
3758     if (!SessionPermission::VerifyCallingPermission(PermissionConstants::PERMISSION_MANAGE_MISSION)) {
3759         TLOGE(WmsLogTag::WMS_LIFE, "The caller has not permission granted");
3760         return WSError::WS_ERROR_INVALID_PERMISSION;
3761     }
3762     auto task = [weakThis = wptr(this), abilitySessionInfo, visible]() {
3763         auto session = weakThis.promote();
3764         if (!session) {
3765             WLOGFE("session is null");
3766             return WSError::WS_ERROR_DESTROYED_OBJECT;
3767         }
3768         if (abilitySessionInfo == nullptr) {
3769             WLOGFE("abilitySessionInfo is null");
3770             return WSError::WS_ERROR_NULLPTR;
3771         }
3772 
3773         SessionInfo info;
3774         info.abilityName_ = abilitySessionInfo->want.GetElement().GetAbilityName();
3775         info.bundleName_ = abilitySessionInfo->want.GetElement().GetBundleName();
3776         info.moduleName_ = abilitySessionInfo->want.GetModuleName();
3777         int32_t appCloneIndex = abilitySessionInfo->want.GetIntParam(APP_CLONE_INDEX, 0);
3778         info.appIndex_ = appCloneIndex == 0 ? abilitySessionInfo->want.GetIntParam(DLP_INDEX, 0) : appCloneIndex;
3779         info.persistentId_ = abilitySessionInfo->persistentId;
3780         info.callerPersistentId_ = session->GetPersistentId();
3781         info.callerBundleName_ = abilitySessionInfo->want.GetStringParam(AAFwk::Want::PARAM_RESV_CALLER_BUNDLE_NAME);
3782         info.callerAbilityName_ = abilitySessionInfo->want.GetStringParam(AAFwk::Want::PARAM_RESV_CALLER_ABILITY_NAME);
3783         info.callState_ = static_cast<uint32_t>(abilitySessionInfo->state);
3784         info.uiAbilityId_ = abilitySessionInfo->uiAbilityId;
3785         info.specifiedId = abilitySessionInfo->tmpSpecifiedId;
3786         info.want = std::make_shared<AAFwk::Want>(abilitySessionInfo->want);
3787         info.requestCode = abilitySessionInfo->requestCode;
3788         info.callerToken_ = abilitySessionInfo->callerToken;
3789         info.startSetting = abilitySessionInfo->startSetting;
3790         info.callingTokenId_ = abilitySessionInfo->callingTokenId;
3791         info.reuse = abilitySessionInfo->reuse;
3792         info.processOptions = abilitySessionInfo->processOptions;
3793 
3794         if (session->changeSessionVisibilityWithStatusBarFunc_) {
3795             session->changeSessionVisibilityWithStatusBarFunc_(info, visible);
3796         }
3797 
3798         return WSError::WS_OK;
3799     };
3800     PostTask(task, "ChangeSessionVisibilityWithStatusBar");
3801     return WSError::WS_OK;
3802 }
3803 
MakeSessionInfoDuringPendingActivation(const sptr<AAFwk::SessionInfo> & abilitySessionInfo,const sptr<SceneSession> & session)3804 static SessionInfo MakeSessionInfoDuringPendingActivation(const sptr<AAFwk::SessionInfo>& abilitySessionInfo,
3805     const sptr<SceneSession>& session)
3806 {
3807     SessionInfo info;
3808     info.abilityName_ = abilitySessionInfo->want.GetElement().GetAbilityName();
3809     info.bundleName_ = abilitySessionInfo->want.GetElement().GetBundleName();
3810     info.moduleName_ = abilitySessionInfo->want.GetModuleName();
3811     int32_t appCloneIndex = abilitySessionInfo->want.GetIntParam(APP_CLONE_INDEX, 0);
3812     info.appIndex_ = appCloneIndex == 0 ? abilitySessionInfo->want.GetIntParam(DLP_INDEX, 0) : appCloneIndex;
3813     info.persistentId_ = abilitySessionInfo->persistentId;
3814     info.callerPersistentId_ = session->GetPersistentId();
3815     info.callerBundleName_ = abilitySessionInfo->want.GetStringParam(AAFwk::Want::PARAM_RESV_CALLER_BUNDLE_NAME);
3816     info.callerAbilityName_ = abilitySessionInfo->want.GetStringParam(AAFwk::Want::PARAM_RESV_CALLER_ABILITY_NAME);
3817     info.callState_ = static_cast<uint32_t>(abilitySessionInfo->state);
3818     info.uiAbilityId_ = abilitySessionInfo->uiAbilityId;
3819     info.specifiedId = abilitySessionInfo->tmpSpecifiedId;
3820     info.want = std::make_shared<AAFwk::Want>(abilitySessionInfo->want);
3821     info.requestCode = abilitySessionInfo->requestCode;
3822     info.callerToken_ = abilitySessionInfo->callerToken;
3823     info.startSetting = abilitySessionInfo->startSetting;
3824     info.callingTokenId_ = abilitySessionInfo->callingTokenId;
3825     info.reuse = abilitySessionInfo->reuse;
3826     info.processOptions = abilitySessionInfo->processOptions;
3827     info.isAtomicService_ = abilitySessionInfo->isAtomicService;
3828     info.isBackTransition_ = abilitySessionInfo->isBackTransition;
3829     info.needClearInNotShowRecent_ = abilitySessionInfo->needClearInNotShowRecent;
3830     info.isFromIcon_ = abilitySessionInfo->isFromIcon;
3831 
3832     if (session->IsPcOrPadEnableActivation()) {
3833         info.startWindowOption = abilitySessionInfo->startWindowOption;
3834         if (!abilitySessionInfo->supportWindowModes.empty()) {
3835             info.supportedWindowModes.assign(abilitySessionInfo->supportWindowModes.begin(),
3836                 abilitySessionInfo->supportWindowModes.end());
3837         }
3838     }
3839     if (info.want != nullptr) {
3840         info.windowMode = info.want->GetIntParam(AAFwk::Want::PARAM_RESV_WINDOW_MODE, 0);
3841         info.sessionAffinity = info.want->GetStringParam(Rosen::PARAM_KEY::PARAM_MISSION_AFFINITY_KEY);
3842         info.screenId_ = static_cast<uint64_t>(info.want->GetIntParam(AAFwk::Want::PARAM_RESV_DISPLAY_ID, -1));
3843         TLOGI(WmsLogTag::WMS_LIFE, "want: screenId %{public}" PRIu64, info.screenId_);
3844     }
3845     if (info.windowMode == static_cast<int32_t>(WindowMode::WINDOW_MODE_FULLSCREEN)) {
3846         info.fullScreenStart_ = true;
3847     }
3848     TLOGI(WmsLogTag::WMS_LIFE, "bundleName:%{public}s, moduleName:%{public}s, abilityName:%{public}s, "
3849         "appIndex:%{public}d, affinity:%{public}s. callState:%{public}d, want persistentId:%{public}d, "
3850         "uiAbilityId:%{public}" PRIu64 ", windowMode:%{public}d, callerId:%{public}d, "
3851         "needClearInNotShowRecent:%{public}u, isFromIcon:%{public}d, supportedWindowModes.size:%{public}zu, "
3852         "specifiedId:%{public}d",
3853         info.bundleName_.c_str(), info.moduleName_.c_str(), info.abilityName_.c_str(), info.appIndex_,
3854         info.sessionAffinity.c_str(), info.callState_, info.persistentId_, info.uiAbilityId_, info.windowMode,
3855         info.callerPersistentId_, info.needClearInNotShowRecent_, info.isFromIcon_, info.supportedWindowModes.size(),
3856         info.specifiedId);
3857     return info;
3858 }
3859 
PendingSessionActivation(const sptr<AAFwk::SessionInfo> abilitySessionInfo)3860 WSError SceneSession::PendingSessionActivation(const sptr<AAFwk::SessionInfo> abilitySessionInfo)
3861 {
3862     if (!SessionPermission::VerifyCallingPermission(PermissionConstants::PERMISSION_MANAGE_MISSION)) {
3863         TLOGE(WmsLogTag::WMS_LIFE, "The caller has not permission granted");
3864         return WSError::WS_ERROR_INVALID_PERMISSION;
3865     }
3866     bool isFoundationCall = SessionPermission::IsFoundationCall();
3867     auto task = [weakThis = wptr(this), abilitySessionInfo, isFoundationCall]() {
3868         auto session = weakThis.promote();
3869         if (!session) {
3870             TLOGE(WmsLogTag::WMS_LIFE, "session is null");
3871             return WSError::WS_ERROR_DESTROYED_OBJECT;
3872         }
3873         if (abilitySessionInfo == nullptr) {
3874             TLOGE(WmsLogTag::WMS_LIFE, "abilitySessionInfo is null");
3875             return WSError::WS_ERROR_NULLPTR;
3876         }
3877         bool isFromAncoAndToAnco = session->IsAnco() && AbilityInfoManager::GetInstance().IsAnco(
3878             abilitySessionInfo->want.GetElement().GetBundleName(),
3879             abilitySessionInfo->want.GetElement().GetAbilityName(), abilitySessionInfo->want.GetModuleName());
3880         if (!session->IsPcOrPadEnableActivation() && WindowHelper::IsMainWindow(session->GetWindowType())) {
3881             SessionState sessionState = session->GetSessionState();
3882             TLOGI(WmsLogTag::WMS_LIFE, "sceneSession state:%{public}d, isFoundationCall:%{public}u, "
3883                 "canStartAbilityFromBackground:%{public}u, foregroundInteractiveStatus:%{public}u",
3884                 sessionState, isFoundationCall, abilitySessionInfo->canStartAbilityFromBackground,
3885                 session->GetForegroundInteractiveStatus());
3886             bool isSessionForeground = sessionState == SessionState::STATE_FOREGROUND ||
3887                 sessionState == SessionState::STATE_ACTIVE;
3888             if (isSessionForeground && !session->GetForegroundInteractiveStatus()) {
3889                 TLOGW(WmsLogTag::WMS_LIFE, "start ability invalid, sceneSession in a non interactive state");
3890                 return WSError::WS_ERROR_INVALID_OPERATION;
3891             }
3892             if (!isSessionForeground && !isFromAncoAndToAnco &&
3893                 !(isFoundationCall && abilitySessionInfo->canStartAbilityFromBackground)) {
3894                 TLOGW(WmsLogTag::WMS_LIFE, "no permission to start ability from Background");
3895                 return WSError::WS_ERROR_INVALID_OPERATION;
3896             }
3897         }
3898         session->sessionInfo_.startMethod = StartMethod::START_CALL;
3899         SessionInfo info = MakeSessionInfoDuringPendingActivation(abilitySessionInfo, session);
3900         session->HandleCastScreenConnection(info, session);
3901         if (session->pendingSessionActivationFunc_) {
3902             session->pendingSessionActivationFunc_(info);
3903         }
3904         return WSError::WS_OK;
3905     };
3906     PostTask(task, "PendingSessionActivation");
3907     return WSError::WS_OK;
3908 }
3909 
HandleCastScreenConnection(SessionInfo & info,sptr<SceneSession> session)3910 void SceneSession::HandleCastScreenConnection(SessionInfo& info, sptr<SceneSession> session)
3911 {
3912     ScreenId defScreenId = ScreenSessionManagerClient::GetInstance().GetDefaultScreenId();
3913     if (defScreenId == info.screenId_) {
3914         return;
3915     }
3916     auto flag = Rosen::ScreenManager::GetInstance().GetVirtualScreenFlag(info.screenId_);
3917     if (flag != VirtualScreenFlag::CAST) {
3918         return;
3919     }
3920     TLOGI(WmsLogTag::WMS_LIFE, "Get exist session state :%{public}d persistentId:%{public}d",
3921         session->GetSessionState(), info.callerPersistentId_);
3922     if (session->GetSessionState() != SessionState::STATE_FOREGROUND &&
3923         session->GetSessionState() != SessionState::STATE_ACTIVE) {
3924         TLOGI(WmsLogTag::WMS_LIFE, "Get exist session state is not foreground");
3925         return;
3926     }
3927     info.isCastSession_ = true;
3928     std::vector<uint64_t> mirrorIds { info.screenId_ };
3929     Rosen::DMError ret = Rosen::ScreenManager::GetInstance().MakeUniqueScreen(mirrorIds);
3930     if (ret != Rosen::DMError::DM_OK) {
3931         TLOGE(WmsLogTag::WMS_LIFE, "MakeUniqueScreen failed,ret: %{public}d", ret);
3932         return;
3933     }
3934 }
3935 
IsNeedSystemPermissionByAction(WSPropertyChangeAction action,const sptr<WindowSessionProperty> & property,const sptr<WindowSessionProperty> & sessionProperty)3936 static bool IsNeedSystemPermissionByAction(WSPropertyChangeAction action,
3937     const sptr<WindowSessionProperty>& property, const sptr<WindowSessionProperty>& sessionProperty)
3938 {
3939     switch (action) {
3940         case WSPropertyChangeAction::ACTION_UPDATE_TURN_SCREEN_ON:
3941         case WSPropertyChangeAction::ACTION_UPDATE_SNAPSHOT_SKIP:
3942         case WSPropertyChangeAction::ACTION_UPDATE_HIDE_NON_SYSTEM_FLOATING_WINDOWS:
3943         case WSPropertyChangeAction::ACTION_UPDATE_TOPMOST:
3944         case WSPropertyChangeAction::ACTION_UPDATE_DECOR_ENABLE:
3945         case WSPropertyChangeAction::ACTION_UPDATE_MODE_SUPPORT_INFO:
3946             return true;
3947         case WSPropertyChangeAction::ACTION_UPDATE_ANIMATION_FLAG:
3948             return property->GetAnimationFlag() == static_cast<uint32_t>(WindowAnimation::CUSTOM);
3949         case WSPropertyChangeAction::ACTION_UPDATE_FLAGS: {
3950             uint32_t oldFlags = sessionProperty->GetWindowFlags();
3951             uint32_t flags = property->GetWindowFlags();
3952             if ((oldFlags ^ flags) == static_cast<uint32_t>(WindowFlag::WINDOW_FLAG_WATER_MARK)) {
3953                 return true;
3954             }
3955             break;
3956         }
3957         default:
3958             break;
3959     }
3960     return false;
3961 }
3962 
UpdateSessionPropertyByAction(const sptr<WindowSessionProperty> & property,WSPropertyChangeAction action)3963 WMError SceneSession::UpdateSessionPropertyByAction(const sptr<WindowSessionProperty>& property,
3964     WSPropertyChangeAction action)
3965 {
3966     if (property == nullptr) {
3967         TLOGE(WmsLogTag::DEFAULT, "property is nullptr");
3968         return WMError::WM_ERROR_NULLPTR;
3969     }
3970     auto sessionProperty = GetSessionProperty();
3971     if (sessionProperty == nullptr) {
3972         TLOGE(WmsLogTag::DEFAULT, "get session property failed");
3973         return WMError::WM_ERROR_NULLPTR;
3974     }
3975     if (action == WSPropertyChangeAction::ACTION_UPDATE_PRIVACY_MODE) {
3976         if (!SessionPermission::VerifyCallingPermission("ohos.permission.PRIVACY_WINDOW")) {
3977             return WMError::WM_ERROR_INVALID_PERMISSION;
3978         }
3979     }
3980     if (action == WSPropertyChangeAction::ACTION_UPDATE_MAIN_WINDOW_TOPMOST) {
3981         uint32_t accessTokenId = property->GetAccessTokenId();
3982         if (!SessionPermission::VerifyPermissionByCallerToken(accessTokenId,
3983             PermissionConstants::PERMISSION_MAIN_WINDOW_TOPMOST)) {
3984             TLOGE(WmsLogTag::WMS_HIERARCHY, "The caller has no permission granted.");
3985             return WMError::WM_ERROR_INVALID_PERMISSION;
3986         }
3987     }
3988 
3989     bool isSystemCalling = SessionPermission::IsSystemCalling() || SessionPermission::IsStartByHdcd();
3990     if (!isSystemCalling && IsNeedSystemPermissionByAction(action, property, sessionProperty)) {
3991         TLOGE(WmsLogTag::DEFAULT, "permission denied! action: %{public}" PRIu64, action);
3992         return WMError::WM_ERROR_NOT_SYSTEM_APP;
3993     }
3994     property->SetSystemCalling(isSystemCalling);
3995     wptr<SceneSession> weak = this;
3996     auto task = [weak, property, action]() -> WMError {
3997         auto sceneSession = weak.promote();
3998         if (sceneSession == nullptr) {
3999             TLOGE(WmsLogTag::DEFAULT, "the session is nullptr");
4000             return WMError::WM_DO_NOTHING;
4001         }
4002         TLOGD(WmsLogTag::DEFAULT, "Id: %{public}d, action: %{public}" PRIu64, sceneSession->GetPersistentId(), action);
4003         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "SceneSession:UpdateProperty");
4004         return sceneSession->HandleUpdatePropertyByAction(property, sceneSession, action);
4005     };
4006     if (AppExecFwk::EventRunner::IsAppMainThread()) {
4007         PostTask(task, "UpdateProperty");
4008         return WMError::WM_OK;
4009     }
4010     return PostSyncTask(task, "UpdateProperty");
4011 }
4012 
SetGestureBackEnabled(bool isEnabled)4013 WMError SceneSession::SetGestureBackEnabled(bool isEnabled)
4014 {
4015     auto task = [weakThis = wptr(this), isEnabled] {
4016         auto sceneSession = weakThis.promote();
4017         if (!sceneSession) {
4018             TLOGNE(WmsLogTag::WMS_IMMS, "session is invalid");
4019             return;
4020         }
4021         if (sceneSession->isEnableGestureBack_ == isEnabled) {
4022             TLOGNI(WmsLogTag::WMS_IMMS, "isEnabled equals last.");
4023             return;
4024         }
4025         TLOGNI(WmsLogTag::WMS_IMMS, "id: %{public}d, isEnabled: %{public}d",
4026             sceneSession->GetPersistentId(), isEnabled);
4027         sceneSession->isEnableGestureBack_ = isEnabled;
4028         sceneSession->isEnableGestureBackHadSet_ = true;
4029         sceneSession->UpdateGestureBackEnabled();
4030     };
4031     PostTask(task, __func__);
4032     return WMError::WM_OK;
4033 }
4034 
GetGestureBackEnabled()4035 bool SceneSession::GetGestureBackEnabled()
4036 {
4037     return isEnableGestureBack_;
4038 }
4039 
GetEnableGestureBackHadSet()4040 bool SceneSession::GetEnableGestureBackHadSet()
4041 {
4042     return isEnableGestureBackHadSet_;
4043 }
4044 
SetSessionChangeByActionNotifyManagerListener(const SessionChangeByActionNotifyManagerFunc & func)4045 void SceneSession::SetSessionChangeByActionNotifyManagerListener(const SessionChangeByActionNotifyManagerFunc& func)
4046 {
4047     TLOGD(WmsLogTag::DEFAULT, "setListener success");
4048     sessionChangeByActionNotifyManagerFunc_ = func;
4049 }
4050 
HandleUpdatePropertyByAction(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4051 WMError SceneSession::HandleUpdatePropertyByAction(const sptr<WindowSessionProperty>& property,
4052     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4053 {
4054     if (sceneSession == nullptr) {
4055         TLOGE(WmsLogTag::DEFAULT, "sceneSession is nullptr");
4056         return WMError::WM_ERROR_NULLPTR;
4057     }
4058     if (property == nullptr) {
4059         TLOGE(WmsLogTag::DEFAULT, "property is nullptr");
4060         return WMError::WM_ERROR_NULLPTR;
4061     }
4062 
4063     return ProcessUpdatePropertyByAction(property, sceneSession, action);
4064 }
4065 
ProcessUpdatePropertyByAction(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4066 WMError SceneSession::ProcessUpdatePropertyByAction(const sptr<WindowSessionProperty>& property,
4067     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4068 {
4069     switch (static_cast<uint64_t>(action)) {
4070         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_TURN_SCREEN_ON):
4071             return HandleActionUpdateTurnScreenOn(property, sceneSession, action);
4072         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_KEEP_SCREEN_ON):
4073             return HandleActionUpdateKeepScreenOn(property, sceneSession, action);
4074         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_FOCUSABLE):
4075             return HandleActionUpdateFocusable(property, sceneSession, action);
4076         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_TOUCHABLE):
4077             return HandleActionUpdateTouchable(property, sceneSession, action);
4078         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_SET_BRIGHTNESS):
4079             return HandleActionUpdateSetBrightness(property, sceneSession, action);
4080         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_ORIENTATION):
4081             return HandleActionUpdateOrientation(property, sceneSession, action);
4082         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_PRIVACY_MODE):
4083             return HandleActionUpdatePrivacyMode(property, sceneSession, action);
4084         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_SYSTEM_PRIVACY_MODE):
4085             return HandleActionUpdatePrivacyMode(property, sceneSession, action);
4086         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_SNAPSHOT_SKIP):
4087             return HandleActionUpdateSnapshotSkip(property, sceneSession, action);
4088         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_MAXIMIZE_STATE):
4089             return HandleActionUpdateMaximizeState(property, sceneSession, action);
4090         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_OTHER_PROPS):
4091             return HandleActionUpdateOtherProps(property, sceneSession, action);
4092         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_STATUS_PROPS):
4093             return HandleActionUpdateStatusProps(property, sceneSession, action);
4094         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_NAVIGATION_PROPS):
4095             return HandleActionUpdateNavigationProps(property, sceneSession, action);
4096         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_NAVIGATION_INDICATOR_PROPS):
4097             return HandleActionUpdateNavigationIndicatorProps(property, sceneSession, action);
4098         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_FLAGS):
4099             return HandleActionUpdateFlags(property, sceneSession, action);
4100         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_MODE):
4101             return HandleActionUpdateMode(property, sceneSession, action);
4102         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_ANIMATION_FLAG):
4103             return HandleActionUpdateAnimationFlag(property, sceneSession, action);
4104         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_TOUCH_HOT_AREA):
4105             return HandleActionUpdateTouchHotArea(property, sceneSession, action);
4106         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_KEYBOARD_TOUCH_HOT_AREA):
4107             return HandleActionUpdateKeyboardTouchHotArea(property, action);
4108         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_DECOR_ENABLE):
4109             return HandleActionUpdateDecorEnable(property, sceneSession, action);
4110         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_WINDOW_LIMITS):
4111             return HandleActionUpdateWindowLimits(property, sceneSession, action);
4112         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_DRAGENABLED):
4113             return HandleActionUpdateDragenabled(property, sceneSession, action);
4114         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_RAISEENABLED):
4115             return HandleActionUpdateRaiseenabled(property, sceneSession, action);
4116         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_HIDE_NON_SYSTEM_FLOATING_WINDOWS):
4117             return HandleActionUpdateHideNonSystemFloatingWindows(property, sceneSession, action);
4118         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_TEXTFIELD_AVOID_INFO):
4119             return HandleActionUpdateTextfieldAvoidInfo(property, sceneSession, action);
4120         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_WINDOW_MASK):
4121             return HandleActionUpdateWindowMask(property, sceneSession, action);
4122         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_TOPMOST):
4123             return HandleActionUpdateTopmost(property, sceneSession, action);
4124         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_MAIN_WINDOW_TOPMOST):
4125             return HandleActionUpdateMainWindowTopmost(property, action);
4126         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_MODE_SUPPORT_INFO):
4127             return HandleActionUpdateWindowModeSupportType(property, sceneSession, action);
4128         case static_cast<uint64_t>(WSPropertyChangeAction::ACTION_UPDATE_EXCLUSIVE_HIGHLIGHTED):
4129             return HandleActionUpdateExclusivelyHighlighted(property, action);
4130         default:
4131             TLOGE(WmsLogTag::DEFAULT, "Failed to find func handler!");
4132             return WMError::WM_DO_NOTHING;
4133     }
4134 }
4135 
HandleActionUpdateTurnScreenOn(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4136 WMError SceneSession::HandleActionUpdateTurnScreenOn(const sptr<WindowSessionProperty>& property,
4137     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4138 {
4139     sceneSession->SetTurnScreenOn(property->IsTurnScreenOn());
4140 #ifdef POWER_MANAGER_ENABLE
4141     auto task = [this, sceneSession]() {
4142         if (sceneSession == nullptr) {
4143             TLOGE(WmsLogTag::DEFAULT, "session is invalid");
4144             return;
4145         }
4146         TLOGD(WmsLogTag::DEFAULT, "Win: %{public}s, is turn on: %{public}d",
4147             sceneSession->GetWindowName().c_str(), sceneSession->IsTurnScreenOn());
4148         std::string identity = IPCSkeleton::ResetCallingIdentity();
4149         if (sceneSession->IsTurnScreenOn()) {
4150             TLOGI(WmsLogTag::DEFAULT, "turn screen on");
4151             PowerMgr::PowerMgrClient::GetInstance().WakeupDevice();
4152         }
4153         // set ipc identity to raw
4154         IPCSkeleton::SetCallingIdentity(identity);
4155     };
4156     PostTask(task, "HandleTurnScreenOn");
4157 #else
4158     TLOGD(WmsLogTag::DEFAULT, "Can not found the sub system of PowerMgr");
4159 #endif
4160     return WMError::WM_OK;
4161 }
4162 
HandleActionUpdateKeepScreenOn(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4163 WMError SceneSession::HandleActionUpdateKeepScreenOn(const sptr<WindowSessionProperty>& property,
4164     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4165 {
4166     sceneSession->SetKeepScreenOn(property->IsKeepScreenOn());
4167     sceneSession->NotifySessionChangeByActionNotifyManager(sceneSession, property, action);
4168     return WMError::WM_OK;
4169 }
4170 
HandleActionUpdateFocusable(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4171 WMError SceneSession::HandleActionUpdateFocusable(const sptr<WindowSessionProperty>& property,
4172     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4173 {
4174     sceneSession->SetFocusable(property->GetFocusable());
4175     sceneSession->NotifySessionChangeByActionNotifyManager(sceneSession, property, action);
4176     return WMError::WM_OK;
4177 }
4178 
HandleActionUpdateTouchable(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4179 WMError SceneSession::HandleActionUpdateTouchable(const sptr<WindowSessionProperty>& property,
4180     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4181 {
4182     sceneSession->SetTouchable(property->GetTouchable());
4183     sceneSession->NotifySessionChangeByActionNotifyManager(sceneSession, property, action);
4184     return WMError::WM_OK;
4185 }
4186 
HandleActionUpdateSetBrightness(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4187 WMError SceneSession::HandleActionUpdateSetBrightness(const sptr<WindowSessionProperty>& property,
4188     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4189 {
4190     if (sceneSession->GetWindowType() != WindowType::WINDOW_TYPE_APP_MAIN_WINDOW) {
4191         TLOGW(WmsLogTag::DEFAULT, "only app main window can set brightness");
4192         return WMError::WM_OK;
4193     }
4194     if (!sceneSession->IsSessionValid()) {
4195         TLOGW(WmsLogTag::WMS_MAIN, "Session is invalid, id: %{public}d state: %{public}u",
4196             sceneSession->GetPersistentId(), sceneSession->GetSessionState());
4197         return WMError::WM_ERROR_INVALID_SESSION;
4198     }
4199     float brightness = property->GetBrightness();
4200     if (std::abs(brightness - sceneSession->GetBrightness()) < std::numeric_limits<float>::epsilon()) {
4201         TLOGD(WmsLogTag::DEFAULT, "Session brightness do not change: [%{public}f]", brightness);
4202         return WMError::WM_OK;
4203     }
4204     sceneSession->SetBrightness(brightness);
4205     sceneSession->NotifySessionChangeByActionNotifyManager(sceneSession, property, action);
4206     return WMError::WM_OK;
4207 }
4208 
HandleActionUpdateOrientation(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4209 WMError SceneSession::HandleActionUpdateOrientation(const sptr<WindowSessionProperty>& property,
4210     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4211 {
4212     sceneSession->SetRequestedOrientation(property->GetRequestedOrientation());
4213     return WMError::WM_OK;
4214 }
4215 
HandleActionUpdatePrivacyMode(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4216 WMError SceneSession::HandleActionUpdatePrivacyMode(const sptr<WindowSessionProperty>& property,
4217     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4218 {
4219     bool isPrivacyMode = property->GetPrivacyMode() || property->GetSystemPrivacyMode();
4220     sceneSession->SetPrivacyMode(isPrivacyMode);
4221     sceneSession->NotifySessionChangeByActionNotifyManager(sceneSession, property, action);
4222     return WMError::WM_OK;
4223 }
4224 
HandleActionUpdateSnapshotSkip(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4225 WMError SceneSession::HandleActionUpdateSnapshotSkip(const sptr<WindowSessionProperty>& property,
4226     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4227 {
4228     return sceneSession->SetSnapshotSkip(property->GetSnapshotSkip());
4229 }
4230 
HandleActionUpdateMaximizeState(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4231 WMError SceneSession::HandleActionUpdateMaximizeState(const sptr<WindowSessionProperty>& property,
4232     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4233 {
4234     auto sessionProperty = sceneSession->GetSessionProperty();
4235     if (sessionProperty != nullptr) {
4236         sessionProperty->SetMaximizeMode(property->GetMaximizeMode());
4237         sessionProperty->SetIsLayoutFullScreen(property->IsLayoutFullScreen());
4238     }
4239     return WMError::WM_OK;
4240 }
4241 
HandleActionUpdateOtherProps(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4242 WMError SceneSession::HandleActionUpdateOtherProps(const sptr<WindowSessionProperty>& property,
4243     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4244 {
4245     auto systemBarProperties = property->GetSystemBarProperty();
4246     for (auto iter : systemBarProperties) {
4247         sceneSession->SetSystemBarProperty(iter.first, iter.second);
4248     }
4249     sceneSession->NotifySessionChangeByActionNotifyManager(sceneSession, property, action);
4250     return WMError::WM_OK;
4251 }
4252 
HandleActionUpdateStatusProps(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4253 WMError SceneSession::HandleActionUpdateStatusProps(const sptr<WindowSessionProperty>& property,
4254     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4255 {
4256     HandleSpecificSystemBarProperty(WindowType::WINDOW_TYPE_STATUS_BAR, property, sceneSession);
4257     sceneSession->NotifySessionChangeByActionNotifyManager(sceneSession, property, action);
4258     return WMError::WM_OK;
4259 }
4260 
HandleActionUpdateNavigationProps(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4261 WMError SceneSession::HandleActionUpdateNavigationProps(const sptr<WindowSessionProperty>& property,
4262     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4263 {
4264     HandleSpecificSystemBarProperty(WindowType::WINDOW_TYPE_NAVIGATION_BAR, property, sceneSession);
4265     sceneSession->NotifySessionChangeByActionNotifyManager(sceneSession, property, action);
4266     return WMError::WM_OK;
4267 }
4268 
HandleActionUpdateNavigationIndicatorProps(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4269 WMError SceneSession::HandleActionUpdateNavigationIndicatorProps(const sptr<WindowSessionProperty>& property,
4270     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4271 {
4272     HandleSpecificSystemBarProperty(WindowType::WINDOW_TYPE_NAVIGATION_INDICATOR, property, sceneSession);
4273     sceneSession->NotifySessionChangeByActionNotifyManager(sceneSession, property, action);
4274     return WMError::WM_OK;
4275 }
4276 
HandleActionUpdateFlags(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4277 WMError SceneSession::HandleActionUpdateFlags(const sptr<WindowSessionProperty>& property,
4278     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4279 {
4280     SetWindowFlags(sceneSession, property);
4281     sceneSession->NotifySessionChangeByActionNotifyManager(sceneSession, property, action);
4282     return WMError::WM_OK;
4283 }
4284 
HandleActionUpdateMode(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4285 WMError SceneSession::HandleActionUpdateMode(const sptr<WindowSessionProperty>& property,
4286     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4287 {
4288     auto sessionProperty = sceneSession->GetSessionProperty();
4289     if (sessionProperty != nullptr) {
4290         sessionProperty->SetWindowMode(property->GetWindowMode());
4291     }
4292     sceneSession->NotifySessionChangeByActionNotifyManager(sceneSession, property, action);
4293     return WMError::WM_OK;
4294 }
4295 
HandleActionUpdateAnimationFlag(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4296 WMError SceneSession::HandleActionUpdateAnimationFlag(const sptr<WindowSessionProperty>& property,
4297     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4298 {
4299     auto sessionProperty = sceneSession->GetSessionProperty();
4300     if (sessionProperty != nullptr) {
4301         sessionProperty->SetAnimationFlag(property->GetAnimationFlag());
4302     }
4303     return WMError::WM_OK;
4304 }
4305 
HandleActionUpdateTouchHotArea(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4306 WMError SceneSession::HandleActionUpdateTouchHotArea(const sptr<WindowSessionProperty>& property,
4307     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4308 {
4309     auto sessionProperty = sceneSession->GetSessionProperty();
4310     if (sessionProperty != nullptr) {
4311         std::vector<Rect> touchHotAreas;
4312         property->GetTouchHotAreas(touchHotAreas);
4313         sessionProperty->SetTouchHotAreas(touchHotAreas);
4314     }
4315     return WMError::WM_OK;
4316 }
4317 
HandleActionUpdateKeyboardTouchHotArea(const sptr<WindowSessionProperty> & property,WSPropertyChangeAction action)4318 WMError SceneSession::HandleActionUpdateKeyboardTouchHotArea(const sptr<WindowSessionProperty>& property,
4319     WSPropertyChangeAction action)
4320 {
4321     if (GetWindowType() != WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT) {
4322         return WMError::WM_ERROR_INVALID_TYPE;
4323     }
4324     GetSessionProperty()->SetKeyboardTouchHotAreas(property->GetKeyboardTouchHotAreas());
4325     return WMError::WM_OK;
4326 }
4327 
HandleActionUpdateDecorEnable(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4328 WMError SceneSession::HandleActionUpdateDecorEnable(const sptr<WindowSessionProperty>& property,
4329     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4330 {
4331     if (property != nullptr && !property->GetSystemCalling()) {
4332         TLOGE(WmsLogTag::DEFAULT, "update decor enable permission denied!");
4333         return WMError::WM_ERROR_NOT_SYSTEM_APP;
4334     }
4335     auto sessionProperty = sceneSession->GetSessionProperty();
4336     if (sessionProperty != nullptr) {
4337         sessionProperty->SetDecorEnable(property->IsDecorEnable());
4338     }
4339     return WMError::WM_OK;
4340 }
4341 
HandleActionUpdateWindowLimits(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4342 WMError SceneSession::HandleActionUpdateWindowLimits(const sptr<WindowSessionProperty>& property,
4343     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4344 {
4345     auto sessionProperty = sceneSession->GetSessionProperty();
4346     if (sessionProperty != nullptr) {
4347         sessionProperty->SetWindowLimits(property->GetWindowLimits());
4348         WindowLimits windowLimits = sessionProperty->GetWindowLimits();
4349         TLOGI(WmsLogTag::WMS_LAYOUT, "UpdateWindowLimits minWidth:%{public}u, minHeight:%{public}u, "
4350             "maxWidth:%{public}u, maxHeight:%{public}u, vpRatio:%{public}f", windowLimits.minWidth_,
4351             windowLimits.minHeight_, windowLimits.maxWidth_, windowLimits.maxHeight_, windowLimits.vpRatio_);
4352     }
4353     return WMError::WM_OK;
4354 }
4355 
HandleActionUpdateDragenabled(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4356 WMError SceneSession::HandleActionUpdateDragenabled(const sptr<WindowSessionProperty>& property,
4357     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4358 {
4359     auto sessionProperty = sceneSession->GetSessionProperty();
4360     if (sessionProperty != nullptr) {
4361         sessionProperty->SetDragEnabled(property->GetDragEnabled());
4362     }
4363     return WMError::WM_OK;
4364 }
4365 
HandleActionUpdateRaiseenabled(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4366 WMError SceneSession::HandleActionUpdateRaiseenabled(const sptr<WindowSessionProperty>& property,
4367     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4368 {
4369     auto sessionProperty = sceneSession->GetSessionProperty();
4370     if (sessionProperty != nullptr) {
4371         TLOGI(WmsLogTag::WMS_HIERARCHY, "id: %{public}d, raise enabled: %{public}d", GetPersistentId(),
4372             property->GetRaiseEnabled());
4373         sessionProperty->SetRaiseEnabled(property->GetRaiseEnabled());
4374     }
4375     return WMError::WM_OK;
4376 }
4377 
HandleActionUpdateHideNonSystemFloatingWindows(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4378 WMError SceneSession::HandleActionUpdateHideNonSystemFloatingWindows(const sptr<WindowSessionProperty>& property,
4379     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4380 {
4381     if (!SessionPermission::IsSystemCalling() && !SessionPermission::IsStartByHdcd()) {
4382         TLOGE(WmsLogTag::DEFAULT, "Update property hideNonSystemFloatingWindows permission denied!");
4383         return WMError::WM_OK;
4384     }
4385     auto currentProperty = sceneSession->GetSessionProperty();
4386     if (currentProperty != nullptr) {
4387         sceneSession->NotifySessionChangeByActionNotifyManager(sceneSession, property, action);
4388         currentProperty->SetHideNonSystemFloatingWindows(property->GetHideNonSystemFloatingWindows());
4389     }
4390     return WMError::WM_OK;
4391 }
4392 
HandleActionUpdateTextfieldAvoidInfo(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4393 WMError SceneSession::HandleActionUpdateTextfieldAvoidInfo(const sptr<WindowSessionProperty>& property,
4394     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4395 {
4396     auto sessionProperty = sceneSession->GetSessionProperty();
4397     if (sessionProperty != nullptr) {
4398         sessionProperty->SetTextFieldPositionY(property->GetTextFieldPositionY());
4399         sessionProperty->SetTextFieldHeight(property->GetTextFieldHeight());
4400     }
4401     return WMError::WM_OK;
4402 }
4403 
HandleActionUpdateWindowMask(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4404 WMError SceneSession::HandleActionUpdateWindowMask(const sptr<WindowSessionProperty>& property,
4405     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4406 {
4407     auto sessionProperty = sceneSession->GetSessionProperty();
4408     if (sessionProperty != nullptr) {
4409         sessionProperty->SetWindowMask(property->GetWindowMask());
4410         sessionProperty->SetIsShaped(property->GetIsShaped());
4411         sceneSession->NotifySessionChangeByActionNotifyManager(sceneSession, property, action);
4412     }
4413     return WMError::WM_OK;
4414 }
4415 
HandleActionUpdateTopmost(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)4416 WMError SceneSession::HandleActionUpdateTopmost(const sptr<WindowSessionProperty>& property,
4417     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
4418 {
4419     if (!SessionPermission::IsSystemCalling()) {
4420         TLOGE(WmsLogTag::WMS_LAYOUT, "UpdateTopmostProperty permission denied!");
4421         return WMError::WM_ERROR_NOT_SYSTEM_APP;
4422     }
4423 
4424     sceneSession->SetTopmost(property->IsTopmost());
4425     return WMError::WM_OK;
4426 }
4427 
HandleActionUpdateMainWindowTopmost(const sptr<WindowSessionProperty> & property,WSPropertyChangeAction action)4428 WMError SceneSession::HandleActionUpdateMainWindowTopmost(const sptr<WindowSessionProperty>& property,
4429     WSPropertyChangeAction action)
4430 {
4431     SetMainWindowTopmost(property->IsMainWindowTopmost());
4432     return WMError::WM_OK;
4433 }
4434 
HandleActionUpdateExclusivelyHighlighted(const sptr<WindowSessionProperty> & property,WSPropertyChangeAction action)4435 WMError SceneSession::HandleActionUpdateExclusivelyHighlighted(const sptr<WindowSessionProperty>& property,
4436     WSPropertyChangeAction action)
4437 {
4438     auto sessionProperty = GetSessionProperty();
4439     if (!sessionProperty) {
4440         TLOGE(WmsLogTag::WMS_FOCUS, "property is null");
4441         return WMError::WM_ERROR_INVALID_PARAM;
4442     }
4443     sessionProperty->SetExclusivelyHighlighted(property->GetExclusivelyHighlighted());
4444     return WMError::WM_OK;
4445 }
4446 
HandleSpecificSystemBarProperty(WindowType type,const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession)4447 void SceneSession::HandleSpecificSystemBarProperty(WindowType type,
4448     const sptr<WindowSessionProperty>& property, const sptr<SceneSession>& sceneSession)
4449 {
4450     auto systemBarProperties = property->GetSystemBarProperty();
4451     if (auto iter = systemBarProperties.find(type); iter != systemBarProperties.end()) {
4452         if (GetIsDisplayStatusBarTemporarily() && specificCallback_ && specificCallback_->onUpdateAvoidArea_) {
4453             SetIsDisplayStatusBarTemporarily(false);
4454             if (Session::IsScbCoreEnabled()) {
4455                 dirtyFlags_ |= static_cast<uint32_t>(SessionUIDirtyFlag::AVOID_AREA);
4456             } else {
4457                 specificCallback_->onUpdateAvoidArea_(GetPersistentId());
4458             }
4459         }
4460         SetSystemBarProperty(iter->first, iter->second);
4461         TLOGD(WmsLogTag::WMS_IMMS, "%{public}d, enable: %{public}d",
4462             static_cast<int32_t>(iter->first), iter->second.enable_);
4463     }
4464 }
4465 
SetWindowFlags(const sptr<SceneSession> & sceneSession,const sptr<WindowSessionProperty> & property)4466 void SceneSession::SetWindowFlags(const sptr<SceneSession>& sceneSession,
4467     const sptr<WindowSessionProperty>& property)
4468 {
4469     if (sceneSession == nullptr) {
4470         TLOGD(WmsLogTag::DEFAULT, "session is nullptr");
4471         return;
4472     }
4473     auto sessionProperty = sceneSession->GetSessionProperty();
4474     if (sessionProperty == nullptr) {
4475         TLOGE(WmsLogTag::DEFAULT, "get session property failed");
4476         return;
4477     }
4478     uint32_t flags = property->GetWindowFlags();
4479     uint32_t oldFlags = sessionProperty->GetWindowFlags();
4480     if (((oldFlags ^ flags) == static_cast<uint32_t>(WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED) ||
4481          (oldFlags ^ flags) == static_cast<uint32_t>(WindowFlag::WINDOW_FLAG_WATER_MARK)) &&
4482         !property->GetSystemCalling()) {
4483         TLOGE(WmsLogTag::DEFAULT, "Set window flags permission denied");
4484         return;
4485     }
4486     sessionProperty->SetWindowFlags(flags);
4487     if ((oldFlags ^ flags) == static_cast<uint32_t>(WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED)) {
4488         sceneSession->OnShowWhenLocked(flags & static_cast<uint32_t>(WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED));
4489     }
4490     TLOGI(WmsLogTag::DEFAULT, "flags: %{public}u", flags);
4491 }
4492 
NotifySessionChangeByActionNotifyManager(const sptr<SceneSession> & sceneSession,const sptr<WindowSessionProperty> & property,WSPropertyChangeAction action)4493 void SceneSession::NotifySessionChangeByActionNotifyManager(const sptr<SceneSession>& sceneSession,
4494     const sptr<WindowSessionProperty>& property, WSPropertyChangeAction action)
4495 {
4496     TLOGD(WmsLogTag::DEFAULT, "id: %{public}d, action: %{public}" PRIu64,
4497         GetPersistentId(), action);
4498     if (sessionChangeByActionNotifyManagerFunc_ == nullptr) {
4499         TLOGW(WmsLogTag::DEFAULT, "func is null");
4500         return;
4501     }
4502     sessionChangeByActionNotifyManagerFunc_(sceneSession, property, action);
4503 }
4504 
TerminateSession(const sptr<AAFwk::SessionInfo> abilitySessionInfo)4505 WSError SceneSession::TerminateSession(const sptr<AAFwk::SessionInfo> abilitySessionInfo)
4506 {
4507     auto task = [weakThis = wptr(this), abilitySessionInfo]() {
4508         auto session = weakThis.promote();
4509         if (!session) {
4510             TLOGE(WmsLogTag::WMS_LIFE, "session is null");
4511             return WSError::WS_ERROR_DESTROYED_OBJECT;
4512         }
4513         if (abilitySessionInfo == nullptr) {
4514             TLOGE(WmsLogTag::WMS_LIFE, "abilitySessionInfo is null");
4515             return WSError::WS_ERROR_NULLPTR;
4516         }
4517         if (session->isTerminating_) {
4518             TLOGE(WmsLogTag::WMS_LIFE, "TerminateSession: is terminating, return!");
4519             return WSError::WS_ERROR_INVALID_OPERATION;
4520         }
4521         session->isTerminating_ = true;
4522         SessionInfo info;
4523         info.abilityName_ = abilitySessionInfo->want.GetElement().GetAbilityName();
4524         info.bundleName_ = abilitySessionInfo->want.GetElement().GetBundleName();
4525         info.callerToken_ = abilitySessionInfo->callerToken;
4526         info.persistentId_ = static_cast<int32_t>(abilitySessionInfo->persistentId);
4527         {
4528             std::lock_guard<std::recursive_mutex> lock(session->sessionInfoMutex_);
4529             session->sessionInfo_.closeAbilityWant = std::make_shared<AAFwk::Want>(abilitySessionInfo->want);
4530             session->sessionInfo_.resultCode = abilitySessionInfo->resultCode;
4531         }
4532         if (session->terminateSessionFunc_) {
4533             session->terminateSessionFunc_(info);
4534         }
4535         return WSError::WS_OK;
4536     };
4537     PostLifeCycleTask(task, "TerminateSession", LifeCycleTaskType::STOP);
4538     return WSError::WS_OK;
4539 }
4540 
NotifySessionExceptionInner(const sptr<AAFwk::SessionInfo> abilitySessionInfo,bool needRemoveSession,bool isFromClient,bool startFail)4541 WSError SceneSession::NotifySessionExceptionInner(const sptr<AAFwk::SessionInfo> abilitySessionInfo,
4542     bool needRemoveSession, bool isFromClient, bool startFail)
4543 {
4544     auto task = [weakThis = wptr(this), abilitySessionInfo, needRemoveSession, isFromClient, startFail]() {
4545         auto session = weakThis.promote();
4546         if (!session) {
4547             TLOGE(WmsLogTag::WMS_LIFE, "session is null");
4548             return WSError::WS_ERROR_DESTROYED_OBJECT;
4549         }
4550         if (abilitySessionInfo == nullptr) {
4551             TLOGE(WmsLogTag::WMS_LIFE, "abilitySessionInfo is null");
4552             return WSError::WS_ERROR_NULLPTR;
4553         }
4554         if (SessionHelper::IsMainWindow(session->GetWindowType()) && isFromClient &&
4555             !session->clientIdentityToken_.empty() &&
4556             session->clientIdentityToken_ != abilitySessionInfo->identityToken) {
4557             TLOGE(WmsLogTag::WMS_LIFE, "client exception not matched: %{public}s, %{public}s",
4558                 session->clientIdentityToken_.c_str(), abilitySessionInfo->identityToken.c_str());
4559             return WSError::WS_ERROR_INVALID_PARAM;
4560         }
4561         if (session->isTerminating_) {
4562             TLOGE(WmsLogTag::WMS_LIFE, "NotifySessionExceptionInner: is terminating, return!");
4563             return WSError::WS_ERROR_INVALID_OPERATION;
4564         }
4565         session->isTerminating_ = true;
4566         SessionInfo info;
4567         info.abilityName_ = abilitySessionInfo->want.GetElement().GetAbilityName();
4568         info.bundleName_ = abilitySessionInfo->want.GetElement().GetBundleName();
4569         info.callerToken_ = abilitySessionInfo->callerToken;
4570         info.errorCode = abilitySessionInfo->errorCode;
4571         info.errorReason = abilitySessionInfo->errorReason;
4572         info.persistentId_ = static_cast<int32_t>(abilitySessionInfo->persistentId);
4573         {
4574             std::lock_guard<std::recursive_mutex> lock(session->sessionInfoMutex_);
4575             session->sessionInfo_.closeAbilityWant = std::make_shared<AAFwk::Want>(abilitySessionInfo->want);
4576             session->sessionInfo_.errorCode = abilitySessionInfo->errorCode;
4577             session->sessionInfo_.errorReason = abilitySessionInfo->errorReason;
4578         }
4579         if (session->sessionExceptionFunc_) {
4580             session->sessionExceptionFunc_(info, needRemoveSession, false);
4581         }
4582         if (session->jsSceneSessionExceptionFunc_) {
4583             session->jsSceneSessionExceptionFunc_(info, needRemoveSession, startFail);
4584         }
4585         return WSError::WS_OK;
4586     };
4587     PostLifeCycleTask(task, "NotifySessionExceptionInner", LifeCycleTaskType::STOP);
4588     return WSError::WS_OK;
4589 }
4590 
NotifySessionException(const sptr<AAFwk::SessionInfo> abilitySessionInfo,bool needRemoveSession)4591 WSError SceneSession::NotifySessionException(const sptr<AAFwk::SessionInfo> abilitySessionInfo, bool needRemoveSession)
4592 {
4593     if (!SessionPermission::VerifyCallingPermission(PermissionConstants::PERMISSION_MANAGE_MISSION)) {
4594         TLOGE(WmsLogTag::WMS_LIFE, "permission failed.");
4595         return WSError::WS_ERROR_INVALID_PERMISSION;
4596     }
4597     return NotifySessionExceptionInner(abilitySessionInfo, needRemoveSession, true);
4598 }
4599 
GetLastSafeRect() const4600 WSRect SceneSession::GetLastSafeRect() const
4601 {
4602     return lastSafeRect;
4603 }
4604 
SetLastSafeRect(WSRect rect)4605 void SceneSession::SetLastSafeRect(WSRect rect)
4606 {
4607     lastSafeRect.posX_ = rect.posX_;
4608     lastSafeRect.posY_ = rect.posY_;
4609     lastSafeRect.width_ = rect.width_;
4610     lastSafeRect.height_ = rect.height_;
4611     return;
4612 }
4613 
GetOriPosYBeforeRaisedByKeyboard() const4614 int32_t SceneSession::GetOriPosYBeforeRaisedByKeyboard() const
4615 {
4616     return oriPosYBeforeRaisedByKeyboard_;
4617 }
4618 
SetOriPosYBeforeRaisedByKeyboard(int32_t posY)4619 void SceneSession::SetOriPosYBeforeRaisedByKeyboard(int32_t posY)
4620 {
4621     oriPosYBeforeRaisedByKeyboard_ = posY;
4622 }
4623 
AddSubSession(const sptr<SceneSession> & subSession)4624 bool SceneSession::AddSubSession(const sptr<SceneSession>& subSession)
4625 {
4626     if (subSession == nullptr) {
4627         TLOGE(WmsLogTag::WMS_SUB, "subSession is nullptr");
4628         return false;
4629     }
4630     const auto& persistentId = subSession->GetPersistentId();
4631     auto iter = std::find_if(subSession_.begin(), subSession_.end(),
4632         [persistentId](sptr<SceneSession> session) {
4633             bool res = (session != nullptr && session->GetPersistentId() == persistentId) ? true : false;
4634             return res;
4635         });
4636     if (iter != subSession_.end()) {
4637         TLOGE(WmsLogTag::WMS_SUB, "Sub ession is already exists, id: %{public}d, parentId: %{public}d",
4638             subSession->GetPersistentId(), GetPersistentId());
4639         return false;
4640     }
4641     TLOGD(WmsLogTag::WMS_SUB, "Success, id: %{public}d, parentId: %{public}d",
4642         subSession->GetPersistentId(), GetPersistentId());
4643     subSession_.push_back(subSession);
4644     return true;
4645 }
4646 
RemoveSubSession(int32_t persistentId)4647 bool SceneSession::RemoveSubSession(int32_t persistentId)
4648 {
4649     auto iter = std::find_if(subSession_.begin(), subSession_.end(),
4650         [persistentId](sptr<SceneSession> session) {
4651             bool res = (session != nullptr && session->GetPersistentId() == persistentId) ? true : false;
4652             return res;
4653         });
4654     if (iter == subSession_.end()) {
4655         TLOGE(WmsLogTag::WMS_SUB, "Could not find subsession, id: %{public}d, parentId: %{public}d",
4656             persistentId, GetPersistentId());
4657         return false;
4658     }
4659     TLOGD(WmsLogTag::WMS_SUB, "Success, id: %{public}d, parentId: %{public}d", persistentId, GetPersistentId());
4660     subSession_.erase(iter);
4661     return true;
4662 }
4663 
AddToastSession(const sptr<SceneSession> & toastSession)4664 bool SceneSession::AddToastSession(const sptr<SceneSession>& toastSession)
4665 {
4666     if (toastSession == nullptr) {
4667         TLOGE(WmsLogTag::WMS_TOAST, "toastSession is nullptr");
4668         return false;
4669     }
4670     const auto& persistentId = toastSession->GetPersistentId();
4671     auto iter = std::find_if(toastSession_.begin(), toastSession_.end(),
4672         [persistentId](sptr<SceneSession> session) {
4673             bool res = (session != nullptr && session->GetPersistentId() == persistentId) ? true : false;
4674             return res;
4675         });
4676     if (iter != toastSession_.end()) {
4677         TLOGE(WmsLogTag::WMS_TOAST, "Toast ession is already exists, id: %{public}d, parentId: %{public}d",
4678             toastSession->GetPersistentId(), GetPersistentId());
4679         return false;
4680     }
4681     TLOGD(WmsLogTag::WMS_TOAST, "Success, id: %{public}d, parentId: %{public}d",
4682         toastSession->GetPersistentId(), GetPersistentId());
4683     toastSession_.push_back(toastSession);
4684     return true;
4685 }
4686 
RemoveToastSession(int32_t persistentId)4687 bool SceneSession::RemoveToastSession(int32_t persistentId)
4688 {
4689     auto iter = std::find_if(toastSession_.begin(), toastSession_.end(),
4690         [persistentId](sptr<SceneSession> session) {
4691             bool res = (session != nullptr && session->GetPersistentId() == persistentId) ? true : false;
4692             return res;
4693         });
4694     if (iter == toastSession_.end()) {
4695         TLOGE(WmsLogTag::WMS_TOAST, "Could not find toastSession, id: %{public}d, parentId: %{public}d",
4696             persistentId, GetPersistentId());
4697         return false;
4698     }
4699     TLOGD(WmsLogTag::WMS_TOAST, "Success, id: %{public}d, parentId: %{public}d", persistentId, GetPersistentId());
4700     toastSession_.erase(iter);
4701     return true;
4702 }
4703 
NotifyPiPWindowPrepareClose()4704 void SceneSession::NotifyPiPWindowPrepareClose()
4705 {
4706     TLOGD(WmsLogTag::WMS_PIP, "NotifyPiPWindowPrepareClose");
4707     int32_t callingPid = IPCSkeleton::GetCallingPid();
4708     auto task = [weakThis = wptr(this), callingPid]() {
4709         auto session = weakThis.promote();
4710         if (!session) {
4711             TLOGE(WmsLogTag::WMS_PIP, "session is null");
4712             return;
4713         }
4714         if (callingPid != session->GetCallingPid()) {
4715             TLOGW(WmsLogTag::WMS_PIP, "permission denied, not call by the same process");
4716             return;
4717         }
4718         if (session->onPrepareClosePiPSession_) {
4719             session->onPrepareClosePiPSession_();
4720         }
4721         TLOGD(WmsLogTag::WMS_PIP, "NotifyPiPWindowPrepareClose, id: %{public}d", session->GetPersistentId());
4722         return;
4723     };
4724     PostTask(task, "NotifyPiPWindowPrepareClose");
4725 }
4726 
SetLandscapeMultiWindow(bool isLandscapeMultiWindow)4727 WSError SceneSession::SetLandscapeMultiWindow(bool isLandscapeMultiWindow)
4728 {
4729     TLOGD(WmsLogTag::WMS_MULTI_WINDOW, "NotifySetLandscapeMultiWindow");
4730     int32_t callingPid = IPCSkeleton::GetCallingPid();
4731     auto task = [weakThis = wptr(this), isLandscapeMultiWindow, callingPid]() {
4732         auto session = weakThis.promote();
4733         if (!session) {
4734             TLOGE(WmsLogTag::WMS_MULTI_WINDOW, "session is null");
4735             return WSError::WS_ERROR_DESTROYED_OBJECT;
4736         }
4737         if (callingPid != session->GetCallingPid()) {
4738             TLOGE(WmsLogTag::WMS_MULTI_WINDOW, "premission denied, not call by the same process");
4739             return WSError::WS_ERROR_INVALID_PERMISSION;
4740         }
4741         if (session->sessionChangeCallback_ &&
4742             session->sessionChangeCallback_->onSetLandscapeMultiWindowFunc_) {
4743             session->sessionChangeCallback_->onSetLandscapeMultiWindowFunc_(
4744                 isLandscapeMultiWindow);
4745         }
4746         TLOGD(WmsLogTag::WMS_MULTI_WINDOW, "NotifySetLandscapeMultiWindow, id: %{public}d,"
4747             "isLandscapeMultiWindow: %{public}u", session->GetPersistentId(), isLandscapeMultiWindow);
4748         return WSError::WS_OK;
4749     };
4750     PostTask(task, "NotifySetLandscapeMultiWindow");
4751     return WSError::WS_OK;
4752 }
4753 
GetSubSession() const4754 std::vector<sptr<SceneSession>> SceneSession::GetSubSession() const
4755 {
4756     return subSession_;
4757 }
4758 
GetToastSession() const4759 std::vector<sptr<SceneSession>> SceneSession::GetToastSession() const
4760 {
4761     return toastSession_;
4762 }
4763 
GetSessionTargetRect() const4764 WSRect SceneSession::GetSessionTargetRect() const
4765 {
4766     WSRect rect;
4767     if (moveDragController_) {
4768         rect = moveDragController_->GetTargetRect();
4769     } else {
4770         WLOGFI("moveDragController_ is null");
4771     }
4772     return rect;
4773 }
4774 
SetWindowDragHotAreaListener(const NotifyWindowDragHotAreaFunc & func)4775 void SceneSession::SetWindowDragHotAreaListener(const NotifyWindowDragHotAreaFunc& func)
4776 {
4777     if (moveDragController_) {
4778         moveDragController_->SetWindowDragHotAreaFunc(func);
4779     }
4780 }
4781 
NotifySessionForeground(uint32_t reason,bool withAnimation)4782 void SceneSession::NotifySessionForeground(uint32_t reason, bool withAnimation)
4783 {
4784     if (!sessionStage_) {
4785         return;
4786     }
4787     return sessionStage_->NotifySessionForeground(reason, withAnimation);
4788 }
4789 
NotifySessionBackground(uint32_t reason,bool withAnimation,bool isFromInnerkits)4790 void SceneSession::NotifySessionBackground(uint32_t reason, bool withAnimation, bool isFromInnerkits)
4791 {
4792     if (!sessionStage_) {
4793         return;
4794     }
4795     return sessionStage_->NotifySessionBackground(reason, withAnimation, isFromInnerkits);
4796 }
4797 
NotifySessionFullScreen(bool fullScreen)4798 void SceneSession::NotifySessionFullScreen(bool fullScreen)
4799 {
4800     if (!sessionStage_) {
4801         TLOGE(WmsLogTag::WMS_LAYOUT, "sessionStage is null");
4802         return;
4803     }
4804     sessionStage_->NotifySessionFullScreen(fullScreen);
4805 }
4806 
UpdatePiPRect(const Rect & rect,SizeChangeReason reason)4807 WSError SceneSession::UpdatePiPRect(const Rect& rect, SizeChangeReason reason)
4808 {
4809     if (!WindowHelper::IsPipWindow(GetWindowType())) {
4810         return WSError::WS_DO_NOTHING;
4811     }
4812     int32_t callingPid = IPCSkeleton::GetCallingPid();
4813     auto task = [weakThis = wptr(this), rect, reason, callingPid]() {
4814         auto session = weakThis.promote();
4815         if (!session || session->isTerminating_) {
4816             TLOGE(WmsLogTag::WMS_PIP, "SceneSession::UpdatePiPRect session is null or is terminating");
4817             return WSError::WS_ERROR_INVALID_OPERATION;
4818         }
4819         if (callingPid != session->GetCallingPid()) {
4820             TLOGW(WmsLogTag::WMS_PIP, "permission denied, not call by the same process");
4821             return WSError::WS_ERROR_INVALID_PERMISSION;
4822         }
4823         WSRect wsRect = SessionHelper::TransferToWSRect(rect);
4824         if (reason == SizeChangeReason::PIP_START) {
4825             session->SetSessionRequestRect(wsRect);
4826         }
4827         TLOGI(WmsLogTag::WMS_PIP, "rect:%{public}s, reason: %{public}u", wsRect.ToString().c_str(),
4828             static_cast<uint32_t>(reason));
4829         session->NotifySessionRectChange(wsRect, reason);
4830         return WSError::WS_OK;
4831     };
4832     if (mainHandler_ != nullptr) {
4833         mainHandler_->PostTask(std::move(task), "wms:UpdatePiPRect", 0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
4834     } else {
4835         PostTask(task, "UpdatePiPRect");
4836     }
4837     return WSError::WS_OK;
4838 }
4839 
UpdatePiPControlStatus(WsPiPControlType controlType,WsPiPControlStatus status)4840 WSError SceneSession::UpdatePiPControlStatus(WsPiPControlType controlType, WsPiPControlStatus status)
4841 {
4842     TLOGI(WmsLogTag::WMS_PIP, "controlType:%{public}u, status:%{public}d", controlType, status);
4843     if (!WindowHelper::IsPipWindow(GetWindowType())) {
4844         return WSError::WS_DO_NOTHING;
4845     }
4846     int32_t callingPid = IPCSkeleton::GetCallingPid();
4847     auto task = [weakThis = wptr(this), controlType, status, callingPid]() {
4848         auto session = weakThis.promote();
4849         if (!session || session->isTerminating_) {
4850             TLOGE(WmsLogTag::WMS_PIP, "session is null or is terminating");
4851             return WSError::WS_ERROR_INVALID_OPERATION;
4852         }
4853         if (callingPid != session->GetCallingPid()) {
4854             TLOGW(WmsLogTag::WMS_PIP, "permission denied, not call by the same process");
4855             return WSError::WS_ERROR_INVALID_PERMISSION;
4856         }
4857         if (session->sessionPiPControlStatusChangeFunc_) {
4858             HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "SceneSession::UpdatePiPControlStatus");
4859             session->sessionPiPControlStatusChangeFunc_(controlType, status);
4860         }
4861         return WSError::WS_OK;
4862     };
4863     PostTask(task, "UpdatePiPControlStatus");
4864     return WSError::WS_OK;
4865 }
4866 
SetAutoStartPiP(bool isAutoStart,uint32_t priority)4867 WSError SceneSession::SetAutoStartPiP(bool isAutoStart, uint32_t priority)
4868 {
4869     TLOGI(WmsLogTag::WMS_PIP, "isAutoStart:%{public}u priority:%{public}u", isAutoStart, priority);
4870     auto task = [weakThis = wptr(this), isAutoStart, priority] {
4871         auto session = weakThis.promote();
4872         if (!session || session->isTerminating_) {
4873             TLOGNE(WmsLogTag::WMS_PIP, "session is null or is terminating");
4874             return;
4875         }
4876         if (session->autoStartPiPStatusChangeFunc_) {
4877             HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "SceneSession::SetAutoStartPiP");
4878             session->autoStartPiPStatusChangeFunc_(isAutoStart, priority);
4879         }
4880     };
4881     PostTask(task, __func__);
4882     return WSError::WS_OK;
4883 }
4884 
SendPointerEventToUI(std::shared_ptr<MMI::PointerEvent> pointerEvent)4885 void SceneSession::SendPointerEventToUI(std::shared_ptr<MMI::PointerEvent> pointerEvent)
4886 {
4887     NotifySystemSessionPointerEventFunc systemSessionPointerEventFunc = nullptr;
4888     {
4889         std::lock_guard<std::mutex> lock(pointerEventMutex_);
4890         systemSessionPointerEventFunc = systemSessionPointerEventFunc_;
4891     }
4892     if (systemSessionPointerEventFunc != nullptr) {
4893         systemSessionPointerEventFunc(pointerEvent);
4894     } else {
4895         TLOGE(WmsLogTag::WMS_EVENT, "PointerEventFunc_ nullptr, id:%{public}d", pointerEvent->GetId());
4896         pointerEvent->MarkProcessed();
4897     }
4898 }
4899 
SendKeyEventToUI(std::shared_ptr<MMI::KeyEvent> keyEvent,bool isPreImeEvent)4900 bool SceneSession::SendKeyEventToUI(std::shared_ptr<MMI::KeyEvent> keyEvent, bool isPreImeEvent)
4901 {
4902     NotifySystemSessionKeyEventFunc systemSessionKeyEventFunc = nullptr;
4903     {
4904         std::shared_lock<std::shared_mutex> lock(keyEventMutex_);
4905         systemSessionKeyEventFunc = systemSessionKeyEventFunc_;
4906     }
4907     if (systemSessionKeyEventFunc != nullptr) {
4908         return systemSessionKeyEventFunc(keyEvent, isPreImeEvent);
4909     } else {
4910         TLOGE(WmsLogTag::WMS_EVENT, "id:%{public}d systemSessionKeyEventFunc_ is null", keyEvent->GetId());
4911         keyEvent->MarkProcessed();
4912     }
4913     return false;
4914 }
4915 
UpdateSizeChangeReason(SizeChangeReason reason)4916 WSError SceneSession::UpdateSizeChangeReason(SizeChangeReason reason)
4917 {
4918     auto task = [weakThis = wptr(this), reason]() {
4919         auto session = weakThis.promote();
4920         if (!session) {
4921             WLOGFE("session is null");
4922             return WSError::WS_ERROR_DESTROYED_OBJECT;
4923         }
4924         session->reason_ = reason;
4925         if (reason != SizeChangeReason::UNDEFINED) {
4926             HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER,
4927                 "SceneSession::UpdateSizeChangeReason%d reason:%d",
4928                 session->GetPersistentId(), static_cast<uint32_t>(reason));
4929             TLOGD(WmsLogTag::WMS_LAYOUT, "UpdateSizeChangeReason Id: %{public}d, reason: %{public}d",
4930                 session->GetPersistentId(), reason);
4931         }
4932         return WSError::WS_OK;
4933     };
4934     PostTask(task, "UpdateSizeChangeReason");
4935     return WSError::WS_OK;
4936 }
4937 
ResetSizeChangeReasonIfDirty()4938 void SceneSession::ResetSizeChangeReasonIfDirty()
4939 {
4940     if (IsDirtyWindow() && GetSizeChangeReason() != SizeChangeReason::DRAG) {
4941         UpdateSizeChangeReason(SizeChangeReason::UNDEFINED);
4942     }
4943 }
4944 
IsDirtyWindow()4945 bool SceneSession::IsDirtyWindow()
4946 {
4947     return dirtyFlags_ & static_cast<uint32_t>(SessionUIDirtyFlag::RECT);
4948 }
4949 
NotifyUILostFocus()4950 void SceneSession::NotifyUILostFocus()
4951 {
4952     if (moveDragController_) {
4953         moveDragController_->OnLostFocus();
4954     }
4955     Session::NotifyUILostFocus();
4956 }
4957 
SetScale(float scaleX,float scaleY,float pivotX,float pivotY)4958 void SceneSession::SetScale(float scaleX, float scaleY, float pivotX, float pivotY)
4959 {
4960     if (scaleX_ != scaleX || scaleY_ != scaleY || pivotX_ != pivotX || pivotY_ != pivotY) {
4961         Session::SetScale(scaleX, scaleY, pivotX, pivotY);
4962         if (specificCallback_ != nullptr) {
4963             specificCallback_->onWindowInfoUpdate_(GetPersistentId(), WindowUpdateType::WINDOW_UPDATE_PROPERTY);
4964         }
4965         if (sessionStage_ != nullptr) {
4966             Transform transform;
4967             transform.scaleX_ = scaleX;
4968             transform.scaleY_ = scaleY;
4969             transform.pivotX_ = pivotX;
4970             transform.pivotY_ = pivotY;
4971             sessionStage_->NotifyTransformChange(transform);
4972         } else {
4973             WLOGFE("sessionStage_ is nullptr");
4974         }
4975     }
4976 }
4977 
RequestHideKeyboard(bool isAppColdStart)4978 void SceneSession::RequestHideKeyboard(bool isAppColdStart)
4979 {
4980 #ifdef IMF_ENABLE
4981     auto task = [weakThis = wptr(this), isAppColdStart]() {
4982         auto session = weakThis.promote();
4983         if (!session) {
4984             TLOGE(WmsLogTag::WMS_KEYBOARD, "Session is null, notify inputMethod framework hide keyboard failed!");
4985             return;
4986         }
4987         TLOGI(WmsLogTag::WMS_KEYBOARD, "Notify inputMethod framework hide keyboard start, id: %{public}d,"
4988             "isAppColdStart: %{public}d", session->GetPersistentId(), isAppColdStart);
4989         if (MiscServices::InputMethodController::GetInstance()) {
4990             MiscServices::InputMethodController::GetInstance()->RequestHideInput();
4991             TLOGI(WmsLogTag::WMS_KEYBOARD, "Notify inputMethod framework hide keyboard end, id: %{public}d",
4992                 session->GetPersistentId());
4993         }
4994     };
4995     PostExportTask(task, "RequestHideKeyboard");
4996 #endif
4997 }
4998 
IsStartMoving()4999 bool SceneSession::IsStartMoving()
5000 {
5001     return isStartMoving_.load();
5002 }
5003 
SetIsStartMoving(bool startMoving)5004 void SceneSession::SetIsStartMoving(bool startMoving)
5005 {
5006     isStartMoving_.store(startMoving);
5007 }
5008 
SetShouldHideNonSecureWindows(bool shouldHide)5009 void SceneSession::SetShouldHideNonSecureWindows(bool shouldHide)
5010 {
5011     shouldHideNonSecureWindows_.store(shouldHide);
5012 }
5013 
CalculateCombinedExtWindowFlags()5014 void SceneSession::CalculateCombinedExtWindowFlags()
5015 {
5016     // Only correct when each flag is true when active, and once a uiextension is active, the host is active
5017     std::unique_lock<std::shared_mutex> lock(combinedExtWindowFlagsMutex_);
5018     combinedExtWindowFlags_.bitData = 0;
5019     for (const auto& iter: extWindowFlagsMap_) {
5020         combinedExtWindowFlags_.bitData |= iter.second.bitData;
5021     }
5022 }
5023 
UpdateExtWindowFlags(int32_t extPersistentId,const ExtensionWindowFlags & extWindowFlags,const ExtensionWindowFlags & extWindowActions)5024 void SceneSession::UpdateExtWindowFlags(int32_t extPersistentId, const ExtensionWindowFlags& extWindowFlags,
5025     const ExtensionWindowFlags& extWindowActions)
5026 {
5027     auto iter = extWindowFlagsMap_.find(extPersistentId);
5028     // Each flag is false when inactive, 0 means all flags are inactive
5029     auto oldFlags = iter != extWindowFlagsMap_.end() ? iter->second : ExtensionWindowFlags();
5030     ExtensionWindowFlags newFlags((extWindowFlags.bitData & extWindowActions.bitData) |
5031         (oldFlags.bitData & ~extWindowActions.bitData));
5032     if (newFlags.bitData == 0) {
5033         extWindowFlagsMap_.erase(extPersistentId);
5034     } else {
5035         extWindowFlagsMap_[extPersistentId] = newFlags;
5036     }
5037     CalculateCombinedExtWindowFlags();
5038 }
5039 
GetCombinedExtWindowFlags()5040 ExtensionWindowFlags SceneSession::GetCombinedExtWindowFlags()
5041 {
5042     std::shared_lock<std::shared_mutex> lock(combinedExtWindowFlagsMutex_);
5043     auto combinedExtWindowFlags = combinedExtWindowFlags_;
5044     combinedExtWindowFlags.hideNonSecureWindowsFlag = IsSessionForeground() &&
5045         (combinedExtWindowFlags.hideNonSecureWindowsFlag || shouldHideNonSecureWindows_.load());
5046     return combinedExtWindowFlags;
5047 }
5048 
NotifyDisplayMove(DisplayId from,DisplayId to)5049 void SceneSession::NotifyDisplayMove(DisplayId from, DisplayId to)
5050 {
5051     if (sessionStage_) {
5052         sessionStage_->NotifyDisplayMove(from, to);
5053     } else {
5054         WLOGFE("Notify display move failed, sessionStage is null");
5055     }
5056 }
5057 
RemoveExtWindowFlags(int32_t extPersistentId)5058 void SceneSession::RemoveExtWindowFlags(int32_t extPersistentId)
5059 {
5060     extWindowFlagsMap_.erase(extPersistentId);
5061     CalculateCombinedExtWindowFlags();
5062 }
5063 
ClearExtWindowFlags()5064 void SceneSession::ClearExtWindowFlags()
5065 {
5066     std::unique_lock<std::shared_mutex> lock(combinedExtWindowFlagsMutex_);
5067     extWindowFlagsMap_.clear();
5068     combinedExtWindowFlags_.bitData = 0;
5069 }
5070 
UpdateRectChangeListenerRegistered(bool isRegister)5071 WSError SceneSession::UpdateRectChangeListenerRegistered(bool isRegister)
5072 {
5073     auto task = [weakThis = wptr(this), isRegister]() {
5074         auto session = weakThis.promote();
5075         if (!session) {
5076             TLOGE(WmsLogTag::WMS_LAYOUT, "session is null");
5077             return WSError::WS_ERROR_DESTROYED_OBJECT;
5078         }
5079         session->rectChangeListenerRegistered_ = isRegister;
5080         return WSError::WS_OK;
5081     };
5082     PostTask(task, "UpdateRectChangeListenerRegistered");
5083     return WSError::WS_OK;
5084 }
5085 
SetIsLayoutFullScreen(bool isLayoutFullScreen)5086 void SceneSession::SetIsLayoutFullScreen(bool isLayoutFullScreen)
5087 {
5088     isLayoutFullScreen_ = isLayoutFullScreen;
5089 }
5090 
IsLayoutFullScreen() const5091 bool SceneSession::IsLayoutFullScreen() const
5092 {
5093     return isLayoutFullScreen_;
5094 }
5095 
OnLayoutFullScreenChange(bool isLayoutFullScreen)5096 WSError SceneSession::OnLayoutFullScreenChange(bool isLayoutFullScreen)
5097 {
5098     auto task = [weakThis = wptr(this), isLayoutFullScreen]() {
5099         auto session = weakThis.promote();
5100         if (!session) {
5101             TLOGE(WmsLogTag::WMS_LAYOUT, "session is null");
5102             return WSError::WS_ERROR_DESTROYED_OBJECT;
5103         }
5104         TLOGI(WmsLogTag::WMS_LAYOUT, "isLayoutFullScreen: %{public}d", isLayoutFullScreen);
5105         if (session->onLayoutFullScreenChangeFunc_) {
5106             session->SetIsLayoutFullScreen(isLayoutFullScreen);
5107             session->onLayoutFullScreenChangeFunc_(isLayoutFullScreen);
5108         }
5109         return WSError::WS_OK;
5110     };
5111     PostTask(task, "OnLayoutFullScreenChange");
5112     return WSError::WS_OK;
5113 }
5114 
OnDefaultDensityEnabled(bool isDefaultDensityEnabled)5115 WSError SceneSession::OnDefaultDensityEnabled(bool isDefaultDensityEnabled)
5116 {
5117     auto task = [weakThis = wptr(this), isDefaultDensityEnabled] {
5118         auto session = weakThis.promote();
5119         if (!session) {
5120             TLOGNE(WmsLogTag::WMS_LAYOUT, "OnDefaultDensityEnabled session is null");
5121             return;
5122         }
5123         TLOGNI(WmsLogTag::WMS_LAYOUT, "OnDefaultDensityEnabled, isDefaultDensityEnabled: %{public}d",
5124             isDefaultDensityEnabled);
5125         if (session->onDefaultDensityEnabledFunc_) {
5126             session->onDefaultDensityEnabledFunc_(isDefaultDensityEnabled);
5127         }
5128     };
5129     PostTask(task, "OnDefaultDensityEnabled");
5130     return WSError::WS_OK;
5131 }
5132 
SetForceHideState(ForceHideState forceHideState)5133 void SceneSession::SetForceHideState(ForceHideState forceHideState)
5134 {
5135     forceHideState_ = forceHideState;
5136 }
5137 
GetForceHideState() const5138 ForceHideState SceneSession::GetForceHideState() const
5139 {
5140     return forceHideState_;
5141 }
5142 
SetIsDisplayStatusBarTemporarily(bool isTemporary)5143 void SceneSession::SetIsDisplayStatusBarTemporarily(bool isTemporary)
5144 {
5145     isDisplayStatusBarTemporarily_.store(isTemporary);
5146 }
5147 
GetIsDisplayStatusBarTemporarily() const5148 bool SceneSession::GetIsDisplayStatusBarTemporarily() const
5149 {
5150     return isDisplayStatusBarTemporarily_.load();
5151 }
5152 
RetrieveStatusBarDefaultVisibility()5153 void SceneSession::RetrieveStatusBarDefaultVisibility()
5154 {
5155     if (specificCallback_ && specificCallback_->onGetStatusBarDefaultVisibilityByDisplayId_) {
5156         isStatusBarVisible_ = specificCallback_->onGetStatusBarDefaultVisibilityByDisplayId_(
5157             GetSessionProperty()->GetDisplayId());
5158     }
5159 }
5160 
IsDeviceWakeupByApplication() const5161 bool SceneSession::IsDeviceWakeupByApplication() const
5162 {
5163     return isDeviceWakeupByApplication_.load();
5164 }
5165 
SetIsLastFrameLayoutFinishedFunc(IsLastFrameLayoutFinishedFunc && func)5166 void SceneSession::SetIsLastFrameLayoutFinishedFunc(IsLastFrameLayoutFinishedFunc&& func)
5167 {
5168     isLastFrameLayoutFinishedFunc_ = std::move(func);
5169 }
5170 
SetIsAINavigationBarAvoidAreaValidFunc(IsAINavigationBarAvoidAreaValidFunc && func)5171 void SceneSession::SetIsAINavigationBarAvoidAreaValidFunc(IsAINavigationBarAvoidAreaValidFunc&& func)
5172 {
5173     isAINavigationBarAvoidAreaValid_ = std::move(func);
5174 }
5175 
SetStartingWindowExitAnimationFlag(bool enable)5176 void SceneSession::SetStartingWindowExitAnimationFlag(bool enable)
5177 {
5178     TLOGI(WmsLogTag::DEFAULT, "SetStartingWindowExitAnimationFlag %{public}d", enable);
5179     needStartingWindowExitAnimation_.store(enable);
5180 }
5181 
NeedStartingWindowExitAnimation() const5182 bool SceneSession::NeedStartingWindowExitAnimation() const
5183 {
5184     return needStartingWindowExitAnimation_.load();
5185 }
5186 
IsSystemSpecificSession() const5187 bool SceneSession::IsSystemSpecificSession() const
5188 {
5189     return isSystemSpecificSession_;
5190 }
5191 
SetIsSystemSpecificSession(bool isSystemSpecificSession)5192 void SceneSession::SetIsSystemSpecificSession(bool isSystemSpecificSession)
5193 {
5194     isSystemSpecificSession_ = isSystemSpecificSession;
5195 }
5196 
SetTemporarilyShowWhenLocked(bool isTemporarilyShowWhenLocked)5197 void SceneSession::SetTemporarilyShowWhenLocked(bool isTemporarilyShowWhenLocked)
5198 {
5199     if (isTemporarilyShowWhenLocked_.load() == isTemporarilyShowWhenLocked) {
5200         return;
5201     }
5202     isTemporarilyShowWhenLocked_.store(isTemporarilyShowWhenLocked);
5203     TLOGI(WmsLogTag::WMS_SCB, "SetTemporarilyShowWhenLocked successfully, target:%{public}u",
5204         isTemporarilyShowWhenLocked);
5205 }
5206 
IsTemporarilyShowWhenLocked() const5207 bool SceneSession::IsTemporarilyShowWhenLocked() const
5208 {
5209     return isTemporarilyShowWhenLocked_.load();
5210 }
5211 
SetSkipDraw(bool skip)5212 void SceneSession::SetSkipDraw(bool skip)
5213 {
5214     auto surfaceNode = GetSurfaceNode();
5215     if (!surfaceNode) {
5216         WLOGFE("surfaceNode_ is null");
5217         return;
5218     }
5219     auto rsTransaction = RSTransactionProxy::GetInstance();
5220     if (rsTransaction != nullptr) {
5221         rsTransaction->Begin();
5222     }
5223     surfaceNode->SetSkipDraw(skip);
5224     if (auto leashWinSurfaceNode = GetLeashWinSurfaceNode()) {
5225         leashWinSurfaceNode->SetSkipDraw(skip);
5226     }
5227     if (rsTransaction != nullptr) {
5228         rsTransaction->Commit();
5229     }
5230 }
5231 
SetSkipSelfWhenShowOnVirtualScreen(bool isSkip)5232 void SceneSession::SetSkipSelfWhenShowOnVirtualScreen(bool isSkip)
5233 {
5234     TLOGW(WmsLogTag::WMS_SCB, "in sceneSession, do nothing");
5235     return;
5236 }
5237 
SetUniqueDensityDpi(bool useUnique,float dpi)5238 WMError SceneSession::SetUniqueDensityDpi(bool useUnique, float dpi)
5239 {
5240     TLOGI(WmsLogTag::DEFAULT, "SceneSession set unique dpi: id = %{public}d, dpi = %{public}f",
5241         GetPersistentId(), dpi);
5242     if (useUnique && (dpi > DOT_PER_INCH_MAXIMUM_VALUE || dpi < DOT_PER_INCH_MINIMUM_VALUE)) {
5243         TLOGE(WmsLogTag::DEFAULT, "Invalid input dpi value, valid input range for DPI is %{public}u ~ %{public}u",
5244             DOT_PER_INCH_MINIMUM_VALUE, DOT_PER_INCH_MAXIMUM_VALUE);
5245         return WMError::WM_ERROR_INVALID_PARAM;
5246     }
5247     float density = static_cast<float>(dpi) / 160; // 160 is the coefficient between density and dpi;
5248     if (!IsSessionValid()) {
5249         return WMError::WM_ERROR_INVALID_SESSION;
5250     }
5251     if (!sessionStage_) {
5252         TLOGE(WmsLogTag::DEFAULT, "sessionStage_ is nullptr");
5253         return WMError::WM_ERROR_NULLPTR;
5254     }
5255     sessionStage_->SetUniqueVirtualPixelRatio(useUnique, density);
5256     return WMError::WM_OK;
5257 }
5258 
SetSystemWindowEnableDrag(bool enableDrag)5259 WMError SceneSession::SetSystemWindowEnableDrag(bool enableDrag)
5260 {
5261     if (!SessionPermission::IsSystemCalling()) {
5262         TLOGE(WmsLogTag::WMS_LAYOUT, "id:%{public}d, permission denied!", GetPersistentId());
5263         return WMError::WM_ERROR_NOT_SYSTEM_APP;
5264     }
5265 
5266     if (!WindowHelper::IsSystemWindow(GetWindowType())) {
5267         TLOGE(WmsLogTag::WMS_LAYOUT, "id:%{public}d, this is not system window", GetPersistentId());
5268         return WMError::WM_ERROR_INVALID_CALLING;
5269     }
5270 
5271     const char* const funcName = __func__;
5272     PostTask([weakThis = wptr(this), enableDrag, funcName] {
5273         auto session = weakThis.promote();
5274         if (!session) {
5275             TLOGNE(WmsLogTag::WMS_LAYOUT, "%{public}s: session is null", funcName);
5276             return;
5277         }
5278         TLOGNI(WmsLogTag::WMS_LAYOUT, "%{public}s: id:%{public}d, enableDrag:%{public}d",
5279             funcName, session->GetPersistentId(), enableDrag);
5280         session->GetSessionProperty()->SetDragEnabled(enableDrag);
5281         session->NotifySessionInfoChange();
5282     }, funcName);
5283     return WMError::WM_OK;
5284 }
5285 
ActivateDragBySystem(bool activateDrag)5286 WMError SceneSession::ActivateDragBySystem(bool activateDrag)
5287 {
5288     PostTask([weakThis = wptr(this), activateDrag, where = __func__] {
5289         auto session = weakThis.promote();
5290         if (!session) {
5291             TLOGNE(WmsLogTag::WMS_LAYOUT, "%{public}s session is null", where);
5292             return;
5293         }
5294         session->SetDragActivated(activateDrag);
5295         session->NotifySessionInfoChange();
5296         TLOGNI(WmsLogTag::WMS_LAYOUT, "%{public}s id: %{public}d, activate drag: %{public}d",
5297             where, session->GetPersistentId(), activateDrag);
5298         if (session->sessionStage_) {
5299             session->sessionStage_->SetDragActivated(activateDrag);
5300         }
5301     }, __func__);
5302     return WMError::WM_OK;
5303 }
5304 
HandleActionUpdateWindowModeSupportType(const sptr<WindowSessionProperty> & property,const sptr<SceneSession> & sceneSession,WSPropertyChangeAction action)5305 WMError SceneSession::HandleActionUpdateWindowModeSupportType(const sptr<WindowSessionProperty>& property,
5306     const sptr<SceneSession>& sceneSession, WSPropertyChangeAction action)
5307 {
5308     if (!property->GetSystemCalling()) {
5309         TLOGE(WmsLogTag::DEFAULT, "permission denied!");
5310         return WMError::WM_ERROR_NOT_SYSTEM_APP;
5311     }
5312 
5313     auto sessionProperty = sceneSession->GetSessionProperty();
5314     if (sessionProperty != nullptr) {
5315         sessionProperty->SetWindowModeSupportType(property->GetWindowModeSupportType());
5316     }
5317     return WMError::WM_OK;
5318 }
5319 
RegisterForceSplitListener(const NotifyForceSplitFunc & func)5320 void SceneSession::RegisterForceSplitListener(const NotifyForceSplitFunc& func)
5321 {
5322     forceSplitFunc_ = func;
5323 }
5324 
RegisterRequestedOrientationChangeCallback(NotifyReqOrientationChangeFunc && callback)5325 void SceneSession::RegisterRequestedOrientationChangeCallback(NotifyReqOrientationChangeFunc&& callback)
5326 {
5327     auto task = [weakThis = wptr(this), callback = std::move(callback)] {
5328         auto session = weakThis.promote();
5329         if (!session) {
5330             TLOGNE(WmsLogTag::WMS_LIFE, "session is null");
5331             return;
5332         }
5333         session->onRequestedOrientationChange_ = std::move(callback);
5334     };
5335     PostTask(task, __func__);
5336 }
5337 
RegisterIsCustomAnimationPlayingCallback(NotifyIsCustomAnimationPlayingCallback && callback)5338 void SceneSession::RegisterIsCustomAnimationPlayingCallback(NotifyIsCustomAnimationPlayingCallback&& callback)
5339 {
5340     auto task = [weakThis = wptr(this), callback = std::move(callback)] {
5341         auto session = weakThis.promote();
5342         if (!session) {
5343             TLOGNE(WmsLogTag::WMS_LIFE, "session is null");
5344             return;
5345         }
5346         session->onIsCustomAnimationPlaying_ = std::move(callback);
5347     };
5348     PostTask(task, __func__);
5349 }
5350 
RegisterLayoutFullScreenChangeCallback(NotifyLayoutFullScreenChangeFunc && callback)5351 void SceneSession::RegisterLayoutFullScreenChangeCallback(NotifyLayoutFullScreenChangeFunc&& callback)
5352 {
5353     auto task = [weakThis = wptr(this), callback = std::move(callback)] {
5354         auto session = weakThis.promote();
5355         if (!session) {
5356             TLOGNE(WmsLogTag::WMS_LAYOUT, "session is null");
5357             return;
5358         }
5359         session->onLayoutFullScreenChangeFunc_ = std::move(callback);
5360     };
5361     PostTask(task, __func__);
5362 }
5363 
GetAppForceLandscapeConfig(AppForceLandscapeConfig & config)5364 WMError SceneSession::GetAppForceLandscapeConfig(AppForceLandscapeConfig& config)
5365 {
5366     if (forceSplitFunc_ == nullptr) {
5367         return WMError::WM_ERROR_NULLPTR;
5368     }
5369     config = forceSplitFunc_(sessionInfo_.bundleName_);
5370     return WMError::WM_OK;
5371 }
5372 
CheckPermissionWithPropertyAnimation(const sptr<WindowSessionProperty> & property) const5373 bool SceneSession::CheckPermissionWithPropertyAnimation(const sptr<WindowSessionProperty>& property) const
5374 {
5375     if (property && property->GetAnimationFlag() == static_cast<uint32_t>(WindowAnimation::CUSTOM)) {
5376         if (!SessionPermission::IsSystemCalling() && !SessionPermission::IsStartByHdcd()) {
5377             TLOGE(WmsLogTag::WMS_LIFE, "Not system app, no permission");
5378             return false;
5379         }
5380     }
5381     return true;
5382 }
5383 
SetNotifyVisibleChangeFunc(const NotifyVisibleChangeFunc & func)5384 void SceneSession::SetNotifyVisibleChangeFunc(const NotifyVisibleChangeFunc& func)
5385 {
5386     notifyVisibleChangeFunc_ = func;
5387 }
5388 
SetUpdatePrivateStateAndNotifyFunc(const UpdatePrivateStateAndNotifyFunc & func)5389 void SceneSession::SetUpdatePrivateStateAndNotifyFunc(const UpdatePrivateStateAndNotifyFunc& func)
5390 {
5391     updatePrivateStateAndNotifyFunc_ = func;
5392 }
5393 
IsPcOrPadEnableActivation() const5394 bool SceneSession::IsPcOrPadEnableActivation() const
5395 {
5396     auto isPC = system::GetParameter("const.product.devicetype", "unknown") == "2in1";
5397     auto property = GetSessionProperty();
5398     bool isPcAppInPad = false;
5399     if (property != nullptr) {
5400         isPcAppInPad = property->GetIsPcAppInPad();
5401     }
5402     return isPC || IsFreeMultiWindowMode() || isPcAppInPad;
5403 }
5404 
UnregisterSessionChangeListeners()5405 void SceneSession::UnregisterSessionChangeListeners()
5406 {
5407     auto task = [weakThis = wptr(this)] {
5408         auto session = weakThis.promote();
5409         if (session == nullptr) {
5410             WLOGFE("UnregisterSessionChangeListeners session is null");
5411             return;
5412         }
5413         if (session->sessionChangeCallback_) {
5414             session->sessionChangeCallback_->onBindDialogTarget_ = nullptr;
5415             session->sessionChangeCallback_->onSessionTopmostChange_ = nullptr;
5416             session->sessionChangeCallback_->onRaiseToTop_ = nullptr;
5417             session->sessionChangeCallback_->OnSessionEvent_ = nullptr;
5418             session->sessionChangeCallback_->onRaiseAboveTarget_ = nullptr;
5419             session->sessionChangeCallback_->onSetLandscapeMultiWindowFunc_ = nullptr;
5420         }
5421         session->Session::UnregisterSessionChangeListeners();
5422     };
5423     PostTask(task, "UnregisterSessionChangeListeners");
5424 }
5425 
UpdateUIParam(const SessionUIParam & uiParam)5426 uint32_t SceneSession::UpdateUIParam(const SessionUIParam& uiParam)
5427 {
5428     bool lastVisible = IsVisible();
5429     dirtyFlags_ |= UpdateInteractiveInner(uiParam.interactive_) ?
5430         static_cast<uint32_t>(SessionUIDirtyFlag::INTERACTIVE) : 0;
5431     if (!uiParam.interactive_) {
5432         // keep ui state in recent
5433         return dirtyFlags_;
5434     }
5435     dirtyFlags_ |= UpdateVisibilityInner(true) ? static_cast<uint32_t>(SessionUIDirtyFlag::VISIBLE) : 0;
5436 
5437     dirtyFlags_ |= UpdateRectInner(uiParam, reason_) ?
5438         static_cast<uint32_t>(SessionUIDirtyFlag::RECT) : 0;
5439     dirtyFlags_ |= UpdateScaleInner(uiParam.scaleX_, uiParam.scaleY_, uiParam.pivotX_, uiParam.pivotY_) ?
5440         static_cast<uint32_t>(SessionUIDirtyFlag::SCALE) : 0;
5441     dirtyFlags_ |= UpdateZOrderInner(uiParam.zOrder_) ? static_cast<uint32_t>(SessionUIDirtyFlag::Z_ORDER) : 0;
5442     if (!lastVisible && IsVisible() && !isFocused_ && !postProcessFocusState_.enabled_ &&
5443         GetForegroundInteractiveStatus()) {
5444         postProcessFocusState_.enabled_ = true;
5445         postProcessFocusState_.isFocused_ = true;
5446         postProcessFocusState_.reason_ = isStarting_ ?
5447             FocusChangeReason::SCB_START_APP : FocusChangeReason::FOREGROUND;
5448     }
5449     return dirtyFlags_;
5450 }
5451 
UpdateUIParam()5452 uint32_t SceneSession::UpdateUIParam()
5453 {
5454     bool lastVisible = IsVisible();
5455     dirtyFlags_ |= UpdateVisibilityInner(false) ? static_cast<uint32_t>(SessionUIDirtyFlag::VISIBLE) : 0;
5456     if (lastVisible && !IsVisible() && isFocused_) {
5457         postProcessFocusState_.enabled_ = true;
5458         postProcessFocusState_.isFocused_ = false;
5459         postProcessFocusState_.reason_ = FocusChangeReason::BACKGROUND;
5460     }
5461     return dirtyFlags_;
5462 }
5463 
UpdateVisibilityInner(bool visibility)5464 bool SceneSession::UpdateVisibilityInner(bool visibility)
5465 {
5466     if (isVisible_ == visibility) {
5467         return false;
5468     }
5469     TLOGI(WmsLogTag::WMS_PIPELINE, "id: %{public}d, visibility: %{public}u -> %{public}u",
5470         GetPersistentId(), isVisible_, visibility);
5471     isVisible_ = visibility;
5472     if (updatePrivateStateAndNotifyFunc_ != nullptr) {
5473         updatePrivateStateAndNotifyFunc_(GetPersistentId());
5474     }
5475     if (notifyVisibleChangeFunc_ != nullptr) {
5476         notifyVisibleChangeFunc_(GetPersistentId());
5477     }
5478     return true;
5479 }
5480 
UpdateInteractiveInner(bool interactive)5481 bool SceneSession::UpdateInteractiveInner(bool interactive)
5482 {
5483     if (GetForegroundInteractiveStatus() == interactive) {
5484         return false;
5485     }
5486     SetForegroundInteractiveStatus(interactive);
5487     NotifyClientToUpdateInteractive(interactive);
5488     return true;
5489 }
5490 
PipelineNeedNotifyClientToUpdateRect() const5491 bool SceneSession::PipelineNeedNotifyClientToUpdateRect() const
5492 {
5493     return IsVisibleForeground() && GetForegroundInteractiveStatus();
5494 }
5495 
UpdateRectInner(const SessionUIParam & uiParam,SizeChangeReason reason)5496 bool SceneSession::UpdateRectInner(const SessionUIParam& uiParam, SizeChangeReason reason)
5497 {
5498     if (!((NotifyServerToUpdateRect(uiParam, reason) || IsDirtyWindow()) && PipelineNeedNotifyClientToUpdateRect())) {
5499         return false;
5500     }
5501     std::shared_ptr<RSTransaction> rsTransaction = nullptr;
5502     auto transactionController = RSSyncTransactionController::GetInstance();
5503     if (transactionController) {
5504         rsTransaction = transactionController->GetRSTransaction();
5505     }
5506     NotifyClientToUpdateRect("WMSPipeline", rsTransaction);
5507     return true;
5508 }
5509 
NotifyServerToUpdateRect(const SessionUIParam & uiParam,SizeChangeReason reason)5510 bool SceneSession::NotifyServerToUpdateRect(const SessionUIParam& uiParam, SizeChangeReason reason)
5511 {
5512     if (!GetForegroundInteractiveStatus()) {
5513         TLOGD(WmsLogTag::WMS_PIPELINE, "skip recent, id:%{public}d", GetPersistentId());
5514         return false;
5515     }
5516     if (uiParam.rect_.IsInvalid()) {
5517         TLOGE(WmsLogTag::WMS_PIPELINE, "id:%{public}d rect:%{public}s is invalid",
5518             GetPersistentId(), uiParam.rect_.ToString().c_str());
5519         return false;
5520     }
5521     auto globalRect = GetSessionGlobalRect();
5522     if (globalRect != uiParam.rect_) {
5523         UpdateAllModalUIExtensions(uiParam.rect_);
5524     }
5525     SetSessionGlobalRect(uiParam.rect_);
5526     if (!uiParam.needSync_ || !isNeedSyncSessionRect_) {
5527         TLOGI(WmsLogTag::WMS_LAYOUT, "id:%{public}d, scenePanelNeedSync:%{public}u needSyncSessionRect:%{public}u "
5528             "rectAfter:%{public}s preRect:%{public}s preGlobalRect:%{public}s", GetPersistentId(), uiParam.needSync_,
5529             isNeedSyncSessionRect_, uiParam.rect_.ToString().c_str(), winRect_.ToString().c_str(),
5530             globalRect.ToString().c_str());
5531         return false;
5532     }
5533     WSRect rect = { uiParam.rect_.posX_ - uiParam.transX_, uiParam.rect_.posY_ - uiParam.transY_,
5534         uiParam.rect_.width_, uiParam.rect_.height_ };
5535     if (winRect_ == rect) {
5536         TLOGD(WmsLogTag::WMS_PIPELINE, "skip same rect update id:%{public}d rect:%{public}s preGlobalRect:%{public}s!",
5537             GetPersistentId(), rect.ToString().c_str(), globalRect.ToString().c_str());
5538         return false;
5539     }
5540     if (rect.IsInvalid()) {
5541         TLOGE(WmsLogTag::WMS_PIPELINE, "id:%{public}d rect:%{public}s is invalid, preGlobalRect:%{public}s",
5542             GetPersistentId(), rect.ToString().c_str(), globalRect.ToString().c_str());
5543         return false;
5544     }
5545     TLOGI(WmsLogTag::WMS_LAYOUT, "id:%{public}d, updateRect rectAfter:%{public}s preRect:%{public}s "
5546         "preGlobalRect:%{public}s", GetPersistentId(), rect.ToString().c_str(),
5547         winRect_.ToString().c_str(), globalRect.ToString().c_str());
5548     winRect_ = rect;
5549     RectCheckProcess();
5550     return true;
5551 }
5552 
PostProcessNotifyAvoidArea()5553 void SceneSession::PostProcessNotifyAvoidArea()
5554 {
5555     if (PipelineNeedNotifyClientToUpdateAvoidArea(dirtyFlags_)) {
5556         NotifyClientToUpdateAvoidArea();
5557     }
5558 }
5559 
PipelineNeedNotifyClientToUpdateAvoidArea(uint32_t dirty) const5560 bool SceneSession::PipelineNeedNotifyClientToUpdateAvoidArea(uint32_t dirty) const
5561 {
5562     return ((dirty & static_cast<uint32_t>(SessionUIDirtyFlag::VISIBLE)) && IsImmersiveType()) ||
5563         ((dirty & static_cast<uint32_t>(SessionUIDirtyFlag::AVOID_AREA)) && isVisible_);
5564 }
5565 
NotifyClientToUpdateAvoidArea()5566 void SceneSession::NotifyClientToUpdateAvoidArea()
5567 {
5568     if (specificCallback_ == nullptr) {
5569         return;
5570     }
5571     // flush avoid areas on (avoid area dirty && (normal session rect NOT dirty || avoid session))
5572     if ((IsImmersiveType() || !IsDirtyWindow()) && specificCallback_->onUpdateAvoidArea_) {
5573         specificCallback_->onUpdateAvoidArea_(GetPersistentId());
5574     }
5575     if (specificCallback_->onUpdateOccupiedAreaIfNeed_) {
5576         specificCallback_->onUpdateOccupiedAreaIfNeed_(GetPersistentId());
5577     }
5578 }
5579 
IsTransformNeedChange(float scaleX,float scaleY,float pivotX,float pivotY)5580 bool SceneSession::IsTransformNeedChange(float scaleX, float scaleY, float pivotX, float pivotY)
5581 {
5582     bool nearEqual = NearEqual(scaleX_, scaleX) && NearEqual(scaleY_, scaleY) &&
5583         NearEqual(pivotX_, pivotX) && NearEqual(pivotY_, pivotY) &&
5584         NearEqual(clientScaleX_, scaleX) && NearEqual(clientScaleY_, scaleY) &&
5585         NearEqual(clientPivotX_, pivotX) && NearEqual(clientPivotY_, pivotY);
5586     return !nearEqual;
5587 }
5588 
UpdateScaleInner(float scaleX,float scaleY,float pivotX,float pivotY)5589 bool SceneSession::UpdateScaleInner(float scaleX, float scaleY, float pivotX, float pivotY)
5590 {
5591     if (!IsTransformNeedChange(scaleX, scaleY, pivotX, pivotY)) {
5592         return false;
5593     }
5594     Session::SetScale(scaleX, scaleY, pivotX, pivotY);
5595     if (!IsSessionForeground()) {
5596         TLOGD(WmsLogTag::WMS_LAYOUT, "id:%{public}d, session is not foreground!", GetPersistentId());
5597         return false;
5598     }
5599     if (sessionStage_ != nullptr) {
5600         Transform transform;
5601         transform.scaleX_ = scaleX;
5602         transform.scaleY_ = scaleY;
5603         transform.pivotX_ = pivotX;
5604         transform.pivotY_ = pivotY;
5605         sessionStage_->NotifyTransformChange(transform);
5606         Session::SetClientScale(scaleX, scaleY, pivotX, pivotY);
5607     } else {
5608         WLOGFE("sessionStage is nullptr");
5609     }
5610     return true;
5611 }
5612 
UpdateZOrderInner(uint32_t zOrder)5613 bool SceneSession::UpdateZOrderInner(uint32_t zOrder)
5614 {
5615     if (zOrder_ == zOrder) {
5616         return false;
5617     }
5618     TLOGI(WmsLogTag::WMS_PIPELINE, "id: %{public}d, zOrder: %{public}u -> %{public}u, lastZOrder: %{public}u",
5619           GetPersistentId(), zOrder_, zOrder, lastZOrder_);
5620     lastZOrder_ = zOrder_;
5621     zOrder_ = zOrder;
5622     return true;
5623 }
5624 
SetPostProcessFocusState(PostProcessFocusState state)5625 void SceneSession::SetPostProcessFocusState(PostProcessFocusState state)
5626 {
5627     postProcessFocusState_ = state;
5628 }
5629 
GetPostProcessFocusState() const5630 PostProcessFocusState SceneSession::GetPostProcessFocusState() const
5631 {
5632     return postProcessFocusState_;
5633 }
5634 
ResetPostProcessFocusState()5635 void SceneSession::ResetPostProcessFocusState()
5636 {
5637     postProcessFocusState_.Reset();
5638 }
5639 
SetPostProcessProperty(bool state)5640 void SceneSession::SetPostProcessProperty(bool state)
5641 {
5642     postProcessProperty_ = state;
5643 }
5644 
GetPostProcessProperty() const5645 bool SceneSession::GetPostProcessProperty() const
5646 {
5647     return postProcessProperty_;
5648 }
5649 
IsImmersiveType() const5650 bool SceneSession::IsImmersiveType() const
5651 {
5652     WindowType type = GetWindowType();
5653     return type == WindowType::WINDOW_TYPE_STATUS_BAR ||
5654         type == WindowType::WINDOW_TYPE_NAVIGATION_BAR ||
5655         type == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT;
5656 }
5657 
SetDefaultDisplayIdIfNeed()5658 void SceneSession::SetDefaultDisplayIdIfNeed()
5659 {
5660     if (sessionInfo_.screenId_ == SCREEN_ID_INVALID) {
5661         auto defaultDisplayId = ScreenSessionManagerClient::GetInstance().GetDefaultScreenId();
5662         sessionInfo_.screenId_ = defaultDisplayId;
5663         TLOGI(WmsLogTag::WMS_LIFE, "winId: %{public}d, update screen id %{public}" PRIu64,
5664             GetPersistentId(), defaultDisplayId);
5665         auto sessionProperty = GetSessionProperty();
5666         if (sessionProperty) {
5667             sessionProperty->SetDisplayId(defaultDisplayId);
5668         }
5669     }
5670 }
5671 
UpdateGestureBackEnabled()5672 void SceneSession::UpdateGestureBackEnabled()
5673 {
5674     if (specificCallback_ != nullptr &&
5675         specificCallback_->onUpdateGestureBackEnabled_ != nullptr) {
5676         specificCallback_->onUpdateGestureBackEnabled_(GetPersistentId());
5677     }
5678 }
5679 
CheckIdentityTokenIfMatched(const std::string & identityToken)5680 bool SceneSession::CheckIdentityTokenIfMatched(const std::string& identityToken)
5681 {
5682     if (!identityToken.empty() && !clientIdentityToken_.empty() && identityToken != clientIdentityToken_) {
5683         TLOGW(WmsLogTag::WMS_LIFE,
5684             "failed, clientIdentityToken: %{public}s, identityToken: %{public}s, bundleName: %{public}s",
5685             clientIdentityToken_.c_str(), identityToken.c_str(), GetSessionInfo().bundleName_.c_str());
5686         return false;
5687     }
5688     return true;
5689 }
5690 
CheckPidIfMatched()5691 bool SceneSession::CheckPidIfMatched()
5692 {
5693     int32_t callingPid = IPCSkeleton::GetCallingPid();
5694     if (callingPid != -1 && callingPid != GetCallingPid()) {
5695         TLOGW(WmsLogTag::WMS_LIFE,
5696             "failed, callingPid_: %{public}d, callingPid: %{public}d, bundleName: %{public}s",
5697             GetCallingPid(), callingPid, GetSessionInfo().bundleName_.c_str());
5698         return false;
5699     }
5700     return true;
5701 }
5702 
SetNeedSyncSessionRect(bool needSync)5703 void SceneSession::SetNeedSyncSessionRect(bool needSync)
5704 {
5705     auto task = [weakThis = wptr(this), needSync]() -> void {
5706         auto session = weakThis.promote();
5707         if (session == nullptr) {
5708             TLOGNE(WmsLogTag::WMS_PIPELINE, "SetNeedSyncSessionRect session is null");
5709             return;
5710         }
5711         TLOGNI(WmsLogTag::WMS_PIPELINE,
5712             "SetNeedSyncSessionRect: change isNeedSync from %{public}d to %{public}d, id:%{public}d",
5713             session->isNeedSyncSessionRect_, needSync, session->GetPersistentId());
5714         session->isNeedSyncSessionRect_ = needSync;
5715     };
5716     PostTask(task, __func__);
5717 }
5718 
SetWindowRectAutoSaveCallback(NotifySetWindowRectAutoSaveFunc && func)5719 void SceneSession::SetWindowRectAutoSaveCallback(NotifySetWindowRectAutoSaveFunc&& func)
5720 {
5721     const char* const where = __func__;
5722     auto task = [weakThis = wptr(this), where, func = std::move(func)] {
5723         auto session = weakThis.promote();
5724         if (!session || !func) {
5725             TLOGNE(WmsLogTag::WMS_MAIN, "session or onSetWindowRectAutoSaveFunc is null");
5726             return;
5727         }
5728         session->onSetWindowRectAutoSaveFunc_ = std::move(func);
5729         TLOGNI(WmsLogTag::WMS_MAIN, "%{public}s id: %{public}d", where,
5730             session->GetPersistentId());
5731     };
5732     PostTask(task, __func__);
5733 }
5734 
RegisterSupportWindowModesCallback(NotifySetSupportedWindowModesFunc && func)5735 void SceneSession::RegisterSupportWindowModesCallback(NotifySetSupportedWindowModesFunc&& func)
5736 {
5737     const char* const where = __func__;
5738     PostTask([weakThis = wptr(this), func = std::move(func), where] {
5739         auto session = weakThis.promote();
5740         if (!session || !func) {
5741             TLOGNE(WmsLogTag::WMS_LAYOUT_PC, "%{public}s session or func is null", where);
5742             return;
5743         }
5744         session->onSetSupportedWindowModesFunc_ = std::move(func);
5745         TLOGND(WmsLogTag::WMS_LAYOUT_PC, "%{public}s id: %{public}d", where, session->GetPersistentId());
5746     }, __func__);
5747 }
5748 
SetFrameGravity(Gravity gravity)5749 bool SceneSession::SetFrameGravity(Gravity gravity)
5750 {
5751     auto surfaceNode = GetSurfaceNode();
5752     if (surfaceNode == nullptr) {
5753         TLOGW(WmsLogTag::WMS_LAYOUT, "fail id:%{public}d gravity:%{public}d", GetPersistentId(), gravity);
5754         return false;
5755     }
5756     TLOGI(WmsLogTag::WMS_LAYOUT, "id:%{public}d gravity:%{public}d", GetPersistentId(), gravity);
5757     surfaceNode->SetFrameGravity(gravity);
5758     return true;
5759 }
5760 
MarkAvoidAreaAsDirty()5761 void SceneSession::MarkAvoidAreaAsDirty()
5762 {
5763     dirtyFlags_ |= static_cast<uint32_t>(SessionUIDirtyFlag::AVOID_AREA);
5764 }
5765 
SetMousePointerDownEventStatus(bool mousePointerDownEventStatus)5766 void SceneSession::SetMousePointerDownEventStatus(bool mousePointerDownEventStatus)
5767 {
5768     isMousePointerDownEventStatus_ = mousePointerDownEventStatus;
5769 }
5770 
GetMousePointerDownEventStatus() const5771 bool SceneSession::GetMousePointerDownEventStatus() const
5772 {
5773     return isMousePointerDownEventStatus_;
5774 }
5775 
SetFingerPointerDownStatus(int32_t fingerId)5776 void SceneSession::SetFingerPointerDownStatus(int32_t fingerId)
5777 {
5778     if (fingerPointerDownStatusList_.find(fingerId) != fingerPointerDownStatusList_.end()) {
5779         TLOGE(WmsLogTag::WMS_EVENT, "wid:%{public}d fingerId:%{public}d receive twice down event",
5780               GetPersistentId(), fingerId);
5781     } else {
5782         fingerPointerDownStatusList_.insert(fingerId);
5783     }
5784 }
5785 
RemoveFingerPointerDownStatus(int32_t fingerId)5786 void SceneSession::RemoveFingerPointerDownStatus(int32_t fingerId)
5787 {
5788     if (fingerPointerDownStatusList_.find(fingerId) == fingerPointerDownStatusList_.end()) {
5789         TLOGE(WmsLogTag::WMS_EVENT, "wid:%{public}d fingerId:%{public}d receive up without down event",
5790               GetPersistentId(), fingerId);
5791     } else {
5792         fingerPointerDownStatusList_.erase(fingerId);
5793     }
5794 }
5795 
GetFingerPointerDownStatusList() const5796 std::unordered_set<int32_t> SceneSession::GetFingerPointerDownStatusList() const
5797 {
5798     return fingerPointerDownStatusList_;
5799 }
5800 
UpdateAllModalUIExtensions(const WSRect & globalRect)5801 void SceneSession::UpdateAllModalUIExtensions(const WSRect& globalRect)
5802 {
5803     const char* const where = __func__;
5804     PostTask([weakThis = wptr(this), where, globalRect] {
5805         auto session = weakThis.promote();
5806         if (!session) {
5807             TLOGNE(WmsLogTag::WMS_UIEXT, "session is null");
5808             return;
5809         }
5810         auto parentTransX = globalRect.posX_ - session->GetSessionRect().posX_;
5811         auto parentTransY = globalRect.posY_ - session->GetSessionRect().posY_;
5812         {
5813             std::unique_lock<std::shared_mutex> lock(session->modalUIExtensionInfoListMutex_);
5814             for (auto& extensionInfo : session->modalUIExtensionInfoList_) {
5815                 if (!extensionInfo.hasUpdatedRect) {
5816                     continue;
5817                 }
5818                 extensionInfo.windowRect = extensionInfo.uiExtRect;
5819                 extensionInfo.windowRect.posX_ += parentTransX;
5820                 extensionInfo.windowRect.posX_ += parentTransY;
5821             }
5822         }
5823         session->NotifySessionInfoChange();
5824         TLOGNI(WmsLogTag::WMS_UIEXT, "%{public}s: id: %{public}d, globalRect: %{public}s, parentTransX: %{public}d, "
5825             "parentTransY: %{public}d", where, session->GetPersistentId(), globalRect.ToString().c_str(),
5826             parentTransX, parentTransY);
5827     }, __func__);
5828 }
5829 
SetColorSpace(ColorSpace colorSpace)5830 void SceneSession::SetColorSpace(ColorSpace colorSpace)
5831 {
5832     auto surfaceNode = GetSurfaceNode();
5833     if (!surfaceNode) {
5834         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "surfaceNode is invalid");
5835         return;
5836     }
5837     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "SetColorSpace value=%{public}u", colorSpace);
5838     auto colorGamut = GraphicColorGamut::GRAPHIC_COLOR_GAMUT_SRGB;
5839     if (colorSpace == ColorSpace::COLOR_SPACE_WIDE_GAMUT) {
5840         colorGamut = GraphicColorGamut::GRAPHIC_COLOR_GAMUT_DCI_P3;
5841     }
5842     auto rsTransaction = RSTransactionProxy::GetInstance();
5843     if (rsTransaction != nullptr) {
5844         rsTransaction->Begin();
5845         surfaceNode->SetColorSpace(colorGamut);
5846     }
5847     if (rsTransaction != nullptr) {
5848         rsTransaction->Commit();
5849     }
5850 }
5851 
SetHighlightChangeNotifyFunc(const NotifyHighlightChangeFunc & func)5852 void SceneSession::SetHighlightChangeNotifyFunc(const NotifyHighlightChangeFunc& func)
5853 {
5854     std::lock_guard lock(highlightChangeFuncMutex_);
5855     highlightChangeFunc_ = func;
5856 }
5857 } // namespace OHOS::Rosen
5858