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