• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 "window_impl.h"
17 
18 #include <ability_manager_client.h>
19 #include <common/rs_common_def.h>
20 #include <filesystem>
21 #include <fstream>
22 #include <hisysevent.h>
23 #include <parameters.h>
24 #include <ipc_skeleton.h>
25 #include <transaction/rs_interfaces.h>
26 #include <transaction/rs_transaction.h>
27 #include <ui/rs_node.h>
28 
29 #include "permission.h"
30 #include "color_parser.h"
31 #include "display_manager.h"
32 #include "display_info.h"
33 #include "ressched_report.h"
34 #include "rs_adapter.h"
35 #include "singleton_container.h"
36 #include "surface_capture_future.h"
37 #include "sys_cap_util.h"
38 #include "window_adapter.h"
39 #include "window_agent.h"
40 #include "window_helper.h"
41 #include "window_inspector.h"
42 #include "window_manager_hilog.h"
43 #include "wm_common.h"
44 #include "wm_common_inner.h"
45 #include "wm_math.h"
46 #include "perform_reporter.h"
47 #include "hitrace_meter.h"
48 #include <hisysevent.h>
49 
50 namespace OHOS {
51 namespace Rosen {
52 namespace {
53 constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, HILOG_DOMAIN_WINDOW, "WindowImpl"};
54 const std::string PARAM_DUMP_HELP = "-h";
55 const uint32_t API_VERSION_MOD = 1000;
56 constexpr int32_t API_VERSION_18 = 18;
57 
GetAceContentInfoType(BackupAndRestoreType type)58 Ace::ContentInfoType GetAceContentInfoType(BackupAndRestoreType type)
59 {
60     auto contentInfoType = Ace::ContentInfoType::NONE;
61     switch (type) {
62         case BackupAndRestoreType::CONTINUATION:
63             contentInfoType = Ace::ContentInfoType::CONTINUATION;
64             break;
65         case BackupAndRestoreType::APP_RECOVERY:
66             contentInfoType = Ace::ContentInfoType::APP_RECOVERY;
67             break;
68         case BackupAndRestoreType::RESOURCESCHEDULE_RECOVERY:
69             contentInfoType = Ace::ContentInfoType::RESOURCESCHEDULE_RECOVERY;
70             break;
71         case BackupAndRestoreType::NONE:
72             [[fallthrough]];
73         default:
74             break;
75     }
76     return contentInfoType;
77 }
78 }
79 
80 WM_IMPLEMENT_SINGLE_INSTANCE(ResSchedReport);
81 
82 const WindowImpl::ColorSpaceConvertMap WindowImpl::colorSpaceConvertMap[] = {
83     { ColorSpace::COLOR_SPACE_DEFAULT, GraphicColorGamut::GRAPHIC_COLOR_GAMUT_SRGB },
84     { ColorSpace::COLOR_SPACE_WIDE_GAMUT, GraphicColorGamut::GRAPHIC_COLOR_GAMUT_DCI_P3 },
85 };
86 
87 std::map<std::string, std::pair<uint32_t, sptr<Window>>> WindowImpl::windowMap_;
88 std::map<uint32_t, std::vector<sptr<WindowImpl>>> WindowImpl::subWindowMap_;
89 std::map<uint32_t, std::vector<sptr<WindowImpl>>> WindowImpl::appFloatingWindowMap_;
90 std::map<uint32_t, std::vector<sptr<WindowImpl>>> WindowImpl::appDialogWindowMap_;
91 std::map<uint32_t, std::vector<sptr<IScreenshotListener>>> WindowImpl::screenshotListeners_;
92 std::map<uint32_t, std::vector<sptr<IScreenshotAppEventListener>>> WindowImpl::screenshotAppEventListeners_;
93 std::map<uint32_t, std::vector<sptr<ITouchOutsideListener>>> WindowImpl::touchOutsideListeners_;
94 std::map<uint32_t, std::vector<sptr<IDialogTargetTouchListener>>> WindowImpl::dialogTargetTouchListeners_;
95 std::map<uint32_t, std::vector<sptr<IWindowLifeCycle>>> WindowImpl::lifecycleListeners_;
96 std::map<uint32_t, std::vector<sptr<IWindowChangeListener>>> WindowImpl::windowChangeListeners_;
97 std::map<uint32_t, std::vector<sptr<IAvoidAreaChangedListener>>> WindowImpl::avoidAreaChangeListeners_;
98 std::map<uint32_t, std::vector<sptr<IOccupiedAreaChangeListener>>> WindowImpl::occupiedAreaChangeListeners_;
99 std::map<uint32_t, sptr<IDialogDeathRecipientListener>> WindowImpl::dialogDeathRecipientListener_;
100 std::recursive_mutex WindowImpl::globalMutex_;
101 std::shared_mutex WindowImpl::windowMapMutex_;
102 int g_constructorCnt = 0;
103 int g_deConstructorCnt = 0;
WindowImpl(const sptr<WindowOption> & option)104 WindowImpl::WindowImpl(const sptr<WindowOption>& option)
105 {
106     handler_ = std::make_shared<AppExecFwk::EventHandler>(AppExecFwk::EventRunner::GetMainEventRunner());
107     property_ = sptr<WindowProperty>::MakeSptr();
108     InitWindowProperty(option);
109 
110     windowTag_ = option->GetWindowTag();
111     isMainHandlerAvailable_ = option->GetMainHandlerAvailable();
112     AdjustWindowAnimationFlag();
113     UpdateDecorEnable();
114     auto& sysBarPropMap = option->GetSystemBarProperty();
115     for (auto it : sysBarPropMap) {
116         property_->SetSystemBarProperty(it.first, it.second);
117     }
118     name_ = option->GetWindowName();
119 
120     RSAdapterUtil::InitRSUIDirector(rsUIDirector_, true, true);
121 
122     surfaceNode_ = CreateSurfaceNode(property_->GetWindowName(), option->GetWindowType());
123     if (surfaceNode_ != nullptr) {
124         vsyncStation_ = std::make_shared<VsyncStation>(surfaceNode_->GetId());
125     }
126 
127     moveDragProperty_ = new (std::nothrow) MoveDragProperty();
128     if (moveDragProperty_ == nullptr) {
129         WLOGFE("MoveDragProperty is null");
130     }
131     WLOGFD("g_constructorCnt: %{public}d name: %{public}s",
132         ++g_constructorCnt, property_->GetWindowName().c_str());
133 }
134 
InitWindowProperty(const sptr<WindowOption> & option)135 void WindowImpl::InitWindowProperty(const sptr<WindowOption>& option)
136 {
137     if (option == nullptr) {
138         TLOGE(WmsLogTag::WMS_MAIN, "Init window property failed, option is nullptr.");
139         return;
140     }
141     property_->SetWindowName(option->GetWindowName());
142     property_->SetRequestRect(option->GetWindowRect());
143     property_->SetWindowType(option->GetWindowType());
144     if (WindowHelper::IsAppFloatingWindow(option->GetWindowType())) {
145         property_->SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
146     } else {
147         property_->SetWindowMode(option->GetWindowMode());
148     }
149     property_->SetFullScreen(option->GetWindowMode() == WindowMode::WINDOW_MODE_FULLSCREEN);
150     property_->SetFocusable(option->GetFocusable());
151     property_->SetTouchable(option->GetTouchable());
152     property_->SetDisplayId(option->GetDisplayId());
153     property_->SetCallingWindow(option->GetCallingWindow());
154     property_->SetWindowFlags(option->GetWindowFlags());
155     property_->SetHitOffset(option->GetHitOffset());
156     property_->SetRequestedOrientation(option->GetRequestedOrientation());
157     property_->SetTurnScreenOn(option->IsTurnScreenOn());
158     property_->SetKeepScreenOn(option->IsKeepScreenOn());
159     property_->SetBrightness(option->GetBrightness());
160 }
161 
CreateSurfaceNode(std::string name,WindowType type)162 RSSurfaceNode::SharedPtr WindowImpl::CreateSurfaceNode(std::string name, WindowType type)
163 {
164     struct RSSurfaceNodeConfig rsSurfaceNodeConfig;
165     rsSurfaceNodeConfig.SurfaceNodeName = name;
166     RSSurfaceNodeType rsSurfaceNodeType = RSSurfaceNodeType::DEFAULT;
167     switch (type) {
168         case WindowType::WINDOW_TYPE_BOOT_ANIMATION:
169         case WindowType::WINDOW_TYPE_POINTER:
170             rsSurfaceNodeType = RSSurfaceNodeType::SELF_DRAWING_WINDOW_NODE;
171             break;
172         case WindowType::WINDOW_TYPE_APP_MAIN_WINDOW:
173             rsSurfaceNodeType = RSSurfaceNodeType::APP_WINDOW_NODE;
174             break;
175         case WindowType::WINDOW_TYPE_PIP:
176             rsSurfaceNodeType = RSSurfaceNodeType::APP_WINDOW_NODE;
177             break;
178         default:
179             rsSurfaceNodeType = RSSurfaceNodeType::DEFAULT;
180             break;
181     }
182 
183     if (windowSystemConfig_.IsPhoneWindow() && WindowHelper::IsWindowFollowParent(type)) {
184         rsSurfaceNodeType = RSSurfaceNodeType::ABILITY_COMPONENT_NODE;
185     }
186     auto surfaceNode = RSSurfaceNode::Create(rsSurfaceNodeConfig, rsSurfaceNodeType, true, false, GetRSUIContext());
187     RSAdapterUtil::SetSkipCheckInMultiInstance(surfaceNode, true);
188     TLOGD(WmsLogTag::WMS_SCB,
189           "Create RSSurfaceNode: %{public}s, name: %{public}s",
190           RSAdapterUtil::RSNodeToStr(surfaceNode).c_str(), name.c_str());
191     return surfaceNode;
192 }
193 
~WindowImpl()194 WindowImpl::~WindowImpl()
195 {
196     WLOGI("windowName: %{public}s, windowId: %{public}d, g_deConstructorCnt: %{public}d, surfaceNode:%{public}d",
197         GetWindowName().c_str(), GetWindowId(), ++g_deConstructorCnt, static_cast<uint32_t>(surfaceNode_.use_count()));
198     Destroy(true, false);
199 }
200 
Find(const std::string & name)201 sptr<Window> WindowImpl::Find(const std::string& name)
202 {
203     std::shared_lock<std::shared_mutex> lock(windowMapMutex_);
204     auto iter = windowMap_.find(name);
205     if (iter == windowMap_.end()) {
206         return nullptr;
207     }
208     return iter->second.second;
209 }
210 
GetContext() const211 const std::shared_ptr<AbilityRuntime::Context> WindowImpl::GetContext() const
212 {
213     return context_;
214 }
215 
FindWindowById(uint32_t WinId)216 sptr<Window> WindowImpl::FindWindowById(uint32_t WinId)
217 {
218     std::shared_lock<std::shared_mutex> lock(windowMapMutex_);
219     if (windowMap_.empty()) {
220         WLOGFE("Please create mainWindow First!");
221         return nullptr;
222     }
223     for (auto iter = windowMap_.begin(); iter != windowMap_.end(); iter++) {
224         if (WinId == iter->second.first) {
225             WLOGI("FindWindow id: %{public}u", WinId);
226             return iter->second.second;
227         }
228     }
229     WLOGFE("Cannot find Window!");
230     return nullptr;
231 }
232 
GetTopWindowWithId(uint32_t mainWinId)233 sptr<Window> WindowImpl::GetTopWindowWithId(uint32_t mainWinId)
234 {
235     uint32_t topWinId = INVALID_WINDOW_ID;
236     WMError ret = SingletonContainer::Get<WindowAdapter>().GetTopWindowId(mainWinId, topWinId);
237     if (ret != WMError::WM_OK) {
238         WLOGFE("GetTopWindowId failed with errCode:%{public}d", static_cast<int32_t>(ret));
239         return nullptr;
240     }
241     return FindWindowById(topWinId);
242 }
243 
GetWindowWithId(uint32_t WinId)244 sptr<Window> WindowImpl::GetWindowWithId(uint32_t WinId)
245 {
246     return FindWindowById(WinId);
247 }
248 
GetTopWindowWithContext(const std::shared_ptr<AbilityRuntime::Context> & context)249 sptr<Window> WindowImpl::GetTopWindowWithContext(const std::shared_ptr<AbilityRuntime::Context>& context)
250 {
251     uint32_t mainWinId = INVALID_WINDOW_ID;
252     {
253         std::shared_lock<std::shared_mutex> lock(windowMapMutex_);
254         if (windowMap_.empty()) {
255             WLOGFE("Please create mainWindow First!");
256             return nullptr;
257         }
258         for (auto iter = windowMap_.begin(); iter != windowMap_.end(); iter++) {
259             auto win = iter->second.second;
260             if (context.get() == win->GetContext().get() && WindowHelper::IsMainWindow(win->GetType())) {
261                 mainWinId = win->GetWindowId();
262                 WLOGI("GetTopWindow Find MainWinId:%{public}u.", mainWinId);
263                 break;
264             }
265         }
266     }
267     WLOGI("GetTopWindowfinal winId:%{public}u!", mainWinId);
268     if (mainWinId == INVALID_WINDOW_ID) {
269         WLOGFE("Cannot find topWindow!");
270         return nullptr;
271     }
272     uint32_t topWinId = INVALID_WINDOW_ID;
273     WMError ret = SingletonContainer::Get<WindowAdapter>().GetTopWindowId(mainWinId, topWinId);
274     if (ret != WMError::WM_OK) {
275         WLOGFE("GetTopWindowId failed with errCode:%{public}d", static_cast<int32_t>(ret));
276         return nullptr;
277     }
278     return FindWindowById(topWinId);
279 }
280 
GetSubWindow(uint32_t parentId)281 std::vector<sptr<Window>> WindowImpl::GetSubWindow(uint32_t parentId)
282 {
283     if (subWindowMap_.find(parentId) == subWindowMap_.end()) {
284         WLOGFE("Cannot parentWindow with id: %{public}u!", parentId);
285         return std::vector<sptr<Window>>();
286     }
287     return std::vector<sptr<Window>>(subWindowMap_[parentId].begin(), subWindowMap_[parentId].end());
288 }
289 
UpdateConfigurationForAll(const std::shared_ptr<AppExecFwk::Configuration> & configuration,const std::vector<std::shared_ptr<AbilityRuntime::Context>> & ignoreWindowContexts)290 void WindowImpl::UpdateConfigurationForAll(const std::shared_ptr<AppExecFwk::Configuration>& configuration,
291     const std::vector<std::shared_ptr<AbilityRuntime::Context>>& ignoreWindowContexts)
292 {
293     std::unordered_set<std::shared_ptr<AbilityRuntime::Context>> ignoreWindowCtxSet(
294         ignoreWindowContexts.begin(), ignoreWindowContexts.end());
295     std::shared_lock<std::shared_mutex> lock(windowMapMutex_);
296     TLOGD(WmsLogTag::WMS_ATTRIBUTE, "impl map size: %{public}u", static_cast<uint32_t>(windowMap_.size()));
297     for (const auto& winPair : windowMap_) {
298         auto window = winPair.second.second;
299         if (window == nullptr) {
300             TLOGE(WmsLogTag::WMS_ATTRIBUTE, "impl window is null");
301             continue;
302         }
303         if (ignoreWindowCtxSet.count(window->GetContext()) == 0) {
304             TLOGD(WmsLogTag::WMS_ATTRIBUTE, "impl win=%{public}u, display=%{public}" PRIu64,
305                 window->GetWindowId(), window->GetDisplayId());
306             window->UpdateConfiguration(configuration);
307         } else {
308             TLOGI(WmsLogTag::WMS_ATTRIBUTE, "skip impl win=%{public}u, display=%{public}" PRIu64,
309                 window->GetWindowId(), window->GetDisplayId());
310         }
311     }
312 }
313 
GetSurfaceNode() const314 std::shared_ptr<RSSurfaceNode> WindowImpl::GetSurfaceNode() const
315 {
316     return surfaceNode_;
317 }
318 
GetRect() const319 Rect WindowImpl::GetRect() const
320 {
321     return property_->GetWindowRect();
322 }
323 
GetRequestRect() const324 Rect WindowImpl::GetRequestRect() const
325 {
326     return property_->GetRequestRect();
327 }
328 
GetType() const329 WindowType WindowImpl::GetType() const
330 {
331     return property_->GetWindowType();
332 }
333 
GetWindowMode() const334 WindowMode WindowImpl::GetWindowMode() const
335 {
336     return property_->GetWindowMode();
337 }
338 
GetAlpha() const339 float WindowImpl::GetAlpha() const
340 {
341     return property_->GetAlpha();
342 }
343 
GetWindowState() const344 WindowState WindowImpl::GetWindowState() const
345 {
346     return state_;
347 }
348 
SetFocusable(bool isFocusable)349 WMError WindowImpl::SetFocusable(bool isFocusable)
350 {
351     if (!IsWindowValid()) {
352         return WMError::WM_ERROR_INVALID_WINDOW;
353     }
354     property_->SetFocusable(isFocusable);
355     if (state_ == WindowState::STATE_SHOWN) {
356         return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_FOCUSABLE);
357     }
358     return WMError::WM_OK;
359 }
360 
GetFocusable() const361 bool WindowImpl::GetFocusable() const
362 {
363     return property_->GetFocusable();
364 }
365 
SetTouchable(bool isTouchable)366 WMError WindowImpl::SetTouchable(bool isTouchable)
367 {
368     if (!IsWindowValid()) {
369         return WMError::WM_ERROR_INVALID_WINDOW;
370     }
371     property_->SetTouchable(isTouchable);
372     if (state_ == WindowState::STATE_SHOWN) {
373         return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_TOUCHABLE);
374     }
375     return WMError::WM_OK;
376 }
377 
GetTouchable() const378 bool WindowImpl::GetTouchable() const
379 {
380     return property_->GetTouchable();
381 }
382 
GetWindowName() const383 const std::string& WindowImpl::GetWindowName() const
384 {
385     return name_;
386 }
387 
GetWindowId() const388 uint32_t WindowImpl::GetWindowId() const
389 {
390     return property_->GetWindowId();
391 }
392 
GetDisplayId() const393 uint64_t WindowImpl::GetDisplayId() const
394 {
395     return property_->GetDisplayId();
396 }
397 
GetWindowFlags() const398 uint32_t WindowImpl::GetWindowFlags() const
399 {
400     return property_->GetWindowFlags();
401 }
402 
GetRequestWindowModeSupportType() const403 uint32_t WindowImpl::GetRequestWindowModeSupportType() const
404 {
405     return property_->GetRequestWindowModeSupportType();
406 }
407 
GetWindowModeSupportType() const408 uint32_t WindowImpl::GetWindowModeSupportType() const
409 {
410     return property_->GetWindowModeSupportType();
411 }
412 
IsMainHandlerAvailable() const413 bool WindowImpl::IsMainHandlerAvailable() const
414 {
415     return isMainHandlerAvailable_;
416 }
417 
GetSystemBarPropertyByType(WindowType type) const418 SystemBarProperty WindowImpl::GetSystemBarPropertyByType(WindowType type) const
419 {
420     auto curProperties = property_->GetSystemBarProperty();
421     return curProperties[type];
422 }
423 
GetAvoidAreaByType(AvoidAreaType type,AvoidArea & avoidArea,const Rect & rect,int32_t apiVersion)424 WMError WindowImpl::GetAvoidAreaByType(AvoidAreaType type, AvoidArea& avoidArea, const Rect& rect, int32_t apiVersion)
425 {
426     if (!IsWindowValid()) {
427         return WMError::WM_ERROR_INVALID_WINDOW;
428     }
429     WLOGI("GetAvoidAreaByType Search Type: %{public}u", static_cast<uint32_t>(type));
430     uint32_t windowId = property_->GetWindowId();
431     WMError ret = SingletonContainer::Get<WindowAdapter>().GetAvoidAreaByType(windowId, type, avoidArea, rect);
432     if (ret != WMError::WM_OK) {
433         WLOGFE("GetAvoidAreaByType errCode:%{public}d winId:%{public}u Type is :%{public}u.",
434             static_cast<int32_t>(ret), property_->GetWindowId(), static_cast<uint32_t>(type));
435     }
436     return ret;
437 }
438 
SetWindowType(WindowType type)439 WMError WindowImpl::SetWindowType(WindowType type)
440 {
441     WLOGFD("window id: %{public}u, type:%{public}u.", property_->GetWindowId(), static_cast<uint32_t>(type));
442     if (type != WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW && !Permission::IsSystemCalling() &&
443         !Permission::IsStartByHdcd()) {
444         WLOGFE("set window type permission denied!");
445         return WMError::WM_ERROR_NOT_SYSTEM_APP;
446     }
447     if (!IsWindowValid()) {
448         return WMError::WM_ERROR_INVALID_WINDOW;
449     }
450     if (state_ == WindowState::STATE_CREATED) {
451         if (!(WindowHelper::IsAppWindow(type) || WindowHelper::IsSystemWindow(type))) {
452             WLOGFE("window type is invalid %{public}u.", type);
453             return WMError::WM_ERROR_INVALID_PARAM;
454         }
455         property_->SetWindowType(type);
456         UpdateDecorEnable();
457         AdjustWindowAnimationFlag();
458         return WMError::WM_OK;
459     }
460     if (property_->GetWindowType() != type) {
461         return WMError::WM_ERROR_INVALID_PARAM;
462     }
463     return WMError::WM_OK;
464 }
465 
SetWindowMode(WindowMode mode)466 WMError WindowImpl::SetWindowMode(WindowMode mode)
467 {
468     WLOGI("Window %{public}u mode %{public}u", property_->GetWindowId(), static_cast<uint32_t>(mode));
469     if (!IsWindowValid()) {
470         return WMError::WM_ERROR_INVALID_WINDOW;
471     }
472     if (!WindowHelper::IsWindowModeSupported(GetWindowModeSupportType(), mode)) {
473         WLOGE("window %{public}u do not support mode: %{public}u",
474             property_->GetWindowId(), static_cast<uint32_t>(mode));
475         return WMError::WM_ERROR_INVALID_WINDOW_MODE_OR_SIZE;
476     }
477     if (state_ == WindowState::STATE_CREATED || state_ == WindowState::STATE_HIDDEN) {
478         UpdateMode(mode);
479     } else if (state_ == WindowState::STATE_SHOWN) {
480         WindowMode lastMode = property_->GetWindowMode();
481         property_->SetWindowMode(mode);
482         UpdateDecorEnable();
483         WMError ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_MODE);
484         if (ret != WMError::WM_OK) {
485             property_->SetWindowMode(lastMode);
486             return ret;
487         }
488         // set client window mode if success.
489         UpdateMode(mode);
490     }
491     if (property_->GetWindowMode() != mode) {
492         WLOGFE("set window mode filed! id: %{public}u.", property_->GetWindowId());
493         return WMError::WM_ERROR_INVALID_PARAM;
494     }
495     return WMError::WM_OK;
496 }
497 
SetAlpha(float alpha)498 WMError WindowImpl::SetAlpha(float alpha)
499 {
500     WLOGI("Window %{public}u alpha %{public}f", property_->GetWindowId(), alpha);
501     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
502         WLOGFE("set alpha permission denied!");
503         return WMError::WM_ERROR_NOT_SYSTEM_APP;
504     }
505     if (!IsWindowValid()) {
506         return WMError::WM_ERROR_INVALID_WINDOW;
507     }
508     property_->SetAlpha(alpha);
509     surfaceNode_->SetAlpha(alpha);
510     RSTransactionAdapter::FlushImplicitTransaction(surfaceNode_);
511     return WMError::WM_OK;
512 }
513 
SetTransform(const Transform & trans)514 WMError WindowImpl::SetTransform(const Transform& trans)
515 {
516     WLOGI("Window %{public}u", property_->GetWindowId());
517     if (!IsWindowValid()) {
518         return WMError::WM_ERROR_INVALID_WINDOW;
519     }
520     Transform oriTrans = property_->GetTransform();
521     property_->SetTransform(trans);
522     WMError ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_TRANSFORM_PROPERTY);
523     if (ret != WMError::WM_OK) {
524         WLOGFE("SetTransform errCode:%{public}d winId:%{public}u",
525             static_cast<int32_t>(ret), property_->GetWindowId());
526         property_->SetTransform(oriTrans); // reset to ori transform when update failed
527     }
528     if (property_->IsDisplayZoomOn()) {
529         TransformSurfaceNode(property_->GetZoomTransform());
530     } else {
531         TransformSurfaceNode(trans);
532     }
533     return ret;
534 }
535 
GetTransform() const536 const Transform& WindowImpl::GetTransform() const
537 {
538     return property_->GetTransform();
539 }
540 
GetZoomTransform() const541 const Transform& WindowImpl::GetZoomTransform() const
542 {
543     return property_->GetZoomTransform();
544 }
545 
AddWindowFlag(WindowFlag flag)546 WMError WindowImpl::AddWindowFlag(WindowFlag flag)
547 {
548     if (!IsWindowValid()) {
549         return WMError::WM_ERROR_INVALID_WINDOW;
550     }
551     if (flag == WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED && state_ != WindowState::STATE_CREATED) {
552         WLOGFE("Only support add show when locked when window create, id: %{public}u", property_->GetWindowId());
553         return WMError::WM_ERROR_INVALID_WINDOW;
554     }
555     if (flag == WindowFlag::WINDOW_FLAG_FORBID_SPLIT_MOVE && !Permission::IsSystemCalling()) {
556         WLOGFE("set forbid split move permission denied!");
557         return WMError::WM_ERROR_NOT_SYSTEM_APP;
558     }
559     uint32_t updateFlags = property_->GetWindowFlags() | (static_cast<uint32_t>(flag));
560     return SetWindowFlags(updateFlags);
561 }
562 
RemoveWindowFlag(WindowFlag flag)563 WMError WindowImpl::RemoveWindowFlag(WindowFlag flag)
564 {
565     if (!IsWindowValid()) {
566         return WMError::WM_ERROR_INVALID_WINDOW;
567     }
568     if (flag == WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED && state_ != WindowState::STATE_CREATED) {
569         WLOGFE("Only support remove show when locked when window create, id: %{public}u", property_->GetWindowId());
570         return WMError::WM_ERROR_INVALID_WINDOW;
571     }
572     if (flag == WindowFlag::WINDOW_FLAG_FORBID_SPLIT_MOVE && !Permission::IsSystemCalling()) {
573         WLOGFE("set forbid split move permission denied!");
574         return WMError::WM_ERROR_NOT_SYSTEM_APP;
575     }
576     uint32_t updateFlags = property_->GetWindowFlags() & (~(static_cast<uint32_t>(flag)));
577     return SetWindowFlags(updateFlags);
578 }
579 
SetWindowFlags(uint32_t flags)580 WMError WindowImpl::SetWindowFlags(uint32_t flags)
581 {
582     WLOGI("Window %{public}u flags %{public}u", property_->GetWindowId(), flags);
583     if (!IsWindowValid()) {
584         return WMError::WM_ERROR_INVALID_WINDOW;
585     }
586     if (property_->GetWindowFlags() == flags) {
587         return WMError::WM_OK;
588     }
589     auto oriFlags = property_->GetWindowFlags();
590     property_->SetWindowFlags(flags);
591     if (state_ == WindowState::STATE_CREATED || state_ == WindowState::STATE_HIDDEN) {
592         return WMError::WM_OK;
593     }
594     WMError ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_FLAGS);
595     if (ret != WMError::WM_OK) {
596         WLOGFE("SetWindowFlags errCode:%{public}d winId:%{public}u",
597             static_cast<int32_t>(ret), property_->GetWindowId());
598         property_->SetWindowFlags(oriFlags);
599     }
600     return ret;
601 }
602 
OnNewWant(const AAFwk::Want & want)603 void WindowImpl::OnNewWant(const AAFwk::Want& want)
604 {
605     WLOGI("Window [name:%{public}s, id:%{public}u]", name_.c_str(), property_->GetWindowId());
606     if (uiContent_ != nullptr) {
607         uiContent_->OnNewWant(want);
608     }
609 }
610 
NapiSetUIContent(const std::string & contentInfo,ani_env * env,ani_object storage,BackupAndRestoreType type,sptr<IRemoteObject> token,AppExecFwk::Ability * ability)611 WMError WindowImpl::NapiSetUIContent(const std::string& contentInfo, ani_env* env, ani_object storage,
612         BackupAndRestoreType type, sptr<IRemoteObject> token, AppExecFwk::Ability* ability)
613 {
614     return SetUIContentInner(contentInfo, env, storage,
615         type == BackupAndRestoreType::NONE ? WindowSetUIContentType::DEFAULT : WindowSetUIContentType::RESTORE,
616         type, ability, 1);
617 }
618 
NapiSetUIContent(const std::string & contentInfo,napi_env env,napi_value storage,BackupAndRestoreType type,sptr<IRemoteObject> token,AppExecFwk::Ability * ability)619 WMError WindowImpl::NapiSetUIContent(const std::string& contentInfo, napi_env env, napi_value storage,
620     BackupAndRestoreType type, sptr<IRemoteObject> token, AppExecFwk::Ability* ability)
621 {
622     return SetUIContentInner(contentInfo, env, storage,
623         type == BackupAndRestoreType::NONE ? WindowSetUIContentType::DEFAULT : WindowSetUIContentType::RESTORE,
624         type, ability);
625 }
626 
SetUIContentByName(const std::string & contentInfo,napi_env env,napi_value storage,AppExecFwk::Ability * ability)627 WMError WindowImpl::SetUIContentByName(
628     const std::string& contentInfo, napi_env env, napi_value storage, AppExecFwk::Ability* ability)
629 {
630     return SetUIContentInner(contentInfo, env, storage, WindowSetUIContentType::BY_NAME,
631         BackupAndRestoreType::NONE, ability);
632 }
633 
SetUIContentByAbc(const std::string & contentInfo,napi_env env,napi_value storage,AppExecFwk::Ability * ability)634 WMError WindowImpl::SetUIContentByAbc(
635     const std::string& contentInfo, napi_env env, napi_value storage, AppExecFwk::Ability* ability)
636 {
637     return SetUIContentInner(contentInfo, env, storage, WindowSetUIContentType::BY_ABC,
638         BackupAndRestoreType::NONE, ability);
639 }
640 
UIContentCreate(AppExecFwk::Ability * ability,void * env,int isAni)641 std::unique_ptr<Ace::UIContent> WindowImpl::UIContentCreate(AppExecFwk::Ability* ability, void* env, int isAni)
642 {
643     if (isAni) {
644         return  ability != nullptr ? Ace::UIContent::Create(ability) :
645             Ace::UIContent::CreateWithAniEnv(context_.get(), reinterpret_cast<ani_env*>(env));
646     } else {
647         return  ability != nullptr ? Ace::UIContent::Create(ability) :
648             Ace::UIContent::Create(context_.get(), reinterpret_cast<NativeEngine*>(env));
649     }
650 }
UIContentInitByName(Ace::UIContent * uiContent,const std::string & contentInfo,void * storage,int isAni)651 Ace::UIContentErrorCode WindowImpl::UIContentInitByName(Ace::UIContent* uiContent,
652     const std::string& contentInfo, void* storage, int isAni)
653 {
654     if (isAni) {
655         return uiContent->InitializeByNameWithAniStorage(this, contentInfo, (ani_object)storage);
656     } else {
657         return uiContent->InitializeByName(this, contentInfo, (napi_value)storage);
658     }
659 }
660 
661 template<typename T>
UIContentInit(Ace::UIContent * uiContent,T contentInfo,void * storage,int isAni)662 Ace::UIContentErrorCode WindowImpl::UIContentInit(Ace::UIContent* uiContent, T contentInfo,
663     void* storage, int isAni)
664 {
665     if (isAni) {
666         return uiContent->InitializeWithAniStorage(this, contentInfo, (ani_object)storage);
667     } else {
668         return uiContent->Initialize(this, contentInfo, (napi_value)storage);
669     }
670 }
671 template<typename T>
UIContentInit(Ace::UIContent * uiContent,T contentInfo,void * storage,const std::string & contentName,int isAni)672 Ace::UIContentErrorCode WindowImpl::UIContentInit(Ace::UIContent* uiContent, T contentInfo,
673     void* storage, const std::string& contentName, int isAni)
674 {
675     if (isAni) {
676         return uiContent->InitializeWithAniStorage(this, contentInfo, (ani_object)storage, contentName);
677     } else {
678         return uiContent->Initialize(this, contentInfo, (napi_value)storage, contentName);
679     }
680 }
681 
UIContentRestore(Ace::UIContent * uiContent,const std::string & contentInfo,void * storage,Ace::ContentInfoType infoType,int isAni)682 Ace::UIContentErrorCode WindowImpl::UIContentRestore(Ace::UIContent* uiContent, const std::string& contentInfo,
683     void* storage, Ace::ContentInfoType infoType, int isAni)
684 {
685     if (isAni) {
686         return uiContent->Restore(this, contentInfo, (ani_object)storage, infoType);
687     } else {
688         return uiContent->Restore(this, contentInfo, (napi_value)storage, infoType);
689     }
690 }
691 
692 
SetUIContentInner(const std::string & contentInfo,void * env,void * storage,WindowSetUIContentType setUIContentType,BackupAndRestoreType restoreType,AppExecFwk::Ability * ability,int isAni)693 WMError WindowImpl::SetUIContentInner(const std::string& contentInfo, void* env, void* storage,
694     WindowSetUIContentType setUIContentType, BackupAndRestoreType restoreType, AppExecFwk::Ability* ability, int isAni)
695 {
696     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "loadContent");
697     if (!IsWindowValid()) {
698         WLOGFD("interrupt set uicontent because window is invalid! window state: %{public}d", state_);
699         return WMError::WM_ERROR_INVALID_WINDOW;
700     }
701     WLOGFD("NapiSetUIContent: %{public}s", contentInfo.c_str());
702     if (uiContent_) {
703         uiContent_->Destroy();
704     }
705     std::unique_ptr<Ace::UIContent> uiContent = UIContentCreate(ability, (void*)env, isAni);
706     if (uiContent == nullptr) {
707         WLOGFE("fail to NapiSetUIContent id: %{public}u", property_->GetWindowId());
708         return WMError::WM_ERROR_NULLPTR;
709     }
710 
711     OHOS::Ace::UIContentErrorCode aceRet = OHOS::Ace::UIContentErrorCode::NO_ERRORS;
712     switch (setUIContentType) {
713         default:
714         case WindowSetUIContentType::DEFAULT: {
715             auto routerStack = GetRestoredRouterStack();
716             auto type = GetAceContentInfoType(BackupAndRestoreType::RESOURCESCHEDULE_RECOVERY);
717             if (!routerStack.empty() && UIContentRestore(uiContent.get(), routerStack, storage, type,
718                 isAni) == Ace::UIContentErrorCode::NO_ERRORS) {
719                 TLOGI(WmsLogTag::WMS_LIFE, "Restore router stack succeed.");
720                 break;
721             }
722             if (!intentParam_.empty()) {
723                 TLOGI(WmsLogTag::WMS_LIFE, "Default setIntentParam, isColdStart:%{public}u", isIntentColdStart_);
724                 uiContent->SetIntentParam(intentParam_, std::move(loadPageCallback_), isIntentColdStart_);
725                 intentParam_ = "";
726             }
727             aceRet = UIContentInit(uiContent.get(), contentInfo, storage, isAni);
728             break;
729         }
730         case WindowSetUIContentType::RESTORE:
731             aceRet = UIContentRestore(uiContent.get(), contentInfo, storage, GetAceContentInfoType(restoreType), isAni);
732             break;
733         case WindowSetUIContentType::BY_NAME:
734             if (!intentParam_.empty()) {
735                 TLOGI(WmsLogTag::WMS_LIFE, "By name setIntentParam, isColdStart:%{public}u", isIntentColdStart_);
736                 uiContent->SetIntentParam(intentParam_, std::move(loadPageCallback_), isIntentColdStart_);
737                 intentParam_ = "";
738             }
739             aceRet = UIContentInitByName(uiContent.get(), contentInfo, storage, isAni);
740             break;
741         case WindowSetUIContentType::BY_ABC:
742             aceRet = UIContentInit(uiContent.get(), GetAbcContent(contentInfo), storage, contentInfo, isAni);
743             break;
744     }
745     // make uiContent available after Initialize/Restore
746     {
747         std::lock_guard<std::recursive_mutex> lock(mutex_);
748         uiContent_ = std::move(uiContent);
749     }
750 
751     if (isIgnoreSafeAreaNeedNotify_) {
752         uiContent_->SetIgnoreViewSafeArea(isIgnoreSafeArea_);
753     }
754     UpdateDecorEnable(true);
755 
756     if (state_ == WindowState::STATE_SHOWN) {
757         // UIContent may be nullptr when show window, need to notify again when window is shown
758         uiContent_->Foreground();
759         UpdateTitleButtonVisibility();
760         Ace::ViewportConfig config;
761         Rect rect = GetRect();
762         config.SetSize(rect.width_, rect.height_);
763         config.SetPosition(rect.posX_, rect.posY_);
764         auto display = SingletonContainer::IsDestroyed() ? nullptr :
765             SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
766         if (display == nullptr) {
767             WLOGFE("get display failed displayId:%{public}" PRIu64", window id:%{public}u", property_->GetDisplayId(),
768                 property_->GetWindowId());
769             return WMError::WM_ERROR_NULLPTR;
770         }
771         float virtualPixelRatio = display->GetVirtualPixelRatio();
772         config.SetDensity(virtualPixelRatio);
773         config.SetDisplayId(GetDisplayId());
774         auto displayInfo = display->GetDisplayInfo();
775         if (displayInfo != nullptr) {
776             config.SetOrientation(static_cast<int32_t>(displayInfo->GetDisplayOrientation()));
777             TLOGI(WmsLogTag::WMS_LIFE, "notify window orientation change end.");
778         }
779         uiContent_->UpdateViewportConfig(config, WindowSizeChangeReason::UNDEFINED, nullptr);
780         WLOGFD("notify uiContent window size change end");
781     }
782     if (aceRet != OHOS::Ace::UIContentErrorCode::NO_ERRORS) {
783         WLOGFE("failed to init or restore uicontent with file %{public}s. errorCode: %{public}d",
784             contentInfo.c_str(), static_cast<uint16_t>(aceRet));
785         return WMError::WM_ERROR_INVALID_PARAM;
786     }
787     return WMError::WM_OK;
788 }
789 
GetVirtualPixelRatio()790 float WindowImpl::GetVirtualPixelRatio()
791 {
792     TLOGD(WmsLogTag::WMS_LAYOUT, "virtualPixelRatio: %{public}f", virtualPixelRatio_.load());
793     return virtualPixelRatio_.load();
794 }
795 
GetAbcContent(const std::string & abcPath)796 std::shared_ptr<std::vector<uint8_t>> WindowImpl::GetAbcContent(const std::string& abcPath)
797 {
798     std::filesystem::path abcFile { abcPath };
799     if (abcFile.empty() || !abcFile.is_absolute() || !std::filesystem::exists(abcFile)) {
800         WLOGFE("abc file path is not valid");
801         return nullptr;
802     }
803     int begin, end;
804     std::fstream file(abcFile, std::ios::in | std::ios::binary);
805     if (!file) {
806         WLOGFE("abc file is not valid");
807         return nullptr;
808     }
809     begin = file.tellg();
810     file.seekg(0, std::ios::end);
811     end = file.tellg();
812     int len = end - begin;
813     WLOGFD("abc file: %{public}s, size: %{public}d", abcPath.c_str(), len);
814 
815     if (len <= 0) {
816         WLOGFE("abc file size is 0");
817         return nullptr;
818     }
819     std::vector<uint8_t> abcBytes(len);
820     file.seekg(0, std::ios::beg);
821     file.read(reinterpret_cast<char *>(abcBytes.data()), len);
822     return std::make_shared<std::vector<uint8_t>>(abcBytes);
823 }
824 
GetUIContent() const825 Ace::UIContent* WindowImpl::GetUIContent() const
826 {
827     return uiContent_.get();
828 }
829 
GetUIContentWithId(uint32_t winId) const830 Ace::UIContent* WindowImpl::GetUIContentWithId(uint32_t winId) const
831 {
832     return nullptr;
833 }
834 
GetContentInfo(BackupAndRestoreType type)835 std::string WindowImpl::GetContentInfo(BackupAndRestoreType type)
836 {
837     WLOGFD("GetContentInfo");
838     if (type == BackupAndRestoreType::NONE) {
839         return "";
840     }
841 
842     if (uiContent_ == nullptr) {
843         WLOGFE("fail to GetContentInfo id: %{public}u", property_->GetWindowId());
844         return "";
845     }
846     return uiContent_->GetContentInfo(GetAceContentInfoType(type));
847 }
848 
SetRestoredRouterStack(const std::string & routerStack)849 WMError WindowImpl::SetRestoredRouterStack(const std::string& routerStack)
850 {
851     TLOGD(WmsLogTag::WMS_LIFE, "Set restored router stack.");
852     restoredRouterStack_ = routerStack;
853     return WMError::WM_OK;
854 }
855 
GetRestoredRouterStack()856 std::string WindowImpl::GetRestoredRouterStack()
857 {
858     TLOGD(WmsLogTag::WMS_LIFE, "Get restored router stack.");
859     return std::move(restoredRouterStack_);
860 }
861 
GetColorSpaceFromSurfaceGamut(GraphicColorGamut colorGamut)862 ColorSpace WindowImpl::GetColorSpaceFromSurfaceGamut(GraphicColorGamut colorGamut)
863 {
864     for (auto item: colorSpaceConvertMap) {
865         if (item.surfaceColorGamut == colorGamut) {
866             return item.colorSpace;
867         }
868     }
869     return ColorSpace::COLOR_SPACE_DEFAULT;
870 }
871 
GetSurfaceGamutFromColorSpace(ColorSpace colorSpace)872 GraphicColorGamut WindowImpl::GetSurfaceGamutFromColorSpace(ColorSpace colorSpace)
873 {
874     for (auto item: colorSpaceConvertMap) {
875         if (item.colorSpace == colorSpace) {
876             return item.surfaceColorGamut;
877         }
878     }
879     return GraphicColorGamut::GRAPHIC_COLOR_GAMUT_SRGB;
880 }
881 
IsSupportWideGamut()882 bool WindowImpl::IsSupportWideGamut()
883 {
884     return true;
885 }
886 
SetColorSpace(ColorSpace colorSpace)887 void WindowImpl::SetColorSpace(ColorSpace colorSpace)
888 {
889     if (!IsWindowValid()) {
890         return;
891     }
892     if (surfaceNode_ == nullptr) {
893         TLOGE(WmsLogTag::DEFAULT, "surface node is nullptr, winId: %{public}u", GetWindowId());
894         return;
895     }
896     auto surfaceGamut = GetSurfaceGamutFromColorSpace(colorSpace);
897     surfaceNode_->SetColorSpace(surfaceGamut);
898 }
899 
GetColorSpace()900 ColorSpace WindowImpl::GetColorSpace()
901 {
902     if (!IsWindowValid()) {
903         return ColorSpace::COLOR_SPACE_DEFAULT;
904     }
905     if (surfaceNode_ == nullptr) {
906         TLOGE(WmsLogTag::DEFAULT, "surface node is nullptr, winId: %{public}u", GetWindowId());
907         return ColorSpace::COLOR_SPACE_DEFAULT;
908     }
909     auto surfaceGamut = surfaceNode_->GetColorSpace();
910     return GetColorSpaceFromSurfaceGamut(surfaceGamut);
911 }
912 
Snapshot()913 std::shared_ptr<Media::PixelMap> WindowImpl::Snapshot()
914 {
915     if (!IsWindowValid()) {
916         return nullptr;
917     }
918     std::shared_ptr<SurfaceCaptureFuture> callback = std::make_shared<SurfaceCaptureFuture>();
919     auto isSucceeded = RSInterfaces::GetInstance().TakeSurfaceCapture(surfaceNode_, callback);
920     std::shared_ptr<Media::PixelMap> pixelMap;
921     if (isSucceeded) {
922         pixelMap = callback->GetResult(2000); // wait for <= 2000ms
923     } else {
924         pixelMap = SingletonContainer::Get<WindowAdapter>().GetSnapshot(property_->GetWindowId());
925     }
926     if (pixelMap != nullptr) {
927         WLOGFD("WMS-Client Save WxH=%{public}dx%{public}d", pixelMap->GetWidth(), pixelMap->GetHeight());
928     } else {
929         WLOGFE("Failed to get pixelmap, return nullptr!");
930     }
931     return pixelMap;
932 }
933 
SnapshotIgnorePrivacy(std::shared_ptr<Media::PixelMap> & pixelMap)934 WMError WindowImpl::SnapshotIgnorePrivacy(std::shared_ptr<Media::PixelMap>& pixelMap)
935 {
936     return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
937 }
938 
DumpInfo(const std::vector<std::string> & params,std::vector<std::string> & info)939 void WindowImpl::DumpInfo(const std::vector<std::string>& params, std::vector<std::string>& info)
940 {
941     if (params.size() == 1 && params[0] == PARAM_DUMP_HELP) { // 1: params num
942         WLOGFD("Dump ArkUI help Info");
943         Ace::UIContent::ShowDumpHelp(info);
944         SingletonContainer::Get<WindowAdapter>().NotifyDumpInfoResult(info);
945         return;
946     }
947     WLOGFD("ArkUI:DumpInfo");
948     if (uiContent_ != nullptr) {
949         uiContent_->DumpInfo(params, info);
950     }
951     SingletonContainer::Get<WindowAdapter>().NotifyDumpInfoResult(info);
952 }
953 
UpdateSystemBarProperties(const std::unordered_map<WindowType,SystemBarProperty> & systemBarProperties,const std::unordered_map<WindowType,SystemBarPropertyFlag> & systemBarPropertyFlags)954 WMError WindowImpl::UpdateSystemBarProperties(
955     const std::unordered_map<WindowType, SystemBarProperty>& systemBarProperties,
956     const std::unordered_map<WindowType, SystemBarPropertyFlag>& systemBarPropertyFlags)
957 {
958     for (auto& [systemBarType, systemBarPropertyFlag] : systemBarPropertyFlags) {
959         if (systemBarProperties.find(systemBarType) == systemBarProperties.end()) {
960             TLOGE(WmsLogTag::WMS_IMMS, "system bar type is invalid");
961             return WMError::WM_DO_NOTHING;
962         }
963         auto property = GetSystemBarPropertyByType(systemBarType);
964         property.enable_ = systemBarPropertyFlag.enableFlag ?
965             systemBarProperties.at(systemBarType).enable_ : property.enable_;
966         property.backgroundColor_ = systemBarPropertyFlag.backgroundColorFlag ?
967             systemBarProperties.at(systemBarType).backgroundColor_ : property.backgroundColor_;
968         property.contentColor_ = systemBarPropertyFlag.contentColorFlag ?
969             systemBarProperties.at(systemBarType).contentColor_ : property.contentColor_;
970         property.enableAnimation_ = systemBarPropertyFlag.enableAnimationFlag ?
971             systemBarProperties.at(systemBarType).enableAnimation_ : property.enableAnimation_;
972 
973         if (systemBarPropertyFlag.enableFlag) {
974             property.settingFlag_ |= SystemBarSettingFlag::ENABLE_SETTING;
975         }
976         if (systemBarPropertyFlag.backgroundColorFlag || systemBarPropertyFlag.contentColorFlag) {
977             property.settingFlag_ |= SystemBarSettingFlag::COLOR_SETTING;
978         }
979 
980         if (systemBarPropertyFlag.enableFlag || systemBarPropertyFlag.backgroundColorFlag ||
981             systemBarPropertyFlag.contentColorFlag || systemBarPropertyFlag.enableAnimationFlag) {
982             auto err = SetSystemBarProperty(systemBarType, property);
983             if (err != WMError::WM_OK) {
984                 return err;
985             }
986         }
987     }
988     return WMError::WM_OK;
989 }
990 
SetSystemBarProperty(WindowType type,const SystemBarProperty & property)991 WMError WindowImpl::SetSystemBarProperty(WindowType type, const SystemBarProperty& property)
992 {
993     WLOGI("Window %{public}u type %{public}u enable:%{public}u, bgColor:%{public}x, Color:%{public}x ",
994         property_->GetWindowId(), static_cast<uint32_t>(type), property.enable_,
995         property.backgroundColor_, property.contentColor_);
996     if (!IsWindowValid()) {
997         return WMError::WM_ERROR_INVALID_WINDOW;
998     }
999     if (GetSystemBarPropertyByType(type) == property) {
1000         return WMError::WM_OK;
1001     }
1002     property_->SetSystemBarProperty(type, property);
1003     if (state_ == WindowState::STATE_CREATED || state_ == WindowState::STATE_HIDDEN) {
1004         return WMError::WM_OK;
1005     }
1006     WMError ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_OTHER_PROPS);
1007     if (ret != WMError::WM_OK) {
1008         WLOGFE("SetSystemBarProperty errCode:%{public}d winId:%{public}u",
1009             static_cast<int32_t>(ret), property_->GetWindowId());
1010     }
1011     return ret;
1012 }
1013 
SetSystemBarProperties(const std::map<WindowType,SystemBarProperty> & properties,const std::map<WindowType,SystemBarPropertyFlag> & propertyFlags)1014 WMError WindowImpl::SetSystemBarProperties(const std::map<WindowType, SystemBarProperty>& properties,
1015     const std::map<WindowType, SystemBarPropertyFlag>& propertyFlags)
1016 {
1017     SystemBarProperty current = GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_STATUS_BAR);
1018     auto flagIter = propertyFlags.find(WindowType::WINDOW_TYPE_STATUS_BAR);
1019     auto propertyIter = properties.find(WindowType::WINDOW_TYPE_STATUS_BAR);
1020     if ((flagIter != propertyFlags.end() && flagIter->second.contentColorFlag) &&
1021         (propertyIter != properties.end() && current.contentColor_ != propertyIter->second.contentColor_)) {
1022         current.contentColor_ = propertyIter->second.contentColor_;
1023         current.settingFlag_ = static_cast<SystemBarSettingFlag>(
1024             static_cast<uint32_t>(propertyIter->second.settingFlag_) |
1025             static_cast<uint32_t>(SystemBarSettingFlag::COLOR_SETTING));
1026         WLOGI("Window:%{public}u %{public}s set status bar content color %{public}u",
1027             GetWindowId(), GetWindowName().c_str(), current.contentColor_);
1028         return SetSystemBarProperty(WindowType::WINDOW_TYPE_STATUS_BAR, current);
1029     }
1030     return WMError::WM_OK;
1031 }
1032 
GetSystemBarProperties(std::map<WindowType,SystemBarProperty> & properties)1033 WMError WindowImpl::GetSystemBarProperties(std::map<WindowType, SystemBarProperty>& properties)
1034 {
1035     if (property_ != nullptr) {
1036         WLOGI("Window:%{public}u", GetWindowId());
1037         properties[WindowType::WINDOW_TYPE_STATUS_BAR] = GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_STATUS_BAR);
1038     } else {
1039         WLOGFE("inner property is null");
1040     }
1041     return WMError::WM_OK;
1042 }
1043 
UpdateSpecificSystemBarEnabled(bool systemBarEnable,bool systemBarEnableAnimation,SystemBarProperty & property)1044 void WindowImpl::UpdateSpecificSystemBarEnabled(bool systemBarEnable, bool systemBarEnableAnimation,
1045     SystemBarProperty& property)
1046 {
1047     property.enable_ = systemBarEnable;
1048     property.enableAnimation_ = systemBarEnableAnimation;
1049     // isolate on api 18
1050     if (GetApiTargetVersion() >= API_VERSION_18) {
1051         property.settingFlag_ |= SystemBarSettingFlag::ENABLE_SETTING;
1052     }
1053 }
1054 
SetSpecificBarProperty(WindowType type,const SystemBarProperty & property)1055 WMError WindowImpl::SetSpecificBarProperty(WindowType type, const SystemBarProperty& property)
1056 {
1057     return WMError::WM_OK;
1058 }
1059 
UpdateSystemBarProperty(bool status)1060 WMError WindowImpl::UpdateSystemBarProperty(bool status)
1061 {
1062     if (!IsWindowValid()) {
1063         WLOGFE("PutSystemBarProperty errCode:%{public}d winId:%{public}u",
1064             static_cast<int32_t>(WMError::WM_ERROR_INVALID_WINDOW), property_->GetWindowId());
1065         return WMError::WM_ERROR_INVALID_WINDOW;
1066     }
1067 
1068     SystemBarProperty statusProperty = GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_STATUS_BAR);
1069     SystemBarProperty naviProperty = GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_NAVIGATION_BAR);
1070     if (status) {
1071         statusProperty.enable_ = false;
1072         naviProperty.enable_ = false;
1073     } else {
1074         statusProperty.enable_ = true;
1075         naviProperty.enable_ = true;
1076     }
1077 
1078     if ((GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_STATUS_BAR) == statusProperty) &&
1079         (GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_NAVIGATION_BAR) == naviProperty)) {
1080         return WMError::WM_OK;
1081     }
1082     if (!(GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_STATUS_BAR) == statusProperty)) {
1083         property_->SetSystemBarProperty(WindowType::WINDOW_TYPE_STATUS_BAR, statusProperty);
1084     }
1085     if (!(GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_NAVIGATION_BAR) == naviProperty)) {
1086         property_->SetSystemBarProperty(WindowType::WINDOW_TYPE_NAVIGATION_BAR, naviProperty);
1087     }
1088     if (state_ == WindowState::STATE_CREATED || state_ == WindowState::STATE_HIDDEN) {
1089         return WMError::WM_OK;
1090     }
1091 
1092     WMError ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_OTHER_PROPS);
1093     if (ret != WMError::WM_OK) {
1094         WLOGFE("SetSystemBarProperty errCode:%{public}d winId:%{public}u",
1095             static_cast<int32_t>(ret), property_->GetWindowId());
1096     }
1097     return ret;
1098 }
1099 
SetLayoutFullScreen(bool status)1100 WMError WindowImpl::SetLayoutFullScreen(bool status)
1101 {
1102     WLOGI("Window %{public}u status: %{public}u", property_->GetWindowId(), status);
1103     if (!IsWindowValid() ||
1104         !WindowHelper::IsWindowModeSupported(GetWindowModeSupportType(), WindowMode::WINDOW_MODE_FULLSCREEN)) {
1105         WLOGFE("invalid window or fullscreen mode is not be supported, winId:%{public}u", property_->GetWindowId());
1106         return WMError::WM_ERROR_INVALID_WINDOW;
1107     }
1108     WMError ret = WMError::WM_OK;
1109     uint32_t version = 0;
1110     if ((context_ != nullptr) && (context_->GetApplicationInfo() != nullptr)) {
1111         version = context_->GetApplicationInfo()->apiCompatibleVersion;
1112     }
1113     ret = SetWindowMode(WindowMode::WINDOW_MODE_FULLSCREEN);
1114     if (ret != WMError::WM_OK) {
1115         WLOGFE("SetWindowMode errCode:%{public}d winId:%{public}u",
1116             static_cast<int32_t>(ret), property_->GetWindowId());
1117         return ret;
1118     }
1119     isIgnoreSafeArea_ = status;
1120     // 10 ArkUI new framework support after API10
1121     if (version >= 10) {
1122         if (uiContent_ != nullptr) {
1123             uiContent_->SetIgnoreViewSafeArea(status);
1124         }
1125         isIgnoreSafeAreaNeedNotify_ = true;
1126     } else {
1127         if (status) {
1128             ret = RemoveWindowFlag(WindowFlag::WINDOW_FLAG_NEED_AVOID);
1129             if (ret != WMError::WM_OK) {
1130                 WLOGFE("RemoveWindowFlag errCode:%{public}d winId:%{public}u",
1131                     static_cast<int32_t>(ret), property_->GetWindowId());
1132                 return ret;
1133             }
1134         } else {
1135             ret = AddWindowFlag(WindowFlag::WINDOW_FLAG_NEED_AVOID);
1136             if (ret != WMError::WM_OK) {
1137                 WLOGFE("AddWindowFlag errCode:%{public}d winId:%{public}u",
1138                     static_cast<int32_t>(ret), property_->GetWindowId());
1139                 return ret;
1140             }
1141         }
1142     }
1143     enableImmersiveMode_ = status;
1144     return ret;
1145 }
1146 
SetFullScreen(bool status)1147 WMError WindowImpl::SetFullScreen(bool status)
1148 {
1149     WLOGI("Window %{public}u status: %{public}d", property_->GetWindowId(), status);
1150     if (!IsWindowValid() ||
1151         !WindowHelper::IsWindowModeSupported(GetWindowModeSupportType(), WindowMode::WINDOW_MODE_FULLSCREEN)) {
1152         WLOGFE("invalid window or fullscreen mode is not be supported, winId:%{public}u", property_->GetWindowId());
1153         return WMError::WM_ERROR_INVALID_WINDOW;
1154     }
1155     WMError ret = UpdateSystemBarProperty(status);
1156     if (ret != WMError::WM_OK) {
1157         WLOGFE("UpdateSystemBarProperty errCode:%{public}d winId:%{public}u",
1158             static_cast<int32_t>(ret), property_->GetWindowId());
1159     }
1160     ret = SetLayoutFullScreen(status);
1161     if (ret != WMError::WM_OK) {
1162         WLOGFE("SetLayoutFullScreen errCode:%{public}d winId:%{public}u",
1163             static_cast<int32_t>(ret), property_->GetWindowId());
1164     }
1165     return ret;
1166 }
1167 
SetFloatingMaximize(bool isEnter)1168 WMError WindowImpl::SetFloatingMaximize(bool isEnter)
1169 {
1170     WLOGFI("id:%{public}d SetFloatingMaximize status: %{public}d", property_->GetWindowId(), isEnter);
1171     if (!IsWindowValid() ||
1172         !WindowHelper::IsWindowModeSupported(GetWindowModeSupportType(), WindowMode::WINDOW_MODE_FULLSCREEN)) {
1173         WLOGFE("invalid window or maximize mode is not be supported, winId:%{public}u", property_->GetWindowId());
1174         return WMError::WM_ERROR_INVALID_WINDOW;
1175     }
1176 
1177     if (isEnter && GetGlobalMaximizeMode() != MaximizeMode::MODE_AVOID_SYSTEM_BAR) {
1178         WMError ret = SetFullScreen(true);
1179         if (ret == WMError::WM_OK) {
1180             property_->SetMaximizeMode(MaximizeMode::MODE_FULL_FILL);
1181         }
1182         return ret;
1183     }
1184 
1185     if (isEnter && GetWindowMode() != WindowMode::WINDOW_MODE_FLOATING) {
1186         if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
1187             SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
1188         }
1189     }
1190     property_->SetMaximizeMode(isEnter ? MaximizeMode::MODE_AVOID_SYSTEM_BAR : MaximizeMode::MODE_RECOVER);
1191     property_->SetWindowSizeChangeReason(WindowSizeChangeReason::RESIZE);
1192     return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_MAXIMIZE_STATE);
1193 }
1194 
SetAspectRatio(float ratio)1195 WMError WindowImpl::SetAspectRatio(float ratio)
1196 {
1197     WLOGFI("windowId: %{public}u, ratio: %{public}f", GetWindowId(), ratio);
1198     if (!WindowHelper::IsMainWindow(GetType())) {
1199         WLOGFE("Invalid operation, windowId: %{public}u", GetWindowId());
1200         return WMError::WM_ERROR_INVALID_OPERATION;
1201     }
1202     if (MathHelper::NearZero(ratio) || ratio < 0.0f) {
1203         WLOGFE("Invalid param, ratio: %{public}f", ratio);
1204         return WMError::WM_ERROR_INVALID_PARAM;
1205     }
1206     property_->SetAspectRatio(ratio);
1207     if (state_ == WindowState::STATE_HIDDEN || state_ == WindowState::STATE_CREATED) {
1208         WLOGFD("window is hidden or created! id: %{public}u, ratio: %{public}f ", property_->GetWindowId(), ratio);
1209         return WMError::WM_OK;
1210     }
1211     auto ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_ASPECT_RATIO);
1212     if (ret != WMError::WM_OK) {
1213         WLOGFE("Set AspectRatio failed. errorCode: %{public}u", ret);
1214     }
1215     return ret;
1216 }
1217 
ResetAspectRatio()1218 WMError WindowImpl::ResetAspectRatio()
1219 {
1220     if (!IsWindowValid()) {
1221         TLOGE(WmsLogTag::WMS_LAYOUT, "Window is invalid");
1222         return WMError::WM_ERROR_INVALID_OPERATION;
1223     }
1224 
1225     WLOGFI("windowId: %{public}u", GetWindowId());
1226     if (!WindowHelper::IsMainWindow(GetType())) {
1227         WLOGFE("Invalid operation, windowId: %{public}u", GetWindowId());
1228         return WMError::WM_ERROR_INVALID_OPERATION;
1229     }
1230     property_->SetAspectRatio(0.0);
1231     if (state_ == WindowState::STATE_HIDDEN || state_ == WindowState::STATE_CREATED) {
1232         WLOGFD("window is hidden or created! id: %{public}u", property_->GetWindowId());
1233         return WMError::WM_OK;
1234     }
1235     UpdateProperty(PropertyChangeAction::ACTION_UPDATE_ASPECT_RATIO);
1236     return WMError::WM_OK;
1237 }
1238 
MapFloatingWindowToAppIfNeeded()1239 void WindowImpl::MapFloatingWindowToAppIfNeeded()
1240 {
1241     if (!WindowHelper::IsAppFloatingWindow(GetType()) || context_.get() == nullptr) {
1242         return;
1243     }
1244 
1245     WLOGFI("In");
1246     std::shared_lock<std::shared_mutex> lock(windowMapMutex_);
1247     for (const auto& winPair : windowMap_) {
1248         auto win = winPair.second.second;
1249         if (win->GetType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW &&
1250             context_.get() == win->GetContext().get()) {
1251             sptr<WindowImpl> selfImpl(this);
1252             appFloatingWindowMap_[win->GetWindowId()].push_back(selfImpl);
1253             WLOGFD("Map FloatingWindow %{public}u to AppMainWindow %{public}u, type is %{public}u",
1254                 GetWindowId(), win->GetWindowId(), GetType());
1255             return;
1256         }
1257     }
1258 }
1259 
MapDialogWindowToAppIfNeeded()1260 void WindowImpl::MapDialogWindowToAppIfNeeded()
1261 {
1262     if (GetType() != WindowType::WINDOW_TYPE_DIALOG) {
1263         return;
1264     }
1265 
1266     std::shared_lock<std::shared_mutex> lock(windowMapMutex_);
1267     for (const auto& winPair : windowMap_) {
1268         auto win = winPair.second.second;
1269         if (win->GetType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW &&
1270             context_.get() == win->GetContext().get()) {
1271             sptr<WindowImpl> selfImpl(this);
1272             appDialogWindowMap_[win->GetWindowId()].push_back(selfImpl);
1273             WLOGFD("Map DialogWindow %{public}u to AppMainWindow %{public}u", GetWindowId(), win->GetWindowId());
1274             return;
1275         }
1276     }
1277 }
1278 
UpdateProperty(PropertyChangeAction action)1279 WMError WindowImpl::UpdateProperty(PropertyChangeAction action)
1280 {
1281     return SingletonContainer::Get<WindowAdapter>().UpdateProperty(property_, action);
1282 }
1283 
GetConfigurationFromAbilityInfo()1284 void WindowImpl::GetConfigurationFromAbilityInfo()
1285 {
1286     auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
1287     if (abilityContext == nullptr) {
1288         WLOGFE("id:%{public}u is not ability Window", property_->GetWindowId());
1289         return;
1290     }
1291     auto abilityInfo = abilityContext->GetAbilityInfo();
1292     if (abilityInfo == nullptr) {
1293         WLOGFE("id:%{public}u Ability window get ability info failed", property_->GetWindowId());
1294         return;
1295     }
1296 
1297     // get support modes configuration
1298     uint32_t windowModeSupportType = WindowHelper::ConvertSupportModesToSupportType(abilityInfo->windowModes);
1299     if (windowModeSupportType == 0) {
1300         WLOGFD("mode config param is 0, all modes is supported");
1301         windowModeSupportType = WindowModeSupport::WINDOW_MODE_SUPPORT_ALL;
1302     }
1303     WLOGFD("winId: %{public}u, windowModeSupportType: %{public}u", GetWindowId(), windowModeSupportType);
1304     SetRequestWindowModeSupportType(windowModeSupportType);
1305 
1306     // get window size limits configuration
1307     WindowLimits sizeLimits;
1308     sizeLimits.maxWidth_ = abilityInfo->maxWindowWidth;
1309     sizeLimits.maxHeight_ = abilityInfo->maxWindowHeight;
1310     sizeLimits.minWidth_ = abilityInfo->minWindowWidth;
1311     sizeLimits.minHeight_ = abilityInfo->minWindowHeight;
1312     sizeLimits.maxRatio_ = static_cast<float>(abilityInfo->maxWindowRatio);
1313     sizeLimits.minRatio_ = static_cast<float>(abilityInfo->minWindowRatio);
1314     property_->SetSizeLimits(sizeLimits);
1315 
1316     // get orientation configuration
1317     OHOS::AppExecFwk::DisplayOrientation displayOrientation =
1318         static_cast<OHOS::AppExecFwk::DisplayOrientation>(
1319             static_cast<uint32_t>(abilityInfo->orientation));
1320     if (ABILITY_TO_WMS_ORIENTATION_MAP.count(displayOrientation) == 0) {
1321         WLOGFE("id:%{public}u Do not support this Orientation type", property_->GetWindowId());
1322         return;
1323     }
1324     Orientation orientation = ABILITY_TO_WMS_ORIENTATION_MAP.at(displayOrientation);
1325     if (orientation < Orientation::BEGIN || orientation > Orientation::END) {
1326         WLOGFE("Set orientation from ability failed");
1327         return;
1328     }
1329     property_->SetRequestedOrientation(orientation);
1330 }
1331 
UpdateTitleButtonVisibility()1332 void WindowImpl::UpdateTitleButtonVisibility()
1333 {
1334     WLOGFD("[Client] UpdateTitleButtonVisibility");
1335     if (uiContent_ == nullptr || !IsDecorEnable()) {
1336         return;
1337     }
1338     auto windowModeSupportType = GetWindowModeSupportType();
1339     bool hideSplitButton = !(windowModeSupportType & WindowModeSupport::WINDOW_MODE_SUPPORT_SPLIT_PRIMARY);
1340     // not support fullscreen in split and floating mode, or not support float in fullscreen mode
1341     bool hideMaximizeButton = (!(windowModeSupportType & WindowModeSupport::WINDOW_MODE_SUPPORT_FULLSCREEN) &&
1342         (GetWindowMode() == WindowMode::WINDOW_MODE_FLOATING || WindowHelper::IsSplitWindowMode(GetWindowMode()))) ||
1343         (!(windowModeSupportType & WindowModeSupport::WINDOW_MODE_SUPPORT_FLOATING) &&
1344         GetWindowMode() == WindowMode::WINDOW_MODE_FULLSCREEN);
1345     WLOGD("[Client] [hideSplit, hideMaximize]: [%{public}d, %{public}d]", hideSplitButton, hideMaximizeButton);
1346     uiContent_->HideWindowTitleButton(hideSplitButton, hideMaximizeButton, false, false);
1347 }
1348 
IsAppMainOrSubOrFloatingWindow()1349 bool WindowImpl::IsAppMainOrSubOrFloatingWindow()
1350 {
1351     // App main window need decor config, stretchable config and effect config
1352     // App sub window and float window need effect config
1353     if (WindowHelper::IsAppWindow(GetType())) {
1354         return true;
1355     }
1356 
1357     if (WindowHelper::IsAppFloatingWindow(GetType())) {
1358         std::shared_lock<std::shared_mutex> lock(windowMapMutex_);
1359         for (const auto& winPair : windowMap_) {
1360             auto win = winPair.second.second;
1361             if (win != nullptr && win->GetType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW &&
1362                 context_.get() == win->GetContext().get()) {
1363                 isAppFloatingWindow_ = true;
1364                 return true;
1365             }
1366         }
1367     }
1368     return false;
1369 }
1370 
SetSystemConfig()1371 void WindowImpl::SetSystemConfig()
1372 {
1373     if (!IsAppMainOrSubOrFloatingWindow()) {
1374         return;
1375     }
1376     if (SingletonContainer::Get<WindowAdapter>().GetSystemConfig(windowSystemConfig_) == WMError::WM_OK) {
1377         if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
1378             WLOGFD("get system decor enable:%{public}d", windowSystemConfig_.isSystemDecorEnable_);
1379             property_->SetDecorEnable(windowSystemConfig_.isSystemDecorEnable_);
1380             WLOGFD("get stretchable enable:%{public}d", windowSystemConfig_.isStretchable_);
1381             property_->SetStretchable(windowSystemConfig_.isStretchable_);
1382             // if window mode is undefined, set it from configuration
1383             if (property_->GetWindowMode() == WindowMode::WINDOW_MODE_UNDEFINED) {
1384                 WLOGFD("get default window mode:%{public}u", windowSystemConfig_.defaultWindowMode_);
1385                 property_->SetWindowMode(windowSystemConfig_.defaultWindowMode_);
1386             }
1387             if (property_->GetLastWindowMode() == WindowMode::WINDOW_MODE_UNDEFINED) {
1388                 property_->SetLastWindowMode(windowSystemConfig_.defaultWindowMode_);
1389             }
1390         }
1391     }
1392 }
1393 
GetKeyboardAnimationConfig()1394 KeyboardAnimationConfig WindowImpl::GetKeyboardAnimationConfig()
1395 {
1396     return { windowSystemConfig_.animationIn_, windowSystemConfig_.animationOut_ };
1397 }
1398 
WindowCreateCheck(uint32_t parentId)1399 WMError WindowImpl::WindowCreateCheck(uint32_t parentId)
1400 {
1401     if (vsyncStation_ == nullptr || !vsyncStation_->IsVsyncReceiverCreated()) {
1402         return WMError::WM_ERROR_NULLPTR;
1403     }
1404     // check window name, same window names are forbidden
1405     {
1406         std::shared_lock<std::shared_mutex> lock(windowMapMutex_);
1407         if (windowMap_.find(name_) != windowMap_.end()) {
1408             WLOGFE("WindowName(%{public}s) already exists.", name_.c_str());
1409             return WMError::WM_ERROR_REPEAT_OPERATION;
1410         }
1411     }
1412     if (CheckCameraFloatingWindowMultiCreated(property_->GetWindowType())) {
1413         WLOGFE("Camera Floating Window already exists.");
1414         return WMError::WM_ERROR_REPEAT_OPERATION;
1415     }
1416     if (parentId == INVALID_WINDOW_ID) {
1417         if (WindowHelper::IsSystemSubWindow(property_->GetWindowType()) ||
1418             WindowHelper::IsSubWindow(property_->GetWindowType())) {
1419             return WMError::WM_ERROR_INVALID_PARENT;
1420         }
1421         return WMError::WM_OK;
1422     }
1423 
1424     if (property_->GetWindowType() == WindowType::WINDOW_TYPE_APP_COMPONENT) {
1425         property_->SetParentId(parentId);
1426     } else {
1427         sptr<Window> parentWindow = nullptr;
1428         {
1429             std::shared_lock<std::shared_mutex> lock(windowMapMutex_);
1430             for (const auto& winPair : windowMap_) {
1431                 if (winPair.second.first == parentId) {
1432                     property_->SetParentId(parentId);
1433                     parentWindow = winPair.second.second;
1434                     break;
1435                 }
1436             }
1437         }
1438         if (WindowHelper::IsSystemSubWindow(property_->GetWindowType())) {
1439             if (parentWindow == nullptr) {
1440                 return WMError::WM_ERROR_INVALID_PARENT;
1441             }
1442             if (!parentWindow->IsAllowHaveSystemSubWindow()) {
1443                 return WMError::WM_ERROR_INVALID_PARENT;
1444             }
1445         }
1446     }
1447     if (property_->GetParentId() != parentId) {
1448         WLOGFE("Parent Window does not exist. ParentId is %{public}u", parentId);
1449         return WMError::WM_ERROR_INVALID_PARENT;
1450     }
1451 
1452     return WMError::WM_OK;
1453 }
1454 
ChangePropertyByApiVersion()1455 void WindowImpl::ChangePropertyByApiVersion()
1456 {
1457     uint32_t version = 0;
1458     if ((context_ != nullptr) && (context_->GetApplicationInfo() != nullptr)) {
1459         version = context_->GetApplicationInfo()->apiCompatibleVersion;
1460     }
1461     // 10 ArkUI new framework support after API10
1462     if (version >= 10) {
1463         if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
1464             SystemBarProperty statusSystemBarProperty(true, 0x00FFFFFF, 0xFF000000);
1465             SystemBarProperty navigationSystemBarProperty(true, 0x00FFFFFF, 0xFF000000);
1466             property_->SetSystemBarProperty(WindowType::WINDOW_TYPE_STATUS_BAR, statusSystemBarProperty);
1467             property_->SetSystemBarProperty(WindowType::WINDOW_TYPE_NAVIGATION_BAR, navigationSystemBarProperty);
1468         }
1469     }
1470 }
1471 
SetDefaultDisplayIdIfNeed()1472 void WindowImpl::SetDefaultDisplayIdIfNeed()
1473 {
1474     auto displayId = property_->GetDisplayId();
1475     if (displayId == DISPLAY_ID_INVALID) {
1476         auto defaultDisplayId = SingletonContainer::IsDestroyed() ? DISPLAY_ID_INVALID :
1477             SingletonContainer::Get<DisplayManager>().GetDefaultDisplayId();
1478         defaultDisplayId = (defaultDisplayId == DISPLAY_ID_INVALID)? 0 : defaultDisplayId;
1479         property_->SetDisplayId(defaultDisplayId);
1480         TLOGI(WmsLogTag::WMS_LIFE, "Reset displayId: %{public}" PRIu64, defaultDisplayId);
1481     }
1482 }
1483 
Create(uint32_t parentId,const std::shared_ptr<AbilityRuntime::Context> & context)1484 WMError WindowImpl::Create(uint32_t parentId, const std::shared_ptr<AbilityRuntime::Context>& context)
1485 {
1486     WLOGFD("Window[%{public}s] Create", name_.c_str());
1487     WMError ret = WindowCreateCheck(parentId);
1488     if (ret != WMError::WM_OK) {
1489         return ret;
1490     }
1491     SetDefaultDisplayIdIfNeed();
1492     context_ = context;
1493     sptr<WindowImpl> window(this);
1494     sptr<IWindow> windowAgent(new WindowAgent(window));
1495     static std::atomic<uint32_t> tempWindowId = 0;
1496     uint32_t windowId = tempWindowId++; // for test
1497     sptr<IRemoteObject> token = context_ ? context_->GetToken() : nullptr;
1498     if (token) {
1499         property_->SetTokenState(true);
1500     }
1501     ChangePropertyByApiVersion();
1502     InitAbilityInfo();
1503     SetSystemConfig();
1504 
1505     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
1506         GetConfigurationFromAbilityInfo();
1507     } else if (property_->GetWindowMode() == WindowMode::WINDOW_MODE_UNDEFINED) {
1508         property_->SetWindowMode(WindowMode::WINDOW_MODE_FULLSCREEN);
1509     }
1510 
1511     if (property_->GetWindowType() == WindowType::WINDOW_TYPE_VOLUME_OVERLAY && surfaceNode_) {
1512         surfaceNode_->SetFrameGravity(Gravity::TOP_LEFT);
1513     }
1514 
1515     ret = SingletonContainer::Get<WindowAdapter>().CreateWindow(windowAgent, property_, surfaceNode_,
1516         windowId, token);
1517     RecordLifeCycleExceptionEvent(LifeCycleEvent::CREATE_EVENT, ret);
1518     if (ret != WMError::WM_OK) {
1519         WLOGFE("create window failed with errCode:%{public}d", static_cast<int32_t>(ret));
1520         return ret;
1521     }
1522     property_->SetWindowId(windowId);
1523     if (surfaceNode_) {
1524         surfaceNode_->SetWindowId(windowId);
1525     }
1526     sptr<Window> self(this);
1527     {
1528         std::unique_lock<std::shared_mutex> lock(windowMapMutex_);
1529         windowMap_.insert(std::make_pair(name_, std::pair<uint32_t, sptr<Window>>(windowId, self)));
1530     }
1531     if (parentId != INVALID_WINDOW_ID) {
1532         subWindowMap_[property_->GetParentId()].push_back(window);
1533     }
1534 
1535     MapFloatingWindowToAppIfNeeded();
1536     MapDialogWindowToAppIfNeeded();
1537     UpdateDecorEnable();
1538 
1539     state_ = WindowState::STATE_CREATED;
1540     InputTransferStation::GetInstance().AddInputWindow(self);
1541     needRemoveWindowInputChannel_ = true;
1542     RegisterWindowInspectorCallback();
1543     return ret;
1544 }
1545 
GetWindowTypeForArkUI(WindowType parentWindowType,WindowType & windowType)1546 WMError WindowImpl::GetWindowTypeForArkUI(WindowType parentWindowType, WindowType& windowType)
1547 {
1548     if (parentWindowType == WindowType::WINDOW_TYPE_SCENE_BOARD ||
1549         parentWindowType == WindowType::WINDOW_TYPE_DESKTOP) {
1550         windowType = WindowType::WINDOW_TYPE_SYSTEM_FLOAT;
1551     } else if (WindowHelper::IsUIExtensionWindow(parentWindowType)) {
1552         windowType = WindowType::WINDOW_TYPE_APP_SUB_WINDOW;
1553     } else if (WindowHelper::IsSystemWindow(parentWindowType)) {
1554         windowType = WindowType::WINDOW_TYPE_SYSTEM_SUB_WINDOW;
1555     } else {
1556         windowType = WindowType::WINDOW_TYPE_APP_SUB_WINDOW;
1557     }
1558     TLOGI(WmsLogTag::WMS_SUB, "parentWindowType:%{public}d, windowType:%{public}d", parentWindowType, windowType);
1559     return WMError::WM_OK;
1560 }
1561 
PreNotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent)1562 bool WindowImpl::PreNotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
1563 {
1564     if (uiContent_ != nullptr) {
1565         return uiContent_->ProcessKeyEvent(keyEvent, true);
1566     }
1567     return false;
1568 }
1569 
InitAbilityInfo()1570 void WindowImpl::InitAbilityInfo()
1571 {
1572     AbilityInfo info;
1573     info.bundleName_ = SysCapUtil::GetBundleName();
1574     auto originalAbilityInfo = GetOriginalAbilityInfo();
1575     if (originalAbilityInfo != nullptr) {
1576         info.abilityName_ = originalAbilityInfo->name;
1577     } else {
1578         WLOGFD("original ability info is null %{public}s", name_.c_str());
1579     }
1580     property_->SetAbilityInfo(info);
1581 }
1582 
GetOriginalAbilityInfo() const1583 std::shared_ptr<AppExecFwk::AbilityInfo> WindowImpl::GetOriginalAbilityInfo() const
1584 {
1585     if (context_ == nullptr) {
1586         WLOGFD("context is null %{public}s", name_.c_str());
1587         return nullptr;
1588     }
1589 
1590     auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
1591     if (abilityContext == nullptr) {
1592         WLOGFD("abilityContext is null %{public}s", name_.c_str());
1593         return nullptr;
1594     }
1595     return abilityContext->GetAbilityInfo();
1596 }
1597 
BindDialogTarget(sptr<IRemoteObject> targetToken)1598 WMError WindowImpl::BindDialogTarget(sptr<IRemoteObject> targetToken)
1599 {
1600     if (!IsWindowValid()) {
1601         return WMError::WM_ERROR_INVALID_WINDOW;
1602     }
1603     uint32_t windowId = property_->GetWindowId();
1604     WMError ret = SingletonContainer::Get<WindowAdapter>().BindDialogTarget(windowId, targetToken);
1605     if (ret != WMError::WM_OK) {
1606         WLOGFE("bind window failed with errCode:%{public}d", static_cast<int32_t>(ret));
1607     }
1608 
1609     return ret;
1610 }
1611 
ResetInputWindow(uint32_t winId)1612 void WindowImpl::ResetInputWindow(uint32_t winId)
1613 {
1614     TLOGI(WmsLogTag::WMS_EVENT, "Id:%{public}u", winId);
1615     InputTransferStation::GetInstance().AddInputWindow(this);
1616 }
1617 
DestroyDialogWindow()1618 void WindowImpl::DestroyDialogWindow()
1619 {
1620     // remove from appDialogWindowMap_
1621     for (auto& dialogWindows: appDialogWindowMap_) {
1622         for (auto iter = dialogWindows.second.begin(); iter != dialogWindows.second.end(); ++iter) {
1623             if ((*iter) == nullptr) {
1624                 continue;
1625             }
1626             if ((*iter)->GetWindowId() == GetWindowId()) {
1627                 dialogWindows.second.erase(iter);
1628                 break;
1629             }
1630         }
1631     }
1632 
1633     // Destroy app dialog window if exist
1634     if (appDialogWindowMap_.count(GetWindowId()) > 0) {
1635         auto& dialogWindows = appDialogWindowMap_.at(GetWindowId());
1636         for (auto iter = dialogWindows.begin(); iter != dialogWindows.end(); iter = dialogWindows.begin()) {
1637             if ((*iter) == nullptr) {
1638                 dialogWindows.erase(iter);
1639                 continue;
1640             }
1641             (*iter)->Destroy(false);
1642         }
1643         appDialogWindowMap_.erase(GetWindowId());
1644     }
1645 }
1646 
DestroyFloatingWindow()1647 void WindowImpl::DestroyFloatingWindow()
1648 {
1649     // remove from appFloatingWindowMap_
1650     TLOGI(WmsLogTag::WMS_LIFE, "Remove from appFloatingWindowMap_");
1651     for (auto& floatingWindows: appFloatingWindowMap_) {
1652         for (auto iter = floatingWindows.second.begin(); iter != floatingWindows.second.end(); ++iter) {
1653             if ((*iter) == nullptr) {
1654                 continue;
1655             }
1656             if ((*iter)->GetWindowId() == GetWindowId()) {
1657                 floatingWindows.second.erase(iter);
1658                 break;
1659             }
1660         }
1661     }
1662 
1663     // Destroy app floating window if exist
1664     TLOGI(WmsLogTag::WMS_LIFE, "Destroy app floating window if exist");
1665     if (appFloatingWindowMap_.count(GetWindowId()) > 0) {
1666         auto& floatingWindows = appFloatingWindowMap_.at(GetWindowId());
1667         for (auto iter = floatingWindows.begin(); iter != floatingWindows.end(); iter = floatingWindows.begin()) {
1668             if ((*iter) == nullptr) {
1669                 floatingWindows.erase(iter);
1670                 continue;
1671             }
1672             (*iter)->Destroy();
1673         }
1674         appFloatingWindowMap_.erase(GetWindowId());
1675     }
1676 }
1677 
DestroySubWindow()1678 void WindowImpl::DestroySubWindow()
1679 {
1680     if (subWindowMap_.count(property_->GetParentId()) > 0) { // remove from subWindowMap_
1681         auto& subWindows = subWindowMap_.at(property_->GetParentId());
1682         for (auto iter = subWindows.begin(); iter < subWindows.end(); ++iter) {
1683             if ((*iter) == nullptr) {
1684                 continue;
1685             }
1686             if ((*iter)->GetWindowId() == GetWindowId()) {
1687                 subWindows.erase(iter);
1688                 break;
1689             }
1690         }
1691     }
1692 
1693     if (subWindowMap_.count(GetWindowId()) > 0) { // remove from subWindowMap_ and windowMap_
1694         auto& subWindows = subWindowMap_.at(GetWindowId());
1695         for (auto iter = subWindows.begin(); iter != subWindows.end(); iter = subWindows.begin()) {
1696             if ((*iter) == nullptr) {
1697                 subWindows.erase(iter);
1698                 continue;
1699             }
1700             (*iter)->Destroy(false);
1701         }
1702         subWindowMap_[GetWindowId()].clear();
1703         subWindowMap_.erase(GetWindowId());
1704     }
1705 }
1706 
ClearVsyncStation()1707 void WindowImpl::ClearVsyncStation()
1708 {
1709     if (vsyncStation_ != nullptr) {
1710         vsyncStation_->Destroy();
1711     }
1712 }
1713 
Destroy(uint32_t reason)1714 WMError WindowImpl::Destroy(uint32_t reason)
1715 {
1716     return Destroy(true, true, reason);
1717 }
1718 
Destroy(bool needNotifyServer,bool needClearListener,uint32_t reason)1719 WMError WindowImpl::Destroy(bool needNotifyServer, bool needClearListener, uint32_t reason)
1720 {
1721     if (!IsWindowValid()) {
1722         return WMError::WM_OK;
1723     }
1724 
1725     WLOGI("Window %{public}u Destroy, reason: %{public}u", property_->GetWindowId(), reason);
1726     WindowInspector::GetInstance().UnregisterGetWMSWindowListCallback(GetWindowId());
1727     WMError ret = WMError::WM_OK;
1728     if (needNotifyServer) {
1729         NotifyBeforeDestroy(GetWindowName());
1730         if (subWindowMap_.count(GetWindowId()) > 0) {
1731             for (auto& subWindow : subWindowMap_.at(GetWindowId())) {
1732                 NotifyBeforeSubWindowDestroy(subWindow);
1733             }
1734         }
1735         ret = SingletonContainer::Get<WindowAdapter>().DestroyWindow(property_->GetWindowId());
1736         RecordLifeCycleExceptionEvent(LifeCycleEvent::DESTROY_EVENT, ret);
1737         if (ret != WMError::WM_OK) {
1738             WLOGFE("destroy window failed with errCode:%{public}d", static_cast<int32_t>(ret));
1739             if (GetType() != WindowType::WINDOW_TYPE_DIALOG) {
1740                 return ret;
1741             }
1742         }
1743     } else {
1744         WLOGI("no need to destroy");
1745     }
1746 
1747     if (needRemoveWindowInputChannel_) {
1748         InputTransferStation::GetInstance().RemoveInputWindow(property_->GetWindowId());
1749     }
1750     {
1751         std::unique_lock<std::shared_mutex> lock(windowMapMutex_);
1752         windowMap_.erase(GetWindowName());
1753     }
1754     if (needClearListener) {
1755         ClearListenersById(GetWindowId());
1756     }
1757     DestroySubWindow();
1758     DestroyFloatingWindow();
1759     DestroyDialogWindow();
1760     ClearVsyncStation();
1761     {
1762         std::lock_guard<std::recursive_mutex> lock(mutex_);
1763         state_ = WindowState::STATE_DESTROYED;
1764     }
1765     return ret;
1766 }
1767 
NeedToStopShowing()1768 bool WindowImpl::NeedToStopShowing()
1769 {
1770     if (!WindowHelper::IsMainWindow(property_->GetWindowType())) {
1771         return false;
1772     }
1773     // show failed when current mode is not support or window only supports split mode and can show when locked
1774     bool isShowWhenLocked = GetWindowFlags() & static_cast<uint32_t>(WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED);
1775     if (!WindowHelper::IsWindowModeSupported(GetWindowModeSupportType(), GetWindowMode()) ||
1776         WindowHelper::IsOnlySupportSplitAndShowWhenLocked(isShowWhenLocked, GetWindowModeSupportType())) {
1777         WLOGFE("current mode is not supported, windowId: %{public}u, "
1778             "windowModeSupportType: %{public}u, winMode: %{public}u",
1779             property_->GetWindowId(), GetWindowModeSupportType(), GetWindowMode());
1780         return true;
1781     }
1782     return false;
1783 }
1784 
UpdateSurfaceNodeAfterCustomAnimation(bool isAdd)1785 WMError WindowImpl::UpdateSurfaceNodeAfterCustomAnimation(bool isAdd)
1786 {
1787     WLOGI("id: %{public}u UpdateRsTree, isAdd:%{public}u",
1788           property_->GetWindowId(), isAdd);
1789     if (!IsWindowValid()) {
1790         return WMError::WM_ERROR_INVALID_WINDOW;
1791     }
1792     if (!WindowHelper::IsSystemWindow(property_->GetWindowType())) {
1793         WLOGFE("only system window can set");
1794         return WMError::WM_ERROR_INVALID_OPERATION;
1795     }
1796     AdjustWindowAnimationFlag(false); // false means update rs tree with default option
1797     // need time out check
1798     WMError ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_ANIMATION_FLAG);
1799     if (ret != WMError::WM_OK) {
1800         WLOGFE("UpdateProperty failed with errCode:%{public}d", static_cast<int32_t>(ret));
1801         return ret;
1802     }
1803     ret = SingletonContainer::Get<WindowAdapter>().UpdateRsTree(property_->GetWindowId(), isAdd);
1804     if (ret != WMError::WM_OK) {
1805         WLOGFE("UpdateRsTree failed with errCode:%{public}d", static_cast<int32_t>(ret));
1806         return ret;
1807     }
1808     return WMError::WM_OK;
1809 }
1810 
AdjustWindowAnimationFlag(bool withAnimation)1811 void WindowImpl::AdjustWindowAnimationFlag(bool withAnimation)
1812 {
1813     // when show/hide with animation
1814     // use custom animation when transitionController exists; else use default animation
1815     WindowType winType = property_->GetWindowType();
1816     bool isAppWindow = WindowHelper::IsAppWindow(winType);
1817     if (withAnimation && !isAppWindow && animationTransitionController_) {
1818         // use custom animation
1819         property_->SetAnimationFlag(static_cast<uint32_t>(WindowAnimation::CUSTOM));
1820     } else if ((isAppWindow && needDefaultAnimation_) || (withAnimation && !animationTransitionController_)) {
1821         // use default animation
1822         property_->SetAnimationFlag(static_cast<uint32_t>(WindowAnimation::DEFAULT));
1823     } else if (winType == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT) {
1824         property_->SetAnimationFlag(static_cast<uint32_t>(WindowAnimation::INPUTE));
1825     } else {
1826         // with no animation
1827         property_->SetAnimationFlag(static_cast<uint32_t>(WindowAnimation::NONE));
1828     }
1829 }
1830 
PreProcessShow(uint32_t reason,bool withAnimation)1831 WMError WindowImpl::PreProcessShow(uint32_t reason, bool withAnimation)
1832 {
1833     if (state_ == WindowState::STATE_FROZEN) {
1834         WLOGFE("window is frozen, can not be shown, windowId: %{public}u", property_->GetWindowId());
1835         return WMError::WM_ERROR_INVALID_OPERATION;
1836     }
1837     SetDefaultOption();
1838     SetWindowModeSupportType(GetRequestWindowModeSupportType());
1839     AdjustWindowAnimationFlag(withAnimation);
1840 
1841     if (NeedToStopShowing()) { // true means stop showing
1842         return WMError::WM_ERROR_INVALID_WINDOW_MODE_OR_SIZE;
1843     }
1844 
1845     // update title button visibility when show
1846     UpdateTitleButtonVisibility();
1847     return WMError::WM_OK;
1848 }
1849 
NotifyMainWindowDidForeground(uint32_t reason)1850 void WindowImpl::NotifyMainWindowDidForeground(uint32_t reason)
1851 {
1852     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
1853         NotifyAfterDidForeground(reason);
1854     }
1855 }
1856 
SetShowWithOptions(bool showWithOptions)1857 void WindowImpl::SetShowWithOptions(bool showWithOptions)
1858 {
1859     showWithOptions_ = showWithOptions;
1860 }
1861 
IsShowWithOptions() const1862 bool WindowImpl::IsShowWithOptions() const
1863 {
1864     return showWithOptions_;
1865 }
1866 
Show(uint32_t reason,bool withAnimation,bool withFocus)1867 WMError WindowImpl::Show(uint32_t reason, bool withAnimation, bool withFocus)
1868 {
1869     return Show(reason, withAnimation, withFocus, false);
1870 }
1871 
Show(uint32_t reason,bool withAnimation,bool withFocus,bool waitAttach)1872 WMError WindowImpl::Show(uint32_t reason, bool withAnimation, bool withFocus, bool waitAttach)
1873 {
1874     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, __PRETTY_FUNCTION__);
1875     WLOGFD("Window Show [name:%{public}s, id:%{public}u, mode: %{public}u], reason:%{public}u, "
1876         "withAnimation:%{public}d", name_.c_str(), property_->GetWindowId(), GetWindowMode(), reason, withAnimation);
1877     if (IsShowWithOptions()) {
1878         SetShowWithOptions(false);
1879         return WMError::WM_ERROR_DEVICE_NOT_SUPPORT;
1880     }
1881     if (!IsWindowValid()) {
1882         return WMError::WM_ERROR_INVALID_WINDOW;
1883     }
1884     UpdateDecorEnable(true);
1885     if (static_cast<WindowStateChangeReason>(reason) == WindowStateChangeReason::KEYGUARD ||
1886         static_cast<WindowStateChangeReason>(reason) == WindowStateChangeReason::TOGGLING) {
1887         state_ = WindowState::STATE_SHOWN;
1888         NotifyAfterForeground();
1889         return WMError::WM_OK;
1890     }
1891     if (state_ == WindowState::STATE_SHOWN) {
1892         if (property_->GetWindowType() == WindowType::WINDOW_TYPE_DESKTOP) {
1893             SingletonContainer::Get<WindowAdapter>().MinimizeAllAppWindows(property_->GetDisplayId());
1894         } else {
1895             WLOGI("window is already shown id: %{public}u", property_->GetWindowId());
1896             SingletonContainer::Get<WindowAdapter>().ProcessPointDown(property_->GetWindowId(), false);
1897         }
1898         // when show sub window, check its parent state
1899         sptr<Window> parent = FindWindowById(property_->GetParentId());
1900         if (parent != nullptr && parent->GetWindowState() == WindowState::STATE_HIDDEN) {
1901             WLOGFD("sub window can not show, because main window hide");
1902             return WMError::WM_OK;
1903         } else {
1904             NotifyAfterForeground(true, false);
1905         }
1906         NotifyMainWindowDidForeground(reason);
1907         return WMError::WM_OK;
1908     }
1909     WMError ret = PreProcessShow(reason, withAnimation);
1910     if (ret != WMError::WM_OK) {
1911         NotifyForegroundFailed(ret);
1912         return ret;
1913     }
1914     // this lock solves the multithreading problem when reading WindowState
1915     std::lock_guard<std::recursive_mutex> lock(windowStateMutex_);
1916     ret = SingletonContainer::Get<WindowAdapter>().AddWindow(property_);
1917     RecordLifeCycleExceptionEvent(LifeCycleEvent::SHOW_EVENT, ret);
1918     if (ret == WMError::WM_OK) {
1919         UpdateWindowStateWhenShow();
1920         NotifyMainWindowDidForeground(reason);
1921     } else {
1922         NotifyForegroundFailed(ret);
1923         WLOGFE("show window id:%{public}u errCode:%{public}d", property_->GetWindowId(), static_cast<int32_t>(ret));
1924     }
1925     // systemui make startbar resident, when refactor immersive, this code can delete
1926     if (property_->GetRequestedOrientation() == Orientation::HORIZONTAL
1927         || property_->GetRequestedOrientation() == Orientation::REVERSE_HORIZONTAL) {
1928         RemoveWindowFlag(WindowFlag::WINDOW_FLAG_NEED_AVOID);
1929     }
1930     needNotifyFocusLater_ = false;
1931     return ret;
1932 }
1933 
ShowKeyboard(KeyboardEffectOption effectOption)1934 WMError WindowImpl::ShowKeyboard(KeyboardEffectOption effectOption)
1935 {
1936     return Show();
1937 }
1938 
Hide(uint32_t reason,bool withAnimation,bool isFromInnerkits)1939 WMError WindowImpl::Hide(uint32_t reason, bool withAnimation, bool isFromInnerkits)
1940 {
1941     return Hide(reason, withAnimation, isFromInnerkits, false);
1942 }
1943 
Hide(uint32_t reason,bool withAnimation,bool isFromInnerkits,bool waitDetach)1944 WMError WindowImpl::Hide(uint32_t reason, bool withAnimation, bool isFromInnerkits, bool waitDetach)
1945 {
1946     WLOGD("id:%{public}u Hide, reason:%{public}u, Animation:%{public}d",
1947         property_->GetWindowId(), reason, withAnimation);
1948     if (!IsWindowValid()) {
1949         return WMError::WM_ERROR_INVALID_WINDOW;
1950     }
1951     WindowStateChangeReason stateChangeReason = static_cast<WindowStateChangeReason>(reason);
1952     if (stateChangeReason == WindowStateChangeReason::KEYGUARD ||
1953         stateChangeReason == WindowStateChangeReason::TOGGLING) {
1954         state_ = stateChangeReason == WindowStateChangeReason::KEYGUARD ?
1955             WindowState::STATE_FROZEN : WindowState::STATE_HIDDEN;
1956         NotifyAfterBackground();
1957         return WMError::WM_OK;
1958     }
1959     if (state_ == WindowState::STATE_HIDDEN || state_ == WindowState::STATE_CREATED) {
1960         WLOGI("already hidden, id: %{public}u", property_->GetWindowId());
1961         NotifyBackgroundFailed(WMError::WM_DO_NOTHING);
1962         return WMError::WM_OK;
1963     }
1964     WMError ret = WMError::WM_OK;
1965     if (WindowHelper::IsSystemWindow(property_->GetWindowType())) {
1966         AdjustWindowAnimationFlag(withAnimation);
1967         // when show(true) with default, hide() with None, to adjust animationFlag to disabled default animation
1968         ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_ANIMATION_FLAG);
1969         if (ret != WMError::WM_OK) {
1970             WLOGFE("UpdateProperty failed with errCode:%{public}d", static_cast<int32_t>(ret));
1971             return ret;
1972         }
1973     }
1974     ret = SingletonContainer::Get<WindowAdapter>().RemoveWindow(property_->GetWindowId(), isFromInnerkits);
1975     RecordLifeCycleExceptionEvent(LifeCycleEvent::HIDE_EVENT, ret);
1976     if (ret != WMError::WM_OK) {
1977         WLOGFE("hide errCode:%{public}d for winId:%{public}u", static_cast<int32_t>(ret), property_->GetWindowId());
1978         return ret;
1979     }
1980     UpdateWindowStateWhenHide();
1981     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
1982         NotifyAfterDidBackground(reason);
1983     }
1984     uint32_t animationFlag = property_->GetAnimationFlag();
1985     if (animationFlag == static_cast<uint32_t>(WindowAnimation::CUSTOM)) {
1986         animationTransitionController_->AnimationForHidden();
1987     }
1988     ResetMoveOrDragState();
1989     escKeyEventTriggered_ = false;
1990     return ret;
1991 }
1992 
MoveTo(int32_t x,int32_t y,bool isMoveToGlobal,MoveConfiguration moveConfiguration)1993 WMError WindowImpl::MoveTo(int32_t x, int32_t y, bool isMoveToGlobal, MoveConfiguration moveConfiguration)
1994 {
1995     WLOGFD("id:%{public}d MoveTo %{public}d %{public}d",
1996           property_->GetWindowId(), x, y);
1997     if (!IsWindowValid()) {
1998         return WMError::WM_ERROR_INVALID_WINDOW;
1999     }
2000 
2001     Rect rect = (WindowHelper::IsMainFloatingWindow(GetType(), GetWindowMode())) ?
2002         GetRect() : property_->GetRequestRect();
2003     Rect moveRect = { x, y, rect.width_, rect.height_ }; // must keep w/h, which may maintain stashed resize info
2004     property_->SetRequestRect(moveRect);
2005     {
2006         // this lock solves the multithreading problem when reading WindowState
2007         std::lock_guard<std::recursive_mutex> lock(windowStateMutex_);
2008         if (state_ == WindowState::STATE_HIDDEN || state_ == WindowState::STATE_CREATED) {
2009         WLOGFD("window is hidden or created! id: %{public}u, oriPos: [%{public}d, %{public}d, "
2010                "movePos: [%{public}d, %{public}d]", property_->GetWindowId(), rect.posX_, rect.posY_, x, y);
2011         return WMError::WM_OK;
2012         }
2013     }
2014 
2015     if (GetWindowMode() != WindowMode::WINDOW_MODE_FLOATING) {
2016         WLOGFE("fullscreen window could not moveto, winId: %{public}u", GetWindowId());
2017         return WMError::WM_ERROR_INVALID_OPERATION;
2018     }
2019     property_->SetWindowSizeChangeReason(WindowSizeChangeReason::MOVE);
2020     return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_RECT);
2021 }
2022 
Resize(uint32_t width,uint32_t height,const RectAnimationConfig & rectAnimationConfig)2023 WMError WindowImpl::Resize(uint32_t width, uint32_t height, const RectAnimationConfig& rectAnimationConfig)
2024 {
2025     WLOGFD("id:%{public}d Resize %{public}u %{public}u",
2026           property_->GetWindowId(), width, height);
2027     if (!IsWindowValid()) {
2028         return WMError::WM_ERROR_INVALID_WINDOW;
2029     }
2030 
2031     Rect rect = (WindowHelper::IsMainFloatingWindow(GetType(), GetWindowMode())) ?
2032         GetRect() : property_->GetRequestRect();
2033     Rect resizeRect = { rect.posX_, rect.posY_, width, height };
2034     property_->SetRequestRect(resizeRect);
2035     property_->SetDecoStatus(false);
2036     {
2037         // this lock solves the multithreading problem when reading WindowState
2038         std::lock_guard<std::recursive_mutex> lock(windowStateMutex_);
2039         if (state_ == WindowState::STATE_HIDDEN || state_ == WindowState::STATE_CREATED) {
2040         WLOGFD("window is hidden or created! id: %{public}u, oriRect: [%{public}u, %{public}u], "
2041                "resizeRect: [%{public}u, %{public}u]", property_->GetWindowId(), rect.width_,
2042                rect.height_, width, height);
2043         return WMError::WM_OK;
2044         }
2045     }
2046 
2047     if (GetWindowMode() != WindowMode::WINDOW_MODE_FLOATING) {
2048         WLOGFE("fullscreen window could not resize, winId: %{public}u", GetWindowId());
2049         return WMError::WM_ERROR_INVALID_OPERATION;
2050     }
2051     property_->SetWindowSizeChangeReason(WindowSizeChangeReason::RESIZE);
2052     return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_RECT);
2053 }
2054 
SetWindowGravity(WindowGravity gravity,uint32_t percent)2055 WMError WindowImpl::SetWindowGravity(WindowGravity gravity, uint32_t percent)
2056 {
2057     WLOGFD("id:%{public}d SetWindowGravity %{public}u %{public}u",
2058         property_->GetWindowId(), gravity, percent);
2059 
2060     return SingletonContainer::Get<WindowAdapter>().SetWindowGravity(property_->GetWindowId(), gravity, percent);
2061 }
2062 
SetKeepScreenOn(bool keepScreenOn)2063 WMError WindowImpl::SetKeepScreenOn(bool keepScreenOn)
2064 {
2065     if (!IsWindowValid()) {
2066         return WMError::WM_ERROR_INVALID_WINDOW;
2067     }
2068     property_->SetKeepScreenOn(keepScreenOn);
2069     if (state_ == WindowState::STATE_SHOWN) {
2070         return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_KEEP_SCREEN_ON);
2071     }
2072     return WMError::WM_OK;
2073 }
2074 
IsKeepScreenOn() const2075 bool WindowImpl::IsKeepScreenOn() const
2076 {
2077     if (!IsWindowValid()) {
2078         return false;
2079     }
2080     return property_->IsKeepScreenOn();
2081 }
2082 
SetTurnScreenOn(bool turnScreenOn)2083 WMError WindowImpl::SetTurnScreenOn(bool turnScreenOn)
2084 {
2085     if (!IsWindowValid()) {
2086         return WMError::WM_ERROR_INVALID_WINDOW;
2087     }
2088     property_->SetTurnScreenOn(turnScreenOn);
2089     if (state_ == WindowState::STATE_SHOWN) {
2090         return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_TURN_SCREEN_ON);
2091     }
2092     return WMError::WM_OK;
2093 }
2094 
IsTurnScreenOn() const2095 bool WindowImpl::IsTurnScreenOn() const
2096 {
2097     if (!IsWindowValid()) {
2098         return false;
2099     }
2100     return property_->IsTurnScreenOn();
2101 }
2102 
SetBackgroundColor(uint32_t color)2103 WMError WindowImpl::SetBackgroundColor(uint32_t color)
2104 {
2105     // 0xff000000: ARGB style, means Opaque color.
2106     const bool isAlphaZero = !(color & 0xff000000);
2107     auto abilityInfo = property_->GetAbilityInfo();
2108     if (isAlphaZero && WindowHelper::IsMainWindow(property_->GetWindowType())) {
2109         auto& reportInstance = SingletonContainer::Get<WindowInfoReporter>();
2110         reportInstance.ReportZeroOpacityInfoImmediately(abilityInfo.bundleName_,
2111             abilityInfo.abilityName_);
2112     }
2113 
2114     if (uiContent_ != nullptr) {
2115         uiContent_->SetBackgroundColor(color);
2116         return WMError::WM_OK;
2117     }
2118     WLOGI("ace is null, Id: %{public}u", GetWindowId());
2119     if (aceAbilityHandler_ != nullptr) {
2120         aceAbilityHandler_->SetBackgroundColor(color);
2121         return WMError::WM_OK;
2122     }
2123     WLOGFE("FA mode could not set bg color: %{public}u", GetWindowId());
2124     return WMError::WM_ERROR_INVALID_OPERATION;
2125 }
2126 
GetBackgroundColor() const2127 uint32_t WindowImpl::GetBackgroundColor() const
2128 {
2129     if (uiContent_ != nullptr) {
2130         return uiContent_->GetBackgroundColor();
2131     }
2132     WLOGD("uiContent is nullptr, windowId: %{public}u, use FA mode", GetWindowId());
2133     if (aceAbilityHandler_ != nullptr) {
2134         return aceAbilityHandler_->GetBackgroundColor();
2135     }
2136     WLOGFE("FA mode does not get bg color: %{public}u", GetWindowId());
2137     return 0xffffffff; // means no background color been set, default color is white
2138 }
2139 
SetBackgroundColor(const std::string & color)2140 WMError WindowImpl::SetBackgroundColor(const std::string& color)
2141 {
2142     if (!IsWindowValid()) {
2143         return WMError::WM_ERROR_INVALID_WINDOW;
2144     }
2145     uint32_t colorValue;
2146     if (ColorParser::Parse(color, colorValue)) {
2147         WLOGD("SetBackgroundColor: window: %{public}s, value: [%{public}s, %{public}u]",
2148             name_.c_str(), color.c_str(), colorValue);
2149         return SetBackgroundColor(colorValue);
2150     }
2151     WLOGFE("invalid color string: %{public}s", color.c_str());
2152     return WMError::WM_ERROR_INVALID_PARAM;
2153 }
2154 
SetTransparent(bool isTransparent)2155 WMError WindowImpl::SetTransparent(bool isTransparent)
2156 {
2157     if (!IsWindowValid()) {
2158         return WMError::WM_ERROR_INVALID_WINDOW;
2159     }
2160     ColorParam backgroundColor;
2161     backgroundColor.value = GetBackgroundColor();
2162     if (isTransparent) {
2163         backgroundColor.argb.alpha = 0x00; // 0x00: completely transparent
2164         return SetBackgroundColor(backgroundColor.value);
2165     } else {
2166         backgroundColor.value = GetBackgroundColor();
2167         if (backgroundColor.argb.alpha == 0x00) {
2168             backgroundColor.argb.alpha = 0xff; // 0xff: completely opaque
2169             return SetBackgroundColor(backgroundColor.value);
2170         }
2171     }
2172     return WMError::WM_OK;
2173 }
2174 
IsTransparent() const2175 bool WindowImpl::IsTransparent() const
2176 {
2177     if (!IsWindowValid()) {
2178         return false;
2179     }
2180     ColorParam backgroundColor;
2181     backgroundColor.value = GetBackgroundColor();
2182     WLOGFD("color: %{public}u, alpha: %{public}u", backgroundColor.value, backgroundColor.argb.alpha);
2183     return backgroundColor.argb.alpha == 0x00; // 0x00: completely transparent
2184 }
2185 
SetBrightness(float brightness)2186 WMError WindowImpl::SetBrightness(float brightness)
2187 {
2188     if (!IsWindowValid()) {
2189         return WMError::WM_ERROR_INVALID_WINDOW;
2190     }
2191     if ((brightness < MINIMUM_BRIGHTNESS &&
2192          std::fabs(brightness - UNDEFINED_BRIGHTNESS) >= std::numeric_limits<float>::min()) ||
2193          brightness > MAXIMUM_BRIGHTNESS) {
2194         WLOGFE("invalid brightness value: %{public}f", brightness);
2195         return WMError::WM_ERROR_INVALID_PARAM;
2196     }
2197     if (!WindowHelper::IsAppWindow(GetType())) {
2198         WLOGFE("non app window does not support set brightness, type: %{public}u", GetType());
2199         return WMError::WM_ERROR_INVALID_TYPE;
2200     }
2201     property_->SetBrightness(brightness);
2202     if (state_ == WindowState::STATE_SHOWN) {
2203         return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_SET_BRIGHTNESS);
2204     }
2205     return WMError::WM_OK;
2206 }
2207 
GetBrightness() const2208 float WindowImpl::GetBrightness() const
2209 {
2210     return property_->GetBrightness();
2211 }
2212 
SetCallingWindow(uint32_t windowId)2213 WMError WindowImpl::SetCallingWindow(uint32_t windowId)
2214 {
2215     if (!IsWindowValid()) {
2216         return WMError::WM_ERROR_INVALID_WINDOW;
2217     }
2218     property_->SetCallingWindow(windowId);
2219     return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_CALLING_WINDOW);
2220 }
2221 
RecordLifeCycleExceptionEvent(LifeCycleEvent event,WMError errCode) const2222 void WindowImpl::RecordLifeCycleExceptionEvent(LifeCycleEvent event, WMError errCode) const
2223 {
2224     if (!(errCode > WMError::WM_ERROR_NEED_REPORT_BASE && errCode < WMError::WM_ERROR_NEED_REPORT_END)) {
2225         return;
2226     }
2227     std::ostringstream oss;
2228     oss << "life cycle is abnormal: " << "window_name: " << name_
2229         << ", id:" << GetWindowId() << ", event: " << TransferLifeCycleEventToString(event)
2230         << ", errCode: " << static_cast<int32_t>(errCode) << ";";
2231     std::string info = oss.str();
2232     WLOGI("window life cycle exception: %{public}s", info.c_str());
2233     int32_t ret = HiSysEventWrite(
2234         OHOS::HiviewDFX::HiSysEvent::Domain::WINDOW_MANAGER,
2235         "WINDOW_LIFE_CYCLE_EXCEPTION",
2236         OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
2237         "PID", getpid(),
2238         "UID", getuid(),
2239         "MSG", info);
2240     if (ret != 0) {
2241         WLOGFE("Write HiSysEvent error, ret:%{public}d", ret);
2242     }
2243 }
2244 
TransferLifeCycleEventToString(LifeCycleEvent type) const2245 std::string WindowImpl::TransferLifeCycleEventToString(LifeCycleEvent type) const
2246 {
2247     std::string event;
2248     switch (type) {
2249         case LifeCycleEvent::CREATE_EVENT:
2250             event = "CREATE";
2251             break;
2252         case LifeCycleEvent::SHOW_EVENT:
2253             event = "SHOW";
2254             break;
2255         case LifeCycleEvent::HIDE_EVENT:
2256             event = "HIDE";
2257             break;
2258         case LifeCycleEvent::DESTROY_EVENT:
2259             event = "DESTROY";
2260             break;
2261         default:
2262             event = "UNDEFINE";
2263             break;
2264     }
2265     return event;
2266 }
2267 
SetPrivacyMode(bool isPrivacyMode)2268 WMError WindowImpl::SetPrivacyMode(bool isPrivacyMode)
2269 {
2270     if (!IsWindowValid()) {
2271         return WMError::WM_ERROR_INVALID_WINDOW;
2272     }
2273     WLOGFD("id : %{public}u, SetPrivacyMode, %{public}u", GetWindowId(), isPrivacyMode);
2274     property_->SetPrivacyMode(isPrivacyMode);
2275     return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_PRIVACY_MODE);
2276 }
2277 
IsPrivacyMode() const2278 bool WindowImpl::IsPrivacyMode() const
2279 {
2280     if (!IsWindowValid()) {
2281         return false;
2282     }
2283     return property_->GetPrivacyMode();
2284 }
2285 
SetSystemPrivacyMode(bool isSystemPrivacyMode)2286 void WindowImpl::SetSystemPrivacyMode(bool isSystemPrivacyMode)
2287 {
2288     WLOGFD("id : %{public}u, SetSystemPrivacyMode, %{public}u", GetWindowId(), isSystemPrivacyMode);
2289     property_->SetSystemPrivacyMode(isSystemPrivacyMode);
2290     UpdateProperty(PropertyChangeAction::ACTION_UPDATE_SYSTEM_PRIVACY_MODE);
2291 }
2292 
SetSnapshotSkip(bool isSkip)2293 WMError WindowImpl::SetSnapshotSkip(bool isSkip)
2294 {
2295     if (!IsWindowValid()) {
2296         return WMError::WM_ERROR_INVALID_WINDOW;
2297     }
2298     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
2299         WLOGFE("set snapshot skip permission denied!");
2300         return WMError::WM_ERROR_NOT_SYSTEM_APP;
2301     }
2302     property_->SetSnapshotSkip(isSkip);
2303     auto ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_SNAPSHOT_SKIP);
2304     WLOGFD("id : %{public}u, set snapshot skip end. isSkip:%{public}u, systemPrivacyMode:%{public}u, ret:%{public}u",
2305         GetWindowId(), isSkip, property_->GetSystemPrivacyMode(), ret);
2306     return WMError::WM_OK;
2307 }
2308 
2309 /** @note @window.hierarchy */
RaiseToAppTop()2310 WMError WindowImpl::RaiseToAppTop()
2311 {
2312     if (!IsWindowValid()) {
2313         TLOGE(WmsLogTag::WMS_HIERARCHY, "Window is invalid");
2314         return WMError::WM_ERROR_INVALID_WINDOW;
2315     }
2316 
2317     auto parentId = property_->GetParentId();
2318     if (parentId == INVALID_WINDOW_ID) {
2319         WLOGFE("Only the children of the main window can be raised!");
2320         return WMError::WM_ERROR_INVALID_PARENT;
2321     }
2322 
2323     if (!WindowHelper::IsSubWindow(property_->GetWindowType())) {
2324         WLOGFE("Must be app sub window window!");
2325         return WMError::WM_ERROR_INVALID_CALLING;
2326     }
2327 
2328     if (state_ != WindowState::STATE_SHOWN) {
2329         WLOGFE("The sub window must be shown!");
2330         return WMError::WM_DO_NOTHING;
2331     }
2332 
2333     return SingletonContainer::Get<WindowAdapter>().RaiseToAppTop(GetWindowId());
2334 }
2335 
DisableAppWindowDecor()2336 WMError WindowImpl::DisableAppWindowDecor()
2337 {
2338     if (!IsWindowValid()) {
2339         return WMError::WM_ERROR_INVALID_WINDOW;
2340     }
2341     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
2342         WLOGFE("disable app window decor permission denied!");
2343         return WMError::WM_ERROR_NOT_SYSTEM_APP;
2344     }
2345     if (!WindowHelper::IsMainWindow(property_->GetWindowType())) {
2346         WLOGFE("window decoration is invalid on sub window");
2347         return WMError::WM_ERROR_INVALID_OPERATION;
2348     }
2349     WLOGI("disable app window decoration.");
2350     windowSystemConfig_.isSystemDecorEnable_ = false;
2351     UpdateDecorEnable(true);
2352     return WMError::WM_OK;
2353 }
2354 
IsDecorEnable() const2355 bool WindowImpl::IsDecorEnable() const
2356 {
2357     bool enable = windowSystemConfig_.isSystemDecorEnable_ &&
2358         WindowHelper::IsMainWindow(property_->GetWindowType());
2359     WLOGFD("get decor enable %{public}d", enable);
2360     return enable;
2361 }
2362 
Maximize()2363 WMError WindowImpl::Maximize()
2364 {
2365     WLOGI("id: %{public}u Maximize", property_->GetWindowId());
2366     if (!IsWindowValid()) {
2367         return WMError::WM_ERROR_INVALID_WINDOW;
2368     }
2369     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
2370         return SetFullScreen(true);
2371     } else {
2372         WLOGI("Maximize fail, not main window");
2373         return WMError::WM_ERROR_INVALID_PARAM;
2374     }
2375 }
2376 
MaximizeFloating()2377 WMError WindowImpl::MaximizeFloating()
2378 {
2379     WLOGI("id: %{public}u MaximizeFloating", property_->GetWindowId());
2380     if (!IsWindowValid()) {
2381         return WMError::WM_ERROR_INVALID_WINDOW;
2382     }
2383     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
2384         return SetFloatingMaximize(true);
2385     } else {
2386         WLOGI("MaximizeFloating fail, not main window");
2387         return WMError::WM_ERROR_INVALID_PARAM;
2388     }
2389 }
2390 
SetGlobalMaximizeMode(MaximizeMode mode)2391 WMError WindowImpl::SetGlobalMaximizeMode(MaximizeMode mode)
2392 {
2393     WLOGI("id: %{public}u SetGlobalMaximizeMode: %{public}u", property_->GetWindowId(),
2394         static_cast<uint32_t>(mode));
2395     if (!IsWindowValid()) {
2396         return WMError::WM_ERROR_INVALID_WINDOW;
2397     }
2398     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
2399         SingletonContainer::Get<WindowAdapter>().SetMaximizeMode(mode);
2400         return WMError::WM_OK;
2401     } else {
2402         WLOGI("SetGlobalMaximizeMode fail, not main window");
2403         return WMError::WM_ERROR_INVALID_PARAM;
2404     }
2405 }
2406 
GetGlobalMaximizeMode() const2407 MaximizeMode WindowImpl::GetGlobalMaximizeMode() const
2408 {
2409     return SingletonContainer::Get<WindowAdapter>().GetMaximizeMode();
2410 }
2411 
SetImmersiveModeEnabledState(bool enable)2412 WMError WindowImpl::SetImmersiveModeEnabledState(bool enable)
2413 {
2414     TLOGD(WmsLogTag::WMS_IMMS, "WindowImpl id: %{public}u SetImmersiveModeEnabledState: %{public}u",
2415         property_->GetWindowId(), static_cast<uint32_t>(enable));
2416     if (!IsWindowValid() ||
2417         !WindowHelper::IsWindowModeSupported(GetWindowModeSupportType(), WindowMode::WINDOW_MODE_FULLSCREEN)) {
2418         TLOGE(WmsLogTag::WMS_IMMS, "invalid window or fullscreen mode is not be supported, winId:%{public}u",
2419             property_->GetWindowId());
2420         return WMError::WM_ERROR_INVALID_WINDOW;
2421     }
2422     const WindowType curWindowType = GetType();
2423     if (!WindowHelper::IsMainWindow(curWindowType) && !WindowHelper::IsSubWindow(curWindowType)) {
2424         return WMError::WM_ERROR_INVALID_WINDOW;
2425     }
2426 
2427     enableImmersiveMode_ = enable;
2428     const WindowMode mode = GetWindowMode();
2429     if (mode == WindowMode::WINDOW_MODE_FULLSCREEN) {
2430         return SetLayoutFullScreen(enableImmersiveMode_);
2431     }
2432     return WMError::WM_OK;
2433 }
2434 
GetImmersiveModeEnabledState() const2435 bool WindowImpl::GetImmersiveModeEnabledState() const
2436 {
2437     if (!IsWindowValid()) {
2438         return false;
2439     }
2440     return enableImmersiveMode_;
2441 }
2442 
NotifyWindowTransition(TransitionReason reason)2443 WMError WindowImpl::NotifyWindowTransition(TransitionReason reason)
2444 {
2445     sptr<WindowTransitionInfo> fromInfo = new(std::nothrow) WindowTransitionInfo();
2446     sptr<WindowTransitionInfo> toInfo = new(std::nothrow) WindowTransitionInfo();
2447     if (fromInfo == nullptr || toInfo == nullptr) {
2448         WLOGFE("new windowTransitionInfo failed");
2449         return WMError::WM_ERROR_NO_MEM;
2450     }
2451     auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
2452     if (abilityContext == nullptr) {
2453         WLOGFE("id:%{public}d is not ability Window", property_->GetWindowId());
2454         return WMError::WM_ERROR_NO_MEM;
2455     }
2456     auto abilityInfo = abilityContext->GetAbilityInfo();
2457     if (abilityInfo == nullptr) {
2458         return WMError::WM_ERROR_NULLPTR;
2459     }
2460     fromInfo->SetBundleName(context_->GetBundleName());
2461     fromInfo->SetAbilityName(abilityInfo->name);
2462     fromInfo->SetWindowMode(property_->GetWindowMode());
2463     fromInfo->SetWindowRect(property_->GetWindowRect());
2464     fromInfo->SetAbilityToken(context_->GetToken());
2465     fromInfo->SetWindowType(property_->GetWindowType());
2466     fromInfo->SetDisplayId(property_->GetDisplayId());
2467     fromInfo->SetTransitionReason(reason);
2468     return SingletonContainer::Get<WindowAdapter>().NotifyWindowTransition(fromInfo, toInfo);
2469 }
2470 
Minimize()2471 WMError WindowImpl::Minimize()
2472 {
2473     WLOGI("id: %{public}u Minimize", property_->GetWindowId());
2474     if (!IsWindowValid()) {
2475         return WMError::WM_ERROR_INVALID_WINDOW;
2476     }
2477     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
2478         if (context_ != nullptr) {
2479             WMError ret = NotifyWindowTransition(TransitionReason::MINIMIZE);
2480             if (ret != WMError::WM_OK) {
2481                 WLOGI("Minimize without animation ret:%{public}u", static_cast<uint32_t>(ret));
2482                 AAFwk::AbilityManagerClient::GetInstance()->MinimizeAbility(context_->GetToken(), true);
2483             }
2484         } else {
2485             Hide();
2486         }
2487     }
2488     return WMError::WM_OK;
2489 }
2490 
Recover()2491 WMError WindowImpl::Recover()
2492 {
2493     WLOGI("id: %{public}u Normalize", property_->GetWindowId());
2494     if (!IsWindowValid()) {
2495         return WMError::WM_ERROR_INVALID_WINDOW;
2496     }
2497     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
2498         if (property_->GetWindowMode() == WindowMode::WINDOW_MODE_FLOATING &&
2499             property_->GetMaximizeMode() == MaximizeMode::MODE_AVOID_SYSTEM_BAR) {
2500             SetFloatingMaximize(false);
2501             return WMError::WM_OK;
2502         }
2503         SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
2504     }
2505     return WMError::WM_OK;
2506 }
2507 
Close()2508 WMError WindowImpl::Close()
2509 {
2510     WLOGI("id: %{public}u Close", property_->GetWindowId());
2511     if (!IsWindowValid()) {
2512         return WMError::WM_ERROR_INVALID_WINDOW;
2513     }
2514     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
2515         auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
2516         if (!abilityContext) {
2517             return Destroy();
2518         }
2519         sptr<AAFwk::IPrepareTerminateCallback> callback = this;
2520         if (AAFwk::AbilityManagerClient::GetInstance()->PrepareTerminateAbility(abilityContext->GetToken(),
2521             callback) != ERR_OK) {
2522             WLOGFW("RegisterWindowManagerServiceHandler failed, do close window");
2523             PendingClose();
2524             return WMError::WM_OK;
2525         }
2526     }
2527     return WMError::WM_OK;
2528 }
2529 
DoPrepareTerminate()2530 void WindowImpl::DoPrepareTerminate()
2531 {
2532     WLOGFI("do pending close by ability");
2533     PendingClose();
2534 }
2535 
PendingClose()2536 void WindowImpl::PendingClose()
2537 {
2538     WLOGFD("begin");
2539     WMError ret = NotifyWindowTransition(TransitionReason::CLOSE_BUTTON);
2540     if (ret != WMError::WM_OK) {
2541         WLOGI("Close without animation ret:%{public}u", static_cast<uint32_t>(ret));
2542         auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
2543         if (abilityContext != nullptr) {
2544             abilityContext->CloseAbility();
2545         }
2546     }
2547 }
2548 
RequestFocus() const2549 WMError WindowImpl::RequestFocus() const
2550 {
2551     if (!IsWindowValid()) {
2552         return WMError::WM_ERROR_INVALID_WINDOW;
2553     }
2554     return SingletonContainer::Get<WindowAdapter>().RequestFocus(property_->GetWindowId());
2555 }
2556 
SetInputEventConsumer(const std::shared_ptr<IInputEventConsumer> & inputEventConsumer)2557 void WindowImpl::SetInputEventConsumer(const std::shared_ptr<IInputEventConsumer>& inputEventConsumer)
2558 {
2559     std::lock_guard<std::recursive_mutex> lock(mutex_);
2560     inputEventConsumer_ = inputEventConsumer;
2561 }
2562 
RegisterLifeCycleListener(const sptr<IWindowLifeCycle> & listener)2563 WMError WindowImpl::RegisterLifeCycleListener(const sptr<IWindowLifeCycle>& listener)
2564 {
2565     WLOGFD("Start register");
2566     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2567     return RegisterListener(lifecycleListeners_[GetWindowId()], listener);
2568 }
2569 
UnregisterLifeCycleListener(const sptr<IWindowLifeCycle> & listener)2570 WMError WindowImpl::UnregisterLifeCycleListener(const sptr<IWindowLifeCycle>& listener)
2571 {
2572     WLOGFD("Start unregister");
2573     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2574     return UnregisterListener(lifecycleListeners_[GetWindowId()], listener);
2575 }
2576 
RegisterWindowChangeListener(const sptr<IWindowChangeListener> & listener)2577 WMError WindowImpl::RegisterWindowChangeListener(const sptr<IWindowChangeListener>& listener)
2578 {
2579     WLOGFD("Start register");
2580     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2581     return RegisterListener(windowChangeListeners_[GetWindowId()], listener);
2582 }
2583 
UnregisterWindowChangeListener(const sptr<IWindowChangeListener> & listener)2584 WMError WindowImpl::UnregisterWindowChangeListener(const sptr<IWindowChangeListener>& listener)
2585 {
2586     WLOGFD("Start unregister");
2587     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2588     return UnregisterListener(windowChangeListeners_[GetWindowId()], listener);
2589 }
2590 
RegisterAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener> & listener)2591 WMError WindowImpl::RegisterAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener>& listener)
2592 {
2593     WLOGFD("Start register");
2594     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2595     WMError ret = RegisterListener(avoidAreaChangeListeners_[GetWindowId()], listener);
2596     if (avoidAreaChangeListeners_[GetWindowId()].size() == 1) {
2597         SingletonContainer::Get<WindowAdapter>().UpdateAvoidAreaListener(property_->GetWindowId(), true);
2598     }
2599     return ret;
2600 }
2601 
UnregisterAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener> & listener)2602 WMError WindowImpl::UnregisterAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener>& listener)
2603 {
2604     WLOGFD("Start unregister");
2605     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2606     WMError ret = UnregisterListener(avoidAreaChangeListeners_[GetWindowId()], listener);
2607     if (avoidAreaChangeListeners_[GetWindowId()].empty()) {
2608         SingletonContainer::Get<WindowAdapter>().UpdateAvoidAreaListener(property_->GetWindowId(), false);
2609     }
2610     return ret;
2611 }
2612 
RegisterDragListener(const sptr<IWindowDragListener> & listener)2613 WMError WindowImpl::RegisterDragListener(const sptr<IWindowDragListener>& listener)
2614 {
2615     WLOGFD("Start register");
2616     std::lock_guard<std::recursive_mutex> lock(mutex_);
2617     return RegisterListener(windowDragListeners_, listener);
2618 }
2619 
UnregisterDragListener(const sptr<IWindowDragListener> & listener)2620 WMError WindowImpl::UnregisterDragListener(const sptr<IWindowDragListener>& listener)
2621 {
2622     WLOGFD("Start unregister");
2623     std::lock_guard<std::recursive_mutex> lock(mutex_);
2624     return UnregisterListener(windowDragListeners_, listener);
2625 }
2626 
RegisterDisplayMoveListener(sptr<IDisplayMoveListener> & listener)2627 WMError WindowImpl::RegisterDisplayMoveListener(sptr<IDisplayMoveListener>& listener)
2628 {
2629     WLOGFD("Start register");
2630     std::lock_guard<std::recursive_mutex> lock(mutex_);
2631     return RegisterListener(displayMoveListeners_, listener);
2632 }
2633 
UnregisterDisplayMoveListener(sptr<IDisplayMoveListener> & listener)2634 WMError WindowImpl::UnregisterDisplayMoveListener(sptr<IDisplayMoveListener>& listener)
2635 {
2636     WLOGFD("Start unregister");
2637     std::lock_guard<std::recursive_mutex> lock(mutex_);
2638     return UnregisterListener(displayMoveListeners_, listener);
2639 }
2640 
RegisterWindowDestroyedListener(const NotifyNativeWinDestroyFunc & func)2641 void WindowImpl::RegisterWindowDestroyedListener(const NotifyNativeWinDestroyFunc& func)
2642 {
2643     WLOGFD("Start register");
2644     notifyNativefunc_ = std::move(func);
2645 }
2646 
RegisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener> & listener)2647 WMError WindowImpl::RegisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener>& listener)
2648 {
2649     WLOGFD("Start register");
2650     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2651     return RegisterListener(occupiedAreaChangeListeners_[GetWindowId()], listener);
2652 }
2653 
UnregisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener> & listener)2654 WMError WindowImpl::UnregisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener>& listener)
2655 {
2656     WLOGFD("Start unregister");
2657     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2658     return UnregisterListener(occupiedAreaChangeListeners_[GetWindowId()], listener);
2659 }
2660 
RegisterTouchOutsideListener(const sptr<ITouchOutsideListener> & listener)2661 WMError WindowImpl::RegisterTouchOutsideListener(const sptr<ITouchOutsideListener>& listener)
2662 {
2663     WLOGFD("Start register");
2664     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2665     return RegisterListener(touchOutsideListeners_[GetWindowId()], listener);
2666 }
2667 
UnregisterTouchOutsideListener(const sptr<ITouchOutsideListener> & listener)2668 WMError WindowImpl::UnregisterTouchOutsideListener(const sptr<ITouchOutsideListener>& listener)
2669 {
2670     WLOGFD("Start unregister");
2671     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2672     return UnregisterListener(touchOutsideListeners_[GetWindowId()], listener);
2673 }
2674 
RegisterAnimationTransitionController(const sptr<IAnimationTransitionController> & listener)2675 WMError WindowImpl::RegisterAnimationTransitionController(const sptr<IAnimationTransitionController>& listener)
2676 {
2677     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
2678         WLOGFE("register animation transition controller permission denied!");
2679         return WMError::WM_ERROR_NOT_SYSTEM_APP;
2680     }
2681     if (listener == nullptr) {
2682         WLOGFE("listener is nullptr");
2683         return WMError::WM_ERROR_NULLPTR;
2684     }
2685     animationTransitionController_ = listener;
2686     wptr<WindowProperty> propertyToken(property_);
2687     wptr<IAnimationTransitionController> animationTransitionControllerToken(animationTransitionController_);
2688     if (uiContent_) {
2689         uiContent_->SetNextFrameLayoutCallback([propertyToken, animationTransitionControllerToken]() {
2690             auto property = propertyToken.promote();
2691             auto animationTransitionController = animationTransitionControllerToken.promote();
2692             if (!property || !animationTransitionController) {
2693                 return;
2694             }
2695             uint32_t animationFlag = property->GetAnimationFlag();
2696             if (animationFlag == static_cast<uint32_t>(WindowAnimation::CUSTOM)) {
2697                 // CustomAnimation is enabled when animationTransitionController_ exists
2698                 animationTransitionController->AnimationForShown();
2699             }
2700         });
2701     }
2702     return WMError::WM_OK;
2703 }
2704 
RegisterScreenshotListener(const sptr<IScreenshotListener> & listener)2705 WMError WindowImpl::RegisterScreenshotListener(const sptr<IScreenshotListener>& listener)
2706 {
2707     WLOGFD("Start register");
2708     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2709     return RegisterListener(screenshotListeners_[GetWindowId()], listener);
2710 }
2711 
UnregisterScreenshotListener(const sptr<IScreenshotListener> & listener)2712 WMError WindowImpl::UnregisterScreenshotListener(const sptr<IScreenshotListener>& listener)
2713 {
2714     WLOGFD("Start unregister");
2715     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2716     return UnregisterListener(screenshotListeners_[GetWindowId()], listener);
2717 }
2718 
RegisterScreenshotAppEventListener(const IScreenshotAppEventListenerSptr & listener)2719 WMError WindowImpl::RegisterScreenshotAppEventListener(const IScreenshotAppEventListenerSptr& listener)
2720 {
2721     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "winId: %{public}u start register", GetWindowId());
2722     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2723     return RegisterListener(screenshotAppEventListeners_[GetWindowId()], listener);
2724 }
2725 
UnregisterScreenshotAppEventListener(const IScreenshotAppEventListenerSptr & listener)2726 WMError WindowImpl::UnregisterScreenshotAppEventListener(const IScreenshotAppEventListenerSptr& listener)
2727 {
2728     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "winId: %{public}u start unregister", GetWindowId());
2729     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2730     return UnregisterListener(screenshotAppEventListeners_[GetWindowId()], listener);
2731 }
2732 
RegisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener> & listener)2733 WMError WindowImpl::RegisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener>& listener)
2734 {
2735     WLOGFD("Start register");
2736     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2737     return RegisterListener(dialogTargetTouchListeners_[GetWindowId()], listener);
2738 }
2739 
UnregisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener> & listener)2740 WMError WindowImpl::UnregisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener>& listener)
2741 {
2742     WLOGFD("Start unregister");
2743     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2744     return UnregisterListener(dialogTargetTouchListeners_[GetWindowId()], listener);
2745 }
2746 
RegisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener> & listener)2747 void WindowImpl::RegisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener>& listener)
2748 {
2749     WLOGFD("Start register");
2750     if (listener == nullptr) {
2751         WLOGFE("listener is nullptr");
2752         return;
2753     }
2754     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2755     dialogDeathRecipientListener_[GetWindowId()] = listener;
2756 }
2757 
UnregisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener> & listener)2758 void WindowImpl::UnregisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener>& listener)
2759 {
2760     WLOGFD("Start unregister");
2761     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2762     dialogDeathRecipientListener_[GetWindowId()] = nullptr;
2763 }
2764 
2765 template<typename T>
RegisterListener(std::vector<sptr<T>> & holder,const sptr<T> & listener)2766 WMError WindowImpl::RegisterListener(std::vector<sptr<T>>& holder, const sptr<T>& listener)
2767 {
2768     if (listener == nullptr) {
2769         WLOGFE("listener is nullptr");
2770         return WMError::WM_ERROR_NULLPTR;
2771     }
2772     if (std::find(holder.begin(), holder.end(), listener) != holder.end()) {
2773         WLOGFE("Listener already registered");
2774         return WMError::WM_OK;
2775     }
2776     holder.emplace_back(listener);
2777     return WMError::WM_OK;
2778 }
2779 
2780 template<typename T>
UnregisterListener(std::vector<sptr<T>> & holder,const sptr<T> & listener)2781 WMError WindowImpl::UnregisterListener(std::vector<sptr<T>>& holder, const sptr<T>& listener)
2782 {
2783     if (listener == nullptr) {
2784         WLOGFE("listener could not be null");
2785         return WMError::WM_ERROR_NULLPTR;
2786     }
2787     holder.erase(std::remove_if(holder.begin(), holder.end(),
2788         [listener](sptr<T> registeredListener) {
2789             return registeredListener == listener;
2790         }), holder.end());
2791     return WMError::WM_OK;
2792 }
2793 
2794 template <typename T>
GetListeners()2795 EnableIfSame<T, IWindowLifeCycle, std::vector<sptr<IWindowLifeCycle>>> WindowImpl::GetListeners()
2796 {
2797     std::vector<sptr<IWindowLifeCycle>> lifecycleListeners;
2798     {
2799         std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2800         for (auto &listener : lifecycleListeners_[GetWindowId()]) {
2801             lifecycleListeners.push_back(listener);
2802         }
2803     }
2804     return lifecycleListeners;
2805 }
2806 
2807 template <typename T>
GetListeners()2808 EnableIfSame<T, IWindowChangeListener, std::vector<sptr<IWindowChangeListener>>> WindowImpl::GetListeners()
2809 {
2810     std::vector<sptr<IWindowChangeListener>> windowChangeListeners;
2811     {
2812         std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2813         for (auto &listener : windowChangeListeners_[GetWindowId()]) {
2814             windowChangeListeners.push_back(listener);
2815         }
2816     }
2817     return windowChangeListeners;
2818 }
2819 
2820 template <typename T>
GetListeners()2821 EnableIfSame<T, IAvoidAreaChangedListener, std::vector<sptr<IAvoidAreaChangedListener>>> WindowImpl::GetListeners()
2822 {
2823     std::vector<sptr<IAvoidAreaChangedListener>> avoidAreaChangeListeners;
2824     {
2825         std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2826         for (auto &listener : avoidAreaChangeListeners_[GetWindowId()]) {
2827             avoidAreaChangeListeners.push_back(listener);
2828         }
2829     }
2830     return avoidAreaChangeListeners;
2831 }
2832 
2833 template <typename T>
GetListeners()2834 EnableIfSame<T, IDisplayMoveListener, std::vector<sptr<IDisplayMoveListener>>> WindowImpl::GetListeners()
2835 {
2836     std::vector<sptr<IDisplayMoveListener>> displayMoveListeners;
2837     {
2838         std::lock_guard<std::recursive_mutex> lock(mutex_);
2839         for (auto &listener : displayMoveListeners_) {
2840             displayMoveListeners.push_back(listener);
2841         }
2842     }
2843     return displayMoveListeners;
2844 }
2845 
2846 template <typename T>
GetListeners()2847 EnableIfSame<T, IScreenshotListener, std::vector<sptr<IScreenshotListener>>> WindowImpl::GetListeners()
2848 {
2849     std::vector<sptr<IScreenshotListener>> screenshotListeners;
2850     {
2851         std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2852         for (auto &listener : screenshotListeners_[GetWindowId()]) {
2853             screenshotListeners.push_back(listener);
2854         }
2855     }
2856     return screenshotListeners;
2857 }
2858 
2859 template <typename T>
GetListeners()2860 EnableIfSame<T, IScreenshotAppEventListener, std::vector<IScreenshotAppEventListenerSptr>> WindowImpl::GetListeners()
2861 {
2862     std::vector<IScreenshotAppEventListenerSptr> screenshotAppEventListeners;
2863     {
2864         std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2865         for (auto &listener : screenshotAppEventListeners_[GetWindowId()]) {
2866             screenshotAppEventListeners.push_back(listener);
2867         }
2868     }
2869     return screenshotAppEventListeners;
2870 }
2871 
2872 template <typename T>
GetListeners()2873 EnableIfSame<T, ITouchOutsideListener, std::vector<sptr<ITouchOutsideListener>>> WindowImpl::GetListeners()
2874 {
2875     std::vector<sptr<ITouchOutsideListener>> touchOutsideListeners;
2876     {
2877         std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2878         for (auto &listener : touchOutsideListeners_[GetWindowId()]) {
2879             touchOutsideListeners.push_back(listener);
2880         }
2881     }
2882     return touchOutsideListeners;
2883 }
2884 
2885 template <typename T>
GetListeners()2886 EnableIfSame<T, IDialogTargetTouchListener, std::vector<sptr<IDialogTargetTouchListener>>> WindowImpl::GetListeners()
2887 {
2888     std::vector<sptr<IDialogTargetTouchListener>> dialogTargetTouchListeners;
2889     {
2890         std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2891         for (auto &listener : dialogTargetTouchListeners_[GetWindowId()]) {
2892             dialogTargetTouchListeners.push_back(listener);
2893         }
2894     }
2895     return dialogTargetTouchListeners;
2896 }
2897 
2898 template <typename T>
GetListeners()2899 EnableIfSame<T, IWindowDragListener, std::vector<sptr<IWindowDragListener>>> WindowImpl::GetListeners()
2900 {
2901     std::vector<sptr<IWindowDragListener>> windowDragListeners;
2902     {
2903         std::lock_guard<std::recursive_mutex> lock(mutex_);
2904         for (auto &listener : windowDragListeners_) {
2905             windowDragListeners.push_back(listener);
2906         }
2907     }
2908     return windowDragListeners;
2909 }
2910 
2911 template <typename T>
GetListeners()2912 EnableIfSame<T, IOccupiedAreaChangeListener, std::vector<sptr<IOccupiedAreaChangeListener>>> WindowImpl::GetListeners()
2913 {
2914     std::vector<sptr<IOccupiedAreaChangeListener>> occupiedAreaChangeListeners;
2915     {
2916         std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2917         for (auto &listener : occupiedAreaChangeListeners_[GetWindowId()]) {
2918             occupiedAreaChangeListeners.push_back(listener);
2919         }
2920     }
2921     return occupiedAreaChangeListeners;
2922 }
2923 
2924 template <typename T>
GetListener()2925 EnableIfSame<T, IDialogDeathRecipientListener, wptr<IDialogDeathRecipientListener>> WindowImpl::GetListener()
2926 {
2927     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2928     return dialogDeathRecipientListener_[GetWindowId()];
2929 }
2930 
SetAceAbilityHandler(const sptr<IAceAbilityHandler> & handler)2931 void WindowImpl::SetAceAbilityHandler(const sptr<IAceAbilityHandler>& handler)
2932 {
2933     if (handler == nullptr) {
2934         WLOGI("ace ability handler is nullptr");
2935     }
2936     std::lock_guard<std::recursive_mutex> lock(mutex_);
2937     aceAbilityHandler_ = handler;
2938 }
2939 
SetRequestWindowModeSupportType(uint32_t windowModeSupportType)2940 void WindowImpl::SetRequestWindowModeSupportType(uint32_t windowModeSupportType)
2941 {
2942     property_->SetRequestWindowModeSupportType(windowModeSupportType);
2943     SetWindowModeSupportType(windowModeSupportType);
2944 }
2945 
SetWindowModeSupportType(uint32_t windowModeSupportType)2946 void WindowImpl::SetWindowModeSupportType(uint32_t windowModeSupportType)
2947 {
2948     property_->SetWindowModeSupportType(windowModeSupportType);
2949 }
2950 
UpdateRect(const struct Rect & rect,bool decoStatus,WindowSizeChangeReason reason,const std::shared_ptr<RSTransaction> & rsTransaction)2951 void WindowImpl::UpdateRect(const struct Rect& rect, bool decoStatus, WindowSizeChangeReason reason,
2952     const std::shared_ptr<RSTransaction>& rsTransaction)
2953 {
2954     if (state_ == WindowState::STATE_DESTROYED) {
2955         WLOGFW("invalid window state");
2956         return;
2957     }
2958     auto display = SingletonContainer::IsDestroyed() ? nullptr :
2959         SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
2960     if (display == nullptr) {
2961         WLOGFE("get display failed displayId:%{public}" PRIu64", window id:%{public}u", property_->GetDisplayId(),
2962             property_->GetWindowId());
2963         return;
2964     }
2965     Rect lastOriRect = property_->GetWindowRect();
2966 
2967     property_->SetDecoStatus(decoStatus);
2968     if (reason == WindowSizeChangeReason::HIDE) {
2969         property_->SetRequestRect(rect);
2970         return;
2971     }
2972     property_->SetWindowRect(rect);
2973 
2974     // update originRect when floating window show for the first time.
2975     if (!isOriginRectSet_ && WindowHelper::IsMainFloatingWindow(GetType(), GetWindowMode())) {
2976         property_->SetOriginRect(rect);
2977         isOriginRectSet_ = true;
2978     }
2979     WLOGFD("winId:%{public}u, rect[%{public}d, %{public}d, %{public}u, %{public}u], reason:%{public}u",
2980         property_->GetWindowId(), rect.posX_, rect.posY_, rect.width_, rect.height_, reason);
2981     Rect rectToAce = rect;
2982     // update rectToAce for stretchable window
2983     if (windowSystemConfig_.isStretchable_ && WindowHelper::IsMainFloatingWindow(GetType(), GetWindowMode())) {
2984         if (IsStretchableReason(reason)) {
2985             rectToAce = property_->GetOriginRect();
2986         } else {
2987             property_->SetOriginRect(rect);
2988         }
2989     }
2990     ScheduleUpdateRectTask(rectToAce, lastOriRect, reason, rsTransaction, display);
2991 }
2992 
ScheduleUpdateRectTask(const Rect & rectToAce,const Rect & lastOriRect,WindowSizeChangeReason reason,const std::shared_ptr<RSTransaction> & rsTransaction,const sptr<class Display> & display)2993 void WindowImpl::ScheduleUpdateRectTask(const Rect& rectToAce, const Rect& lastOriRect, WindowSizeChangeReason reason,
2994     const std::shared_ptr<RSTransaction>& rsTransaction, const sptr<class Display>& display)
2995 {
2996     auto task = [weakThis = wptr(this), reason, rsTransaction, rectToAce, lastOriRect, display]() mutable {
2997         auto window = weakThis.promote();
2998         if (!window) {
2999             TLOGNE(WmsLogTag::WMS_IMMS, "window is null");
3000             return;
3001         }
3002         auto rsUIContext = window->GetRSUIContext();
3003         if (rsTransaction) {
3004             RSTransactionAdapter::FlushImplicitTransaction(rsUIContext);
3005             rsTransaction->Begin();
3006         }
3007         RSAnimationTimingProtocol protocol;
3008         protocol.SetDuration(600);
3009         auto curve = RSAnimationTimingCurve::CreateCubicCurve(0.2, 0.0, 0.2, 1.0);
3010         RSNode::OpenImplicitAnimation(rsUIContext, protocol, curve);
3011         if ((rectToAce != lastOriRect) || (reason != window->lastSizeChangeReason_)) {
3012             window->NotifySizeChange(rectToAce, reason, rsTransaction);
3013             window->lastSizeChangeReason_ = reason;
3014         }
3015         window->UpdateViewportConfig(rectToAce, display, reason, rsTransaction);
3016         RSNode::CloseImplicitAnimation(rsUIContext);
3017         if (rsTransaction) {
3018             rsTransaction->Commit();
3019         }
3020         window->postTaskDone_ = true;
3021     };
3022     ResSchedReport::GetInstance().RequestPerfIfNeed(reason, GetType(), GetWindowMode());
3023     if (reason == WindowSizeChangeReason::ROTATION) {
3024         postTaskDone_ = false;
3025         handler_->PostTask(task, "wms:UpdateRect");
3026     } else {
3027         if ((rectToAce != lastOriRect) || (reason != lastSizeChangeReason_) || !postTaskDone_) {
3028             NotifySizeChange(rectToAce, reason, rsTransaction);
3029             lastSizeChangeReason_ = reason;
3030             postTaskDone_ = true;
3031         }
3032         UpdateViewportConfig(rectToAce, display, reason, rsTransaction);
3033     }
3034 }
3035 
UpdateMode(WindowMode mode)3036 void WindowImpl::UpdateMode(WindowMode mode)
3037 {
3038     WLOGI("UpdateMode %{public}u", mode);
3039     property_->SetWindowMode(mode);
3040     UpdateTitleButtonVisibility();
3041     UpdateDecorEnable(true);
3042 }
3043 
UpdateWindowModeSupportType(uint32_t windowModeSupportType)3044 void WindowImpl::UpdateWindowModeSupportType(uint32_t windowModeSupportType)
3045 {
3046     WLOGFD("windowModeSupportType: %{public}u, winId: %{public}u", windowModeSupportType, GetWindowId());
3047     SetWindowModeSupportType(windowModeSupportType);
3048     UpdateTitleButtonVisibility();
3049 }
3050 
HandleBackKeyPressedEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent)3051 void WindowImpl::HandleBackKeyPressedEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
3052 {
3053     std::shared_ptr<IInputEventConsumer> inputEventConsumer;
3054     {
3055         std::lock_guard<std::recursive_mutex> lock(mutex_);
3056         inputEventConsumer = inputEventConsumer_;
3057     }
3058     SingletonContainer::Get<WindowInfoReporter>().ReportBackButtonInfoImmediately();
3059 
3060     bool isConsumed = false;
3061     if (inputEventConsumer != nullptr) {
3062         WLOGD("Transfer back key event to inputEventConsumer");
3063         isConsumed = inputEventConsumer->OnInputEvent(keyEvent);
3064     } else if (uiContent_ != nullptr) {
3065         WLOGD("Transfer back key event to uiContent");
3066         isConsumed = uiContent_->ProcessBackPressed();
3067     } else {
3068         WLOGFE("There is no back key event consumer");
3069     }
3070     if (isConsumed) {
3071         WLOGD("Back key event is consumed");
3072         return;
3073     }
3074     PerformBack();
3075 }
3076 
PerformBack()3077 void WindowImpl::PerformBack()
3078 {
3079     auto task = [weakThis = wptr(this)]() {
3080         auto window = weakThis.promote();
3081         if (!window) {
3082             TLOGNE(WmsLogTag::WMS_IMMS, "window is null");
3083             return;
3084         }
3085         if (!WindowHelper::IsMainWindow(window->property_->GetWindowType())) {
3086             WLOGD("it is not a main window");
3087             return;
3088         }
3089         auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(window->context_);
3090         if (abilityContext == nullptr) {
3091             WLOGFE("abilityContext is null");
3092             return;
3093         }
3094         bool needMoveToBackground = false;
3095         int ret = abilityContext->OnBackPressedCallBack(needMoveToBackground);
3096         if (ret == ERR_OK && needMoveToBackground) {
3097             abilityContext->MoveAbilityToBackground();
3098             WLOGD("id: %{public}u closed, to move Ability: %{public}u",
3099                   window->property_->GetWindowId(), needMoveToBackground);
3100             return;
3101         }
3102         // TerminateAbility will invoke last ability, CloseAbility will not.
3103         bool shouldTerminateAbility = WindowHelper::IsFullScreenWindow(window->property_->GetWindowMode());
3104         if (shouldTerminateAbility) {
3105             abilityContext->TerminateSelf();
3106         } else {
3107             abilityContext->CloseAbility();
3108         }
3109         WLOGD("id: %{public}u closed, to kill Ability: %{public}u",
3110               window->property_->GetWindowId(), static_cast<uint32_t>(shouldTerminateAbility));
3111     };
3112     handler_->PostTask(task, "WindowImpl::PerformBack");
3113 }
3114 
ConsumeKeyEvent(std::shared_ptr<MMI::KeyEvent> & keyEvent)3115 void WindowImpl::ConsumeKeyEvent(std::shared_ptr<MMI::KeyEvent>& keyEvent)
3116 {
3117     int32_t keyCode = keyEvent->GetKeyCode();
3118     int32_t keyAction = keyEvent->GetKeyAction();
3119     WLOGFD("KeyCode: %{public}d, action: %{public}d", keyCode, keyAction);
3120     bool shouldMarkProcess = true;
3121     if (keyCode == MMI::KeyEvent::KEYCODE_BACK && keyAction == MMI::KeyEvent::KEY_ACTION_UP) {
3122         HandleBackKeyPressedEvent(keyEvent);
3123     } else {
3124         std::shared_ptr<IInputEventConsumer> inputEventConsumer;
3125         {
3126             std::lock_guard<std::recursive_mutex> lock(mutex_);
3127             inputEventConsumer = inputEventConsumer_;
3128         }
3129         if (inputEventConsumer != nullptr) {
3130             WLOGD("Transfer key event to inputEventConsumer");
3131             (void)inputEventConsumer->OnInputEvent(keyEvent);
3132             shouldMarkProcess = false;
3133         } else if (uiContent_ != nullptr) {
3134             WLOGD("Transfer key event to uiContent");
3135             bool handled = static_cast<bool>(uiContent_->ProcessKeyEvent(keyEvent));
3136             if (!handled && keyCode == MMI::KeyEvent::KEYCODE_ESCAPE &&
3137                 GetWindowMode() == WindowMode::WINDOW_MODE_FULLSCREEN &&
3138                 property_->GetMaximizeMode() == MaximizeMode::MODE_FULL_FILL &&
3139                 keyAction == MMI::KeyEvent::KEY_ACTION_DOWN && !escKeyEventTriggered_) {
3140                 WLOGI("recover from fullscreen cause KEYCODE_ESCAPE");
3141                 Recover();
3142             }
3143             if (keyEvent->GetKeyCode() == MMI::KeyEvent::KEYCODE_ESCAPE) {
3144                 escKeyEventTriggered_ = (keyAction == MMI::KeyEvent::KEY_ACTION_UP) ? false : true;
3145             }
3146             shouldMarkProcess = !handled;
3147         } else {
3148             WLOGFE("There is no key event consumer");
3149         }
3150     }
3151     if (GetType() == WindowType::WINDOW_TYPE_APP_COMPONENT) {
3152         WLOGFI("DispatchKeyEvent: %{public}u", GetWindowId());
3153         SingletonContainer::Get<WindowAdapter>().DispatchKeyEvent(GetWindowId(), keyEvent);
3154         keyEvent->MarkProcessed();
3155         return;
3156     }
3157     if (shouldMarkProcess) {
3158         keyEvent->MarkProcessed();
3159     }
3160 }
3161 
HandleModeChangeHotZones(int32_t posX,int32_t posY)3162 void WindowImpl::HandleModeChangeHotZones(int32_t posX, int32_t posY)
3163 {
3164     if (!WindowHelper::IsMainFloatingWindow(GetType(), GetWindowMode())) {
3165         return;
3166     }
3167 
3168     ModeChangeHotZones hotZones;
3169     auto res = SingletonContainer::Get<WindowAdapter>().GetModeChangeHotZones(property_->GetDisplayId(), hotZones);
3170     WLOGD("[HotZone] Window %{public}u, Pointer[%{public}d, %{public}d]", GetWindowId(), posX, posY);
3171     if (res == WMError::WM_OK) {
3172         WLOGD("[HotZone] Fullscreen [%{public}d, %{public}d, %{public}u, %{public}u]", hotZones.fullscreen_.posX_,
3173             hotZones.fullscreen_.posY_, hotZones.fullscreen_.width_, hotZones.fullscreen_.height_);
3174         WLOGD("[HotZone] Primary [%{public}d, %{public}d, %{public}u, %{public}u]", hotZones.primary_.posX_,
3175             hotZones.primary_.posY_, hotZones.primary_.width_, hotZones.primary_.height_);
3176         WLOGD("[HotZone] Secondary [%{public}d, %{public}d, %{public}u, %{public}u]", hotZones.secondary_.posX_,
3177             hotZones.secondary_.posY_, hotZones.secondary_.width_, hotZones.secondary_.height_);
3178 
3179         if (WindowHelper::IsPointInTargetRectWithBound(posX, posY, hotZones.fullscreen_)) {
3180             SetFullScreen(true);
3181         } else if (WindowHelper::IsPointInTargetRectWithBound(posX, posY, hotZones.primary_)) {
3182             SetWindowMode(WindowMode::WINDOW_MODE_SPLIT_PRIMARY);
3183         } else if (WindowHelper::IsPointInTargetRectWithBound(posX, posY, hotZones.secondary_)) {
3184             SetWindowMode(WindowMode::WINDOW_MODE_SPLIT_SECONDARY);
3185         }
3186     }
3187 }
3188 
UpdatePointerEventForStretchableWindow(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)3189 void WindowImpl::UpdatePointerEventForStretchableWindow(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
3190 {
3191     MMI::PointerEvent::PointerItem pointerItem;
3192     if (!pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
3193         WLOGFW("Point item is invalid");
3194         return;
3195     }
3196     const Rect& originRect = property_->GetOriginRect();
3197     PointInfo originPos =
3198         WindowHelper::CalculateOriginPosition(originRect, GetRect(),
3199         { pointerItem.GetDisplayX(), pointerItem.GetDisplayY() });
3200     pointerItem.SetDisplayX(originPos.x);
3201     pointerItem.SetDisplayY(originPos.y);
3202     pointerItem.SetWindowX(originPos.x - originRect.posX_);
3203     pointerItem.SetWindowY(originPos.y - originRect.posY_);
3204     pointerEvent->UpdatePointerItem(pointerEvent->GetPointerId(), pointerItem);
3205 }
3206 
UpdateDragType(int32_t startPointPosX,int32_t startPointPosY)3207 void WindowImpl::UpdateDragType(int32_t startPointPosX, int32_t startPointPosY)
3208 {
3209     const auto& startRectExceptCorner = moveDragProperty_->startRectExceptCorner_;
3210     if (startPointPosX > startRectExceptCorner.posX_ &&
3211         (startPointPosX < startRectExceptCorner.posX_ +
3212         static_cast<int32_t>(startRectExceptCorner.width_))) {
3213         moveDragProperty_->dragType_ = DragType::DRAG_BOTTOM_OR_TOP;
3214     } else if (startPointPosY > startRectExceptCorner.posY_ &&
3215         (startPointPosY < startRectExceptCorner.posY_ +
3216         static_cast<int32_t>(startRectExceptCorner.height_))) {
3217         moveDragProperty_->dragType_ = DragType::DRAG_LEFT_OR_RIGHT;
3218     } else if ((startPointPosX <= startRectExceptCorner.posX_ && startPointPosY <= startRectExceptCorner.posY_) ||
3219         (startPointPosX >= startRectExceptCorner.posX_ + static_cast<int32_t>(startRectExceptCorner.width_) &&
3220          startPointPosY >= startRectExceptCorner.posY_ + static_cast<int32_t>(startRectExceptCorner.height_))) {
3221         moveDragProperty_->dragType_ = DragType::DRAG_LEFT_TOP_CORNER;
3222     } else {
3223         moveDragProperty_->dragType_ = DragType::DRAG_RIGHT_TOP_CORNER;
3224     }
3225 }
3226 
CalculateStartRectExceptHotZone(float vpr)3227 void WindowImpl::CalculateStartRectExceptHotZone(float vpr)
3228 {
3229     TransformHelper::Vector2 hotZoneScale(1, 1);
3230     if (property_->isNeedComputerTransform()) {
3231         property_->ComputeTransform();
3232         hotZoneScale = WindowHelper::CalculateHotZoneScale(property_->GetTransformMat());
3233     }
3234 
3235     const auto& startPointRect = GetRect();
3236     auto& startRectExceptFrame = moveDragProperty_->startRectExceptFrame_;
3237     startRectExceptFrame.posX_ = startPointRect.posX_ +
3238         static_cast<int32_t>(WINDOW_FRAME_WIDTH * vpr / hotZoneScale.x_);
3239     startRectExceptFrame.posY_ = startPointRect.posY_ +
3240         static_cast<int32_t>(WINDOW_FRAME_WIDTH * vpr / hotZoneScale.y_);
3241     startRectExceptFrame.width_ = startPointRect.width_ -
3242         static_cast<uint32_t>((WINDOW_FRAME_WIDTH + WINDOW_FRAME_WIDTH) * vpr / hotZoneScale.x_);
3243     startRectExceptFrame.height_ = startPointRect.height_ -
3244         static_cast<uint32_t>((WINDOW_FRAME_WIDTH + WINDOW_FRAME_WIDTH) * vpr / hotZoneScale.y_);
3245 
3246     auto& startRectExceptCorner =  moveDragProperty_->startRectExceptCorner_;
3247     startRectExceptCorner.posX_ = startPointRect.posX_ +
3248         static_cast<int32_t>(WINDOW_FRAME_CORNER_WIDTH * vpr / hotZoneScale.x_);
3249     startRectExceptCorner.posY_ = startPointRect.posY_ +
3250         static_cast<int32_t>(WINDOW_FRAME_CORNER_WIDTH * vpr / hotZoneScale.y_);
3251     startRectExceptCorner.width_ = startPointRect.width_ -
3252         static_cast<uint32_t>((WINDOW_FRAME_CORNER_WIDTH + WINDOW_FRAME_CORNER_WIDTH) * vpr / hotZoneScale.x_);
3253     startRectExceptCorner.height_ = startPointRect.height_ -
3254         static_cast<uint32_t>((WINDOW_FRAME_CORNER_WIDTH + WINDOW_FRAME_CORNER_WIDTH) * vpr / hotZoneScale.y_);
3255 }
3256 
IsPointInDragHotZone(int32_t startPointPosX,int32_t startPointPosY,int32_t sourceType)3257 bool WindowImpl::IsPointInDragHotZone(int32_t startPointPosX, int32_t startPointPosY, int32_t sourceType)
3258 {
3259     // calculate rect with hotzone
3260     Rect rectWithHotzone;
3261     rectWithHotzone.posX_ = GetRect().posX_ - static_cast<int32_t>(HOTZONE_POINTER);
3262     rectWithHotzone.posY_ = GetRect().posY_ - static_cast<int32_t>(HOTZONE_POINTER);
3263     rectWithHotzone.width_ = GetRect().width_ + HOTZONE_POINTER * 2;   // 2: calculate width need
3264     rectWithHotzone.height_ = GetRect().height_ + HOTZONE_POINTER * 2; // 2: calculate height need
3265 
3266     if (sourceType == MMI::PointerEvent::SOURCE_TYPE_MOUSE &&
3267         !WindowHelper::IsPointInTargetRectWithBound(startPointPosX, startPointPosY, rectWithHotzone)) {
3268         return false;
3269     } else if ((!WindowHelper::IsPointInTargetRect(startPointPosX,
3270         startPointPosY, moveDragProperty_->startRectExceptFrame_)) ||
3271         (!WindowHelper::IsPointInWindowExceptCorner(startPointPosX,
3272         startPointPosY, moveDragProperty_->startRectExceptCorner_))) {
3273         return true;
3274     }
3275     return false;
3276 }
3277 
StartMove()3278 void WindowImpl::StartMove()
3279 {
3280     if (!WindowHelper::IsMainFloatingWindow(GetType(), GetWindowMode())) {
3281         WLOGE("[StartMove] current window can not be moved, windowId %{public}u", GetWindowId());
3282         return;
3283     }
3284     if (!moveDragProperty_->pointEventStarted_ || moveDragProperty_->startDragFlag_) {
3285         WLOGE("[StartMove] pointerEvent has not been started, or is dragging now");
3286         return;
3287     }
3288     moveDragProperty_->startMoveFlag_ = true;
3289     SingletonContainer::Get<WindowAdapter>().NotifyServerReadyToMoveOrDrag(property_->GetWindowId(),
3290         property_, moveDragProperty_);
3291     WLOGI("[StartMove] windowId %{public}u", GetWindowId());
3292 }
3293 
ResetMoveOrDragState()3294 void WindowImpl::ResetMoveOrDragState()
3295 {
3296     if (!WindowHelper::IsMainWindow(GetType())) {
3297         return;
3298     }
3299     moveDragProperty_->pointEventStarted_ = false;
3300     moveDragProperty_->startDragFlag_ = false;
3301     moveDragProperty_->startMoveFlag_ = false;
3302     UpdateRect(GetRect(), property_->GetDecoStatus(), WindowSizeChangeReason::DRAG_END);
3303 }
3304 
ReadyToMoveOrDragWindow(const std::shared_ptr<MMI::PointerEvent> & pointerEvent,const MMI::PointerEvent::PointerItem & pointerItem)3305 void WindowImpl::ReadyToMoveOrDragWindow(const std::shared_ptr<MMI::PointerEvent>& pointerEvent,
3306     const MMI::PointerEvent::PointerItem& pointerItem)
3307 {
3308     if (moveDragProperty_->pointEventStarted_) {
3309         return;
3310     }
3311 
3312     moveDragProperty_->startPointRect_ = GetRect();
3313     moveDragProperty_->startPointPosX_ = pointerItem.GetDisplayX();
3314     moveDragProperty_->startPointPosY_ = pointerItem.GetDisplayY();
3315     moveDragProperty_->startPointerId_ = pointerEvent->GetPointerId();
3316     moveDragProperty_->targetDisplayId_ = pointerEvent->GetTargetDisplayId();
3317     moveDragProperty_->sourceType_ = pointerEvent->GetSourceType();
3318     moveDragProperty_->pointEventStarted_ = true;
3319 
3320     // calculate window inner rect except frame
3321     auto display = SingletonContainer::IsDestroyed() ? nullptr :
3322         SingletonContainer::Get<DisplayManager>().GetDisplayById(moveDragProperty_->targetDisplayId_);
3323     if (display == nullptr) {
3324         WLOGFE("get display failed moveDragProperty targetDisplayId:%{public}u, window id:%{public}u",
3325             moveDragProperty_->targetDisplayId_, property_->GetWindowId());
3326         return;
3327     }
3328     auto displayInfo = display->GetDisplayInfo();
3329     if (displayInfo == nullptr) {
3330         WLOGFE("get display info failed moveDragProperty targetDisplayId:%{public}u, window id:%{public}u",
3331             moveDragProperty_->targetDisplayId_, property_->GetWindowId());
3332         return;
3333     }
3334     float vpr = display->GetVirtualPixelRatio();
3335     int32_t startPointPosX = moveDragProperty_->startPointPosX_ + displayInfo->GetOffsetX();
3336     int32_t startPointPosY = moveDragProperty_->startPointPosY_ + displayInfo->GetOffsetY();
3337 
3338     CalculateStartRectExceptHotZone(vpr);
3339 
3340     if (GetType() == WindowType::WINDOW_TYPE_DOCK_SLICE) {
3341         moveDragProperty_->startMoveFlag_ = true;
3342         SingletonContainer::Get<WindowAdapter>().NotifyServerReadyToMoveOrDrag(property_->GetWindowId(),
3343             property_, moveDragProperty_);
3344     } else if (IsPointInDragHotZone(startPointPosX, startPointPosY, moveDragProperty_->sourceType_)
3345         && property_->GetMaximizeMode() != MaximizeMode::MODE_AVOID_SYSTEM_BAR) {
3346         moveDragProperty_->startDragFlag_ = true;
3347         UpdateDragType(startPointPosX, startPointPosY);
3348         SingletonContainer::Get<WindowAdapter>().NotifyServerReadyToMoveOrDrag(property_->GetWindowId(),
3349             property_, moveDragProperty_);
3350     }
3351     return;
3352 }
3353 
EndMoveOrDragWindow(int32_t posX,int32_t posY,int32_t pointId,int32_t sourceType)3354 void WindowImpl::EndMoveOrDragWindow(int32_t posX, int32_t posY, int32_t pointId, int32_t sourceType)
3355 {
3356     if (pointId != moveDragProperty_->startPointerId_ || sourceType != moveDragProperty_->sourceType_) {
3357         return;
3358     }
3359 
3360     if (moveDragProperty_->startDragFlag_) {
3361         SingletonContainer::Get<WindowAdapter>().ProcessPointUp(GetWindowId());
3362         moveDragProperty_->startDragFlag_ = false;
3363     }
3364 
3365     if (moveDragProperty_->startMoveFlag_) {
3366         SingletonContainer::Get<WindowAdapter>().ProcessPointUp(GetWindowId());
3367         moveDragProperty_->startMoveFlag_ = false;
3368         HandleModeChangeHotZones(posX, posY);
3369     }
3370     moveDragProperty_->pointEventStarted_ = false;
3371     ResSchedReport::GetInstance().StopPerfIfNeed();
3372 }
3373 
ConsumeMoveOrDragEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)3374 void WindowImpl::ConsumeMoveOrDragEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
3375 {
3376     MMI::PointerEvent::PointerItem pointerItem;
3377     int32_t pointId = pointerEvent->GetPointerId();
3378     int32_t sourceType = pointerEvent->GetSourceType();
3379     if (!pointerEvent->GetPointerItem(pointId, pointerItem) ||
3380         (sourceType == MMI::PointerEvent::SOURCE_TYPE_MOUSE &&
3381         pointerEvent->GetButtonId() != MMI::PointerEvent::MOUSE_BUTTON_LEFT)) {
3382         WLOGFW("invalid pointerEvent");
3383         return;
3384     }
3385     int32_t pointDisplayX = pointerItem.GetDisplayX();
3386     int32_t pointDisplayY = pointerItem.GetDisplayY();
3387     int32_t action = pointerEvent->GetPointerAction();
3388     int32_t targetDisplayId = pointerEvent->GetTargetDisplayId();
3389     switch (action) {
3390         // Ready to move or drag
3391         case MMI::PointerEvent::POINTER_ACTION_DOWN:
3392         case MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN: {
3393             const auto& rect = GetRect();
3394             ReadyToMoveOrDragWindow(pointerEvent, pointerItem);
3395             if (IsPointerEventConsumed()) {
3396                 ResSchedReport::GetInstance().TrigClick();
3397             }
3398             TLOGD(WmsLogTag::WMS_EVENT, "windowId:%{public}u, pointId:%{public}d, sourceType:%{public}d, "
3399                   "hasPointStarted:%{public}d, startMove:%{public}d, startDrag:%{public}d, targetDisplayId:"
3400                   "%{public}d, pointPos:[%{private}d, %{private}d], winRect:[%{public}d, %{public}d, %{public}u, "
3401                   "%{public}u]", GetWindowId(), pointId, sourceType, moveDragProperty_->pointEventStarted_,
3402                   moveDragProperty_->startMoveFlag_, moveDragProperty_->startDragFlag_, targetDisplayId,
3403                   pointDisplayX, pointDisplayY, rect.posX_, rect.posY_, rect.width_, rect.height_);
3404             break;
3405         }
3406         // End move or drag
3407         case MMI::PointerEvent::POINTER_ACTION_UP:
3408         case MMI::PointerEvent::POINTER_ACTION_BUTTON_UP:
3409         case MMI::PointerEvent::POINTER_ACTION_CANCEL: {
3410             EndMoveOrDragWindow(pointDisplayX, pointDisplayY, pointId, sourceType);
3411             WLOGFD("[Client Point Up/Cancel]: windowId: %{public}u, action: %{public}d, sourceType: %{public}d, "
3412                 "startMove: %{public}d, startDrag: %{public}d", GetWindowId(), action, sourceType,
3413                 moveDragProperty_->startMoveFlag_, moveDragProperty_->startDragFlag_);
3414             break;
3415         }
3416         default:
3417             break;
3418     }
3419 }
3420 
IsPointerEventConsumed()3421 bool WindowImpl::IsPointerEventConsumed()
3422 {
3423     return moveDragProperty_->startDragFlag_ || moveDragProperty_->startMoveFlag_;
3424 }
3425 
TransferPointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)3426 void WindowImpl::TransferPointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
3427 {
3428     if (pointerEvent == nullptr) {
3429         WLOGFE("The pointer event is nullptr");
3430         return;
3431     }
3432     if (windowSystemConfig_.isStretchable_ && GetWindowMode() == WindowMode::WINDOW_MODE_FLOATING) {
3433         UpdatePointerEventForStretchableWindow(pointerEvent);
3434     }
3435     std::shared_ptr<IInputEventConsumer> inputEventConsumer;
3436     {
3437         std::lock_guard<std::recursive_mutex> lock(mutex_);
3438         inputEventConsumer = inputEventConsumer_;
3439     }
3440     if (inputEventConsumer != nullptr) {
3441         WLOGFD("Transfer pointer event to inputEventConsumer");
3442         if (!(inputEventConsumer->OnInputEvent(pointerEvent))) {
3443             WLOGFI("The Input event consumer consumes pointer event failed.");
3444             pointerEvent->MarkProcessed();
3445         }
3446     } else if (uiContent_ != nullptr) {
3447         WLOGFD("Transfer pointer event to uiContent");
3448         if (!(uiContent_->ProcessPointerEvent(pointerEvent))) {
3449             WLOGFI("The UI content consumes pointer event failed.");
3450             pointerEvent->MarkProcessed();
3451         }
3452     } else {
3453         WLOGFW("pointerEvent is not consumed, windowId: %{public}u", GetWindowId());
3454         pointerEvent->MarkProcessed();
3455     }
3456 }
3457 
CalculatePointerDirection(int32_t pointerX,int32_t pointerY)3458 uint32_t WindowImpl::CalculatePointerDirection(int32_t pointerX, int32_t pointerY)
3459 {
3460     UpdateDragType(pointerX, pointerY);
3461     return STYLEID_MAP.at(moveDragProperty_->dragType_);
3462 }
3463 
HandlePointerStyle(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)3464 void WindowImpl::HandlePointerStyle(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
3465 {
3466     MMI::PointerEvent::PointerItem pointerItem;
3467     if (!pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
3468         WLOGFE("Get pointeritem failed");
3469         pointerEvent->MarkProcessed();
3470         return;
3471     }
3472     auto action = pointerEvent->GetPointerAction();
3473     uint32_t windowId = static_cast<uint32_t>(pointerEvent->GetAgentWindowId());
3474     int32_t mousePointX = pointerItem.GetDisplayX();
3475     int32_t mousePointY = pointerItem.GetDisplayY();
3476     int32_t sourceType = pointerEvent->GetSourceType();
3477     uint32_t oldStyleID = mouseStyleID_;
3478     uint32_t newStyleID = 0;
3479     if (WindowHelper::IsMainFloatingWindow(GetType(), GetWindowMode())) {
3480         auto display = SingletonContainer::IsDestroyed() ? nullptr :
3481             SingletonContainer::Get<DisplayManager>().GetDisplayById(pointerEvent->GetTargetDisplayId());
3482         if (display == nullptr || display->GetDisplayInfo() == nullptr) {
3483             WLOGFE("get display failed displayId:%{public}" PRIu64", window id:%{public}u",
3484                 property_->GetDisplayId(), property_->GetWindowId());
3485             return;
3486         }
3487         float vpr = display->GetVirtualPixelRatio();
3488         CalculateStartRectExceptHotZone(vpr);
3489         if (IsPointInDragHotZone(mousePointX, mousePointY, sourceType) &&
3490             property_->GetMaximizeMode() != MaximizeMode::MODE_AVOID_SYSTEM_BAR) {
3491             newStyleID = CalculatePointerDirection(mousePointX, mousePointY);
3492         } else if (action == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP) {
3493             newStyleID = MMI::MOUSE_ICON::DEFAULT;
3494         }
3495     } else if (GetType() == WindowType::WINDOW_TYPE_DOCK_SLICE) {
3496         newStyleID = (GetRect().width_ > GetRect().height_) ?
3497             MMI::MOUSE_ICON::NORTH_SOUTH : MMI::MOUSE_ICON::WEST_EAST;
3498         if (action == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP) {
3499             newStyleID = MMI::MOUSE_ICON::DEFAULT; // when receive up event, set default style
3500         }
3501     }
3502     TLOGD(WmsLogTag::WMS_EVENT, "winId:%{public}u, Mouse posX:%{private}u, posY:%{private}u, action:%{public}u, "
3503            "winRect posX:%{public}u, posY:%{public}u, W:%{public}u, H:%{public}u, "
3504            "newStyle:%{public}u, oldStyle:%{public}u",
3505            windowId, mousePointX, mousePointY, action, GetRect().posX_,
3506            GetRect().posY_, GetRect().width_, GetRect().height_, newStyleID, oldStyleID);
3507     if (oldStyleID != newStyleID) {
3508         MMI::PointerStyle pointerStyle;
3509         pointerStyle.id = static_cast<int32_t>(newStyleID);
3510         int32_t res = MMI::InputManager::GetInstance()->SetPointerStyle(windowId, pointerStyle);
3511         if (res != 0) {
3512             WLOGFE("set pointer style failed, res is %{public}u", res);
3513             return;
3514         }
3515         mouseStyleID_ = newStyleID;
3516     }
3517 }
3518 
PerfLauncherHotAreaIfNeed(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)3519 void WindowImpl::PerfLauncherHotAreaIfNeed(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
3520 {
3521 #ifdef RESOURCE_SCHEDULE_SERVICE_ENABLE
3522     int32_t action = pointerEvent->GetPointerAction();
3523     if (action != MMI::PointerEvent::POINTER_ACTION_CANCEL) {
3524         return;
3525     }
3526     MMI::PointerEvent::PointerItem pointerItem;
3527     int32_t pointId = pointerEvent->GetPointerId();
3528     if (!pointerEvent->GetPointerItem(pointId, pointerItem)) {
3529         WLOGFW("invalid pointerEvent");
3530         return;
3531     }
3532     auto display = SingletonContainer::IsDestroyed() ? nullptr :
3533         SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
3534     if (display == nullptr) {
3535         return;
3536     }
3537     auto displayHeight = display->GetHeight();
3538     constexpr float HOT_RATE = 0.07;
3539     auto height = static_cast<int32_t>(displayHeight * HOT_RATE);
3540     int32_t pointDisplayY = pointerItem.GetDisplayY();
3541     if (pointDisplayY > displayHeight - height) {
3542         ResSchedReport::GetInstance().AnimationBoost();
3543     }
3544 #endif
3545 }
3546 
ConsumePointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)3547 void WindowImpl::ConsumePointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
3548 {
3549     // If windowRect transformed, transform event back to its origin position
3550     if (property_) {
3551         property_->UpdatePointerEvent(pointerEvent);
3552     }
3553     int32_t action = pointerEvent->GetPointerAction();
3554     if (action == MMI::PointerEvent::POINTER_ACTION_MOVE || action == MMI::PointerEvent::POINTER_ACTION_DOWN ||
3555         action == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN) {
3556         ResSchedReport::GetInstance().TrigSlide(GetType(), true);
3557     }
3558     if (action == MMI::PointerEvent::POINTER_ACTION_UP || action == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP ||
3559         action == MMI::PointerEvent::POINTER_ACTION_CANCEL) {
3560         ResSchedReport::GetInstance().TrigSlide(GetType(), false);
3561     }
3562     if ((action == MMI::PointerEvent::POINTER_ACTION_MOVE || action == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP) &&
3563         pointerEvent->GetSourceType() == MMI::PointerEvent::SOURCE_TYPE_MOUSE) {
3564         HandlePointerStyle(pointerEvent);
3565     }
3566     PerfLauncherHotAreaIfNeed(pointerEvent);
3567     if (action == MMI::PointerEvent::POINTER_ACTION_DOWN || action == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN) {
3568         WLOGFD("WMS process point down, id:%{public}u, action: %{public}d", GetWindowId(), action);
3569         if (GetType() == WindowType::WINDOW_TYPE_LAUNCHER_RECENT) {
3570             MMI::PointerEvent::PointerItem pointerItem;
3571             if (!pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
3572                 WLOGFW("Point item is invalid");
3573                 pointerEvent->MarkProcessed();
3574                 return;
3575             }
3576             if (!WindowHelper::IsPointInTargetRect(pointerItem.GetDisplayX(), pointerItem.GetDisplayY(), GetRect())) {
3577                 NotifyAfterUnfocused(false);
3578                 pointerEvent->MarkProcessed();
3579                 return;
3580             }
3581         }
3582         if (property_ != nullptr) {
3583             SingletonContainer::Get<WindowAdapter>().ProcessPointDown(property_->GetWindowId());
3584         }
3585     }
3586 
3587     // If point event type is up, should reset start move flag
3588     if (WindowHelper::IsMainFloatingWindow(GetType(), GetWindowMode()) ||
3589         GetType() == WindowType::WINDOW_TYPE_DOCK_SLICE || (action == MMI::PointerEvent::POINTER_ACTION_UP ||
3590         action == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP || action == MMI::PointerEvent::POINTER_ACTION_CANCEL)) {
3591         ConsumeMoveOrDragEvent(pointerEvent);
3592     }
3593 
3594     if (IsPointerEventConsumed()) {
3595         pointerEvent->MarkProcessed();
3596         return;
3597     }
3598 
3599     TransferPointerEvent(pointerEvent);
3600 }
3601 
RequestVsync(const std::shared_ptr<VsyncCallback> & vsyncCallback)3602 void WindowImpl::RequestVsync(const std::shared_ptr<VsyncCallback>& vsyncCallback)
3603 {
3604     if (vsyncStation_ != nullptr) {
3605         vsyncStation_->RequestVsync(vsyncCallback);
3606     }
3607 }
3608 
GetVSyncPeriod()3609 int64_t WindowImpl::GetVSyncPeriod()
3610 {
3611     if (vsyncStation_ != nullptr) {
3612         return vsyncStation_->GetVSyncPeriod();
3613     }
3614     return 0;
3615 }
3616 
UpdateFocusStatus(bool focused)3617 void WindowImpl::UpdateFocusStatus(bool focused)
3618 {
3619     if (!IsWindowValid()) {
3620         TLOGE(WmsLogTag::WMS_FOCUS, "Window is invalid");
3621         return;
3622     }
3623 
3624     WLOGFD("IsFocused: %{public}d, id: %{public}u", focused, property_->GetWindowId());
3625     isFocused_ = focused;
3626     if (focused) {
3627         HiSysEventWrite(
3628             OHOS::HiviewDFX::HiSysEvent::Domain::WINDOW_MANAGER,
3629             "FOCUS_WINDOW",
3630             OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR,
3631             "PID", getpid(),
3632             "UID", getuid(),
3633             "BUNDLE_NAME", property_->GetAbilityInfo().bundleName_,
3634             "WINDOW_TYPE", static_cast<uint32_t>(GetType()));
3635         if (state_ <= WindowState::STATE_CREATED || state_ == WindowState::STATE_HIDDEN) {
3636             needNotifyFocusLater_ = true;
3637             return;
3638         }
3639         NotifyAfterFocused();
3640     } else {
3641         NotifyAfterUnfocused();
3642     }
3643 }
3644 
IsFocused() const3645 bool WindowImpl::IsFocused() const
3646 {
3647     if (!IsWindowValid()) {
3648         TLOGE(WmsLogTag::WMS_FOCUS, "Window is invalid");
3649         return false;
3650     }
3651 
3652     return isFocused_;
3653 }
3654 
UpdateConfiguration(const std::shared_ptr<AppExecFwk::Configuration> & configuration)3655 void WindowImpl::UpdateConfiguration(const std::shared_ptr<AppExecFwk::Configuration>& configuration)
3656 {
3657     if (uiContent_ != nullptr) {
3658         TLOGI(WmsLogTag::WMS_ATTRIBUTE, "notify ace impl win=%{public}u, display=%{public}" PRIu64,
3659             GetWindowId(), GetDisplayId());
3660         uiContent_->UpdateConfiguration(configuration);
3661     } else {
3662         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "uiContent null, impl win=%{public}u, display=%{public}" PRIu64,
3663             GetWindowId(), GetDisplayId());
3664     }
3665     TLOGD(WmsLogTag::WMS_ATTRIBUTE, "impl win=%{public}u, subWinSize=%{public}u, display=%{public}" PRIu64,
3666         GetWindowId(), static_cast<uint32_t>(subWindowMap_.size()), GetDisplayId());
3667     if (subWindowMap_.count(GetWindowId()) == 0) {
3668         return;
3669     }
3670     for (auto& subWindow : subWindowMap_.at(GetWindowId())) {
3671         if (subWindow == nullptr) {
3672             TLOGE(WmsLogTag::WMS_ATTRIBUTE, "impl sub window is null");
3673             continue;
3674         }
3675         TLOGD(WmsLogTag::WMS_ATTRIBUTE, "impl win=%{public}u, display=%{public}" PRIu64,
3676             subWindow->GetWindowId(), subWindow->GetDisplayId());
3677         subWindow->UpdateConfiguration(configuration);
3678     }
3679 }
3680 
UpdateConfigurationForSpecified(const std::shared_ptr<AppExecFwk::Configuration> & configuration,const std::shared_ptr<Global::Resource::ResourceManager> & resourceManager)3681 void WindowImpl::UpdateConfigurationForSpecified(const std::shared_ptr<AppExecFwk::Configuration>& configuration,
3682     const std::shared_ptr<Global::Resource::ResourceManager>& resourceManager)
3683 {
3684     if (uiContent_ != nullptr) {
3685         TLOGI(WmsLogTag::WMS_ATTRIBUTE, "notify ace impl win=%{public}u, display=%{public}" PRIu64,
3686             GetWindowId(), GetDisplayId());
3687         uiContent_->UpdateConfiguration(configuration, resourceManager);
3688     } else {
3689         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "uiContent null, impl win=%{public}u, display=%{public}" PRIu64,
3690             GetWindowId(), GetDisplayId());
3691     }
3692     TLOGD(WmsLogTag::WMS_ATTRIBUTE, "impl win=%{public}u, subWinSize=%{public}u, display=%{public}" PRIu64,
3693         GetWindowId(), static_cast<uint32_t>(subWindowMap_.size()), GetDisplayId());
3694     if (subWindowMap_.count(GetWindowId()) == 0) {
3695         return;
3696     }
3697     for (auto& subWindow : subWindowMap_.at(GetWindowId())) {
3698         if (subWindow == nullptr) {
3699             TLOGE(WmsLogTag::WMS_ATTRIBUTE, "impl sub window is null");
3700             continue;
3701         }
3702         TLOGD(WmsLogTag::WMS_ATTRIBUTE, "impl win=%{public}u, display=%{public}" PRIu64,
3703             subWindow->GetWindowId(), subWindow->GetDisplayId());
3704         subWindow->UpdateConfigurationForSpecified(configuration, resourceManager);
3705     }
3706 }
3707 
UpdateConfigurationSync(const std::shared_ptr<AppExecFwk::Configuration> & configuration)3708 void WindowImpl::UpdateConfigurationSync(const std::shared_ptr<AppExecFwk::Configuration>& configuration)
3709 {
3710     if (uiContent_ != nullptr) {
3711         TLOGI(WmsLogTag::WMS_ATTRIBUTE, "notify ace impl win=%{public}u, display=%{public}" PRIu64,
3712             GetWindowId(), GetDisplayId());
3713         uiContent_->UpdateConfigurationSyncForAll(configuration);
3714     } else {
3715         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "uiContent null, impl win=%{public}u, display=%{public}" PRIu64,
3716             GetWindowId(), GetDisplayId());
3717     }
3718     TLOGD(WmsLogTag::WMS_ATTRIBUTE, "impl win=%{public}u, subWinSize=%{public}u, display=%{public}" PRIu64,
3719         GetWindowId(), static_cast<uint32_t>(subWindowMap_.size()), GetDisplayId());
3720     if (subWindowMap_.count(GetWindowId()) == 0) {
3721         return;
3722     }
3723     for (auto& subWindow : subWindowMap_.at(GetWindowId())) {
3724         if (subWindow == nullptr) {
3725             TLOGE(WmsLogTag::WMS_ATTRIBUTE, "impl sub window is null");
3726             continue;
3727         }
3728         TLOGD(WmsLogTag::WMS_ATTRIBUTE, "impl win=%{public}u, display=%{public}" PRIu64,
3729             subWindow->GetWindowId(), subWindow->GetDisplayId());
3730         subWindow->UpdateConfigurationSync(configuration);
3731     }
3732 }
3733 
UpdateConfigurationSyncForAll(const std::shared_ptr<AppExecFwk::Configuration> & configuration)3734 void WindowImpl::UpdateConfigurationSyncForAll(const std::shared_ptr<AppExecFwk::Configuration>& configuration)
3735 {
3736     std::shared_lock<std::shared_mutex> lock(windowMapMutex_);
3737     TLOGD(WmsLogTag::WMS_ATTRIBUTE, "impl map size: %{public}u", static_cast<uint32_t>(windowMap_.size()));
3738     for (const auto& winPair : windowMap_) {
3739         if (auto window = winPair.second.second) {
3740             TLOGD(WmsLogTag::WMS_ATTRIBUTE, "impl win=%{public}u, display=%{public}" PRIu64,
3741                 window->GetWindowId(), window->GetDisplayId());
3742             window->UpdateConfigurationSync(configuration);
3743         }
3744     }
3745 }
3746 
UpdateAvoidArea(const sptr<AvoidArea> & avoidArea,AvoidAreaType type)3747 void WindowImpl::UpdateAvoidArea(const sptr<AvoidArea>& avoidArea, AvoidAreaType type)
3748 {
3749     WLOGI("Update AvoidArea, id: %{public}u", property_->GetWindowId());
3750     auto display = SingletonContainer::IsDestroyed() ? nullptr :
3751         SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
3752     UpdateViewportConfig(GetRect(), display, WindowSizeChangeReason::AVOID_AREA_CHANGE, nullptr, {{type, *avoidArea}});
3753     NotifyAvoidAreaChange(avoidArea, type);
3754 }
3755 
UpdateViewportConfig(const Rect & rect,const sptr<Display> & display,WindowSizeChangeReason reason,const std::shared_ptr<RSTransaction> & rsTransaction,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)3756 void WindowImpl::UpdateViewportConfig(const Rect& rect, const sptr<Display>& display, WindowSizeChangeReason reason,
3757     const std::shared_ptr<RSTransaction>& rsTransaction,
3758     const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
3759 {
3760     std::lock_guard<std::recursive_mutex> lock(mutex_);
3761     if (uiContent_ == nullptr) {
3762         return;
3763     }
3764     Ace::ViewportConfig config;
3765     config.SetSize(rect.width_, rect.height_);
3766     config.SetPosition(rect.posX_, rect.posY_);
3767     config.SetDisplayId(GetDisplayId());
3768     if (display) {
3769         float virtualPixelRatio = display->GetVirtualPixelRatio();
3770         virtualPixelRatio_.store(virtualPixelRatio);
3771         config.SetDensity(virtualPixelRatio);
3772         auto displayInfo = display->GetDisplayInfo();
3773         if (displayInfo != nullptr) {
3774             config.SetOrientation(static_cast<int32_t>(displayInfo->GetDisplayOrientation()));
3775         }
3776     }
3777     uiContent_->UpdateViewportConfig(config, reason, rsTransaction, avoidAreas);
3778     WLOGFD("Id:%{public}u, windowRect:[%{public}d, %{public}d, %{public}u, %{public}u]",
3779         property_->GetWindowId(), rect.posX_, rect.posY_, rect.width_, rect.height_);
3780 }
3781 
UpdateDecorEnable(bool needNotify)3782 void WindowImpl::UpdateDecorEnable(bool needNotify)
3783 {
3784     WLOGFD("Start");
3785     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
3786         bool enable = windowSystemConfig_.isSystemDecorEnable_ &&
3787             WindowHelper::IsWindowModeSupported(windowSystemConfig_.decorWindowModeSupportType_, GetWindowMode());
3788         WLOGFD("Decor enable: %{public}d", static_cast<int32_t>(enable));
3789         property_->SetDecorEnable(enable);
3790     } else {
3791         property_->SetDecorEnable(false);
3792     }
3793     if (needNotify) {
3794         if (uiContent_ != nullptr) {
3795             uiContent_->UpdateWindowMode(GetWindowMode(), property_->GetDecorEnable());
3796             WLOGFD("Notify uiContent window mode change end");
3797         }
3798         NotifyModeChange(GetWindowMode(), property_->GetDecorEnable());
3799     }
3800 }
3801 
UpdateWindowStateUnfrozen()3802 void WindowImpl::UpdateWindowStateUnfrozen()
3803 {
3804     auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
3805     if (abilityContext != nullptr && windowTag_ == WindowTag::MAIN_WINDOW) {
3806         WLOGFD("DoAbilityForeground KEYGUARD, id: %{public}u", GetWindowId());
3807         AAFwk::AbilityManagerClient::GetInstance()->DoAbilityForeground(abilityContext->GetToken(),
3808             static_cast<uint32_t>(WindowStateChangeReason::KEYGUARD));
3809     } else if (state_ != WindowState::STATE_SHOWN) {
3810         state_ = WindowState::STATE_SHOWN;
3811         NotifyAfterForeground();
3812     }
3813 }
3814 
UpdateWindowState(WindowState state)3815 void WindowImpl::UpdateWindowState(WindowState state)
3816 {
3817     WLOGFI("id: %{public}u, State to set:%{public}u", GetWindowId(), state);
3818     if (!IsWindowValid()) {
3819         return;
3820     }
3821     auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
3822     switch (state) {
3823         case WindowState::STATE_FROZEN: {
3824             if (abilityContext != nullptr && windowTag_ == WindowTag::MAIN_WINDOW) {
3825                 WLOGFD("DoAbilityBackground KEYGUARD, id: %{public}u", GetWindowId());
3826                 AAFwk::AbilityManagerClient::GetInstance()->DoAbilityBackground(abilityContext->GetToken(),
3827                     static_cast<uint32_t>(WindowStateChangeReason::KEYGUARD));
3828             } else {
3829                 state_ = WindowState::STATE_FROZEN;
3830                 NotifyAfterBackground(false, true);
3831             }
3832             break;
3833         }
3834         case WindowState::STATE_UNFROZEN: {
3835             UpdateWindowStateUnfrozen();
3836             break;
3837         }
3838         case WindowState::STATE_SHOWN: {
3839             if (abilityContext != nullptr && windowTag_ == WindowTag::MAIN_WINDOW) {
3840                 WLOGFD("WindowState::STATE_SHOWN, id: %{public}u", GetWindowId());
3841                 AAFwk::AbilityManagerClient::GetInstance()->DoAbilityForeground(abilityContext->GetToken(),
3842                     static_cast<uint32_t>(WindowStateChangeReason::TOGGLING));
3843             } else {
3844                 state_ = WindowState::STATE_SHOWN;
3845                 NotifyAfterForeground();
3846             }
3847             break;
3848         }
3849         case WindowState::STATE_HIDDEN: {
3850             if (abilityContext != nullptr && windowTag_ == WindowTag::MAIN_WINDOW &&
3851                 state_ == WindowState::STATE_SHOWN) {
3852                 WLOGFD("WindowState: STATE_SHOWN, id: %{public}u", GetWindowId());
3853                 AAFwk::AbilityManagerClient::GetInstance()->DoAbilityBackground(abilityContext->GetToken(),
3854                     static_cast<uint32_t>(WindowStateChangeReason::NORMAL));
3855             } else {
3856                 Hide(static_cast<uint32_t>(WindowStateChangeReason::NORMAL), false);
3857             }
3858             break;
3859         }
3860         default: {
3861             WLOGFE("windowState to set is invalid");
3862             break;
3863         }
3864     }
3865 }
3866 
UpdateWindowStateWhenShow()3867 WmErrorCode WindowImpl::UpdateWindowStateWhenShow()
3868 {
3869     state_ = WindowState::STATE_SHOWN;
3870     if (WindowHelper::IsMainWindow(property_->GetWindowType()) ||
3871         WindowHelper::IsSystemMainWindow(property_->GetWindowType())) {
3872         // update subwindow subWindowState_ and notify subwindow shown or not
3873         UpdateSubWindowStateAndNotify(GetWindowId());
3874         NotifyAfterForeground();
3875     } else if (GetType() == WindowType::WINDOW_TYPE_APP_COMPONENT) {
3876         subWindowState_ = WindowState::STATE_SHOWN;
3877         NotifyAfterForeground();
3878     } else {
3879         uint32_t parentId = property_->GetParentId();
3880         sptr<Window> parentWindow = FindWindowById(parentId);
3881         if (parentWindow == nullptr) {
3882             WLOGE("parent window is null");
3883             return WmErrorCode::WM_ERROR_STATE_ABNORMALLY;
3884         }
3885         if (parentWindow->GetWindowState() == WindowState::STATE_HIDDEN) {
3886             // not notify user shown and update subwindowState_
3887             subWindowState_ = WindowState::STATE_HIDDEN;
3888         } else if (parentWindow->GetWindowState() == WindowState::STATE_SHOWN) {
3889             NotifyAfterForeground();
3890             subWindowState_ = WindowState::STATE_SHOWN;
3891         }
3892     }
3893     if (needNotifyFocusLater_ && isFocused_) {
3894         UpdateFocusStatus(true);
3895     }
3896     return WmErrorCode::WM_OK;
3897 }
3898 
UpdateWindowStateWhenHide()3899 WmErrorCode WindowImpl::UpdateWindowStateWhenHide()
3900 {
3901     state_ = WindowState::STATE_HIDDEN;
3902     if (WindowHelper::IsSystemMainWindow(property_->GetWindowType()) ||
3903         WindowHelper::IsMainWindow(property_->GetWindowType())) {
3904         // main window need to update subwindow subWindowState_ and notify subwindow shown or not
3905         UpdateSubWindowStateAndNotify(GetWindowId());
3906         NotifyAfterBackground();
3907     } else if (GetType() == WindowType::WINDOW_TYPE_APP_COMPONENT) {
3908         subWindowState_ = WindowState::STATE_HIDDEN;
3909         NotifyAfterBackground();
3910     } else {
3911         uint32_t parentId = property_->GetParentId();
3912         sptr<Window> parentWindow = FindWindowById(parentId);
3913         if (parentWindow == nullptr) {
3914             WLOGE("parent window is null");
3915             return WmErrorCode::WM_ERROR_STATE_ABNORMALLY;
3916         }
3917         if (subWindowState_ == WindowState::STATE_SHOWN) {
3918             NotifyAfterBackground();
3919         }
3920         subWindowState_ = WindowState::STATE_HIDDEN;
3921     }
3922     return WmErrorCode::WM_OK;
3923 }
3924 
UpdateSubWindowStateAndNotify(uint32_t parentId)3925 WmErrorCode WindowImpl::UpdateSubWindowStateAndNotify(uint32_t parentId)
3926 {
3927     if (subWindowMap_.find(parentId) == subWindowMap_.end()) {
3928         WLOGFD("main window: %{public}u has no child node", parentId);
3929         return WmErrorCode::WM_OK;
3930     }
3931     std::vector<sptr<WindowImpl>> subWindows = subWindowMap_[parentId];
3932     if (subWindows.empty()) {
3933         WLOGFD("main window: %{public}u, its subWindowMap is empty", parentId);
3934         return WmErrorCode::WM_OK;
3935     }
3936     // when main window hide and subwindow whose state is shown should hide and notify user
3937     if (state_ == WindowState::STATE_HIDDEN) {
3938         for (auto subwindow : subWindows) {
3939             if (subwindow->GetWindowState() == WindowState::STATE_SHOWN &&
3940                 subwindow->subWindowState_ == WindowState::STATE_SHOWN) {
3941                 subwindow->NotifyAfterBackground();
3942             }
3943             subwindow->subWindowState_ = WindowState::STATE_HIDDEN;
3944         }
3945     // when main window show and subwindow whose state is shown should show and notify user
3946     } else if (state_ == WindowState::STATE_SHOWN) {
3947         for (auto subwindow : subWindows) {
3948             if (subwindow->GetWindowState() == WindowState::STATE_SHOWN &&
3949                 subwindow->subWindowState_ == WindowState::STATE_HIDDEN) {
3950                 subwindow->NotifyAfterForeground();
3951                 subwindow->subWindowState_ = WindowState::STATE_SHOWN;
3952             } else {
3953                 subwindow->subWindowState_ = WindowState::STATE_HIDDEN;
3954             }
3955         }
3956     }
3957     return WmErrorCode::WM_OK;
3958 }
3959 
GetWindowProperty()3960 sptr<WindowProperty> WindowImpl::GetWindowProperty()
3961 {
3962     return property_;
3963 }
3964 
RestoreSplitWindowMode(uint32_t mode)3965 void WindowImpl::RestoreSplitWindowMode(uint32_t mode)
3966 {
3967     if (!IsWindowValid()) {
3968         return;
3969     }
3970     auto windowMode = static_cast<WindowMode>(mode);
3971     if (windowMode == WindowMode::WINDOW_MODE_SPLIT_PRIMARY || windowMode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY) {
3972         UpdateMode(windowMode);
3973     }
3974 }
3975 
UpdateDragEvent(const PointInfo & point,DragEvent event)3976 void WindowImpl::UpdateDragEvent(const PointInfo& point, DragEvent event)
3977 {
3978     NotifyDragEvent(point, event);
3979 }
3980 
NotifyDragEvent(const PointInfo & point,DragEvent event)3981 void WindowImpl::NotifyDragEvent(const PointInfo& point, DragEvent event)
3982 {
3983     auto windowDragListeners = GetListeners<IWindowDragListener>();
3984     Rect rect = GetRect();
3985     for (auto& listener : windowDragListeners) {
3986         if (listener != nullptr) {
3987             listener->OnDrag(point.x - rect.posX_, point.y - rect.posY_, event);
3988         }
3989     }
3990 }
3991 
UpdateDisplayId(DisplayId from,DisplayId to)3992 void WindowImpl::UpdateDisplayId(DisplayId from, DisplayId to)
3993 {
3994     WLOGFD("update displayId. win %{public}u", GetWindowId());
3995     NotifyDisplayMoveChange(from, to);
3996     property_->SetDisplayId(to);
3997 }
3998 
UpdateOccupiedAreaChangeInfo(const sptr<OccupiedAreaChangeInfo> & info,const std::shared_ptr<RSTransaction> & rsTransaction)3999 void WindowImpl::UpdateOccupiedAreaChangeInfo(const sptr<OccupiedAreaChangeInfo>& info,
4000     const std::shared_ptr<RSTransaction>& rsTransaction)
4001 {
4002     WLOGFD("Update OccupiedArea, id: %{public}u", property_->GetWindowId());
4003     NotifyOccupiedAreaChange(info, rsTransaction);
4004 }
4005 
UpdateActiveStatus(bool isActive)4006 void WindowImpl::UpdateActiveStatus(bool isActive)
4007 {
4008     WLOGFD("window active status: %{public}d, id: %{public}u", isActive, property_->GetWindowId());
4009     if (isActive) {
4010         NotifyAfterActive();
4011     } else {
4012         NotifyAfterInactive();
4013     }
4014 }
4015 
NotifyScreenshot()4016 void WindowImpl::NotifyScreenshot()
4017 {
4018     auto screenshotListeners = GetListeners<IScreenshotListener>();
4019     for (auto& screenshotListener : screenshotListeners) {
4020         if (screenshotListener != nullptr) {
4021             screenshotListener->OnScreenshot();
4022         }
4023     }
4024 }
4025 
NotifyScreenshotAppEvent(ScreenshotEventType type)4026 WMError WindowImpl::NotifyScreenshotAppEvent(ScreenshotEventType type)
4027 {
4028     auto screenshotAppEventListeners = GetListeners<IScreenshotAppEventListener>();
4029     for (auto& screenshotAppEventListener : screenshotAppEventListeners) {
4030         if (screenshotAppEventListener != nullptr) {
4031             screenshotAppEventListener->OnScreenshotAppEvent(type);
4032         }
4033     }
4034     return WMError::WM_OK;
4035 }
4036 
NotifyTouchOutside()4037 void WindowImpl::NotifyTouchOutside()
4038 {
4039     auto touchOutsideListeners = GetListeners<ITouchOutsideListener>();
4040     for (auto& touchOutsideListener : touchOutsideListeners) {
4041         if (touchOutsideListener != nullptr) {
4042             touchOutsideListener->OnTouchOutside();
4043         }
4044     }
4045 }
4046 
NotifyTouchDialogTarget(int32_t posX,int32_t posY)4047 void WindowImpl::NotifyTouchDialogTarget(int32_t posX, int32_t posY)
4048 {
4049     SingletonContainer::Get<WindowAdapter>().ProcessPointDown(property_->GetWindowId());
4050     auto dialogTargetTouchListeners = GetListeners<IDialogTargetTouchListener>();
4051     for (auto& dialogTargetTouchListener : dialogTargetTouchListeners) {
4052         if (dialogTargetTouchListener != nullptr) {
4053             dialogTargetTouchListener->OnDialogTargetTouch();
4054         }
4055     }
4056 }
4057 
NotifyDestroy()4058 void WindowImpl::NotifyDestroy()
4059 {
4060     auto dialogDeathRecipientListener = GetListener<IDialogDeathRecipientListener>();
4061     if (dialogDeathRecipientListener != nullptr) {
4062         dialogDeathRecipientListener->OnDialogDeathRecipient();
4063     }
4064 }
4065 
NotifyForeground()4066 void WindowImpl::NotifyForeground()
4067 {
4068     NotifyAfterForeground();
4069 }
4070 
NotifyBackground()4071 void WindowImpl::NotifyBackground()
4072 {
4073     NotifyAfterBackground();
4074 }
4075 
NotifyForegroundInteractiveStatus(bool interactive)4076 void WindowImpl::NotifyForegroundInteractiveStatus(bool interactive)
4077 {
4078     WLOGFI("NotifyForegroundInteractiveStatus %{public}d", interactive);
4079     if (!IsWindowValid() || state_ != WindowState::STATE_SHOWN) {
4080         return;
4081     }
4082     if (interactive) {
4083         NotifyAfterResumed();
4084     } else {
4085         NotifyAfterPaused();
4086     }
4087 }
4088 
NotifyMMIServiceOnline(uint32_t winId)4089 void WindowImpl::NotifyMMIServiceOnline(uint32_t winId)
4090 {
4091     TLOGI(WmsLogTag::WMS_EVENT, "Id:%{public}u", winId);
4092     ResetInputWindow(winId);
4093 }
4094 
TransformSurfaceNode(const Transform & trans)4095 void WindowImpl::TransformSurfaceNode(const Transform& trans)
4096 {
4097     if (surfaceNode_ == nullptr) {
4098         return;
4099     }
4100     surfaceNode_->SetPivotX(trans.pivotX_);
4101     surfaceNode_->SetPivotY(trans.pivotY_);
4102     surfaceNode_->SetScaleX(trans.scaleX_);
4103     surfaceNode_->SetScaleY(trans.scaleY_);
4104     surfaceNode_->SetTranslateX(trans.translateX_);
4105     surfaceNode_->SetTranslateY(trans.translateY_);
4106     surfaceNode_->SetTranslateZ(trans.translateZ_);
4107     surfaceNode_->SetRotationX(trans.rotationX_);
4108     surfaceNode_->SetRotationY(trans.rotationY_);
4109     surfaceNode_->SetRotation(trans.rotationZ_);
4110 }
4111 
UpdateZoomTransform(const Transform & trans,bool isDisplayZoomOn)4112 void WindowImpl::UpdateZoomTransform(const Transform& trans, bool isDisplayZoomOn)
4113 {
4114     WLOGFD("%{public}s zoomTrans, pivotX:%{public}f, pivotY:%{public}f, scaleX:%{public}f, scaleY:%{public}f"
4115         ", transX:%{public}f, transY:%{public}f, transZ:%{public}f, rotateX:%{public}f, rotateY:%{public}f "
4116         "rotateZ:%{public}f", property_->GetWindowName().c_str(), trans.pivotX_, trans.pivotY_, trans.scaleX_,
4117         trans.scaleY_, trans.translateX_, trans.translateY_, trans.translateZ_, trans.rotationX_,
4118         trans.rotationY_, trans.rotationZ_);
4119     property_->SetZoomTransform(trans);
4120     property_->SetDisplayZoomState(isDisplayZoomOn);
4121 }
4122 
ClearListenersById(uint32_t winId)4123 void WindowImpl::ClearListenersById(uint32_t winId)
4124 {
4125     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
4126     ClearUselessListeners(screenshotListeners_, winId);
4127     ClearUselessListeners(touchOutsideListeners_, winId);
4128     ClearUselessListeners(dialogTargetTouchListeners_, winId);
4129     ClearUselessListeners(lifecycleListeners_, winId);
4130     ClearUselessListeners(windowChangeListeners_, winId);
4131     ClearUselessListeners(avoidAreaChangeListeners_, winId);
4132     ClearUselessListeners(occupiedAreaChangeListeners_, winId);
4133     ClearUselessListeners(dialogDeathRecipientListener_, winId);
4134 }
4135 
NotifyAfterForeground(bool needNotifyListeners,bool needNotifyUiContent)4136 void WindowImpl::NotifyAfterForeground(bool needNotifyListeners, bool needNotifyUiContent)
4137 {
4138     if (needNotifyListeners) {
4139         auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4140         CALL_LIFECYCLE_LISTENER(AfterForeground, lifecycleListeners);
4141     }
4142     if (needNotifyUiContent) {
4143         CALL_UI_CONTENT(Foreground);
4144     }
4145     if (!intentParam_.empty()) {
4146         auto uiContent = GetUIContent();
4147         if (uiContent != nullptr) {
4148             TLOGI(WmsLogTag::WMS_LIFE, "SetIntentParam, isColdStart:%{public}u", isIntentColdStart_);
4149             uiContent->SetIntentParam(intentParam_, std::move(loadPageCallback_), isIntentColdStart_);
4150             intentParam_ = "";
4151         } else {
4152             TLOGE(WmsLogTag::WMS_LIFE, "uiContent is nullptr.");
4153         }
4154     }
4155 }
4156 
NotifyAfterDidForeground(uint32_t reason)4157 void WindowImpl::NotifyAfterDidForeground(uint32_t reason)
4158 {
4159     TLOGI(WmsLogTag::WMS_LIFE, "reason: %{public}d", reason);
4160     if (reason != static_cast<uint32_t>(WindowStateChangeReason::ABILITY_CALL)) {
4161         TLOGI(WmsLogTag::WMS_LIFE, "reason: %{public}d no need notify did foreground", reason);
4162         return;
4163     }
4164     if (handler_ == nullptr) {
4165         TLOGE(WmsLogTag::WMS_LIFE, "handler is nullptr");
4166         return;
4167     }
4168     const char* const where = __func__;
4169     handler_->PostTask([weak = wptr(this), where] {
4170         auto window = weak.promote();
4171         if (window == nullptr) {
4172             TLOGNE(WmsLogTag::WMS_LIFE, "%{public}s window is nullptr", where);
4173             return;
4174         }
4175         TLOGNI(WmsLogTag::WMS_LIFE, "%{public}s execute", where);
4176         auto lifecycleListeners = window->GetListeners<IWindowLifeCycle>();
4177         CALL_LIFECYCLE_LISTENER(AfterDidForeground, lifecycleListeners);
4178     }, where, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
4179 }
4180 
NotifyAfterBackground(bool needNotifyListeners,bool needNotifyUiContent)4181 void WindowImpl::NotifyAfterBackground(bool needNotifyListeners, bool needNotifyUiContent)
4182 {
4183     if (needNotifyListeners) {
4184         auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4185         CALL_LIFECYCLE_LISTENER(AfterBackground, lifecycleListeners);
4186     }
4187     if (needNotifyUiContent) {
4188         CALL_UI_CONTENT(Background);
4189     }
4190 }
4191 
NotifyAfterDidBackground(uint32_t reason)4192 void WindowImpl::NotifyAfterDidBackground(uint32_t reason)
4193 {
4194     TLOGI(WmsLogTag::WMS_LIFE, "reason: %{public}d", reason);
4195     if (reason != static_cast<uint32_t>(WindowStateChangeReason::ABILITY_CALL)) {
4196         TLOGI(WmsLogTag::WMS_LIFE, "reason: %{public}d no need notify did background", reason);
4197         return;
4198     }
4199     if (handler_ == nullptr) {
4200         TLOGE(WmsLogTag::WMS_LIFE, "handler is nullptr");
4201         return;
4202     }
4203     const char* const where = __func__;
4204     handler_->PostTask([weak = wptr(this), where] {
4205         auto window = weak.promote();
4206         if (window == nullptr) {
4207             TLOGNI(WmsLogTag::WMS_LIFE, "%{public}s window is nullptr", where);
4208             return;
4209         }
4210         TLOGNI(WmsLogTag::WMS_LIFE, "%{public}s execute", where);
4211         auto lifecycleListeners = window->GetListeners<IWindowLifeCycle>();
4212         CALL_LIFECYCLE_LISTENER(AfterDidBackground, lifecycleListeners);
4213     }, where, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
4214 }
4215 
NotifyAfterFocused()4216 void WindowImpl::NotifyAfterFocused()
4217 {
4218     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4219     CALL_LIFECYCLE_LISTENER(AfterFocused, lifecycleListeners);
4220     CALL_UI_CONTENT(Focus);
4221 }
4222 
NotifyAfterUnfocused(bool needNotifyUiContent)4223 void WindowImpl::NotifyAfterUnfocused(bool needNotifyUiContent)
4224 {
4225     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4226     // use needNotifyUinContent to separate ui content callbacks
4227     CALL_LIFECYCLE_LISTENER(AfterUnfocused, lifecycleListeners);
4228     if (needNotifyUiContent) {
4229         CALL_UI_CONTENT(UnFocus);
4230     }
4231 }
4232 
NotifyAfterResumed()4233 void WindowImpl::NotifyAfterResumed()
4234 {
4235     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4236     CALL_LIFECYCLE_LISTENER(AfterResumed, lifecycleListeners);
4237 }
4238 
NotifyAfterPaused()4239 void WindowImpl::NotifyAfterPaused()
4240 {
4241     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4242     CALL_LIFECYCLE_LISTENER(AfterPaused, lifecycleListeners);
4243 }
4244 
NotifyBeforeDestroy(std::string windowName)4245 void WindowImpl::NotifyBeforeDestroy(std::string windowName)
4246 {
4247     std::lock_guard<std::recursive_mutex> lock(mutex_);
4248     if (uiContent_ != nullptr) {
4249         auto uiContent = std::move(uiContent_);
4250         uiContent_ = nullptr;
4251         uiContent->Destroy();
4252     }
4253     if (notifyNativefunc_) {
4254         notifyNativefunc_(windowName);
4255     }
4256 }
4257 
NotifyBeforeSubWindowDestroy(sptr<WindowImpl> window)4258 void WindowImpl::NotifyBeforeSubWindowDestroy(sptr<WindowImpl> window)
4259 {
4260     auto uiContent = window->GetUIContent();
4261     if (uiContent != nullptr) {
4262         uiContent->Destroy();
4263     }
4264     if (window->GetNativeDestroyCallback()) {
4265         window->GetNativeDestroyCallback()(window->GetWindowName());
4266     }
4267 }
4268 
NotifyAfterActive()4269 void WindowImpl::NotifyAfterActive()
4270 {
4271     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4272     CALL_LIFECYCLE_LISTENER(AfterActive, lifecycleListeners);
4273 }
4274 
NotifyAfterInactive()4275 void WindowImpl::NotifyAfterInactive()
4276 {
4277     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4278     CALL_LIFECYCLE_LISTENER(AfterInactive, lifecycleListeners);
4279 }
4280 
NotifyForegroundFailed(WMError ret)4281 void WindowImpl::NotifyForegroundFailed(WMError ret)
4282 {
4283     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4284     CALL_LIFECYCLE_LISTENER_WITH_PARAM(ForegroundFailed, lifecycleListeners, static_cast<int32_t>(ret));
4285 }
4286 
NotifyBackgroundFailed(WMError ret)4287 void WindowImpl::NotifyBackgroundFailed(WMError ret)
4288 {
4289     auto lifecycleListeners = GetListeners<IWindowLifeCycle>();
4290     CALL_LIFECYCLE_LISTENER_WITH_PARAM(BackgroundFailed, lifecycleListeners, static_cast<int32_t>(ret));
4291 }
4292 
IsStretchableReason(WindowSizeChangeReason reason)4293 bool WindowImpl::IsStretchableReason(WindowSizeChangeReason reason)
4294 {
4295     return reason == WindowSizeChangeReason::DRAG || reason == WindowSizeChangeReason::DRAG_END ||
4296            reason == WindowSizeChangeReason::DRAG_START || reason == WindowSizeChangeReason::RECOVER ||
4297            IsMoveToOrDragMove(reason) || reason == WindowSizeChangeReason::UNDEFINED;
4298 }
4299 
NotifySizeChange(Rect rect,WindowSizeChangeReason reason,const std::shared_ptr<RSTransaction> & rsTransaction)4300 void WindowImpl::NotifySizeChange(Rect rect, WindowSizeChangeReason reason,
4301     const std::shared_ptr<RSTransaction>& rsTransaction)
4302 {
4303     auto windowChangeListeners = GetListeners<IWindowChangeListener>();
4304     for (auto& listener : windowChangeListeners) {
4305         if (listener != nullptr) {
4306             listener->OnSizeChange(rect, reason, rsTransaction);
4307         }
4308     }
4309 }
4310 
NotifyAvoidAreaChange(const sptr<AvoidArea> & avoidArea,AvoidAreaType type)4311 void WindowImpl::NotifyAvoidAreaChange(const sptr<AvoidArea>& avoidArea, AvoidAreaType type)
4312 {
4313     auto avoidAreaChangeListeners = GetListeners<IAvoidAreaChangedListener>();
4314     for (auto& listener : avoidAreaChangeListeners) {
4315         if (listener != nullptr) {
4316             listener->OnAvoidAreaChanged(*avoidArea, type);
4317         }
4318     }
4319 }
4320 
NotifyDisplayMoveChange(DisplayId from,DisplayId to)4321 void WindowImpl::NotifyDisplayMoveChange(DisplayId from, DisplayId to)
4322 {
4323     auto displayMoveListeners = GetListeners<IDisplayMoveListener>();
4324     for (auto& listener : displayMoveListeners) {
4325         if (listener != nullptr) {
4326             listener->OnDisplayMove(from, to);
4327         }
4328     }
4329 }
4330 
NotifyModeChange(WindowMode mode,bool hasDeco)4331 void WindowImpl::NotifyModeChange(WindowMode mode, bool hasDeco)
4332 {
4333     auto windowChangeListeners = GetListeners<IWindowChangeListener>();
4334     for (auto& listener : windowChangeListeners) {
4335         if (listener != nullptr) {
4336             listener->OnModeChange(mode, hasDeco);
4337         }
4338     }
4339 }
4340 
NotifyOccupiedAreaChange(const sptr<OccupiedAreaChangeInfo> & info,const std::shared_ptr<RSTransaction> & rsTransaction)4341 void WindowImpl::NotifyOccupiedAreaChange(const sptr<OccupiedAreaChangeInfo>& info,
4342     const std::shared_ptr<RSTransaction>& rsTransaction)
4343 {
4344     auto occupiedAreaChangeListeners = GetListeners<IOccupiedAreaChangeListener>();
4345     for (auto& listener : occupiedAreaChangeListeners) {
4346         if (listener != nullptr) {
4347             listener->OnSizeChange(info, rsTransaction);
4348         }
4349     }
4350 }
4351 
SetNeedRemoveWindowInputChannel(bool needRemoveWindowInputChannel)4352 void WindowImpl::SetNeedRemoveWindowInputChannel(bool needRemoveWindowInputChannel)
4353 {
4354     needRemoveWindowInputChannel_ = needRemoveWindowInputChannel;
4355 }
4356 
GetSystemAlarmWindowDefaultSize(Rect defaultRect)4357 Rect WindowImpl::GetSystemAlarmWindowDefaultSize(Rect defaultRect)
4358 {
4359     auto display = SingletonContainer::IsDestroyed() ? nullptr :
4360         SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
4361     if (display == nullptr) {
4362         WLOGFE("get display failed displayId:%{public}" PRIu64", window id:%{public}u", property_->GetDisplayId(),
4363             property_->GetWindowId());
4364         return defaultRect;
4365     }
4366     uint32_t width = static_cast<uint32_t>(display->GetWidth());
4367     uint32_t height = static_cast<uint32_t>(display->GetHeight());
4368     WLOGFD("width:%{public}u, height:%{public}u, displayId:%{public}" PRIu64"",
4369         width, height, property_->GetDisplayId());
4370     uint32_t alarmWidth = static_cast<uint32_t>((static_cast<float>(width) *
4371         SYSTEM_ALARM_WINDOW_WIDTH_RATIO));
4372     uint32_t alarmHeight = static_cast<uint32_t>((static_cast<float>(height) *
4373         SYSTEM_ALARM_WINDOW_HEIGHT_RATIO));
4374 
4375     Rect rect = { static_cast<int32_t>((width - alarmWidth) / 2), static_cast<int32_t>((height - alarmHeight) / 2),
4376         alarmWidth, alarmHeight }; // divided by 2 to middle the window
4377     return rect;
4378 }
4379 
SetDefaultOption()4380 void WindowImpl::SetDefaultOption()
4381 {
4382     switch (property_->GetWindowType()) {
4383         case WindowType::WINDOW_TYPE_STATUS_BAR:
4384         case WindowType::WINDOW_TYPE_NAVIGATION_BAR:
4385         case WindowType::WINDOW_TYPE_VOLUME_OVERLAY:
4386         case WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT:
4387         case WindowType::WINDOW_TYPE_INPUT_METHOD_STATUS_BAR: {
4388             property_->SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
4389             property_->SetFocusable(false);
4390             break;
4391         }
4392         case WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW: {
4393             property_->SetRequestRect(GetSystemAlarmWindowDefaultSize(property_->GetRequestRect()));
4394             property_->SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
4395             break;
4396         }
4397         case WindowType::WINDOW_TYPE_KEYGUARD: {
4398             RemoveWindowFlag(WindowFlag::WINDOW_FLAG_NEED_AVOID);
4399             property_->SetWindowMode(WindowMode::WINDOW_MODE_FULLSCREEN);
4400             break;
4401         }
4402         case WindowType::WINDOW_TYPE_DRAGGING_EFFECT: {
4403             property_->SetWindowFlags(0);
4404             break;
4405         }
4406         case WindowType::WINDOW_TYPE_APP_COMPONENT: {
4407             property_->SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
4408             property_->SetAnimationFlag(static_cast<uint32_t>(WindowAnimation::NONE));
4409             break;
4410         }
4411         case WindowType::WINDOW_TYPE_TOAST:
4412         case WindowType::WINDOW_TYPE_FLOAT:
4413         case WindowType::WINDOW_TYPE_SYSTEM_FLOAT:
4414         case WindowType::WINDOW_TYPE_FLOAT_CAMERA:
4415         case WindowType::WINDOW_TYPE_VOICE_INTERACTION:
4416         case WindowType::WINDOW_TYPE_LAUNCHER_DOCK:
4417         case WindowType::WINDOW_TYPE_SEARCHING_BAR:
4418         case WindowType::WINDOW_TYPE_SCREENSHOT:
4419         case WindowType::WINDOW_TYPE_GLOBAL_SEARCH:
4420         case WindowType::WINDOW_TYPE_DIALOG: {
4421             property_->SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
4422             break;
4423         }
4424         case WindowType::WINDOW_TYPE_BOOT_ANIMATION:
4425         case WindowType::WINDOW_TYPE_POINTER: {
4426             property_->SetFocusable(false);
4427             break;
4428         }
4429         case WindowType::WINDOW_TYPE_DOCK_SLICE: {
4430             property_->SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
4431             property_->SetFocusable(false);
4432             break;
4433         }
4434         case WindowType::WINDOW_TYPE_SYSTEM_TOAST: {
4435             property_->SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
4436             property_->SetTouchable(false);
4437             property_->SetFocusable(false);
4438             break;
4439         }
4440         case WindowType::WINDOW_TYPE_SCREEN_CONTROL: {
4441             property_->SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
4442             property_->SetTouchable(false);
4443             property_->SetFocusable(false);
4444             SetAlpha(0);
4445             break;
4446         }
4447         default:
4448             break;
4449     }
4450 }
4451 
IsWindowValid() const4452 bool WindowImpl::IsWindowValid() const
4453 {
4454     bool res = ((state_ > WindowState::STATE_INITIAL) && (state_ < WindowState::STATE_BOTTOM));
4455     if (!res) {
4456         WLOGW("already destroyed or not created! id: %{public}u", GetWindowId());
4457     }
4458     return res;
4459 }
4460 
IsLayoutFullScreen() const4461 bool WindowImpl::IsLayoutFullScreen() const
4462 {
4463     if (!IsWindowValid()) {
4464         return false;
4465     }
4466     auto mode = GetWindowMode();
4467     return (mode == WindowMode::WINDOW_MODE_FULLSCREEN && isIgnoreSafeArea_);
4468 }
4469 
IsFullScreen() const4470 bool WindowImpl::IsFullScreen() const
4471 {
4472     if (!IsWindowValid()) {
4473         return false;
4474     }
4475     auto statusProperty = GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_STATUS_BAR);
4476     auto naviProperty = GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_NAVIGATION_BAR);
4477     return (IsLayoutFullScreen() && !statusProperty.enable_ && !naviProperty.enable_);
4478 }
4479 
SetRequestedOrientation(Orientation orientation,bool needAnimation)4480 void WindowImpl::SetRequestedOrientation(Orientation orientation, bool needAnimation)
4481 {
4482     if (!IsWindowValid()) {
4483         TLOGE(WmsLogTag::DEFAULT, "window is invalid");
4484         return;
4485     }
4486     if (property_->GetRequestedOrientation() == orientation) {
4487         return;
4488     }
4489     property_->SetRequestedOrientation(orientation);
4490     if (state_ == WindowState::STATE_SHOWN) {
4491         UpdateProperty(PropertyChangeAction::ACTION_UPDATE_ORIENTATION);
4492     }
4493 }
4494 
GetRequestedOrientation()4495 Orientation WindowImpl::GetRequestedOrientation()
4496 {
4497     if (!IsWindowValid()) {
4498         TLOGE(WmsLogTag::DEFAULT, "window is invalid");
4499         return Orientation::UNSPECIFIED;
4500     }
4501     return property_->GetRequestedOrientation();
4502 }
4503 
SetTouchHotAreas(const std::vector<Rect> & rects)4504 WMError WindowImpl::SetTouchHotAreas(const std::vector<Rect>& rects)
4505 {
4506     std::vector<Rect> lastTouchHotAreas;
4507     property_->GetTouchHotAreas(lastTouchHotAreas);
4508 
4509     property_->SetTouchHotAreas(rects);
4510     WMError result = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_TOUCH_HOT_AREA);
4511     if (result != WMError::WM_OK) {
4512         property_->SetTouchHotAreas(lastTouchHotAreas);
4513     }
4514     return result;
4515 }
4516 
GetRequestedTouchHotAreas(std::vector<Rect> & rects) const4517 void WindowImpl::GetRequestedTouchHotAreas(std::vector<Rect>& rects) const
4518 {
4519     property_->GetTouchHotAreas(rects);
4520 }
4521 
SetAPPWindowLabel(const std::string & label)4522 WMError WindowImpl::SetAPPWindowLabel(const std::string& label)
4523 {
4524     if (uiContent_ == nullptr) {
4525         WLOGFE("uicontent is empty");
4526         return WMError::WM_ERROR_NULLPTR;
4527     }
4528     uiContent_->SetAppWindowTitle(label);
4529     WLOGI("Set app window label success, label : %{public}s", label.c_str());
4530     return WMError::WM_OK;
4531 }
4532 
SetAPPWindowIcon(const std::shared_ptr<Media::PixelMap> & icon)4533 WMError WindowImpl::SetAPPWindowIcon(const std::shared_ptr<Media::PixelMap>& icon)
4534 {
4535     if (icon == nullptr) {
4536         WLOGFE("window icon is empty");
4537         return WMError::WM_ERROR_NULLPTR;
4538     }
4539     if (uiContent_ == nullptr) {
4540         WLOGFE("uicontent is empty");
4541         return WMError::WM_ERROR_NULLPTR;
4542     }
4543     uiContent_->SetAppWindowIcon(icon);
4544     WLOGI("Set app window icon success");
4545     return WMError::WM_OK;
4546 }
4547 
CheckCameraFloatingWindowMultiCreated(WindowType type)4548 bool WindowImpl::CheckCameraFloatingWindowMultiCreated(WindowType type)
4549 {
4550     if (type != WindowType::WINDOW_TYPE_FLOAT_CAMERA) {
4551         return false;
4552     }
4553 
4554     {
4555         std::shared_lock<std::shared_mutex> lock(windowMapMutex_);
4556         for (auto& winPair : windowMap_) {
4557             if (winPair.second.second->GetType() == WindowType::WINDOW_TYPE_FLOAT_CAMERA) {
4558                 return true;
4559             }
4560         }
4561     }
4562     uint32_t accessTokenId = static_cast<uint32_t>(IPCSkeleton::GetCallingTokenID());
4563     property_->SetAccessTokenId(accessTokenId);
4564     TLOGI(WmsLogTag::DEFAULT, "Create camera float window, TokenId=%{private}u", accessTokenId);
4565     return false;
4566 }
4567 
SetCornerRadius(float cornerRadius)4568 WMError WindowImpl::SetCornerRadius(float cornerRadius)
4569 {
4570     WLOGI("Window %{public}s set corner radius %{public}f", name_.c_str(), cornerRadius);
4571     surfaceNode_->SetCornerRadius(cornerRadius);
4572     RSTransactionAdapter::FlushImplicitTransaction(surfaceNode_);
4573     return WMError::WM_OK;
4574 }
4575 
SetShadowRadius(float radius)4576 WMError WindowImpl::SetShadowRadius(float radius)
4577 {
4578     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
4579         WLOGFE("set shadow radius permission denied!");
4580         return WMError::WM_ERROR_NOT_SYSTEM_APP;
4581     }
4582     WLOGI("Window %{public}s set shadow radius %{public}f", name_.c_str(), radius);
4583     if (MathHelper::LessNotEqual(radius, 0.0)) {
4584         return WMError::WM_ERROR_INVALID_PARAM;
4585     }
4586     surfaceNode_->SetShadowRadius(radius);
4587     RSTransactionAdapter::FlushImplicitTransaction(surfaceNode_);
4588     return WMError::WM_OK;
4589 }
4590 
SetShadowColor(std::string color)4591 WMError WindowImpl::SetShadowColor(std::string color)
4592 {
4593     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
4594         WLOGFE("set shadow color permission denied!");
4595         return WMError::WM_ERROR_NOT_SYSTEM_APP;
4596     }
4597     WLOGI("Window %{public}s set shadow color %{public}s", name_.c_str(), color.c_str());
4598     uint32_t colorValue;
4599     if (!ColorParser::Parse(color, colorValue)) {
4600         return WMError::WM_ERROR_INVALID_PARAM;
4601     }
4602     surfaceNode_->SetShadowColor(colorValue);
4603     RSTransactionAdapter::FlushImplicitTransaction(surfaceNode_);
4604     return WMError::WM_OK;
4605 }
4606 
SetShadowOffsetX(float offsetX)4607 WMError WindowImpl::SetShadowOffsetX(float offsetX)
4608 {
4609     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
4610         WLOGFE("set shadow offset x permission denied!");
4611         return WMError::WM_ERROR_NOT_SYSTEM_APP;
4612     }
4613     WLOGI("Window %{public}s set shadow offsetX %{public}f", name_.c_str(), offsetX);
4614     surfaceNode_->SetShadowOffsetX(offsetX);
4615     RSTransactionAdapter::FlushImplicitTransaction(surfaceNode_);
4616     return WMError::WM_OK;
4617 }
4618 
SetShadowOffsetY(float offsetY)4619 WMError WindowImpl::SetShadowOffsetY(float offsetY)
4620 {
4621     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
4622         WLOGFE("set shadow offset y permission denied!");
4623         return WMError::WM_ERROR_NOT_SYSTEM_APP;
4624     }
4625     WLOGI("Window %{public}s set shadow offsetY %{public}f", name_.c_str(), offsetY);
4626     surfaceNode_->SetShadowOffsetY(offsetY);
4627     RSTransactionAdapter::FlushImplicitTransaction(surfaceNode_);
4628     return WMError::WM_OK;
4629 }
4630 
SetBlur(float radius)4631 WMError WindowImpl::SetBlur(float radius)
4632 {
4633     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
4634         WLOGFE("set blur permission denied!");
4635         return WMError::WM_ERROR_NOT_SYSTEM_APP;
4636     }
4637     WLOGI("Window %{public}s set blur radius %{public}f", name_.c_str(), radius);
4638     if (MathHelper::LessNotEqual(radius, 0.0)) {
4639         return WMError::WM_ERROR_INVALID_PARAM;
4640     }
4641     radius = ConvertRadiusToSigma(radius);
4642     WLOGFI("[Client] Window %{public}s set blur radius after conversion %{public}f", name_.c_str(), radius);
4643     surfaceNode_->SetFilter(RSFilter::CreateBlurFilter(radius, radius));
4644     RSTransactionAdapter::FlushImplicitTransaction(surfaceNode_);
4645     return WMError::WM_OK;
4646 }
4647 
SetBackdropBlur(float radius)4648 WMError WindowImpl::SetBackdropBlur(float radius)
4649 {
4650     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
4651         WLOGFE("set backdrop blur permission denied!");
4652         return WMError::WM_ERROR_NOT_SYSTEM_APP;
4653     }
4654     WLOGI("Window %{public}s set backdrop blur radius %{public}f", name_.c_str(), radius);
4655     if (MathHelper::LessNotEqual(radius, 0.0)) {
4656         return WMError::WM_ERROR_INVALID_PARAM;
4657     }
4658     radius = ConvertRadiusToSigma(radius);
4659     WLOGFI("[Client] Window %{public}s set backdrop blur radius after conversion %{public}f", name_.c_str(), radius);
4660     surfaceNode_->SetBackgroundFilter(RSFilter::CreateBlurFilter(radius, radius));
4661     RSTransactionAdapter::FlushImplicitTransaction(surfaceNode_);
4662     return WMError::WM_OK;
4663 }
4664 
SetBackdropBlurStyle(WindowBlurStyle blurStyle)4665 WMError WindowImpl::SetBackdropBlurStyle(WindowBlurStyle blurStyle)
4666 {
4667     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
4668         WLOGFE("set backdrop blur style permission denied!");
4669         return WMError::WM_ERROR_NOT_SYSTEM_APP;
4670     }
4671     WLOGI("Window %{public}s set backdrop blur style %{public}u", name_.c_str(), blurStyle);
4672     if (blurStyle < WindowBlurStyle::WINDOW_BLUR_OFF || blurStyle > WindowBlurStyle::WINDOW_BLUR_THICK) {
4673         return WMError::WM_ERROR_INVALID_PARAM;
4674     }
4675 
4676     if (blurStyle == WindowBlurStyle::WINDOW_BLUR_OFF) {
4677         surfaceNode_->SetBackgroundFilter(nullptr);
4678     } else {
4679         auto display = SingletonContainer::IsDestroyed() ? nullptr :
4680             SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
4681         if (display == nullptr) {
4682             WLOGFE("get display failed displayId:%{public}" PRIu64", window id:%{public}u", property_->GetDisplayId(),
4683                 property_->GetWindowId());
4684             return WMError::WM_ERROR_INVALID_PARAM;
4685         }
4686         surfaceNode_->SetBackgroundFilter(RSFilter::CreateMaterialFilter(static_cast<int>(blurStyle),
4687                                                                          display->GetVirtualPixelRatio()));
4688     }
4689     RSTransactionAdapter::FlushImplicitTransaction(surfaceNode_);
4690     return WMError::WM_OK;
4691 }
4692 
NotifyMemoryLevel(int32_t level)4693 WMError WindowImpl::NotifyMemoryLevel(int32_t level)
4694 {
4695     WLOGFD("id: %{public}u, notify memory level: %{public}d", property_->GetWindowId(), level);
4696     std::lock_guard<std::recursive_mutex> lock(mutex_);
4697     if (uiContent_ == nullptr) {
4698         WLOGFE("Window %{public}s notify memory level failed, ace is null.", name_.c_str());
4699         return WMError::WM_ERROR_NULLPTR;
4700     }
4701     // notify memory level
4702     uiContent_->NotifyMemoryLevel(level);
4703     return WMError::WM_OK;
4704 }
4705 
IsAllowHaveSystemSubWindow()4706 bool WindowImpl::IsAllowHaveSystemSubWindow()
4707 {
4708     auto windowType = property_->GetWindowType();
4709     if (WindowHelper::IsSystemSubWindow(windowType) ||
4710         WindowHelper::IsSubWindow(windowType) ||
4711         windowType == WindowType::WINDOW_TYPE_DIALOG) {
4712         WLOGI("type %{public}u not allowed to add subwindow", windowType);
4713         return false;
4714     }
4715     return true;
4716 }
4717 
SetNeedDefaultAnimation(bool needDefaultAnimation)4718 void WindowImpl::SetNeedDefaultAnimation(bool needDefaultAnimation)
4719 {
4720     needDefaultAnimation_= needDefaultAnimation;
4721 }
4722 
SetTextFieldAvoidInfo(double textFieldPositionY,double textFieldHeight)4723 WMError WindowImpl::SetTextFieldAvoidInfo(double textFieldPositionY, double textFieldHeight)
4724 {
4725     property_->SetTextFieldPositionY(textFieldPositionY);
4726     property_->SetTextFieldHeight(textFieldHeight);
4727     UpdateProperty(PropertyChangeAction::ACTION_UPDATE_TEXTFIELD_AVOID_INFO);
4728     return WMError::WM_OK;
4729 }
4730 
RegisterWindowInspectorCallback()4731 void WindowImpl::RegisterWindowInspectorCallback()
4732 {
4733     auto getWMSWindowListCallback = [weakThis = wptr(this)]() -> std::optional<WindowListInfo> {
4734         if (auto window = weakThis.promote()) {
4735             return std::make_optional<WindowListInfo>({
4736                 window->GetWindowName(), window->GetWindowId(),
4737                 static_cast<uint32_t>(window->GetType()), window->GetRect()
4738             });
4739         } else {
4740             return std::nullopt;
4741         }
4742     };
4743     WindowInspector::GetInstance().RegisterGetWMSWindowListCallback(GetWindowId(), std::move(getWMSWindowListCallback));
4744 }
4745 
GetApiTargetVersion() const4746 uint32_t WindowImpl::GetApiTargetVersion() const
4747 {
4748     uint32_t version = 0;
4749     if ((context_ != nullptr) && (context_->GetApplicationInfo() != nullptr)) {
4750         version = static_cast<uint32_t>(context_->GetApplicationInfo()->apiTargetVersion) % API_VERSION_MOD;
4751     }
4752     return version;
4753 }
4754 
GetWindowPropertyInfo(WindowPropertyInfo & windowPropertyInfo)4755 WMError WindowImpl::GetWindowPropertyInfo(WindowPropertyInfo& windowPropertyInfo)
4756 {
4757     if (!IsWindowValid()) {
4758         return WMError::WM_ERROR_INVALID_WINDOW;
4759     }
4760     windowPropertyInfo.windowRect = GetRect();
4761     auto uicontent = GetUIContent();
4762     if (uicontent == nullptr) {
4763         TLOGW(WmsLogTag::WMS_ATTRIBUTE, "uicontent is nullptr");
4764     } else {
4765         uicontent->GetWindowPaintSize(windowPropertyInfo.drawableRect);
4766     }
4767     windowPropertyInfo.type = GetType();
4768     windowPropertyInfo.isLayoutFullScreen = IsLayoutFullScreen();
4769     windowPropertyInfo.isFullScreen = IsFullScreen();
4770     windowPropertyInfo.isTouchable = GetTouchable();
4771     windowPropertyInfo.isFocusable = GetFocusable();
4772     windowPropertyInfo.name = GetWindowName();
4773     windowPropertyInfo.isPrivacyMode = IsPrivacyMode();
4774     windowPropertyInfo.isKeepScreenOn = IsKeepScreenOn();
4775     windowPropertyInfo.brightness = GetBrightness();
4776     windowPropertyInfo.isTransparent = IsTransparent();
4777     windowPropertyInfo.id = GetWindowId();
4778     windowPropertyInfo.displayId = GetDisplayId();
4779     return WMError::WM_OK;
4780 }
4781 
GetRSUIDirector() const4782 std::shared_ptr<RSUIDirector> WindowImpl::GetRSUIDirector() const
4783 {
4784     RETURN_IF_RS_CLIENT_MULTI_INSTANCE_DISABLED(nullptr);
4785     TLOGD(WmsLogTag::WMS_SCB, "%{public}s, windowId: %{public}u",
4786           RSAdapterUtil::RSUIDirectorToStr(rsUIDirector_).c_str(), GetWindowId());
4787     return rsUIDirector_;
4788 }
4789 
GetRSUIContext() const4790 std::shared_ptr<RSUIContext> WindowImpl::GetRSUIContext() const
4791 {
4792     RETURN_IF_RS_CLIENT_MULTI_INSTANCE_DISABLED(nullptr);
4793     auto rsUIContext = rsUIDirector_ ? rsUIDirector_->GetRSUIContext() : nullptr;
4794     TLOGD(WmsLogTag::WMS_SCB, "%{public}s, windowId: %{public}u",
4795           RSAdapterUtil::RSUIContextToStr(rsUIContext).c_str(), GetWindowId());
4796     return rsUIContext;
4797 }
4798 
SetIntentParam(const std::string & intentParam,const std::function<void ()> & loadPageCallback,bool isColdStart)4799 WMError WindowImpl::SetIntentParam(const std::string& intentParam,
4800     const std::function<void()>& loadPageCallback, bool isColdStart)
4801 {
4802     TLOGI(WmsLogTag::WMS_LIFE, "in");
4803     intentParam_ = intentParam;
4804     loadPageCallback_ = loadPageCallback;
4805     isIntentColdStart_ = isColdStart;
4806     return WMError::WM_OK;
4807 }
4808 } // namespace Rosen
4809 } // namespace OHOS
4810