• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 
19 #include <ability_manager_client.h>
20 #include <common/rs_common_def.h>
21 #include <hisysevent.h>
22 #include <ipc_skeleton.h>
23 #include <transaction/rs_interfaces.h>
24 #include <transaction/rs_transaction.h>
25 
26 #include "permission.h"
27 #include "color_parser.h"
28 #include "display_manager.h"
29 #include "display_info.h"
30 #include "ressched_report.h"
31 #include "singleton_container.h"
32 #include "surface_capture_future.h"
33 #include "sys_cap_util.h"
34 #include "window_adapter.h"
35 #include "window_agent.h"
36 #include "window_helper.h"
37 #include "window_manager_hilog.h"
38 #include "wm_common.h"
39 #include "wm_common_inner.h"
40 #include "wm_math.h"
41 
42 namespace OHOS {
43 namespace Rosen {
44 namespace {
45     constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, HILOG_DOMAIN_WINDOW, "WindowImpl"};
46     const std::string PARAM_DUMP_HELP = "-h";
47 }
48 
49 WM_IMPLEMENT_SINGLE_INSTANCE(ResSchedReport);
50 
51 const WindowImpl::ColorSpaceConvertMap WindowImpl::colorSpaceConvertMap[] = {
52     { ColorSpace::COLOR_SPACE_DEFAULT, ColorGamut::COLOR_GAMUT_SRGB },
53     { ColorSpace::COLOR_SPACE_WIDE_GAMUT, ColorGamut::COLOR_GAMUT_DCI_P3 },
54 };
55 
56 std::map<std::string, std::pair<uint32_t, sptr<Window>>> WindowImpl::windowMap_;
57 std::map<uint32_t, std::vector<sptr<WindowImpl>>> WindowImpl::subWindowMap_;
58 std::map<uint32_t, std::vector<sptr<WindowImpl>>> WindowImpl::appFloatingWindowMap_;
59 std::map<uint32_t, std::vector<sptr<WindowImpl>>> WindowImpl::appDialogWindowMap_;
60 std::map<uint32_t, std::vector<sptr<IScreenshotListener>>> WindowImpl::screenshotListeners_;
61 std::map<uint32_t, std::vector<sptr<ITouchOutsideListener>>> WindowImpl::touchOutsideListeners_;
62 std::map<uint32_t, std::vector<sptr<IDialogTargetTouchListener>>> WindowImpl::dialogTargetTouchListeners_;
63 std::map<uint32_t, std::vector<sptr<IWindowLifeCycle>>> WindowImpl::lifecycleListeners_;
64 std::map<uint32_t, std::vector<sptr<IWindowChangeListener>>> WindowImpl::windowChangeListeners_;
65 std::map<uint32_t, std::vector<sptr<IAvoidAreaChangedListener>>> WindowImpl::avoidAreaChangeListeners_;
66 std::map<uint32_t, std::vector<sptr<IOccupiedAreaChangeListener>>> WindowImpl::occupiedAreaChangeListeners_;
67 std::map<uint32_t, sptr<IDialogDeathRecipientListener>> WindowImpl::dialogDeathRecipientListener_;
68 std::recursive_mutex WindowImpl::globalMutex_;
69 int constructorCnt = 0;
70 int deConstructorCnt = 0;
WindowImpl(const sptr<WindowOption> & option)71 WindowImpl::WindowImpl(const sptr<WindowOption>& option)
72 {
73     property_ = new (std::nothrow) WindowProperty();
74     property_->SetWindowName(option->GetWindowName());
75     property_->SetRequestRect(option->GetWindowRect());
76     property_->SetWindowType(option->GetWindowType());
77     property_->SetWindowMode(option->GetWindowMode());
78     property_->SetFullScreen(option->GetWindowMode() == WindowMode::WINDOW_MODE_FULLSCREEN);
79     property_->SetFocusable(option->GetFocusable());
80     property_->SetTouchable(option->GetTouchable());
81     property_->SetDisplayId(option->GetDisplayId());
82     property_->SetCallingWindow(option->GetCallingWindow());
83     property_->SetWindowFlags(option->GetWindowFlags());
84     property_->SetHitOffset(option->GetHitOffset());
85     property_->SetRequestedOrientation(option->GetRequestedOrientation());
86     windowTag_ = option->GetWindowTag();
87     isMainHandlerAvailable_ = option->GetMainHandlerAvailable();
88     property_->SetTurnScreenOn(option->IsTurnScreenOn());
89     property_->SetKeepScreenOn(option->IsKeepScreenOn());
90     property_->SetBrightness(option->GetBrightness());
91     AdjustWindowAnimationFlag();
92     auto& sysBarPropMap = option->GetSystemBarProperty();
93     for (auto it : sysBarPropMap) {
94         property_->SetSystemBarProperty(it.first, it.second);
95     }
96     name_ = option->GetWindowName();
97 
98     surfaceNode_ = CreateSurfaceNode(property_->GetWindowName(), option->GetWindowType());
99 
100     moveDragProperty_ = new (std::nothrow) MoveDragProperty();
101     WLOGFI("WindowImpl constructorCnt: %{public}d name: %{public}s",
102         ++constructorCnt, property_->GetWindowName().c_str());
103 }
104 
CreateSurfaceNode(std::string name,WindowType type)105 RSSurfaceNode::SharedPtr WindowImpl::CreateSurfaceNode(std::string name, WindowType type)
106 {
107     struct RSSurfaceNodeConfig rsSurfaceNodeConfig;
108     rsSurfaceNodeConfig.SurfaceNodeName = name;
109     RSSurfaceNodeType rsSurfaceNodeType = RSSurfaceNodeType::DEFAULT;
110     switch (type) {
111         case WindowType::WINDOW_TYPE_BOOT_ANIMATION:
112         case WindowType::WINDOW_TYPE_POINTER:
113             rsSurfaceNodeType = RSSurfaceNodeType::SELF_DRAWING_WINDOW_NODE;
114             break;
115         default:
116             rsSurfaceNodeType = RSSurfaceNodeType::DEFAULT;
117             break;
118     }
119     return RSSurfaceNode::Create(rsSurfaceNodeConfig, rsSurfaceNodeType);
120 }
121 
~WindowImpl()122 WindowImpl::~WindowImpl()
123 {
124     WLOGFI("windowName: %{public}s, windowId: %{public}d, deConstructorCnt: %{public}d, surfaceNode:%{public}d",
125         GetWindowName().c_str(), GetWindowId(), ++deConstructorCnt, static_cast<uint32_t>(surfaceNode_.use_count()));
126     Destroy(true, false);
127 }
128 
Find(const std::string & name)129 sptr<Window> WindowImpl::Find(const std::string& name)
130 {
131     auto iter = windowMap_.find(name);
132     if (iter == windowMap_.end()) {
133         return nullptr;
134     }
135     return iter->second.second;
136 }
137 
GetContext() const138 const std::shared_ptr<AbilityRuntime::Context> WindowImpl::GetContext() const
139 {
140     return context_;
141 }
142 
FindTopWindow(uint32_t topWinId)143 sptr<Window> WindowImpl::FindTopWindow(uint32_t topWinId)
144 {
145     if (windowMap_.empty()) {
146         WLOGFE("Please create mainWindow First!");
147         return nullptr;
148     }
149     for (auto iter = windowMap_.begin(); iter != windowMap_.end(); iter++) {
150         if (topWinId == iter->second.first) {
151             WLOGFI("FindTopWindow id: %{public}u", topWinId);
152             return iter->second.second;
153         }
154     }
155     WLOGFE("Cannot find topWindow!");
156     return nullptr;
157 }
158 
GetTopWindowWithId(uint32_t mainWinId)159 sptr<Window> WindowImpl::GetTopWindowWithId(uint32_t mainWinId)
160 {
161     uint32_t topWinId = INVALID_WINDOW_ID;
162     WMError ret = SingletonContainer::Get<WindowAdapter>().GetTopWindowId(mainWinId, topWinId);
163     if (ret != WMError::WM_OK) {
164         WLOGFE("GetTopWindowId failed with errCode:%{public}d", static_cast<int32_t>(ret));
165         return nullptr;
166     }
167     return FindTopWindow(topWinId);
168 }
169 
GetTopWindowWithContext(const std::shared_ptr<AbilityRuntime::Context> & context)170 sptr<Window> WindowImpl::GetTopWindowWithContext(const std::shared_ptr<AbilityRuntime::Context>& context)
171 {
172     if (windowMap_.empty()) {
173         WLOGFE("Please create mainWindow First!");
174         return nullptr;
175     }
176     uint32_t mainWinId = INVALID_WINDOW_ID;
177     for (auto iter = windowMap_.begin(); iter != windowMap_.end(); iter++) {
178         auto win = iter->second.second;
179         if (context.get() == win->GetContext().get() && WindowHelper::IsMainWindow(win->GetType())) {
180             mainWinId = win->GetWindowId();
181             WLOGFI("GetTopWindow Find MainWinId:%{public}u.", mainWinId);
182             break;
183         }
184     }
185     WLOGFI("GetTopWindowfinal MainWinId:%{public}u!", mainWinId);
186     if (mainWinId == INVALID_WINDOW_ID) {
187         WLOGFE("Cannot find topWindow!");
188         return nullptr;
189     }
190     uint32_t topWinId = INVALID_WINDOW_ID;
191     WMError ret = SingletonContainer::Get<WindowAdapter>().GetTopWindowId(mainWinId, topWinId);
192     if (ret != WMError::WM_OK) {
193         WLOGFE("GetTopWindowId failed with errCode:%{public}d", static_cast<int32_t>(ret));
194         return nullptr;
195     }
196     return FindTopWindow(topWinId);
197 }
198 
GetSubWindow(uint32_t parentId)199 std::vector<sptr<Window>> WindowImpl::GetSubWindow(uint32_t parentId)
200 {
201     if (subWindowMap_.find(parentId) == subWindowMap_.end()) {
202         WLOGFE("Cannot parentWindow with id: %{public}u!", parentId);
203         return std::vector<sptr<Window>>();
204     }
205     return std::vector<sptr<Window>>(subWindowMap_[parentId].begin(), subWindowMap_[parentId].end());
206 }
207 
UpdateConfigurationForAll(const std::shared_ptr<AppExecFwk::Configuration> & configuration)208 void WindowImpl::UpdateConfigurationForAll(const std::shared_ptr<AppExecFwk::Configuration>& configuration)
209 {
210     for (const auto& winPair : windowMap_) {
211         auto window = winPair.second.second;
212         window->UpdateConfiguration(configuration);
213     }
214 }
215 
GetSurfaceNode() const216 std::shared_ptr<RSSurfaceNode> WindowImpl::GetSurfaceNode() const
217 {
218     return surfaceNode_;
219 }
220 
GetRect() const221 Rect WindowImpl::GetRect() const
222 {
223     return property_->GetWindowRect();
224 }
225 
GetRequestRect() const226 Rect WindowImpl::GetRequestRect() const
227 {
228     return property_->GetRequestRect();
229 }
230 
GetType() const231 WindowType WindowImpl::GetType() const
232 {
233     return property_->GetWindowType();
234 }
235 
GetMode() const236 WindowMode WindowImpl::GetMode() const
237 {
238     return property_->GetWindowMode();
239 }
240 
GetAlpha() const241 float WindowImpl::GetAlpha() const
242 {
243     return property_->GetAlpha();
244 }
245 
GetWindowState() const246 WindowState WindowImpl::GetWindowState() const
247 {
248     return state_;
249 }
250 
SetFocusable(bool isFocusable)251 WMError WindowImpl::SetFocusable(bool isFocusable)
252 {
253     if (!IsWindowValid()) {
254         return WMError::WM_ERROR_INVALID_WINDOW;
255     }
256     property_->SetFocusable(isFocusable);
257     if (state_ == WindowState::STATE_SHOWN) {
258         return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_FOCUSABLE);
259     }
260     return WMError::WM_OK;
261 }
262 
GetFocusable() const263 bool WindowImpl::GetFocusable() const
264 {
265     return property_->GetFocusable();
266 }
267 
SetTouchable(bool isTouchable)268 WMError WindowImpl::SetTouchable(bool isTouchable)
269 {
270     if (!IsWindowValid()) {
271         return WMError::WM_ERROR_INVALID_WINDOW;
272     }
273     property_->SetTouchable(isTouchable);
274     if (state_ == WindowState::STATE_SHOWN) {
275         return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_TOUCHABLE);
276     }
277     return WMError::WM_OK;
278 }
279 
GetTouchable() const280 bool WindowImpl::GetTouchable() const
281 {
282     return property_->GetTouchable();
283 }
284 
GetWindowName() const285 const std::string& WindowImpl::GetWindowName() const
286 {
287     return name_;
288 }
289 
GetWindowId() const290 uint32_t WindowImpl::GetWindowId() const
291 {
292     return property_->GetWindowId();
293 }
294 
GetWindowFlags() const295 uint32_t WindowImpl::GetWindowFlags() const
296 {
297     return property_->GetWindowFlags();
298 }
299 
GetRequestModeSupportInfo() const300 uint32_t WindowImpl::GetRequestModeSupportInfo() const
301 {
302     return property_->GetRequestModeSupportInfo();
303 }
304 
GetModeSupportInfo() const305 uint32_t WindowImpl::GetModeSupportInfo() const
306 {
307     return property_->GetModeSupportInfo();
308 }
309 
IsMainHandlerAvailable() const310 bool WindowImpl::IsMainHandlerAvailable() const
311 {
312     return isMainHandlerAvailable_;
313 }
314 
GetSystemBarPropertyByType(WindowType type) const315 SystemBarProperty WindowImpl::GetSystemBarPropertyByType(WindowType type) const
316 {
317     auto curProperties = property_->GetSystemBarProperty();
318     return curProperties[type];
319 }
320 
GetAvoidAreaByType(AvoidAreaType type,AvoidArea & avoidArea)321 WMError WindowImpl::GetAvoidAreaByType(AvoidAreaType type, AvoidArea& avoidArea)
322 {
323     WLOGFI("GetAvoidAreaByType  Search Type: %{public}u", static_cast<uint32_t>(type));
324     uint32_t windowId = property_->GetWindowId();
325     WMError ret = SingletonContainer::Get<WindowAdapter>().GetAvoidAreaByType(windowId, type, avoidArea);
326     if (ret != WMError::WM_OK) {
327         WLOGFE("GetAvoidAreaByType errCode:%{public}d winId:%{public}u Type is :%{public}u.",
328             static_cast<int32_t>(ret), property_->GetWindowId(), static_cast<uint32_t>(type));
329     }
330     return ret;
331 }
332 
SetWindowType(WindowType type)333 WMError WindowImpl::SetWindowType(WindowType type)
334 {
335     WLOGFD("window id: %{public}u, type:%{public}u.", property_->GetWindowId(), static_cast<uint32_t>(type));
336     if (type != WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW && !Permission::IsSystemCalling()) {
337         WLOGFE("set window type permission denied!");
338         return WMError::WM_ERROR_INVALID_PERMISSION;
339     }
340     if (!IsWindowValid()) {
341         return WMError::WM_ERROR_INVALID_WINDOW;
342     }
343     if (state_ == WindowState::STATE_CREATED) {
344         if (!(WindowHelper::IsAppWindow(type) || WindowHelper::IsSystemWindow(type))) {
345             WLOGFE("window type is invalid %{public}u.", type);
346             return WMError::WM_ERROR_INVALID_PARAM;
347         }
348         property_->SetWindowType(type);
349         if (isAppDecorEnable_ && windowSystemConfig_.isSystemDecorEnable_) {
350             property_->SetDecorEnable(WindowHelper::IsMainWindow(property_->GetWindowType()));
351         }
352         AdjustWindowAnimationFlag();
353         return WMError::WM_OK;
354     }
355     if (property_->GetWindowType() != type) {
356         return WMError::WM_ERROR_INVALID_PARAM;
357     }
358     return WMError::WM_OK;
359 }
360 
SetWindowMode(WindowMode mode)361 WMError WindowImpl::SetWindowMode(WindowMode mode)
362 {
363     WLOGFI("[Client] Window %{public}u mode %{public}u", property_->GetWindowId(), static_cast<uint32_t>(mode));
364     if (!IsWindowValid()) {
365         return WMError::WM_ERROR_INVALID_WINDOW;
366     }
367     if (!WindowHelper::IsWindowModeSupported(GetModeSupportInfo(), mode)) {
368         WLOGFI("window %{public}u do not support window mode: %{public}u",
369                property_->GetWindowId(), static_cast<uint32_t>(mode));
370         return WMError::WM_ERROR_INVALID_WINDOW_MODE_OR_SIZE;
371     }
372     if (state_ == WindowState::STATE_CREATED || state_ == WindowState::STATE_HIDDEN) {
373         UpdateMode(mode);
374     } else if (state_ == WindowState::STATE_SHOWN) {
375         WindowMode lastMode = property_->GetWindowMode();
376         property_->SetWindowMode(mode);
377         WMError ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_MODE);
378         if (ret != WMError::WM_OK) {
379             property_->SetWindowMode(lastMode);
380             return ret;
381         }
382         // set client window mode if success.
383         UpdateMode(mode);
384     }
385     if (property_->GetWindowMode() != mode) {
386         WLOGFE("set window mode filed! id: %{public}u.", property_->GetWindowId());
387         return WMError::WM_ERROR_INVALID_PARAM;
388     }
389     return WMError::WM_OK;
390 }
391 
SetAlpha(float alpha)392 void WindowImpl::SetAlpha(float alpha)
393 {
394     WLOGFI("[Client] Window %{public}u alpha %{public}f", property_->GetWindowId(), alpha);
395     if (!Permission::IsSystemCalling()) {
396         WLOGFE("set alpha permission denied!");
397         return;
398     }
399     if (!IsWindowValid()) {
400         return;
401     }
402     property_->SetAlpha(alpha);
403     surfaceNode_->SetAlpha(alpha);
404     RSTransaction::FlushImplicitTransaction();
405 }
406 
SetTransform(const Transform & trans)407 void WindowImpl::SetTransform(const Transform& trans)
408 {
409     WLOGFI("[Client] Window %{public}u SetTransform", property_->GetWindowId());
410     if (!IsWindowValid()) {
411         return;
412     }
413     Transform oriTrans = property_->GetTransform();
414     property_->SetTransform(trans);
415     WMError ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_TRANSFORM_PROPERTY);
416     if (ret != WMError::WM_OK) {
417         WLOGFE("SetTransform errCode:%{public}d winId:%{public}u",
418             static_cast<int32_t>(ret), property_->GetWindowId());
419         property_->SetTransform(oriTrans); // reset to ori transform when update failed
420     }
421     if (property_->IsDisplayZoomOn()) {
422         TransformSurfaceNode(property_->GetZoomTransform());
423     } else {
424         TransformSurfaceNode(trans);
425     }
426 }
427 
GetTransform() const428 const Transform& WindowImpl::GetTransform() const
429 {
430     return property_->GetTransform();
431 }
432 
GetZoomTransform() const433 const Transform& WindowImpl::GetZoomTransform() const
434 {
435     return property_->GetZoomTransform();
436 }
437 
AddWindowFlag(WindowFlag flag)438 WMError WindowImpl::AddWindowFlag(WindowFlag flag)
439 {
440     if (flag == WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED && state_ != WindowState::STATE_CREATED) {
441         WLOGFE("Only support add show when locked when window create, id: %{public}u", property_->GetWindowId());
442         return WMError::WM_ERROR_INVALID_WINDOW;
443     }
444 
445     uint32_t updateFlags = property_->GetWindowFlags() | (static_cast<uint32_t>(flag));
446     return SetWindowFlags(updateFlags);
447 }
448 
RemoveWindowFlag(WindowFlag flag)449 WMError WindowImpl::RemoveWindowFlag(WindowFlag flag)
450 {
451     if (flag == WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED && state_ != WindowState::STATE_CREATED) {
452         WLOGFE("Only support remove show when locked when window create, id: %{public}u", property_->GetWindowId());
453         return WMError::WM_ERROR_INVALID_WINDOW;
454     }
455 
456     uint32_t updateFlags = property_->GetWindowFlags() & (~(static_cast<uint32_t>(flag)));
457     return SetWindowFlags(updateFlags);
458 }
459 
SetWindowFlags(uint32_t flags)460 WMError WindowImpl::SetWindowFlags(uint32_t flags)
461 {
462     WLOGFI("[Client] Window %{public}u flags %{public}u", property_->GetWindowId(), flags);
463     if (!IsWindowValid()) {
464         return WMError::WM_ERROR_INVALID_WINDOW;
465     }
466     if (property_->GetWindowFlags() == flags) {
467         return WMError::WM_OK;
468     }
469     auto oriFlags = property_->GetWindowFlags();
470     property_->SetWindowFlags(flags);
471     if (state_ == WindowState::STATE_CREATED || state_ == WindowState::STATE_HIDDEN) {
472         return WMError::WM_OK;
473     }
474     WMError ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_FLAGS);
475     if (ret != WMError::WM_OK) {
476         WLOGFE("SetWindowFlags errCode:%{public}d winId:%{public}u",
477             static_cast<int32_t>(ret), property_->GetWindowId());
478         property_->SetWindowFlags(oriFlags);
479     }
480     return ret;
481 }
482 
OnNewWant(const AAFwk::Want & want)483 void WindowImpl::OnNewWant(const AAFwk::Want& want)
484 {
485     WLOGFI("[Client] Window [name:%{public}s, id:%{public}u] OnNewWant", name_.c_str(), property_->GetWindowId());
486     if (uiContent_ != nullptr) {
487         uiContent_->OnNewWant(want);
488     }
489 }
490 
SetUIContent(const std::string & contentInfo,NativeEngine * engine,NativeValue * storage,bool isdistributed,AppExecFwk::Ability * ability)491 WMError WindowImpl::SetUIContent(const std::string& contentInfo,
492     NativeEngine* engine, NativeValue* storage, bool isdistributed, AppExecFwk::Ability* ability)
493 {
494     WLOGFI("SetUIContent contentInfo: %{public}s", contentInfo.c_str());
495     if (uiContent_) {
496         uiContent_->Destroy();
497     }
498     std::unique_ptr<Ace::UIContent> uiContent;
499     if (ability != nullptr) {
500         uiContent = Ace::UIContent::Create(ability);
501     } else {
502         uiContent = Ace::UIContent::Create(context_.get(), engine);
503     }
504     if (uiContent == nullptr) {
505         WLOGFE("fail to SetUIContent id: %{public}u", property_->GetWindowId());
506         return WMError::WM_ERROR_NULLPTR;
507     }
508     if (!isAppDecorEnable_ || !windowSystemConfig_.isSystemDecorEnable_) {
509         WLOGFI("app set decor enable false");
510         property_->SetDecorEnable(false);
511     }
512     if (isdistributed) {
513         uiContent->Restore(this, contentInfo, storage);
514     } else {
515         uiContent->Initialize(this, contentInfo, storage);
516     }
517     // make uiContent available after Initialize/Restore
518     uiContent_ = std::move(uiContent);
519 
520     if (state_ == WindowState::STATE_SHOWN) {
521         // UIContent may be nullptr when show window, need to notify again when window is shown
522         uiContent_->Foreground();
523         UpdateTitleButtonVisibility();
524         Ace::ViewportConfig config;
525         Rect rect = GetRect();
526         config.SetSize(rect.width_, rect.height_);
527         config.SetPosition(rect.posX_, rect.posY_);
528         auto display = SingletonContainer::IsDestroyed() ? nullptr :
529             SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
530         if (display == nullptr) {
531             WLOGFE("get display failed displayId:%{public}" PRIu64", window id:%{public}u", property_->GetDisplayId(),
532                 property_->GetWindowId());
533             return WMError::WM_ERROR_NULLPTR;
534         }
535         float virtualPixelRatio = display->GetVirtualPixelRatio();
536         config.SetDensity(virtualPixelRatio);
537         uiContent_->UpdateViewportConfig(config, WindowSizeChangeReason::UNDEFINED);
538         WLOGFI("notify uiContent window size change end");
539     }
540     return WMError::WM_OK;
541 }
542 
GetUIContent() const543 Ace::UIContent* WindowImpl::GetUIContent() const
544 {
545     return uiContent_.get();
546 }
547 
GetContentInfo()548 std::string WindowImpl::GetContentInfo()
549 {
550     WLOGFI("GetContentInfo");
551     if (uiContent_ == nullptr) {
552         WLOGFE("fail to GetContentInfo id: %{public}u", property_->GetWindowId());
553         return "";
554     }
555     return uiContent_->GetContentInfo();
556 }
557 
GetColorSpaceFromSurfaceGamut(ColorGamut ColorGamut)558 ColorSpace WindowImpl::GetColorSpaceFromSurfaceGamut(ColorGamut ColorGamut)
559 {
560     for (auto item: colorSpaceConvertMap) {
561         if (item.surfaceColorGamut == ColorGamut) {
562             return item.colorSpace;
563         }
564     }
565     return ColorSpace::COLOR_SPACE_DEFAULT;
566 }
567 
GetSurfaceGamutFromColorSpace(ColorSpace colorSpace)568 ColorGamut WindowImpl::GetSurfaceGamutFromColorSpace(ColorSpace colorSpace)
569 {
570     for (auto item: colorSpaceConvertMap) {
571         if (item.colorSpace == colorSpace) {
572             return item.surfaceColorGamut;
573         }
574     }
575     return ColorGamut::COLOR_GAMUT_SRGB;
576 }
577 
IsSupportWideGamut()578 bool WindowImpl::IsSupportWideGamut()
579 {
580     return true;
581 }
582 
SetColorSpace(ColorSpace colorSpace)583 void WindowImpl::SetColorSpace(ColorSpace colorSpace)
584 {
585     auto surfaceGamut = GetSurfaceGamutFromColorSpace(colorSpace);
586     surfaceNode_->SetColorSpace(surfaceGamut);
587 }
588 
GetColorSpace()589 ColorSpace WindowImpl::GetColorSpace()
590 {
591     auto surfaceGamut = surfaceNode_->GetColorSpace();
592     return GetColorSpaceFromSurfaceGamut(surfaceGamut);
593 }
594 
Snapshot()595 std::shared_ptr<Media::PixelMap> WindowImpl::Snapshot()
596 {
597     WLOGFI("WMS-Client Snapshot");
598     std::shared_ptr<SurfaceCaptureFuture> callback = std::make_shared<SurfaceCaptureFuture>();
599     auto isSucceeded = RSInterfaces::GetInstance().TakeSurfaceCapture(surfaceNode_, callback);
600     std::shared_ptr<Media::PixelMap> pixelMap;
601     if (isSucceeded) {
602         pixelMap = callback->GetResult(2000); // wait for <= 2000ms
603     } else {
604         pixelMap = SingletonContainer::Get<WindowAdapter>().GetSnapshot(property_->GetWindowId());
605     }
606     if (pixelMap != nullptr) {
607         WLOGFI("WMS-Client Save WxH = %{public}dx%{public}d", pixelMap->GetWidth(), pixelMap->GetHeight());
608     } else {
609         WLOGFE("Failed to get pixelmap, return nullptr!");
610     }
611     return pixelMap;
612 }
613 
DumpInfo(const std::vector<std::string> & params,std::vector<std::string> & info)614 void WindowImpl::DumpInfo(const std::vector<std::string>& params, std::vector<std::string>& info)
615 {
616     if (params.size() == 1 && params[0] == PARAM_DUMP_HELP) { // 1: params num
617         WLOGFI("Dump ArkUI help Info");
618         Ace::UIContent::ShowDumpHelp(info);
619         return;
620     }
621     WLOGFI("ArkUI:DumpInfo");
622     if (uiContent_ != nullptr) {
623         uiContent_->DumpInfo(params, info);
624     }
625     SingletonContainer::Get<WindowAdapter>().NotifyDumpInfoResult(info);
626 }
627 
SetSystemBarProperty(WindowType type,const SystemBarProperty & property)628 WMError WindowImpl::SetSystemBarProperty(WindowType type, const SystemBarProperty& property)
629 {
630     WLOGFI("[Client] Window %{public}u SetSystemBarProperty type %{public}u " \
631         "enable:%{public}u, backgroundColor:%{public}x, contentColor:%{public}x ",
632         property_->GetWindowId(), static_cast<uint32_t>(type), property.enable_,
633         property.backgroundColor_, property.contentColor_);
634     if (!IsWindowValid()) {
635         return WMError::WM_ERROR_INVALID_WINDOW;
636     }
637     if (GetSystemBarPropertyByType(type) == property) {
638         return WMError::WM_OK;
639     }
640     property_->SetSystemBarProperty(type, property);
641     if (state_ == WindowState::STATE_CREATED || state_ == WindowState::STATE_HIDDEN) {
642         return WMError::WM_OK;
643     }
644     WMError ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_OTHER_PROPS);
645     if (ret != WMError::WM_OK) {
646         WLOGFE("SetSystemBarProperty errCode:%{public}d winId:%{public}u",
647             static_cast<int32_t>(ret), property_->GetWindowId());
648     }
649     return ret;
650 }
651 
UpdateSystemBarProperty(bool status)652 WMError WindowImpl::UpdateSystemBarProperty(bool status)
653 {
654     if (!IsWindowValid()) {
655         WLOGFE("PutSystemBarProperty errCode:%{public}d winId:%{public}u",
656             static_cast<int32_t>(WMError::WM_ERROR_INVALID_WINDOW), property_->GetWindowId());
657         return WMError::WM_ERROR_INVALID_WINDOW;
658     }
659 
660     SystemBarProperty statusProperty = GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_STATUS_BAR);
661     SystemBarProperty naviProperty = GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_NAVIGATION_BAR);
662     if (status) {
663         statusProperty.enable_ = false;
664         naviProperty.enable_ = false;
665     } else {
666         statusProperty.enable_ = true;
667         naviProperty.enable_ = true;
668     }
669 
670     if ((GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_STATUS_BAR) == statusProperty) &&
671         (GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_NAVIGATION_BAR) == naviProperty)) {
672         return WMError::WM_OK;
673     }
674     if (!(GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_STATUS_BAR) == statusProperty)) {
675         property_->SetSystemBarProperty(WindowType::WINDOW_TYPE_STATUS_BAR, statusProperty);
676     }
677     if (!(GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_NAVIGATION_BAR) == naviProperty)) {
678         property_->SetSystemBarProperty(WindowType::WINDOW_TYPE_NAVIGATION_BAR, naviProperty);
679     }
680     if (state_ == WindowState::STATE_CREATED || state_ == WindowState::STATE_HIDDEN) {
681         return WMError::WM_OK;
682     }
683 
684     WMError ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_OTHER_PROPS);
685     if (ret != WMError::WM_OK) {
686         WLOGFE("SetSystemBarProperty errCode:%{public}d winId:%{public}u",
687             static_cast<int32_t>(ret), property_->GetWindowId());
688     }
689     return ret;
690 }
691 
SetLayoutFullScreen(bool status)692 WMError WindowImpl::SetLayoutFullScreen(bool status)
693 {
694     WLOGFI("[Client] Window %{public}u SetLayoutFullScreen: %{public}u", property_->GetWindowId(), status);
695     if (!IsWindowValid() ||
696         !WindowHelper::IsWindowModeSupported(GetModeSupportInfo(), WindowMode::WINDOW_MODE_FULLSCREEN)) {
697         WLOGFE("invalid window or fullscreen mode is not be supported, winId:%{public}u", property_->GetWindowId());
698         return WMError::WM_ERROR_INVALID_WINDOW;
699     }
700     WMError ret = SetWindowMode(WindowMode::WINDOW_MODE_FULLSCREEN);
701     if (ret != WMError::WM_OK) {
702         WLOGFE("SetWindowMode errCode:%{public}d winId:%{public}u",
703             static_cast<int32_t>(ret), property_->GetWindowId());
704         return ret;
705     }
706     if (status) {
707         ret = RemoveWindowFlag(WindowFlag::WINDOW_FLAG_NEED_AVOID);
708         if (ret != WMError::WM_OK) {
709             WLOGFE("RemoveWindowFlag errCode:%{public}d winId:%{public}u",
710                 static_cast<int32_t>(ret), property_->GetWindowId());
711             return ret;
712         }
713     } else {
714         ret = AddWindowFlag(WindowFlag::WINDOW_FLAG_NEED_AVOID);
715         if (ret != WMError::WM_OK) {
716             WLOGFE("AddWindowFlag errCode:%{public}d winId:%{public}u",
717                 static_cast<int32_t>(ret), property_->GetWindowId());
718             return ret;
719         }
720     }
721     return ret;
722 }
723 
SetFullScreen(bool status)724 WMError WindowImpl::SetFullScreen(bool status)
725 {
726     WLOGFI("[Client] Window %{public}u SetFullScreen: %{public}d", property_->GetWindowId(), status);
727     if (!IsWindowValid() ||
728         !WindowHelper::IsWindowModeSupported(GetModeSupportInfo(), WindowMode::WINDOW_MODE_FULLSCREEN)) {
729         WLOGFE("invalid window or fullscreen mode is not be supported, winId:%{public}u", property_->GetWindowId());
730         return WMError::WM_ERROR_INVALID_WINDOW;
731     }
732     WMError ret = UpdateSystemBarProperty(status);
733     if (ret != WMError::WM_OK) {
734         WLOGFE("UpdateSystemBarProperty errCode:%{public}d winId:%{public}u",
735             static_cast<int32_t>(ret), property_->GetWindowId());
736     }
737     ret = SetLayoutFullScreen(status);
738     if (ret != WMError::WM_OK) {
739         WLOGFE("SetLayoutFullScreen errCode:%{public}d winId:%{public}u",
740             static_cast<int32_t>(ret), property_->GetWindowId());
741     }
742     return ret;
743 }
744 
MapFloatingWindowToAppIfNeeded()745 void WindowImpl::MapFloatingWindowToAppIfNeeded()
746 {
747     if (!WindowHelper::IsAppFloatingWindow(GetType()) || context_.get() == nullptr) {
748         return;
749     }
750 
751     for (const auto& winPair : windowMap_) {
752         auto win = winPair.second.second;
753         if (win->GetType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW &&
754             context_.get() == win->GetContext().get()) {
755             sptr<WindowImpl> selfImpl(this);
756             appFloatingWindowMap_[win->GetWindowId()].push_back(selfImpl);
757             WLOGFI("Map FloatingWindow %{public}u to AppMainWindow %{public}u, type is %{public}u",
758                 GetWindowId(), win->GetWindowId(), GetType());
759             return;
760         }
761     }
762 }
763 
MapDialogWindowToAppIfNeeded()764 void WindowImpl::MapDialogWindowToAppIfNeeded()
765 {
766     if (GetType() != WindowType::WINDOW_TYPE_DIALOG) {
767         return;
768     }
769 
770     for (const auto& winPair : windowMap_) {
771         auto win = winPair.second.second;
772         if (win->GetType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW &&
773             context_.get() == win->GetContext().get()) {
774             sptr<WindowImpl> selfImpl(this);
775             appDialogWindowMap_[win->GetWindowId()].push_back(selfImpl);
776             WLOGFI("Map DialogWindow %{public}u to AppMainWindow %{public}u", GetWindowId(), win->GetWindowId());
777             return;
778         }
779     }
780 }
781 
UpdateProperty(PropertyChangeAction action)782 WMError WindowImpl::UpdateProperty(PropertyChangeAction action)
783 {
784     return SingletonContainer::Get<WindowAdapter>().UpdateProperty(property_, action);
785 }
786 
GetConfigurationFromAbilityInfo()787 void WindowImpl::GetConfigurationFromAbilityInfo()
788 {
789     auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
790     if (abilityContext == nullptr) {
791         WLOGFE("id:%{public}u is not ability Window", property_->GetWindowId());
792         return;
793     }
794     auto abilityInfo = abilityContext->GetAbilityInfo();
795     if (abilityInfo == nullptr) {
796         WLOGFE("id:%{public}u Ability window get ability info failed", property_->GetWindowId());
797         return;
798     }
799 
800     // get support modes configuration
801     uint32_t modeSupportInfo = WindowHelper::ConvertSupportModesToSupportInfo(abilityInfo->windowModes);
802     if (modeSupportInfo == 0) {
803         WLOGFD("mode config param is 0, all modes is supported");
804         modeSupportInfo = WindowModeSupport::WINDOW_MODE_SUPPORT_ALL;
805     }
806     WLOGFD("winId: %{public}u, modeSupportInfo: %{public}u", GetWindowId(), modeSupportInfo);
807     SetRequestModeSupportInfo(modeSupportInfo);
808 
809     // get window size limits configuration
810     WindowSizeLimits sizeLimits;
811     sizeLimits.maxWidth_ = abilityInfo->maxWindowWidth;
812     sizeLimits.maxHeight_ = abilityInfo->maxWindowHeight;
813     sizeLimits.minWidth_ = abilityInfo->minWindowWidth;
814     sizeLimits.minHeight_ = abilityInfo->minWindowHeight;
815     sizeLimits.maxRatio_ = static_cast<float>(abilityInfo->maxWindowRatio);
816     sizeLimits.minRatio_ = static_cast<float>(abilityInfo->minWindowRatio);
817     property_->SetSizeLimits(sizeLimits);
818 
819     // get orientation configuration
820     DisplayOrientation displayOrientation = static_cast<DisplayOrientation>(
821         static_cast<uint32_t>(abilityInfo->orientation));
822     if (ABILITY_TO_WMS_ORIENTATION_MAP.count(displayOrientation) == 0) {
823         WLOGFE("id:%{public}u Do not support this Orientation type", property_->GetWindowId());
824         return;
825     }
826     Orientation orientation = ABILITY_TO_WMS_ORIENTATION_MAP.at(displayOrientation);
827     if (orientation < Orientation::BEGIN || orientation > Orientation::END) {
828         WLOGFE("Set orientation from ability failed");
829         return;
830     }
831     property_->SetRequestedOrientation(orientation);
832 }
833 
UpdateTitleButtonVisibility()834 void WindowImpl::UpdateTitleButtonVisibility()
835 {
836     WLOGFD("[Client] UpdateTitleButtonVisibility");
837     if (uiContent_ == nullptr || !isAppDecorEnable_) {
838         return;
839     }
840     auto modeSupportInfo = GetModeSupportInfo();
841     bool hideSplitButton = !(modeSupportInfo & WindowModeSupport::WINDOW_MODE_SUPPORT_SPLIT_PRIMARY);
842     // not support fullscreen in split and floating mode, or not support float in fullscreen mode
843     bool hideMaximizeButton = (!(modeSupportInfo & WindowModeSupport::WINDOW_MODE_SUPPORT_FULLSCREEN) &&
844         (GetMode() == WindowMode::WINDOW_MODE_FLOATING || WindowHelper::IsSplitWindowMode(GetMode()))) ||
845         (!(modeSupportInfo & WindowModeSupport::WINDOW_MODE_SUPPORT_FLOATING) &&
846         GetMode() == WindowMode::WINDOW_MODE_FULLSCREEN);
847     WLOGFI("[Client] [hideSplit, hideMaximize]: [%{public}d, %{public}d]", hideSplitButton, hideMaximizeButton);
848     uiContent_->HideWindowTitleButton(hideSplitButton, hideMaximizeButton, false);
849 }
850 
IsAppMainOrSubOrFloatingWindow()851 bool WindowImpl::IsAppMainOrSubOrFloatingWindow()
852 {
853     // App main window need decor config, stretchable config and effect config
854     // App sub window and float window need effect config
855     if (WindowHelper::IsAppWindow(GetType())) {
856         return true;
857     }
858 
859     if (WindowHelper::IsAppFloatingWindow(GetType())) {
860         for (const auto& winPair : windowMap_) {
861             auto win = winPair.second.second;
862             if (win != nullptr && win->GetType() == WindowType::WINDOW_TYPE_APP_MAIN_WINDOW &&
863                 context_.get() == win->GetContext().get()) {
864                 isAppFloatingWindow_ = true;
865                 return true;
866             }
867         }
868     }
869     return false;
870 }
871 
SetWindowCornerRadiusAccordingToSystemConfig()872 void WindowImpl::SetWindowCornerRadiusAccordingToSystemConfig()
873 {
874     auto display = SingletonContainer::IsDestroyed() ? nullptr :
875         SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
876     if (display == nullptr) {
877         WLOGFE("get display failed displayId:%{public}" PRIu64", window id:%{public}u", property_->GetDisplayId(),
878             property_->GetWindowId());
879         return;
880     }
881     auto vpr = display->GetVirtualPixelRatio();
882     auto fullscreenRadius = windowSystemConfig_.effectConfig_.fullScreenCornerRadius_ * vpr;
883     auto splitRadius = windowSystemConfig_.effectConfig_.splitCornerRadius_ * vpr;
884     auto floatRadius = windowSystemConfig_.effectConfig_.floatCornerRadius_ * vpr;
885 
886     WLOGFD("[WEffect] [name:%{public}s] mode: %{public}u, vpr: %{public}f, [%{public}f, %{public}f, %{public}f]",
887         name_.c_str(), GetMode(), vpr, fullscreenRadius, splitRadius, floatRadius);
888 
889     if (WindowHelper::IsFullScreenWindow(GetMode()) && MathHelper::GreatNotEqual(fullscreenRadius, 0.0)) {
890         SetCornerRadius(fullscreenRadius);
891     } else if (WindowHelper::IsSplitWindowMode(GetMode()) && MathHelper::GreatNotEqual(splitRadius, 0.0)) {
892         SetCornerRadius(splitRadius);
893     } else if (WindowHelper::IsFloatingWindow(GetMode()) && MathHelper::GreatNotEqual(floatRadius, 0.0)) {
894         SetCornerRadius(floatRadius);
895     }
896 }
897 
UpdateWindowShadowAccordingToSystemConfig()898 void WindowImpl::UpdateWindowShadowAccordingToSystemConfig()
899 {
900     if (!WindowHelper::IsAppWindow(GetType()) && !isAppFloatingWindow_) {
901         return;
902     }
903 
904     auto& shadow = isFocused_ ? windowSystemConfig_.effectConfig_.focusedShadow_ :
905         windowSystemConfig_.effectConfig_.unfocusedShadow_;
906 
907     if (MathHelper::NearZero(shadow.elevation_)) {
908         return;
909     }
910 
911     if (!WindowHelper::IsFloatingWindow(GetMode())) {
912         surfaceNode_->SetShadowElevation(0.f);
913         WLOGFI("[WEffect][%{public}s]close shadow", name_.c_str());
914         return;
915     }
916 
917     auto display = SingletonContainer::IsDestroyed() ? nullptr :
918         SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
919     if (display == nullptr) {
920         WLOGFE("get display failed displayId:%{public}" PRIu64", window id:%{public}u", property_->GetDisplayId(),
921             property_->GetWindowId());
922         return;
923     }
924     auto vpr = display->GetVirtualPixelRatio();
925 
926     uint32_t colorValue;
927     if (!ColorParser::Parse(shadow.color_, colorValue)) {
928         WLOGFE("[WEffect]invalid color string: %{public}s", shadow.color_.c_str());
929         return;
930     }
931 
932     WLOGFI("[WEffect][%{public}s]focused: %{public}u, [%{public}f, %{public}s, %{public}f, %{public}f, %{public}f]",
933         name_.c_str(), isFocused_, shadow.elevation_, shadow.color_.c_str(),
934         shadow.offsetX_, shadow.offsetY_, shadow.alpha_);
935 
936     surfaceNode_->SetShadowElevation(shadow.elevation_ * vpr);
937     surfaceNode_->SetShadowColor(colorValue);
938     surfaceNode_->SetShadowOffsetX(shadow.offsetX_);
939     surfaceNode_->SetShadowOffsetY(shadow.offsetY_);
940     surfaceNode_->SetShadowAlpha(shadow.alpha_);
941     RSTransaction::FlushImplicitTransaction();
942 }
943 
SetSystemConfig()944 void WindowImpl::SetSystemConfig()
945 {
946     if (!IsAppMainOrSubOrFloatingWindow()) {
947         return;
948     }
949     if (SingletonContainer::Get<WindowAdapter>().GetSystemConfig(windowSystemConfig_) == WMError::WM_OK) {
950         if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
951             WLOGFD("get system decor enable:%{public}d", windowSystemConfig_.isSystemDecorEnable_);
952             property_->SetDecorEnable(windowSystemConfig_.isSystemDecorEnable_);
953             WLOGFD("get stretchable enable:%{public}d", windowSystemConfig_.isStretchable_);
954             property_->SetStretchable(windowSystemConfig_.isStretchable_);
955             // if window mode is undefined, set it from configuration
956             if (property_->GetWindowMode() == WindowMode::WINDOW_MODE_UNDEFINED) {
957                 WLOGFD("get default window mode:%{public}u", windowSystemConfig_.defaultWindowMode_);
958                 property_->SetWindowMode(windowSystemConfig_.defaultWindowMode_);
959             }
960             if (property_->GetLastWindowMode() == WindowMode::WINDOW_MODE_UNDEFINED) {
961                 property_->SetLastWindowMode(windowSystemConfig_.defaultWindowMode_);
962             }
963         }
964         SetWindowCornerRadiusAccordingToSystemConfig();
965     }
966     UpdateWindowShadowAccordingToSystemConfig();
967 }
968 
WindowCreateCheck(uint32_t parentId)969 bool WindowImpl::WindowCreateCheck(uint32_t parentId)
970 {
971     // check window name, same window names are forbidden
972     if (windowMap_.find(name_) != windowMap_.end()) {
973         WLOGFE("WindowName(%{public}s) already exists.", name_.c_str());
974         return false;
975     }
976     if (CheckCameraFloatingWindowMultiCreated(property_->GetWindowType())) {
977         WLOGFE("Camera Floating Window already exists.");
978         return false;
979     }
980     if (parentId == INVALID_WINDOW_ID) {
981         if (WindowHelper::IsSystemSubWindow(property_->GetWindowType()) ||
982             WindowHelper::IsSubWindow(property_->GetWindowType())) {
983             return false;
984         }
985         return true;
986     }
987 
988     if (property_->GetWindowType() == WindowType::WINDOW_TYPE_APP_COMPONENT) {
989         property_->SetParentId(parentId);
990     } else {
991         sptr<Window> parentWindow = nullptr;
992         for (const auto& winPair : windowMap_) {
993             if (winPair.second.first == parentId) {
994                 property_->SetParentId(parentId);
995                 parentWindow = winPair.second.second;
996                 break;
997             }
998         }
999         if (WindowHelper::IsSystemSubWindow(property_->GetWindowType())) {
1000             if (parentWindow == nullptr) {
1001                 return false;
1002             }
1003             if (!parentWindow->IsAllowHaveSystemSubWindow()) {
1004                 return false;
1005             }
1006         }
1007     }
1008     if (property_->GetParentId() != parentId) {
1009         WLOGFE("Parent Window does not exist. ParentId is %{public}u", parentId);
1010         return false;
1011     }
1012 
1013     return true;
1014 }
1015 
Create(uint32_t parentId,const std::shared_ptr<AbilityRuntime::Context> & context)1016 WMError WindowImpl::Create(uint32_t parentId, const std::shared_ptr<AbilityRuntime::Context>& context)
1017 {
1018     WLOGFI("[Client] Window [name:%{public}s] Create", name_.c_str());
1019     if (!WindowCreateCheck(parentId)) {
1020         return WMError::WM_ERROR_INVALID_PARAM;
1021     }
1022 
1023     context_ = context;
1024     sptr<WindowImpl> window(this);
1025     sptr<IWindow> windowAgent(new WindowAgent(window));
1026     static std::atomic<uint32_t> tempWindowId = 0;
1027     uint32_t windowId = tempWindowId++; // for test
1028     sptr<IRemoteObject> token = nullptr;
1029     if (context_ != nullptr) {
1030         token = context_->GetToken();
1031         if (token != nullptr) {
1032             property_->SetTokenState(true);
1033         }
1034     }
1035     InitAbilityInfo();
1036     SetSystemConfig();
1037 
1038     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
1039         GetConfigurationFromAbilityInfo();
1040     } else if (property_->GetWindowMode() == WindowMode::WINDOW_MODE_UNDEFINED) {
1041         property_->SetWindowMode(WindowMode::WINDOW_MODE_FULLSCREEN);
1042     }
1043 
1044     if (property_->GetWindowType() == WindowType::WINDOW_TYPE_VOLUME_OVERLAY) {
1045         surfaceNode_->SetFrameGravity(Gravity::TOP_LEFT);
1046     }
1047 
1048     WMError ret = SingletonContainer::Get<WindowAdapter>().CreateWindow(windowAgent, property_, surfaceNode_,
1049         windowId, token);
1050     RecordLifeCycleExceptionEvent(LifeCycleEvent::CREATE_EVENT, ret);
1051     if (ret != WMError::WM_OK) {
1052         WLOGFE("create window failed with errCode:%{public}d", static_cast<int32_t>(ret));
1053         return ret;
1054     }
1055     property_->SetWindowId(windowId);
1056     if (surfaceNode_) {
1057         surfaceNode_->SetWindowId(windowId);
1058     }
1059     sptr<Window> self(this);
1060     windowMap_.insert(std::make_pair(name_, std::pair<uint32_t, sptr<Window>>(windowId, self)));
1061     if (parentId != INVALID_WINDOW_ID) {
1062         subWindowMap_[property_->GetParentId()].push_back(window);
1063     }
1064 
1065     MapFloatingWindowToAppIfNeeded();
1066     MapDialogWindowToAppIfNeeded();
1067 
1068     state_ = WindowState::STATE_CREATED;
1069     InputTransferStation::GetInstance().AddInputWindow(self);
1070     needRemoveWindowInputChannel_ = true;
1071     return ret;
1072 }
1073 
InitAbilityInfo()1074 void WindowImpl::InitAbilityInfo()
1075 {
1076     AbilityInfo info;
1077     info.bundleName_ = SysCapUtil::GetBundleName();
1078     auto originalAbilityInfo = GetOriginalAbilityInfo();
1079     if (originalAbilityInfo != nullptr) {
1080         info.abilityName_ = originalAbilityInfo->name;
1081     } else {
1082         WLOGFD("original ability info is null %{public}s", name_.c_str());
1083     }
1084     property_->SetAbilityInfo(info);
1085 }
1086 
GetOriginalAbilityInfo() const1087 std::shared_ptr<AppExecFwk::AbilityInfo> WindowImpl::GetOriginalAbilityInfo() const
1088 {
1089     if (context_ == nullptr) {
1090         WLOGFD("context is null %{public}s", name_.c_str());
1091         return nullptr;
1092     }
1093 
1094     auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
1095     if (abilityContext == nullptr) {
1096         WLOGFD("abilityContext is null %{public}s", name_.c_str());
1097         return nullptr;
1098     }
1099     return abilityContext->GetAbilityInfo();
1100 }
1101 
BindDialogTarget(sptr<IRemoteObject> targetToken)1102 WMError WindowImpl::BindDialogTarget(sptr<IRemoteObject> targetToken)
1103 {
1104     uint32_t windowId = property_->GetWindowId();
1105     WMError ret = SingletonContainer::Get<WindowAdapter>().BindDialogTarget(windowId, targetToken);
1106     if (ret != WMError::WM_OK) {
1107         WLOGFE("bind window failed with errCode:%{public}d", static_cast<int32_t>(ret));
1108     }
1109 
1110     return ret;
1111 }
1112 
DestroyDialogWindow()1113 void WindowImpl::DestroyDialogWindow()
1114 {
1115     // remove from appDialogWindowMap_
1116     for (auto& dialogWindows: appDialogWindowMap_) {
1117         for (auto iter = dialogWindows.second.begin(); iter != dialogWindows.second.end(); ++iter) {
1118             if ((*iter) == nullptr) {
1119                 continue;
1120             }
1121             if ((*iter)->GetWindowId() == GetWindowId()) {
1122                 dialogWindows.second.erase(iter);
1123                 break;
1124             }
1125         }
1126     }
1127 
1128     // Destroy app dialog window if exist
1129     if (appDialogWindowMap_.count(GetWindowId()) > 0) {
1130         auto& dialogWindows = appDialogWindowMap_.at(GetWindowId());
1131         for (auto iter = dialogWindows.begin(); iter != dialogWindows.end(); iter = dialogWindows.begin()) {
1132             if ((*iter) == nullptr) {
1133                 dialogWindows.erase(iter);
1134                 continue;
1135             }
1136             (*iter)->Destroy(false);
1137         }
1138         appDialogWindowMap_.erase(GetWindowId());
1139     }
1140 }
1141 
DestroyFloatingWindow()1142 void WindowImpl::DestroyFloatingWindow()
1143 {
1144     // remove from appFloatingWindowMap_
1145     for (auto& floatingWindows: appFloatingWindowMap_) {
1146         for (auto iter = floatingWindows.second.begin(); iter != floatingWindows.second.end(); ++iter) {
1147             if ((*iter) == nullptr) {
1148                 continue;
1149             }
1150             if ((*iter)->GetWindowId() == GetWindowId()) {
1151                 floatingWindows.second.erase(iter);
1152                 break;
1153             }
1154         }
1155     }
1156 
1157     // Destroy app floating window if exist
1158     if (appFloatingWindowMap_.count(GetWindowId()) > 0) {
1159         auto& floatingWindows = appFloatingWindowMap_.at(GetWindowId());
1160         for (auto iter = floatingWindows.begin(); iter != floatingWindows.end(); iter = floatingWindows.begin()) {
1161             if ((*iter) == nullptr) {
1162                 floatingWindows.erase(iter);
1163                 continue;
1164             }
1165             (*iter)->Destroy();
1166         }
1167         appFloatingWindowMap_.erase(GetWindowId());
1168     }
1169 }
1170 
DestroySubWindow()1171 void WindowImpl::DestroySubWindow()
1172 {
1173     if (subWindowMap_.count(property_->GetParentId()) > 0) { // remove from subWindowMap_
1174         std::vector<sptr<WindowImpl>>& subWindows = subWindowMap_.at(property_->GetParentId());
1175         for (auto iter = subWindows.begin(); iter < subWindows.end(); ++iter) {
1176             if ((*iter) == nullptr) {
1177                 continue;
1178             }
1179             if ((*iter)->GetWindowId() == GetWindowId()) {
1180                 subWindows.erase(iter);
1181                 break;
1182             }
1183         }
1184     }
1185 
1186     if (subWindowMap_.count(GetWindowId()) > 0) { // remove from subWindowMap_ and windowMap_
1187         auto& subWindows = subWindowMap_.at(GetWindowId());
1188         for (auto iter = subWindows.begin(); iter != subWindows.end(); iter = subWindows.begin()) {
1189             if ((*iter) == nullptr) {
1190                 subWindows.erase(iter);
1191                 continue;
1192             }
1193             (*iter)->Destroy(false);
1194         }
1195         subWindowMap_[GetWindowId()].clear();
1196         subWindowMap_.erase(GetWindowId());
1197     }
1198 }
1199 
Destroy()1200 WMError WindowImpl::Destroy()
1201 {
1202     return Destroy(true);
1203 }
1204 
Destroy(bool needNotifyServer,bool needClearListener)1205 WMError WindowImpl::Destroy(bool needNotifyServer, bool needClearListener)
1206 {
1207     if (!IsWindowValid()) {
1208         return WMError::WM_OK;
1209     }
1210 
1211     WLOGFI("[Client] Window %{public}u Destroy", property_->GetWindowId());
1212     WMError ret = WMError::WM_OK;
1213     if (needNotifyServer) {
1214         NotifyBeforeDestroy(GetWindowName());
1215         if (subWindowMap_.count(GetWindowId()) > 0) {
1216             for (auto& subWindow : subWindowMap_.at(GetWindowId())) {
1217                 NotifyBeforeSubWindowDestroy(subWindow);
1218             }
1219         }
1220         ret = SingletonContainer::Get<WindowAdapter>().DestroyWindow(property_->GetWindowId());
1221         RecordLifeCycleExceptionEvent(LifeCycleEvent::DESTROY_EVENT, ret);
1222         if (ret != WMError::WM_OK) {
1223             WLOGFE("destroy window failed with errCode:%{public}d", static_cast<int32_t>(ret));
1224             if (GetType() != WindowType::WINDOW_TYPE_DIALOG) {
1225                 return ret;
1226             }
1227         }
1228     } else {
1229         WLOGFI("Do not need to notify server to destroy window");
1230     }
1231 
1232     if (needRemoveWindowInputChannel_) {
1233         InputTransferStation::GetInstance().RemoveInputWindow(property_->GetWindowId());
1234     }
1235     windowMap_.erase(GetWindowName());
1236     if (needClearListener) {
1237         ClearListenersById(GetWindowId());
1238     }
1239     DestroySubWindow();
1240     DestroyFloatingWindow();
1241     DestroyDialogWindow();
1242     {
1243         std::lock_guard<std::recursive_mutex> lock(mutex_);
1244         state_ = WindowState::STATE_DESTROYED;
1245     }
1246     return ret;
1247 }
1248 
NeedToStopShowing()1249 bool WindowImpl::NeedToStopShowing()
1250 {
1251     if (!WindowHelper::IsMainWindow(property_->GetWindowType())) {
1252         return false;
1253     }
1254     // show failed when current mode is not support or window only supports split mode and can show when locked
1255     bool isShowWhenLocked = GetWindowFlags() & static_cast<uint32_t>(WindowFlag::WINDOW_FLAG_SHOW_WHEN_LOCKED);
1256     if (!WindowHelper::IsWindowModeSupported(GetModeSupportInfo(), GetMode()) ||
1257         WindowHelper::IsOnlySupportSplitAndShowWhenLocked(isShowWhenLocked, GetModeSupportInfo())) {
1258         WLOGFE("current mode is not supported, windowId: %{public}u, modeSupportInfo: %{public}u, winMode: %{public}u",
1259             property_->GetWindowId(), GetModeSupportInfo(), GetMode());
1260         return true;
1261     }
1262     return false;
1263 }
1264 
UpdateSurfaceNodeAfterCustomAnimation(bool isAdd)1265 WMError WindowImpl::UpdateSurfaceNodeAfterCustomAnimation(bool isAdd)
1266 {
1267     WLOGFI("[Client] Window [name:%{public}s, id:%{public}u] UpdateRsTree, isAdd:%{public}u",
1268         name_.c_str(), property_->GetWindowId(), isAdd);
1269     if (!IsWindowValid()) {
1270         return WMError::WM_ERROR_INVALID_WINDOW;
1271     }
1272     if (!WindowHelper::IsSystemWindow(property_->GetWindowType())) {
1273         WLOGFE("only system window can set");
1274         return WMError::WM_ERROR_INVALID_OPERATION;
1275     }
1276     AdjustWindowAnimationFlag(false); // false means update rs tree with default option
1277     // need time out check
1278     WMError ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_ANIMATION_FLAG);
1279     if (ret != WMError::WM_OK) {
1280         WLOGFE("UpdateProperty failed with errCode:%{public}d", static_cast<int32_t>(ret));
1281         return ret;
1282     }
1283     ret = SingletonContainer::Get<WindowAdapter>().UpdateRsTree(property_->GetWindowId(), isAdd);
1284     if (ret != WMError::WM_OK) {
1285         WLOGFE("UpdateRsTree failed with errCode:%{public}d", static_cast<int32_t>(ret));
1286         return ret;
1287     }
1288     return WMError::WM_OK;
1289 }
1290 
AdjustWindowAnimationFlag(bool withAnimation)1291 void WindowImpl::AdjustWindowAnimationFlag(bool withAnimation)
1292 {
1293     // when show/hide with animation
1294     // use custom animation when transitionController exists; else use default animation
1295     WindowType winType = property_->GetWindowType();
1296     bool isAppWindow = WindowHelper::IsAppWindow(winType);
1297     if (withAnimation && !isAppWindow && animationTransitionController_) {
1298         // use custom animation
1299         property_->SetAnimationFlag(static_cast<uint32_t>(WindowAnimation::CUSTOM));
1300     } else if (isAppWindow || (withAnimation && !animationTransitionController_)) {
1301         // use default animation
1302         property_->SetAnimationFlag(static_cast<uint32_t>(WindowAnimation::DEFAULT));
1303     } else if (winType == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT) {
1304         property_->SetAnimationFlag(static_cast<uint32_t>(WindowAnimation::INPUTE));
1305     } else {
1306         // with no animation
1307         property_->SetAnimationFlag(static_cast<uint32_t>(WindowAnimation::NONE));
1308     }
1309 }
1310 
PreProcessShow(uint32_t reason,bool withAnimation)1311 WMError WindowImpl::PreProcessShow(uint32_t reason, bool withAnimation)
1312 {
1313     if (state_ == WindowState::STATE_FROZEN) {
1314         WLOGFE("window is frozen, can not be shown, windowId: %{public}u", property_->GetWindowId());
1315         return WMError::WM_ERROR_INVALID_OPERATION;
1316     }
1317     SetDefaultOption();
1318     SetModeSupportInfo(GetRequestModeSupportInfo());
1319     AdjustWindowAnimationFlag(withAnimation);
1320 
1321     if (NeedToStopShowing()) { // true means stop showing
1322         return WMError::WM_ERROR_INVALID_WINDOW_MODE_OR_SIZE;
1323     }
1324 
1325     // update title button visibility when show
1326     UpdateTitleButtonVisibility();
1327     return WMError::WM_OK;
1328 }
1329 
Show(uint32_t reason,bool withAnimation)1330 WMError WindowImpl::Show(uint32_t reason, bool withAnimation)
1331 {
1332     WLOGFD("[Client] Window Show [name:%{public}s, id:%{public}u, mode: %{public}u], reason:%{public}u, "
1333         "withAnimation:%{public}d", name_.c_str(), property_->GetWindowId(), GetMode(), reason, withAnimation);
1334     if (!IsWindowValid()) {
1335         return WMError::WM_ERROR_INVALID_WINDOW;
1336     }
1337     WindowStateChangeReason stateChangeReason = static_cast<WindowStateChangeReason>(reason);
1338     if (stateChangeReason == WindowStateChangeReason::KEYGUARD ||
1339         stateChangeReason == WindowStateChangeReason::TOGGLING) {
1340         state_ = WindowState::STATE_SHOWN;
1341         NotifyAfterForeground();
1342         return WMError::WM_OK;
1343     }
1344     if (state_ == WindowState::STATE_SHOWN) {
1345         if (property_->GetWindowType() == WindowType::WINDOW_TYPE_DESKTOP) {
1346             WLOGFI("desktop window [id:%{public}u] is shown, minimize all app windows", property_->GetWindowId());
1347             SingletonContainer::Get<WindowAdapter>().MinimizeAllAppWindows(property_->GetDisplayId());
1348         } else {
1349             WLOGFI("window is already shown id: %{public}u, raise to top", property_->GetWindowId());
1350             SingletonContainer::Get<WindowAdapter>().ProcessPointDown(property_->GetWindowId(), false);
1351         }
1352         NotifyAfterForeground(false);
1353         return WMError::WM_OK;
1354     }
1355     WMError ret = PreProcessShow(reason, withAnimation);
1356     if (ret != WMError::WM_OK) {
1357         NotifyForegroundFailed(ret);
1358         return ret;
1359     }
1360 
1361     ret = SingletonContainer::Get<WindowAdapter>().AddWindow(property_);
1362     RecordLifeCycleExceptionEvent(LifeCycleEvent::SHOW_EVENT, ret);
1363     if (ret == WMError::WM_OK) {
1364         state_ = WindowState::STATE_SHOWN;
1365         NotifyAfterForeground();
1366     } else {
1367         NotifyForegroundFailed(ret);
1368         WLOGFE("show window id:%{public}u errCode:%{public}d", property_->GetWindowId(), static_cast<int32_t>(ret));
1369     }
1370     return ret;
1371 }
1372 
Hide(uint32_t reason,bool withAnimation)1373 WMError WindowImpl::Hide(uint32_t reason, bool withAnimation)
1374 {
1375     WLOGFI("[Client] Window [name:%{public}s, id:%{public}u] Hide, reason:%{public}u, withAnimation:%{public}d",
1376         name_.c_str(), property_->GetWindowId(), reason, withAnimation);
1377     if (!IsWindowValid()) {
1378         return WMError::WM_ERROR_INVALID_WINDOW;
1379     }
1380     WindowStateChangeReason stateChangeReason = static_cast<WindowStateChangeReason>(reason);
1381     if (stateChangeReason == WindowStateChangeReason::KEYGUARD ||
1382         stateChangeReason == WindowStateChangeReason::TOGGLING) {
1383         state_ = stateChangeReason == WindowStateChangeReason::KEYGUARD ?
1384             WindowState::STATE_FROZEN : WindowState::STATE_HIDDEN;
1385         NotifyAfterBackground();
1386         return WMError::WM_OK;
1387     }
1388     if (state_ == WindowState::STATE_HIDDEN || state_ == WindowState::STATE_CREATED) {
1389         WLOGFI("window is already hidden id: %{public}u", property_->GetWindowId());
1390         return WMError::WM_OK;
1391     }
1392     WMError ret = WMError::WM_OK;
1393     if (WindowHelper::IsSystemWindow(property_->GetWindowType())) {
1394         AdjustWindowAnimationFlag(withAnimation);
1395         // when show(true) with default, hide() with None, to adjust animationFlag to disabled default animation
1396         ret = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_ANIMATION_FLAG);
1397         if (ret != WMError::WM_OK) {
1398             WLOGFE("UpdateProperty failed with errCode:%{public}d", static_cast<int32_t>(ret));
1399             return ret;
1400         }
1401     }
1402     ret = SingletonContainer::Get<WindowAdapter>().RemoveWindow(property_->GetWindowId());
1403     RecordLifeCycleExceptionEvent(LifeCycleEvent::HIDE_EVENT, ret);
1404     if (ret != WMError::WM_OK) {
1405         WLOGFE("hide errCode:%{public}d for winId:%{public}u", static_cast<int32_t>(ret), property_->GetWindowId());
1406         return ret;
1407     }
1408     state_ = WindowState::STATE_HIDDEN;
1409     NotifyAfterBackground();
1410     uint32_t animationFlag = property_->GetAnimationFlag();
1411     if (animationFlag == static_cast<uint32_t>(WindowAnimation::CUSTOM)) {
1412         animationTransitionController_->AnimationForHidden();
1413     }
1414     ResetMoveOrDragState();
1415     return ret;
1416 }
1417 
MoveTo(int32_t x,int32_t y)1418 WMError WindowImpl::MoveTo(int32_t x, int32_t y)
1419 {
1420     WLOGFI("[Client] Window [name:%{public}s, id:%{public}d] MoveTo %{public}d %{public}d",
1421         name_.c_str(), property_->GetWindowId(), x, y);
1422     if (!IsWindowValid()) {
1423         return WMError::WM_ERROR_INVALID_WINDOW;
1424     }
1425 
1426     Rect rect = (WindowHelper::IsMainFloatingWindow(GetType(), GetMode())) ?
1427         GetRect() : property_->GetRequestRect();
1428     Rect moveRect = { x, y, rect.width_, rect.height_ }; // must keep w/h, which may maintain stashed resize info
1429     property_->SetRequestRect(moveRect);
1430     if (state_ == WindowState::STATE_HIDDEN || state_ == WindowState::STATE_CREATED) {
1431         WLOGFI("window is hidden or created! id: %{public}u, oriPos: [%{public}d, %{public}d, "
1432                "movePos: [%{public}d, %{public}d]", property_->GetWindowId(), rect.posX_, rect.posY_, x, y);
1433         return WMError::WM_OK;
1434     }
1435 
1436     if (GetMode() != WindowMode::WINDOW_MODE_FLOATING) {
1437         WLOGFE("fullscreen window could not resize, winId: %{public}u", GetWindowId());
1438         return WMError::WM_ERROR_INVALID_OPERATION;
1439     }
1440     property_->SetWindowSizeChangeReason(WindowSizeChangeReason::MOVE);
1441     return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_RECT);
1442 }
1443 
Resize(uint32_t width,uint32_t height)1444 WMError WindowImpl::Resize(uint32_t width, uint32_t height)
1445 {
1446     WLOGFI("[Client] Window [name:%{public}s, id:%{public}d] Resize %{public}u %{public}u",
1447         name_.c_str(), property_->GetWindowId(), width, height);
1448     if (!IsWindowValid()) {
1449         return WMError::WM_ERROR_INVALID_WINDOW;
1450     }
1451 
1452     Rect rect = (WindowHelper::IsMainFloatingWindow(GetType(), GetMode())) ?
1453         GetRect() : property_->GetRequestRect();
1454     Rect resizeRect = { rect.posX_, rect.posY_, width, height };
1455     property_->SetRequestRect(resizeRect);
1456     property_->SetDecoStatus(false);
1457     if (state_ == WindowState::STATE_HIDDEN || state_ == WindowState::STATE_CREATED) {
1458         WLOGFI("window is hidden or created! id: %{public}u, oriRect: [%{public}u, %{public}u], "
1459                "resizeRect: [%{public}u, %{public}u]", property_->GetWindowId(), rect.width_,
1460                rect.height_, width, height);
1461         return WMError::WM_OK;
1462     }
1463 
1464     if (GetMode() != WindowMode::WINDOW_MODE_FLOATING) {
1465         WLOGFE("fullscreen window could not resize, winId: %{public}u", GetWindowId());
1466         return WMError::WM_ERROR_INVALID_OPERATION;
1467     }
1468     property_->SetWindowSizeChangeReason(WindowSizeChangeReason::RESIZE);
1469     return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_RECT);
1470 }
1471 
SetKeepScreenOn(bool keepScreenOn)1472 WMError WindowImpl::SetKeepScreenOn(bool keepScreenOn)
1473 {
1474     if (!IsWindowValid()) {
1475         return WMError::WM_ERROR_INVALID_WINDOW;
1476     }
1477     property_->SetKeepScreenOn(keepScreenOn);
1478     if (state_ == WindowState::STATE_SHOWN) {
1479         return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_KEEP_SCREEN_ON);
1480     }
1481     return WMError::WM_OK;
1482 }
1483 
IsKeepScreenOn() const1484 bool WindowImpl::IsKeepScreenOn() const
1485 {
1486     return property_->IsKeepScreenOn();
1487 }
1488 
SetTurnScreenOn(bool turnScreenOn)1489 WMError WindowImpl::SetTurnScreenOn(bool turnScreenOn)
1490 {
1491     if (!IsWindowValid()) {
1492         return WMError::WM_ERROR_INVALID_WINDOW;
1493     }
1494     property_->SetTurnScreenOn(turnScreenOn);
1495     if (state_ == WindowState::STATE_SHOWN) {
1496         return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_TURN_SCREEN_ON);
1497     }
1498     return WMError::WM_OK;
1499 }
1500 
IsTurnScreenOn() const1501 bool WindowImpl::IsTurnScreenOn() const
1502 {
1503     return property_->IsTurnScreenOn();
1504 }
1505 
SetBackgroundColor(uint32_t color)1506 WMError WindowImpl::SetBackgroundColor(uint32_t color)
1507 {
1508     if (uiContent_ != nullptr) {
1509         uiContent_->SetBackgroundColor(color);
1510         return WMError::WM_OK;
1511     }
1512     WLOGFI("uiContent is nullptr, windowId: %{public}u, use FA mode", GetWindowId());
1513     if (aceAbilityHandler_ != nullptr) {
1514         aceAbilityHandler_->SetBackgroundColor(color);
1515         return WMError::WM_OK;
1516     }
1517     WLOGFE("FA mode could not set background color: %{public}u", GetWindowId());
1518     return WMError::WM_ERROR_INVALID_OPERATION;
1519 }
1520 
GetBackgroundColor() const1521 uint32_t WindowImpl::GetBackgroundColor() const
1522 {
1523     if (uiContent_ != nullptr) {
1524         return uiContent_->GetBackgroundColor();
1525     }
1526     WLOGFI("uiContent is nullptr, windowId: %{public}u, use FA mode", GetWindowId());
1527     if (aceAbilityHandler_ != nullptr) {
1528         return aceAbilityHandler_->GetBackgroundColor();
1529     }
1530     WLOGFE("FA mode does not get background color: %{public}u", GetWindowId());
1531     return 0xffffffff; // means no background color been set, default color is white
1532 }
1533 
SetBackgroundColor(const std::string & color)1534 WMError WindowImpl::SetBackgroundColor(const std::string& color)
1535 {
1536     if (!IsWindowValid()) {
1537         return WMError::WM_ERROR_INVALID_WINDOW;
1538     }
1539     uint32_t colorValue;
1540     if (ColorParser::Parse(color, colorValue)) {
1541         WLOGFI("SetBackgroundColor: window: %{public}s, value: [%{public}s, %{public}u]",
1542             name_.c_str(), color.c_str(), colorValue);
1543         return SetBackgroundColor(colorValue);
1544     }
1545     WLOGFE("invalid color string: %{public}s", color.c_str());
1546     return WMError::WM_ERROR_INVALID_PARAM;
1547 }
1548 
SetTransparent(bool isTransparent)1549 WMError WindowImpl::SetTransparent(bool isTransparent)
1550 {
1551     if (!IsWindowValid()) {
1552         return WMError::WM_ERROR_INVALID_WINDOW;
1553     }
1554     ColorParam backgroundColor;
1555     backgroundColor.value = GetBackgroundColor();
1556     if (isTransparent) {
1557         backgroundColor.argb.alpha = 0x00; // 0x00: completely transparent
1558         return SetBackgroundColor(backgroundColor.value);
1559     } else {
1560         backgroundColor.value = GetBackgroundColor();
1561         if (backgroundColor.argb.alpha == 0x00) {
1562             backgroundColor.argb.alpha = 0xff; // 0xff: completely opaque
1563             return SetBackgroundColor(backgroundColor.value);
1564         }
1565     }
1566     return WMError::WM_OK;
1567 }
1568 
IsTransparent() const1569 bool WindowImpl::IsTransparent() const
1570 {
1571     ColorParam backgroundColor;
1572     backgroundColor.value = GetBackgroundColor();
1573     WLOGFI("color: %{public}u, alpha: %{public}u", backgroundColor.value, backgroundColor.argb.alpha);
1574     return backgroundColor.argb.alpha == 0x00; // 0x00: completely transparent
1575 }
1576 
SetBrightness(float brightness)1577 WMError WindowImpl::SetBrightness(float brightness)
1578 {
1579     if (!IsWindowValid()) {
1580         return WMError::WM_ERROR_INVALID_WINDOW;
1581     }
1582     if (brightness < MINIMUM_BRIGHTNESS || brightness > MAXIMUM_BRIGHTNESS) {
1583         WLOGFE("invalid brightness value: %{public}f", brightness);
1584         return WMError::WM_ERROR_INVALID_PARAM;
1585     }
1586     if (!WindowHelper::IsAppWindow(GetType())) {
1587         WLOGFE("non app window does not support set brightness, type: %{public}u", GetType());
1588         return WMError::WM_ERROR_INVALID_TYPE;
1589     }
1590     property_->SetBrightness(brightness);
1591     if (state_ == WindowState::STATE_SHOWN) {
1592         return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_SET_BRIGHTNESS);
1593     }
1594     return WMError::WM_OK;
1595 }
1596 
GetBrightness() const1597 float WindowImpl::GetBrightness() const
1598 {
1599     return property_->GetBrightness();
1600 }
1601 
SetCallingWindow(uint32_t windowId)1602 WMError WindowImpl::SetCallingWindow(uint32_t windowId)
1603 {
1604     if (!IsWindowValid()) {
1605         return WMError::WM_ERROR_INVALID_WINDOW;
1606     }
1607     property_->SetCallingWindow(windowId);
1608     return UpdateProperty(PropertyChangeAction::ACTION_UPDATE_CALLING_WINDOW);
1609 }
1610 
RecordLifeCycleExceptionEvent(LifeCycleEvent event,WMError errCode) const1611 void WindowImpl::RecordLifeCycleExceptionEvent(LifeCycleEvent event, WMError errCode) const
1612 {
1613     if (!(errCode > WMError::WM_ERROR_NEED_REPORT_BASE && errCode < WMError::WM_ERROR_NEED_REPORT_END)) {
1614         return;
1615     }
1616     std::ostringstream oss;
1617     oss << "life cycle is abnormal: " << "window_name: " << name_
1618         << ", id:" << GetWindowId() << ", event: " << TransferLifeCycleEventToString(event)
1619         << ", errCode: " << static_cast<int32_t>(errCode) << ";";
1620     std::string info = oss.str();
1621     WLOGFI("window life cycle exception: %{public}s", info.c_str());
1622     int32_t ret = OHOS::HiviewDFX::HiSysEvent::Write(
1623         OHOS::HiviewDFX::HiSysEvent::Domain::WINDOW_MANAGER,
1624         "WINDOW_LIFE_CYCLE_EXCEPTION",
1625         OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
1626         "PID", getpid(),
1627         "UID", getuid(),
1628         "MSG", info);
1629     if (ret != 0) {
1630         WLOGFE("Write HiSysEvent error, ret:%{public}d", ret);
1631     }
1632 }
1633 
TransferLifeCycleEventToString(LifeCycleEvent type) const1634 std::string WindowImpl::TransferLifeCycleEventToString(LifeCycleEvent type) const
1635 {
1636     std::string event;
1637     switch (type) {
1638         case LifeCycleEvent::CREATE_EVENT:
1639             event = "CREATE";
1640             break;
1641         case LifeCycleEvent::SHOW_EVENT:
1642             event = "SHOW";
1643             break;
1644         case LifeCycleEvent::HIDE_EVENT:
1645             event = "HIDE";
1646             break;
1647         case LifeCycleEvent::DESTROY_EVENT:
1648             event = "DESTROY";
1649             break;
1650         default:
1651             event = "UNDEFINE";
1652             break;
1653     }
1654     return event;
1655 }
1656 
SetPrivacyMode(bool isPrivacyMode)1657 void WindowImpl::SetPrivacyMode(bool isPrivacyMode)
1658 {
1659     property_->SetPrivacyMode(isPrivacyMode);
1660     surfaceNode_->SetSecurityLayer(isPrivacyMode || property_->GetSystemPrivacyMode());
1661     UpdateProperty(PropertyChangeAction::ACTION_UPDATE_PRIVACY_MODE);
1662 }
1663 
IsPrivacyMode() const1664 bool WindowImpl::IsPrivacyMode() const
1665 {
1666     return property_->GetPrivacyMode();
1667 }
1668 
SetSystemPrivacyMode(bool isSystemPrivacyMode)1669 void WindowImpl::SetSystemPrivacyMode(bool isSystemPrivacyMode)
1670 {
1671     property_->SetSystemPrivacyMode(isSystemPrivacyMode);
1672     surfaceNode_->SetSecurityLayer(isSystemPrivacyMode || property_->GetPrivacyMode());
1673 }
1674 
SetSnapshotSkip(bool isSkip)1675 void WindowImpl::SetSnapshotSkip(bool isSkip)
1676 {
1677     if (!Permission::IsSystemCalling()) {
1678         WLOGFE("set snapshot skip permission denied!");
1679         return;
1680     }
1681     surfaceNode_->SetSecurityLayer(isSkip || property_->GetSystemPrivacyMode());
1682 }
1683 
DisableAppWindowDecor()1684 void WindowImpl::DisableAppWindowDecor()
1685 {
1686     if (!Permission::IsSystemCalling()) {
1687         WLOGFE("disable app window decor permission denied!");
1688         return;
1689     }
1690     if (!WindowHelper::IsMainWindow(property_->GetWindowType())) {
1691         WLOGFE("window decoration is invalid on sub window");
1692         return;
1693     }
1694     WLOGFI("disable app window decoration.");
1695     isAppDecorEnable_ = false;
1696 }
1697 
IsDecorEnable() const1698 bool WindowImpl::IsDecorEnable() const
1699 {
1700     WLOGFD("get decor enable %{public}d", property_->GetDecorEnable());
1701     return property_->GetDecorEnable();
1702 }
1703 
Maximize()1704 WMError WindowImpl::Maximize()
1705 {
1706     WLOGFI("[Client] Window %{public}u Maximize", property_->GetWindowId());
1707     if (!IsWindowValid()) {
1708         return WMError::WM_ERROR_INVALID_WINDOW;
1709     }
1710     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
1711         return SetFullScreen(true);
1712     } else {
1713         WLOGFI("Maximize Window failed. The window is not main window");
1714         return WMError::WM_ERROR_INVALID_PARAM;
1715     }
1716 }
1717 
NotifyWindowTransition(TransitionReason reason)1718 WMError WindowImpl::NotifyWindowTransition(TransitionReason reason)
1719 {
1720     sptr<WindowTransitionInfo> fromInfo = new(std::nothrow) WindowTransitionInfo();
1721     sptr<WindowTransitionInfo> toInfo = new(std::nothrow) WindowTransitionInfo();
1722     if (fromInfo == nullptr || toInfo == nullptr) {
1723         WLOGFE("client new windowTransitionInfo failed");
1724         return WMError::WM_ERROR_NO_MEM;
1725     }
1726     auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
1727     if (abilityContext == nullptr) {
1728         WLOGFE("id:%{public}d is not ability Window", property_->GetWindowId());
1729         return WMError::WM_ERROR_NO_MEM;
1730     }
1731     auto abilityInfo = abilityContext->GetAbilityInfo();
1732     if (abilityInfo == nullptr) {
1733         return WMError::WM_ERROR_NULLPTR;
1734     }
1735     fromInfo->SetBundleName(context_->GetBundleName());
1736     fromInfo->SetAbilityName(abilityInfo->name);
1737     fromInfo->SetWindowMode(property_->GetWindowMode());
1738     fromInfo->SetWindowRect(property_->GetWindowRect());
1739     fromInfo->SetAbilityToken(context_->GetToken());
1740     fromInfo->SetWindowType(property_->GetWindowType());
1741     fromInfo->SetDisplayId(property_->GetDisplayId());
1742     fromInfo->SetTransitionReason(reason);
1743     return SingletonContainer::Get<WindowAdapter>().NotifyWindowTransition(fromInfo, toInfo);
1744 }
1745 
Minimize()1746 WMError WindowImpl::Minimize()
1747 {
1748     WLOGFI("[Client] Window %{public}u Minimize", property_->GetWindowId());
1749     if (!IsWindowValid()) {
1750         return WMError::WM_ERROR_INVALID_WINDOW;
1751     }
1752     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
1753         if (context_ != nullptr) {
1754             WMError ret = NotifyWindowTransition(TransitionReason::MINIMIZE);
1755             if (ret != WMError::WM_OK) {
1756                 WLOGFI("[Client] Window %{public}u Minimize without remote animation ret:%{public}u",
1757                     property_->GetWindowId(), static_cast<uint32_t>(ret));
1758                 AAFwk::AbilityManagerClient::GetInstance()->MinimizeAbility(context_->GetToken(), true);
1759             }
1760         } else {
1761             Hide();
1762         }
1763     }
1764     return WMError::WM_OK;
1765 }
1766 
Recover()1767 WMError WindowImpl::Recover()
1768 {
1769     WLOGFI("[Client] Window %{public}u Normalize", property_->GetWindowId());
1770     if (!IsWindowValid()) {
1771         return WMError::WM_ERROR_INVALID_WINDOW;
1772     }
1773     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
1774         SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
1775     }
1776     return WMError::WM_OK;
1777 }
1778 
Close()1779 WMError WindowImpl::Close()
1780 {
1781     WLOGFI("[Client] Window %{public}u Close", property_->GetWindowId());
1782     if (!IsWindowValid()) {
1783         return WMError::WM_ERROR_INVALID_WINDOW;
1784     }
1785     if (WindowHelper::IsMainWindow(property_->GetWindowType())) {
1786         auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
1787         if (abilityContext != nullptr) {
1788             WMError ret = NotifyWindowTransition(TransitionReason::CLOSE);
1789             if (ret != WMError::WM_OK) {
1790                 WLOGFI("[Client] Window %{public}u Close without remote animation ret:%{public}u",
1791                     property_->GetWindowId(), static_cast<uint32_t>(ret));
1792                 abilityContext->CloseAbility();
1793             }
1794         } else {
1795             Destroy();
1796         }
1797     }
1798     return WMError::WM_OK;
1799 }
1800 
RequestFocus() const1801 WMError WindowImpl::RequestFocus() const
1802 {
1803     if (!IsWindowValid()) {
1804         return WMError::WM_ERROR_INVALID_WINDOW;
1805     }
1806     return SingletonContainer::Get<WindowAdapter>().RequestFocus(property_->GetWindowId());
1807 }
1808 
SetInputEventConsumer(const std::shared_ptr<IInputEventConsumer> & inputEventConsumer)1809 void WindowImpl::SetInputEventConsumer(const std::shared_ptr<IInputEventConsumer>& inputEventConsumer)
1810 {
1811     std::lock_guard<std::recursive_mutex> lock(mutex_);
1812     inputEventConsumer_ = inputEventConsumer;
1813 }
1814 
RegisterLifeCycleListener(const sptr<IWindowLifeCycle> & listener)1815 bool WindowImpl::RegisterLifeCycleListener(const sptr<IWindowLifeCycle>& listener)
1816 {
1817     WLOGFD("Start register");
1818     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1819     return RegisterListener(lifecycleListeners_[GetWindowId()], listener);
1820 }
1821 
UnregisterLifeCycleListener(const sptr<IWindowLifeCycle> & listener)1822 bool WindowImpl::UnregisterLifeCycleListener(const sptr<IWindowLifeCycle>& listener)
1823 {
1824     WLOGFD("Start unregister");
1825     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1826     return UnregisterListener(lifecycleListeners_[GetWindowId()], listener);
1827 }
1828 
RegisterWindowChangeListener(const sptr<IWindowChangeListener> & listener)1829 bool WindowImpl::RegisterWindowChangeListener(const sptr<IWindowChangeListener>& listener)
1830 {
1831     WLOGFD("Start register");
1832     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1833     return RegisterListener(windowChangeListeners_[GetWindowId()], listener);
1834 }
1835 
UnregisterWindowChangeListener(const sptr<IWindowChangeListener> & listener)1836 bool WindowImpl::UnregisterWindowChangeListener(const sptr<IWindowChangeListener>& listener)
1837 {
1838     WLOGFD("Start register");
1839     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1840     return UnregisterListener(windowChangeListeners_[GetWindowId()], listener);
1841 }
1842 
RegisterAvoidAreaChangeListener(sptr<IAvoidAreaChangedListener> & listener)1843 bool WindowImpl::RegisterAvoidAreaChangeListener(sptr<IAvoidAreaChangedListener>& listener)
1844 {
1845     WLOGFD("Start register");
1846     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1847     bool ret = RegisterListener(avoidAreaChangeListeners_[GetWindowId()], listener);
1848     if (avoidAreaChangeListeners_[GetWindowId()].size() == 1) {
1849         SingletonContainer::Get<WindowAdapter>().UpdateAvoidAreaListener(property_->GetWindowId(), true);
1850     }
1851     return ret;
1852 }
1853 
UnregisterAvoidAreaChangeListener(sptr<IAvoidAreaChangedListener> & listener)1854 bool WindowImpl::UnregisterAvoidAreaChangeListener(sptr<IAvoidAreaChangedListener>& listener)
1855 {
1856     WLOGFD("Start unregister");
1857     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1858     bool ret = UnregisterListener(avoidAreaChangeListeners_[GetWindowId()], listener);
1859     if (avoidAreaChangeListeners_[GetWindowId()].empty()) {
1860         SingletonContainer::Get<WindowAdapter>().UpdateAvoidAreaListener(property_->GetWindowId(), false);
1861     }
1862     return ret;
1863 }
1864 
RegisterDragListener(const sptr<IWindowDragListener> & listener)1865 bool WindowImpl::RegisterDragListener(const sptr<IWindowDragListener>& listener)
1866 {
1867     WLOGFD("Start register");
1868     std::lock_guard<std::recursive_mutex> lock(mutex_);
1869     return RegisterListener(windowDragListeners_, listener);
1870 }
1871 
UnregisterDragListener(const sptr<IWindowDragListener> & listener)1872 bool WindowImpl::UnregisterDragListener(const sptr<IWindowDragListener>& listener)
1873 {
1874     WLOGFD("Start unregister");
1875     std::lock_guard<std::recursive_mutex> lock(mutex_);
1876     return UnregisterListener(windowDragListeners_, listener);
1877 }
1878 
RegisterDisplayMoveListener(sptr<IDisplayMoveListener> & listener)1879 bool WindowImpl::RegisterDisplayMoveListener(sptr<IDisplayMoveListener>& listener)
1880 {
1881     WLOGFD("Start register");
1882     std::lock_guard<std::recursive_mutex> lock(mutex_);
1883     return RegisterListener(displayMoveListeners_, listener);
1884 }
1885 
UnregisterDisplayMoveListener(sptr<IDisplayMoveListener> & listener)1886 bool WindowImpl::UnregisterDisplayMoveListener(sptr<IDisplayMoveListener>& listener)
1887 {
1888     WLOGFD("Start unregister");
1889     std::lock_guard<std::recursive_mutex> lock(mutex_);
1890     return UnregisterListener(displayMoveListeners_, listener);
1891 }
1892 
RegisterWindowDestroyedListener(const NotifyNativeWinDestroyFunc & func)1893 void WindowImpl::RegisterWindowDestroyedListener(const NotifyNativeWinDestroyFunc& func)
1894 {
1895     WLOGFD("Start register");
1896     notifyNativefunc_ = std::move(func);
1897 }
1898 
RegisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener> & listener)1899 bool WindowImpl::RegisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener>& listener)
1900 {
1901     WLOGFD("Start register");
1902     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1903     return RegisterListener(occupiedAreaChangeListeners_[GetWindowId()], listener);
1904 }
1905 
UnregisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener> & listener)1906 bool WindowImpl::UnregisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener>& listener)
1907 {
1908     WLOGFD("Start unregister");
1909     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1910     return UnregisterListener(occupiedAreaChangeListeners_[GetWindowId()], listener);
1911 }
1912 
RegisterTouchOutsideListener(const sptr<ITouchOutsideListener> & listener)1913 bool WindowImpl::RegisterTouchOutsideListener(const sptr<ITouchOutsideListener>& listener)
1914 {
1915     WLOGFD("Start register");
1916     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1917     return RegisterListener(touchOutsideListeners_[GetWindowId()], listener);
1918 }
1919 
UnregisterTouchOutsideListener(const sptr<ITouchOutsideListener> & listener)1920 bool WindowImpl::UnregisterTouchOutsideListener(const sptr<ITouchOutsideListener>& listener)
1921 {
1922     WLOGFD("Start unregister");
1923     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1924     return UnregisterListener(touchOutsideListeners_[GetWindowId()], listener);
1925 }
1926 
RegisterAnimationTransitionController(const sptr<IAnimationTransitionController> & listener)1927 bool WindowImpl::RegisterAnimationTransitionController(const sptr<IAnimationTransitionController>& listener)
1928 {
1929     if (listener == nullptr) {
1930         WLOGFE("listener is nullptr");
1931         return false;
1932     }
1933     animationTransitionController_ = listener;
1934     wptr<WindowProperty> propertyToken(property_);
1935     wptr<IAnimationTransitionController> animationTransitionControllerToken(animationTransitionController_);
1936     if (uiContent_) {
1937         uiContent_->SetNextFrameLayoutCallback([propertyToken, animationTransitionControllerToken]() {
1938             auto property = propertyToken.promote();
1939             auto animationTransitionController = animationTransitionControllerToken.promote();
1940             if (!property || !animationTransitionController) {
1941                 return;
1942             }
1943             uint32_t animationFlag = property->GetAnimationFlag();
1944             if (animationFlag == static_cast<uint32_t>(WindowAnimation::CUSTOM)) {
1945                 // CustomAnimation is enabled when animationTransitionController_ exists
1946                 animationTransitionController->AnimationForShown();
1947             }
1948         });
1949     }
1950     return true;
1951 }
1952 
RegisterScreenshotListener(const sptr<IScreenshotListener> & listener)1953 bool WindowImpl::RegisterScreenshotListener(const sptr<IScreenshotListener>& listener)
1954 {
1955     WLOGFD("Start register");
1956     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1957     return RegisterListener(screenshotListeners_[GetWindowId()], listener);
1958 }
1959 
UnregisterScreenshotListener(const sptr<IScreenshotListener> & listener)1960 bool WindowImpl::UnregisterScreenshotListener(const sptr<IScreenshotListener>& listener)
1961 {
1962     WLOGFD("Start unregister");
1963     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1964     return UnregisterListener(screenshotListeners_[GetWindowId()], listener);
1965 }
1966 
RegisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener> & listener)1967 bool WindowImpl::RegisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener>& listener)
1968 {
1969     WLOGFD("Start register");
1970     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1971     return RegisterListener(dialogTargetTouchListeners_[GetWindowId()], listener);
1972 }
1973 
UnregisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener> & listener)1974 bool WindowImpl::UnregisterDialogTargetTouchListener(const sptr<IDialogTargetTouchListener>& listener)
1975 {
1976     WLOGFD("Start unregister");
1977     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1978     return UnregisterListener(dialogTargetTouchListeners_[GetWindowId()], listener);
1979 }
1980 
RegisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener> & listener)1981 void WindowImpl::RegisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener>& listener)
1982 {
1983     WLOGFD("Start register");
1984     if (listener == nullptr) {
1985         WLOGFE("listener is nullptr");
1986         return;
1987     }
1988     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1989     dialogDeathRecipientListener_[GetWindowId()] = listener;
1990 }
1991 
UnregisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener> & listener)1992 void WindowImpl::UnregisterDialogDeathRecipientListener(const sptr<IDialogDeathRecipientListener>& listener)
1993 {
1994     WLOGFD("Start unregister");
1995     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
1996     dialogDeathRecipientListener_[GetWindowId()] = nullptr;
1997 }
1998 
1999 template<typename T>
RegisterListener(std::vector<sptr<T>> & holder,const sptr<T> & listener)2000 bool WindowImpl::RegisterListener(std::vector<sptr<T>>& holder, const sptr<T>& listener)
2001 {
2002     if (listener == nullptr) {
2003         WLOGFE("listener is nullptr");
2004         return false;
2005     }
2006     if (std::find(holder.begin(), holder.end(), listener) != holder.end()) {
2007         WLOGFE("Listener already registered");
2008         return true;
2009     }
2010     holder.emplace_back(listener);
2011     return true;
2012 }
2013 
2014 template<typename T>
UnregisterListener(std::vector<sptr<T>> & holder,const sptr<T> & listener)2015 bool WindowImpl::UnregisterListener(std::vector<sptr<T>>& holder, const sptr<T>& listener)
2016 {
2017     if (listener == nullptr) {
2018         WLOGFE("listener could not be null");
2019         return false;
2020     }
2021     holder.erase(std::remove_if(holder.begin(), holder.end(),
2022         [listener](sptr<T> registeredListener) {
2023             return registeredListener == listener;
2024         }), holder.end());
2025     return true;
2026 }
2027 
SetAceAbilityHandler(const sptr<IAceAbilityHandler> & handler)2028 void WindowImpl::SetAceAbilityHandler(const sptr<IAceAbilityHandler>& handler)
2029 {
2030     if (handler == nullptr) {
2031         WLOGFI("ace ability handler is nullptr");
2032     }
2033     std::lock_guard<std::recursive_mutex> lock(mutex_);
2034     aceAbilityHandler_ = handler;
2035 }
2036 
SetRequestModeSupportInfo(uint32_t modeSupportInfo)2037 void WindowImpl::SetRequestModeSupportInfo(uint32_t modeSupportInfo)
2038 {
2039     property_->SetRequestModeSupportInfo(modeSupportInfo);
2040     SetModeSupportInfo(modeSupportInfo);
2041 }
2042 
SetModeSupportInfo(uint32_t modeSupportInfo)2043 void WindowImpl::SetModeSupportInfo(uint32_t modeSupportInfo)
2044 {
2045     property_->SetModeSupportInfo(modeSupportInfo);
2046 }
2047 
UpdateRect(const struct Rect & rect,bool decoStatus,WindowSizeChangeReason reason)2048 void WindowImpl::UpdateRect(const struct Rect& rect, bool decoStatus, WindowSizeChangeReason reason)
2049 {
2050     if (state_ == WindowState::STATE_DESTROYED) {
2051         WLOGFW("invalid window state");
2052         return;
2053     }
2054     auto display = SingletonContainer::IsDestroyed() ? nullptr :
2055         SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
2056     if (display == nullptr) {
2057         WLOGFE("get display failed displayId:%{public}" PRIu64", window id:%{public}u", property_->GetDisplayId(),
2058             property_->GetWindowId());
2059         return;
2060     }
2061     Rect lastOriRect = property_->GetWindowRect();
2062 
2063     property_->SetDecoStatus(decoStatus);
2064     if (reason == WindowSizeChangeReason::HIDE) {
2065         property_->SetRequestRect(rect);
2066         return;
2067     }
2068     property_->SetWindowRect(rect);
2069 
2070     // update originRect when floating window show for the first time.
2071     if (!isOriginRectSet_ && WindowHelper::IsMainFloatingWindow(GetType(), GetMode())) {
2072         property_->SetOriginRect(rect);
2073         isOriginRectSet_ = true;
2074     }
2075     WLOGFD("winId:%{public}u, rect[%{public}d, %{public}d, %{public}u, %{public}u], reason:%{public}u",
2076         property_->GetWindowId(), rect.posX_, rect.posY_, rect.width_, rect.height_, reason);
2077     Rect rectToAce = rect;
2078     // update rectToAce for stretchable window
2079     if (windowSystemConfig_.isStretchable_ && WindowHelper::IsMainFloatingWindow(GetType(), GetMode())) {
2080         if (IsStretchableReason(reason)) {
2081             rectToAce = property_->GetOriginRect();
2082         } else {
2083             property_->SetOriginRect(rect);
2084         }
2085     }
2086     ResSchedReport::GetInstance().RequestPerfIfNeed(reason, GetType(), GetMode());
2087     if ((rectToAce != lastOriRect) || (reason != lastSizeChangeReason_)) {
2088         NotifySizeChange(rectToAce, reason);
2089         lastSizeChangeReason_ = reason;
2090     }
2091     UpdateViewportConfig(rectToAce, display, reason);
2092 }
2093 
UpdateMode(WindowMode mode)2094 void WindowImpl::UpdateMode(WindowMode mode)
2095 {
2096     WLOGI("UpdateMode %{public}u", mode);
2097     property_->SetWindowMode(mode);
2098     UpdateTitleButtonVisibility();
2099     NotifyModeChange(mode);
2100     if (uiContent_ != nullptr) {
2101         uiContent_->UpdateWindowMode(mode);
2102         WLOGFI("notify uiContent window mode change end");
2103     }
2104     // different modes have different corner radius settings
2105     SetWindowCornerRadiusAccordingToSystemConfig();
2106     // fullscreen and split have no shadow, float has shadow
2107     UpdateWindowShadowAccordingToSystemConfig();
2108 }
2109 
UpdateModeSupportInfo(uint32_t modeSupportInfo)2110 void WindowImpl::UpdateModeSupportInfo(uint32_t modeSupportInfo)
2111 {
2112     WLOGI("modeSupportInfo: %{public}u, winId: %{public}u", modeSupportInfo, GetWindowId());
2113     SetModeSupportInfo(modeSupportInfo);
2114     UpdateTitleButtonVisibility();
2115 }
2116 
HandleBackKeyPressedEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent)2117 void WindowImpl::HandleBackKeyPressedEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
2118 {
2119     std::shared_ptr<IInputEventConsumer> inputEventConsumer;
2120     {
2121         std::lock_guard<std::recursive_mutex> lock(mutex_);
2122         inputEventConsumer = inputEventConsumer_;
2123     }
2124     bool isConsumed = false;
2125     if (inputEventConsumer != nullptr) {
2126         WLOGFI("Transfer back key event to inputEventConsumer");
2127         isConsumed = inputEventConsumer->OnInputEvent(keyEvent);
2128     } else if (uiContent_ != nullptr) {
2129         WLOGFI("Transfer back key event to uiContent");
2130         isConsumed = uiContent_->ProcessBackPressed();
2131     } else {
2132         WLOGFE("There is no back key event consumer");
2133     }
2134     if (isConsumed || !WindowHelper::IsMainWindow(property_->GetWindowType())) {
2135         WLOGFI("Back key event is consumed or it is not a main window");
2136         return;
2137     }
2138     auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
2139     if (abilityContext == nullptr) {
2140         WLOGFE("abilityContext is null");
2141         return;
2142     }
2143     // TerminateAbility will invoke last ability, CloseAbility will not.
2144     bool shouldTerminateAbility = WindowHelper::IsFullScreenWindow(property_->GetWindowMode());
2145     if (shouldTerminateAbility) {
2146         abilityContext->TerminateSelf();
2147     } else {
2148         WMError ret = NotifyWindowTransition(TransitionReason::CLOSE);
2149         if (ret != WMError::WM_OK) {
2150             abilityContext->CloseAbility();
2151         }
2152     }
2153     WLOGFI("Window %{public}u will be closed, shouldTerminateAbility: %{public}u",
2154         property_->GetWindowId(), static_cast<uint32_t>(shouldTerminateAbility));
2155 }
2156 
ConsumeKeyEvent(std::shared_ptr<MMI::KeyEvent> & keyEvent)2157 void WindowImpl::ConsumeKeyEvent(std::shared_ptr<MMI::KeyEvent>& keyEvent)
2158 {
2159     int32_t keyCode = keyEvent->GetKeyCode();
2160     int32_t keyAction = keyEvent->GetKeyAction();
2161     WLOGFI("KeyCode: %{public}d, action: %{public}d", keyCode, keyAction);
2162     if (keyCode == MMI::KeyEvent::KEYCODE_BACK && keyAction == MMI::KeyEvent::KEY_ACTION_UP) {
2163         HandleBackKeyPressedEvent(keyEvent);
2164     } else {
2165         std::shared_ptr<IInputEventConsumer> inputEventConsumer;
2166         {
2167             std::lock_guard<std::recursive_mutex> lock(mutex_);
2168             inputEventConsumer = inputEventConsumer_;
2169         }
2170         if (inputEventConsumer != nullptr) {
2171             WLOGFI("Transfer key event to inputEventConsumer");
2172             (void)inputEventConsumer->OnInputEvent(keyEvent);
2173         } else if (uiContent_ != nullptr) {
2174             WLOGFI("Transfer key event to uiContent");
2175             (void)uiContent_->ProcessKeyEvent(keyEvent);
2176         } else {
2177             WLOGFE("There is no key event consumer");
2178         }
2179     }
2180 }
2181 
HandleModeChangeHotZones(int32_t posX,int32_t posY)2182 void WindowImpl::HandleModeChangeHotZones(int32_t posX, int32_t posY)
2183 {
2184     if (!WindowHelper::IsMainFloatingWindow(GetType(), GetMode())) {
2185         return;
2186     }
2187 
2188     ModeChangeHotZones hotZones;
2189     auto res = SingletonContainer::Get<WindowAdapter>().GetModeChangeHotZones(property_->GetDisplayId(), hotZones);
2190     WLOGFI("[HotZone] Window %{public}u, Pointer[%{public}d, %{public}d]", GetWindowId(), posX, posY);
2191     if (res == WMError::WM_OK) {
2192         WLOGFI("[HotZone] Fullscreen [%{public}d, %{public}d, %{public}u, %{public}u]", hotZones.fullscreen_.posX_,
2193             hotZones.fullscreen_.posY_, hotZones.fullscreen_.width_, hotZones.fullscreen_.height_);
2194         WLOGFI("[HotZone] Primary [%{public}d, %{public}d, %{public}u, %{public}u]", hotZones.primary_.posX_,
2195             hotZones.primary_.posY_, hotZones.primary_.width_, hotZones.primary_.height_);
2196         WLOGFI("[HotZone] Secondary [%{public}d, %{public}d, %{public}u, %{public}u]", hotZones.secondary_.posX_,
2197             hotZones.secondary_.posY_, hotZones.secondary_.width_, hotZones.secondary_.height_);
2198 
2199         if (WindowHelper::IsPointInTargetRectWithBound(posX, posY, hotZones.fullscreen_)) {
2200             SetFullScreen(true);
2201         } else if (WindowHelper::IsPointInTargetRectWithBound(posX, posY, hotZones.primary_)) {
2202             SetWindowMode(WindowMode::WINDOW_MODE_SPLIT_PRIMARY);
2203         } else if (WindowHelper::IsPointInTargetRectWithBound(posX, posY, hotZones.secondary_)) {
2204             SetWindowMode(WindowMode::WINDOW_MODE_SPLIT_SECONDARY);
2205         }
2206     }
2207 }
2208 
UpdatePointerEventForStretchableWindow(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)2209 void WindowImpl::UpdatePointerEventForStretchableWindow(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
2210 {
2211     MMI::PointerEvent::PointerItem pointerItem;
2212     if (!pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
2213         WLOGFW("Point item is invalid");
2214         return;
2215     }
2216     const Rect& originRect = property_->GetOriginRect();
2217     PointInfo originPos =
2218         WindowHelper::CalculateOriginPosition(originRect, GetRect(),
2219         { pointerItem.GetDisplayX(), pointerItem.GetDisplayY() });
2220     pointerItem.SetDisplayX(originPos.x);
2221     pointerItem.SetDisplayY(originPos.y);
2222     pointerItem.SetWindowX(originPos.x - originRect.posX_);
2223     pointerItem.SetWindowY(originPos.y - originRect.posY_);
2224     pointerEvent->UpdatePointerItem(pointerEvent->GetPointerId(), pointerItem);
2225 }
2226 
UpdateDragType(int32_t startPointPosX,int32_t startPointPosY)2227 void WindowImpl::UpdateDragType(int32_t startPointPosX, int32_t startPointPosY)
2228 {
2229     const auto& startRectExceptCorner = moveDragProperty_->startRectExceptCorner_;
2230     if (startPointPosX > startRectExceptCorner.posX_ &&
2231         (startPointPosX < startRectExceptCorner.posX_ +
2232         static_cast<int32_t>(startRectExceptCorner.width_))) {
2233         moveDragProperty_->dragType_ = DragType::DRAG_BOTTOM_OR_TOP;
2234     } else if (startPointPosY > startRectExceptCorner.posY_ &&
2235         (startPointPosY < startRectExceptCorner.posY_ +
2236         static_cast<int32_t>(startRectExceptCorner.height_))) {
2237         moveDragProperty_->dragType_ = DragType::DRAG_LEFT_OR_RIGHT;
2238     } else if ((startPointPosX <= startRectExceptCorner.posX_ && startPointPosY <= startRectExceptCorner.posY_) ||
2239         (startPointPosX >= startRectExceptCorner.posX_ + static_cast<int32_t>(startRectExceptCorner.width_) &&
2240          startPointPosY >= startRectExceptCorner.posY_ + static_cast<int32_t>(startRectExceptCorner.height_))) {
2241         moveDragProperty_->dragType_ = DragType::DRAG_LEFT_TOP_CORNER;
2242     } else {
2243         moveDragProperty_->dragType_ = DragType::DRAG_RIGHT_TOP_CORNER;
2244     }
2245 }
2246 
CalculateStartRectExceptHotZone(float vpr)2247 void WindowImpl::CalculateStartRectExceptHotZone(float vpr)
2248 {
2249     TransformHelper::Vector2 hotZoneScale(1, 1);
2250     if (property_->isNeedComputerTransform()) {
2251         property_->ComputeTransform();
2252         hotZoneScale = WindowHelper::CalculateHotZoneScale(property_->GetTransformMat());
2253     }
2254 
2255     const auto& startPointRect = GetRect();
2256     auto& startRectExceptFrame = moveDragProperty_->startRectExceptFrame_;
2257     startRectExceptFrame.posX_ = startPointRect.posX_ +
2258         static_cast<int32_t>(WINDOW_FRAME_WIDTH * vpr / hotZoneScale.x_);
2259     startRectExceptFrame.posY_ = startPointRect.posY_ +
2260         static_cast<int32_t>(WINDOW_FRAME_WIDTH * vpr / hotZoneScale.y_);
2261     startRectExceptFrame.width_ = startPointRect.width_ -
2262         static_cast<uint32_t>((WINDOW_FRAME_WIDTH + WINDOW_FRAME_WIDTH) * vpr / hotZoneScale.x_);
2263     startRectExceptFrame.height_ = startPointRect.height_ -
2264         static_cast<uint32_t>((WINDOW_FRAME_WIDTH + WINDOW_FRAME_WIDTH) * vpr / hotZoneScale.y_);
2265 
2266     auto& startRectExceptCorner =  moveDragProperty_->startRectExceptCorner_;
2267     startRectExceptCorner.posX_ = startPointRect.posX_ +
2268         static_cast<int32_t>(WINDOW_FRAME_CORNER_WIDTH * vpr / hotZoneScale.x_);
2269     startRectExceptCorner.posY_ = startPointRect.posY_ +
2270         static_cast<int32_t>(WINDOW_FRAME_CORNER_WIDTH * vpr / hotZoneScale.y_);
2271     startRectExceptCorner.width_ = startPointRect.width_ -
2272         static_cast<uint32_t>((WINDOW_FRAME_CORNER_WIDTH + WINDOW_FRAME_CORNER_WIDTH) * vpr / hotZoneScale.x_);
2273     startRectExceptCorner.height_ = startPointRect.height_ -
2274         static_cast<uint32_t>((WINDOW_FRAME_CORNER_WIDTH + WINDOW_FRAME_CORNER_WIDTH) * vpr / hotZoneScale.y_);
2275 }
2276 
IsPointInDragHotZone(int32_t startPointPosX,int32_t startPointPosY)2277 bool WindowImpl::IsPointInDragHotZone(int32_t startPointPosX, int32_t startPointPosY)
2278 {
2279     if (!WindowHelper::IsPointInTargetRect(startPointPosX,
2280         startPointPosY, moveDragProperty_->startRectExceptFrame_) ||
2281         (!WindowHelper::IsPointInWindowExceptCorner(startPointPosX,
2282         startPointPosY, moveDragProperty_->startRectExceptCorner_))) {
2283         return true;
2284     }
2285     return false;
2286 }
2287 
StartMove()2288 void WindowImpl::StartMove()
2289 {
2290     if (!WindowHelper::IsMainFloatingWindow(GetType(), GetMode())) {
2291         WLOGFE("[StartMove] current window can not be moved, windowId %{public}u", GetWindowId());
2292         return;
2293     }
2294     if (!moveDragProperty_->pointEventStarted_ || moveDragProperty_->startDragFlag_) {
2295         WLOGFE("[StartMove] pointerEvent has not been started, or is dragging now");
2296         return;
2297     }
2298     moveDragProperty_->startMoveFlag_ = true;
2299     SingletonContainer::Get<WindowAdapter>().NotifyServerReadyToMoveOrDrag(property_->GetWindowId(),
2300         property_, moveDragProperty_);
2301     WLOGFI("[StartMove] windowId %{public}u", GetWindowId());
2302 }
2303 
ResetMoveOrDragState()2304 void WindowImpl::ResetMoveOrDragState()
2305 {
2306     if (!WindowHelper::IsMainWindow(GetType())) {
2307         return;
2308     }
2309     moveDragProperty_->pointEventStarted_ = false;
2310     moveDragProperty_->startDragFlag_ = false;
2311     moveDragProperty_->startMoveFlag_ = false;
2312     UpdateRect(GetRect(), property_->GetDecoStatus(), WindowSizeChangeReason::DRAG_END);
2313 }
2314 
ReadyToMoveOrDragWindow(const std::shared_ptr<MMI::PointerEvent> & pointerEvent,const MMI::PointerEvent::PointerItem & pointerItem)2315 void WindowImpl::ReadyToMoveOrDragWindow(const std::shared_ptr<MMI::PointerEvent>& pointerEvent,
2316     const MMI::PointerEvent::PointerItem& pointerItem)
2317 {
2318     if (moveDragProperty_->pointEventStarted_) {
2319         return;
2320     }
2321 
2322     moveDragProperty_->startPointRect_ = GetRect();
2323     moveDragProperty_->startPointPosX_ = pointerItem.GetDisplayX();
2324     moveDragProperty_->startPointPosY_ = pointerItem.GetDisplayY();
2325     moveDragProperty_->startPointerId_ = pointerEvent->GetPointerId();
2326     moveDragProperty_->targetDisplayId_ = pointerEvent->GetTargetDisplayId();
2327     moveDragProperty_->sourceType_ = pointerEvent->GetSourceType();
2328     moveDragProperty_->pointEventStarted_ = true;
2329 
2330     // calculate window inner rect except frame
2331     auto display = SingletonContainer::IsDestroyed() ? nullptr :
2332         SingletonContainer::Get<DisplayManager>().GetDisplayById(moveDragProperty_->targetDisplayId_);
2333     if (display == nullptr || display->GetDisplayInfo() == nullptr) {
2334         WLOGFE("get display failed displayId:%{public}" PRIu64", window id:%{public}u", property_->GetDisplayId(),
2335             property_->GetWindowId());
2336         return;
2337     }
2338     float vpr = display->GetVirtualPixelRatio();
2339     int32_t startPointPosX = moveDragProperty_->startPointPosX_ + display->GetDisplayInfo()->GetOffsetX();
2340     int32_t startPointPosY = moveDragProperty_->startPointPosY_ + display->GetDisplayInfo()->GetOffsetY();
2341 
2342     CalculateStartRectExceptHotZone(vpr);
2343 
2344     if (GetType() == WindowType::WINDOW_TYPE_DOCK_SLICE) {
2345         moveDragProperty_->startMoveFlag_ = true;
2346         SingletonContainer::Get<WindowAdapter>().NotifyServerReadyToMoveOrDrag(property_->GetWindowId(),
2347             property_, moveDragProperty_);
2348     } else if (IsPointInDragHotZone(startPointPosX, startPointPosY)) {
2349         moveDragProperty_->startDragFlag_ = true;
2350         UpdateDragType(startPointPosX, startPointPosY);
2351         SingletonContainer::Get<WindowAdapter>().NotifyServerReadyToMoveOrDrag(property_->GetWindowId(),
2352             property_, moveDragProperty_);
2353     }
2354     return;
2355 }
2356 
EndMoveOrDragWindow(int32_t posX,int32_t posY,int32_t pointId,int32_t sourceType)2357 void WindowImpl::EndMoveOrDragWindow(int32_t posX, int32_t posY, int32_t pointId, int32_t sourceType)
2358 {
2359     if (pointId != moveDragProperty_->startPointerId_ || sourceType != moveDragProperty_->sourceType_) {
2360         return;
2361     }
2362 
2363     if (moveDragProperty_->startDragFlag_) {
2364         SingletonContainer::Get<WindowAdapter>().ProcessPointUp(GetWindowId());
2365         moveDragProperty_->startDragFlag_ = false;
2366     }
2367 
2368     if (moveDragProperty_->startMoveFlag_) {
2369         SingletonContainer::Get<WindowAdapter>().ProcessPointUp(GetWindowId());
2370         moveDragProperty_->startMoveFlag_ = false;
2371         HandleModeChangeHotZones(posX, posY);
2372     }
2373     moveDragProperty_->pointEventStarted_ = false;
2374     ResSchedReport::GetInstance().StopPerfIfNeed();
2375 }
2376 
ConsumeMoveOrDragEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)2377 void WindowImpl::ConsumeMoveOrDragEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
2378 {
2379     MMI::PointerEvent::PointerItem pointerItem;
2380     int32_t pointId = pointerEvent->GetPointerId();
2381     int32_t sourceType = pointerEvent->GetSourceType();
2382     if (!pointerEvent->GetPointerItem(pointId, pointerItem) ||
2383         (sourceType == MMI::PointerEvent::SOURCE_TYPE_MOUSE &&
2384         pointerEvent->GetButtonId() != MMI::PointerEvent::MOUSE_BUTTON_LEFT)) {
2385         WLOGFW("invalid pointerEvent");
2386         return;
2387     }
2388     int32_t pointDisplayX = pointerItem.GetDisplayX();
2389     int32_t pointDisplayY = pointerItem.GetDisplayY();
2390     int32_t action = pointerEvent->GetPointerAction();
2391     int32_t targetDisplayId = pointerEvent->GetTargetDisplayId();
2392     switch (action) {
2393         // Ready to move or drag
2394         case MMI::PointerEvent::POINTER_ACTION_DOWN:
2395         case MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN: {
2396             const auto& rect = GetRect();
2397             ReadyToMoveOrDragWindow(pointerEvent, pointerItem);
2398             if (IsPointerEventConsumed()) {
2399                 ResSchedReport::GetInstance().TrigClick();
2400             }
2401             WLOGFI("[Client Point Down]: windowId: %{public}u, pointId: %{public}d, sourceType: %{public}d, "
2402                    "hasPointStarted: %{public}d, startMove: %{public}d, startDrag: %{public}d, targetDisplayId: "
2403                    "%{public}d, pointPos: [%{public}d, %{public}d], winRect: [%{public}d, %{public}d, %{public}u, "
2404                    "%{public}u]", GetWindowId(), pointId, sourceType, moveDragProperty_->pointEventStarted_,
2405                    moveDragProperty_->startMoveFlag_, moveDragProperty_->startDragFlag_, targetDisplayId,
2406                    pointDisplayX, pointDisplayY, rect.posX_, rect.posY_, rect.width_, rect.height_);
2407             break;
2408         }
2409         // End move or drag
2410         case MMI::PointerEvent::POINTER_ACTION_UP:
2411         case MMI::PointerEvent::POINTER_ACTION_BUTTON_UP:
2412         case MMI::PointerEvent::POINTER_ACTION_CANCEL: {
2413             EndMoveOrDragWindow(pointDisplayX, pointDisplayY, pointId, sourceType);
2414             WLOGFI("[Client Point Up/Cancel]: windowId: %{public}u, action: %{public}d, sourceType: %{public}d, "
2415                 "startMove: %{public}d, startDrag: %{public}d", GetWindowId(), action, sourceType,
2416                 moveDragProperty_->startMoveFlag_, moveDragProperty_->startDragFlag_);
2417             break;
2418         }
2419         default:
2420             break;
2421     }
2422 }
2423 
IsPointerEventConsumed()2424 bool WindowImpl::IsPointerEventConsumed()
2425 {
2426     return moveDragProperty_->startDragFlag_ || moveDragProperty_->startMoveFlag_;
2427 }
2428 
TransferPointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)2429 void WindowImpl::TransferPointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
2430 {
2431     if (windowSystemConfig_.isStretchable_ && GetMode() == WindowMode::WINDOW_MODE_FLOATING) {
2432         UpdatePointerEventForStretchableWindow(pointerEvent);
2433     }
2434     std::shared_ptr<IInputEventConsumer> inputEventConsumer;
2435     {
2436         std::lock_guard<std::recursive_mutex> lock(mutex_);
2437         inputEventConsumer = inputEventConsumer_;
2438     }
2439     if (inputEventConsumer != nullptr) {
2440         WLOGFI("Transfer pointer event to inputEventConsumer");
2441         (void)inputEventConsumer->OnInputEvent(pointerEvent);
2442     } else if (uiContent_ != nullptr) {
2443         WLOGFD("Transfer pointer event to uiContent");
2444         (void)uiContent_->ProcessPointerEvent(pointerEvent);
2445     } else {
2446         WLOGE("pointerEvent is not consumed, windowId: %{public}u", GetWindowId());
2447         pointerEvent->MarkProcessed();
2448     }
2449 }
2450 
CalculatePointerDirection(int32_t pointerX,int32_t pointerY)2451 uint32_t WindowImpl::CalculatePointerDirection(int32_t pointerX, int32_t pointerY)
2452 {
2453     UpdateDragType(pointerX, pointerY);
2454     return STYLEID_MAP.at(moveDragProperty_->dragType_);
2455 }
2456 
HandlePointerStyle(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)2457 void WindowImpl::HandlePointerStyle(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
2458 {
2459     MMI::PointerEvent::PointerItem pointerItem;
2460     if (!pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
2461         WLOGFE("Get pointeritem failed");
2462         pointerEvent->MarkProcessed();
2463         return;
2464     }
2465     auto action = pointerEvent->GetPointerAction();
2466     if (WindowHelper::IsMainFloatingWindow(GetType(), GetMode())) {
2467         auto display = SingletonContainer::IsDestroyed() ? nullptr :
2468             SingletonContainer::Get<DisplayManager>().GetDisplayById(moveDragProperty_->targetDisplayId_);
2469         if (display == nullptr || display->GetDisplayInfo() == nullptr) {
2470             WLOGFE("get display failed displayId:%{public}" PRIu64", window id:%{public}u",
2471                 property_->GetDisplayId(), property_->GetWindowId());
2472             return;
2473         }
2474         float vpr = display->GetVirtualPixelRatio();
2475         CalculateStartRectExceptHotZone(vpr);
2476         if (IsPointInDragHotZone(pointerItem.GetDisplayX(), pointerItem.GetDisplayY())) {
2477             uint32_t tempStyleID = mouseStyleID_;
2478             // calculate pointer style
2479             mouseStyleID_ = CalculatePointerDirection(pointerItem.GetDisplayX(), pointerItem.GetDisplayY());
2480             if (tempStyleID != mouseStyleID_) {
2481                 MMI::InputManager::GetInstance()->SetPointerStyle(
2482                     static_cast<uint32_t>(pointerEvent->GetAgentWindowId()), mouseStyleID_);
2483             }
2484             isPointerStyleChanged_ = true;
2485         } else if (action == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP) {
2486             MMI::InputManager::GetInstance()->SetPointerStyle(
2487                 static_cast<uint32_t>(pointerEvent->GetAgentWindowId()), MMI::MOUSE_ICON::DEFAULT);
2488         }
2489     } else if (GetType() == WindowType::WINDOW_TYPE_DOCK_SLICE && isPointerStyleChanged_ == false) {
2490         uint32_t mouseStyle = (GetRect().width_ > GetRect().height_) ?
2491             MMI::MOUSE_ICON::NORTH_SOUTH : MMI::MOUSE_ICON::WEST_EAST;
2492         MMI::InputManager::GetInstance()->SetPointerStyle(
2493             static_cast<uint32_t>(pointerEvent->GetAgentWindowId()), mouseStyle);
2494         isPointerStyleChanged_ = true;
2495     }
2496     if (isPointerStyleChanged_ && (action == MMI::PointerEvent::POINTER_ACTION_LEAVE_WINDOW ||
2497         !IsPointInDragHotZone(pointerItem.GetDisplayX(), pointerItem.GetDisplayY()))) {
2498         MMI::InputManager::GetInstance()->SetPointerStyle(static_cast<uint32_t>(pointerEvent->GetAgentWindowId()),
2499             MMI::MOUSE_ICON::DEFAULT);
2500         isPointerStyleChanged_ = false;
2501         mouseStyleID_ = 0;
2502     }
2503 }
2504 
ConsumePointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)2505 void WindowImpl::ConsumePointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
2506 {
2507     // If windowRect transformed, transform event back to its origin position
2508     if (property_) {
2509         property_->UpdatePointerEvent(pointerEvent);
2510     }
2511     int32_t action = pointerEvent->GetPointerAction();
2512     if (action == MMI::PointerEvent::POINTER_ACTION_MOVE || action == MMI::PointerEvent::POINTER_ACTION_DOWN ||
2513         action == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN) {
2514         ResSchedReport::GetInstance().TrigSlide(GetType(), true);
2515     }
2516     if (action == MMI::PointerEvent::POINTER_ACTION_UP || action == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP ||
2517         action == MMI::PointerEvent::POINTER_ACTION_CANCEL) {
2518         ResSchedReport::GetInstance().TrigSlide(GetType(), false);
2519     }
2520     if ((action == MMI::PointerEvent::POINTER_ACTION_MOVE || action == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP) &&
2521         pointerEvent->GetSourceType() == MMI::PointerEvent::SOURCE_TYPE_MOUSE) {
2522         HandlePointerStyle(pointerEvent);
2523     }
2524     if (action == MMI::PointerEvent::POINTER_ACTION_DOWN || action == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN) {
2525         WLOGI("WMS process point down, window: [name:%{public}s, id:%{public}u], action: %{public}d",
2526             name_.c_str(), GetWindowId(), action);
2527         if (GetType() == WindowType::WINDOW_TYPE_LAUNCHER_RECENT) {
2528             MMI::PointerEvent::PointerItem pointerItem;
2529             if (!pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
2530                 WLOGFW("Point item is invalid");
2531                 pointerEvent->MarkProcessed();
2532                 return;
2533             }
2534             if (!WindowHelper::IsPointInTargetRect(pointerItem.GetDisplayX(), pointerItem.GetDisplayY(), GetRect())) {
2535                 NotifyAfterUnfocused(false);
2536                 pointerEvent->MarkProcessed();
2537                 return;
2538             }
2539         }
2540         if (property_ != nullptr) {
2541             SingletonContainer::Get<WindowAdapter>().ProcessPointDown(property_->GetWindowId());
2542         }
2543     }
2544 
2545     // If point event type is up, should reset start move flag
2546     if (WindowHelper::IsMainFloatingWindow(GetType(), GetMode()) || GetType() == WindowType::WINDOW_TYPE_DOCK_SLICE ||
2547         (action == MMI::PointerEvent::POINTER_ACTION_UP || action == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP ||
2548         action == MMI::PointerEvent::POINTER_ACTION_CANCEL)) {
2549         ConsumeMoveOrDragEvent(pointerEvent);
2550     }
2551 
2552     if (IsPointerEventConsumed()) {
2553         pointerEvent->MarkProcessed();
2554         return;
2555     }
2556 
2557     TransferPointerEvent(pointerEvent);
2558 }
2559 
RequestVsync(const std::shared_ptr<VsyncCallback> & vsyncCallback)2560 void WindowImpl::RequestVsync(const std::shared_ptr<VsyncCallback>& vsyncCallback)
2561 {
2562     std::lock_guard<std::recursive_mutex> lock(mutex_);
2563     if (state_ == WindowState::STATE_DESTROYED) {
2564         WLOGFE("[WM] Receive Vsync Request failed, window is destroyed");
2565         return;
2566     }
2567     if (!SingletonContainer::IsDestroyed()) {
2568         VsyncStation::GetInstance().RequestVsync(vsyncCallback);
2569     }
2570 }
2571 
UpdateFocusStatus(bool focused)2572 void WindowImpl::UpdateFocusStatus(bool focused)
2573 {
2574     WLOGFD("window focus status: %{public}d, id: %{public}u", focused, property_->GetWindowId());
2575     if (focused) {
2576         NotifyAfterFocused();
2577     } else {
2578         NotifyAfterUnfocused();
2579     }
2580     isFocused_ = focused;
2581     UpdateWindowShadowAccordingToSystemConfig();
2582 }
2583 
IsFocused() const2584 bool WindowImpl::IsFocused() const
2585 {
2586     return isFocused_;
2587 }
2588 
UpdateConfiguration(const std::shared_ptr<AppExecFwk::Configuration> & configuration)2589 void WindowImpl::UpdateConfiguration(const std::shared_ptr<AppExecFwk::Configuration>& configuration)
2590 {
2591     if (uiContent_ != nullptr) {
2592         WLOGFD("notify ace winId:%{public}u", GetWindowId());
2593         uiContent_->UpdateConfiguration(configuration);
2594     }
2595     if (subWindowMap_.count(GetWindowId()) == 0) {
2596         return;
2597     }
2598     for (auto& subWindow : subWindowMap_.at(GetWindowId())) {
2599         subWindow->UpdateConfiguration(configuration);
2600     }
2601 }
2602 
UpdateAvoidArea(const sptr<AvoidArea> & avoidArea,AvoidAreaType type)2603 void WindowImpl::UpdateAvoidArea(const sptr<AvoidArea>& avoidArea, AvoidAreaType type)
2604 {
2605     WLOGFI("Window Update AvoidArea, id: %{public}u", property_->GetWindowId());
2606     NotifyAvoidAreaChange(avoidArea, type);
2607 }
2608 
UpdateViewportConfig(const Rect & rect,const sptr<Display> & display,WindowSizeChangeReason reason)2609 void WindowImpl::UpdateViewportConfig(const Rect& rect, const sptr<Display>& display, WindowSizeChangeReason reason)
2610 {
2611     std::lock_guard<std::recursive_mutex> lock(mutex_);
2612     if (uiContent_ == nullptr) {
2613         return;
2614     }
2615     Ace::ViewportConfig config;
2616     config.SetSize(rect.width_, rect.height_);
2617     config.SetPosition(rect.posX_, rect.posY_);
2618     if (display) {
2619         config.SetDensity(display->GetVirtualPixelRatio());
2620     }
2621     uiContent_->UpdateViewportConfig(config, reason);
2622     WLOGFD("UpdateViewportConfig Id:%{public}u, windowRect:[%{public}d, %{public}d, %{public}u, %{public}u]",
2623         property_->GetWindowId(), rect.posX_, rect.posY_, rect.width_, rect.height_);
2624 }
2625 
UpdateWindowStateUnfrozen()2626 void WindowImpl::UpdateWindowStateUnfrozen()
2627 {
2628     auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
2629     if (abilityContext != nullptr && windowTag_ == WindowTag::MAIN_WINDOW) {
2630         WLOGFD("DoAbilityForeground KEYGUARD, id: %{public}u", GetWindowId());
2631         AAFwk::AbilityManagerClient::GetInstance()->DoAbilityForeground(abilityContext->GetToken(),
2632             static_cast<uint32_t>(WindowStateChangeReason::KEYGUARD));
2633     } else if (state_ != WindowState::STATE_SHOWN) {
2634         state_ = WindowState::STATE_SHOWN;
2635         NotifyAfterForeground();
2636     }
2637 }
2638 
UpdateWindowState(WindowState state)2639 void WindowImpl::UpdateWindowState(WindowState state)
2640 {
2641     WLOGFI("[Client] Window %{public}u, %{public}s WindowState to set:%{public}u", GetWindowId(), name_.c_str(), state);
2642     if (!IsWindowValid()) {
2643         return;
2644     }
2645     auto abilityContext = AbilityRuntime::Context::ConvertTo<AbilityRuntime::AbilityContext>(context_);
2646     switch (state) {
2647         case WindowState::STATE_FROZEN: {
2648             if (abilityContext != nullptr && windowTag_ == WindowTag::MAIN_WINDOW) {
2649                 WLOGFD("DoAbilityBackground KEYGUARD, id: %{public}u", GetWindowId());
2650                 AAFwk::AbilityManagerClient::GetInstance()->DoAbilityBackground(abilityContext->GetToken(),
2651                     static_cast<uint32_t>(WindowStateChangeReason::KEYGUARD));
2652             } else {
2653                 state_ = WindowState::STATE_FROZEN;
2654                 NotifyAfterBackground();
2655             }
2656             break;
2657         }
2658         case WindowState::STATE_UNFROZEN: {
2659             if (abilityContext != nullptr && windowTag_ == WindowTag::MAIN_WINDOW) {
2660                 WLOGFD("DoAbilityForeground KEYGUARD, id: %{public}u", GetWindowId());
2661                 AAFwk::AbilityManagerClient::GetInstance()->DoAbilityForeground(abilityContext->GetToken(),
2662                     static_cast<uint32_t>(WindowStateChangeReason::KEYGUARD));
2663             } else {
2664                 state_ = WindowState::STATE_SHOWN;
2665                 NotifyAfterForeground();
2666             }
2667             break;
2668         }
2669         case WindowState::STATE_SHOWN: {
2670             if (abilityContext != nullptr && windowTag_ == WindowTag::MAIN_WINDOW) {
2671                 WLOGFD("WindowState::STATE_SHOWN, id: %{public}u", GetWindowId());
2672                 AAFwk::AbilityManagerClient::GetInstance()->DoAbilityForeground(abilityContext->GetToken(),
2673                     static_cast<uint32_t>(WindowStateChangeReason::TOGGLING));
2674             } else {
2675                 state_ = WindowState::STATE_SHOWN;
2676                 NotifyAfterForeground();
2677             }
2678             break;
2679         }
2680         case WindowState::STATE_HIDDEN: {
2681             if (abilityContext != nullptr && windowTag_ == WindowTag::MAIN_WINDOW &&
2682                 state_ == WindowState::STATE_SHOWN) {
2683                 WLOGFI("WindowState: STATE_SHOWN, id: %{public}u", GetWindowId());
2684                 AAFwk::AbilityManagerClient::GetInstance()->DoAbilityBackground(abilityContext->GetToken(),
2685                     static_cast<uint32_t>(WindowStateChangeReason::NORMAL));
2686             } else {
2687                 Hide(static_cast<uint32_t>(WindowStateChangeReason::NORMAL), false);
2688             }
2689             break;
2690         }
2691         default: {
2692             WLOGFE("windowState to set is invalid");
2693             break;
2694         }
2695     }
2696 }
2697 
GetWindowProperty()2698 sptr<WindowProperty> WindowImpl::GetWindowProperty()
2699 {
2700     WLOGFI("[Client] Window %{public}u, %{public}s", GetWindowId(), name_.c_str());
2701     if (!IsWindowValid()) {
2702         return nullptr;
2703     }
2704     return property_;
2705 }
2706 
RestoreSplitWindowMode(uint32_t mode)2707 void WindowImpl::RestoreSplitWindowMode(uint32_t mode)
2708 {
2709     if (!IsWindowValid()) {
2710         return;
2711     }
2712     auto windowMode = static_cast<WindowMode>(mode);
2713     if (windowMode == WindowMode::WINDOW_MODE_SPLIT_PRIMARY || windowMode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY) {
2714         UpdateMode(windowMode);
2715     }
2716 }
2717 
UpdateDragEvent(const PointInfo & point,DragEvent event)2718 void WindowImpl::UpdateDragEvent(const PointInfo& point, DragEvent event)
2719 {
2720     NotifyDragEvent(point, event);
2721 }
2722 
NotifyDragEvent(const PointInfo & point,DragEvent event)2723 void WindowImpl::NotifyDragEvent(const PointInfo& point, DragEvent event)
2724 {
2725     auto windowDragListeners = GetListeners<IWindowDragListener>();
2726     Rect rect = GetRect();
2727     for (auto& listener : windowDragListeners) {
2728         if (listener.GetRefPtr() != nullptr) {
2729             listener.GetRefPtr()->OnDrag(point.x - rect.posX_, point.y - rect.posY_, event);
2730         }
2731     }
2732 }
2733 
UpdateDisplayId(DisplayId from,DisplayId to)2734 void WindowImpl::UpdateDisplayId(DisplayId from, DisplayId to)
2735 {
2736     WLOGFD("update displayId. win %{public}u", GetWindowId());
2737     NotifyDisplayMoveChange(from, to);
2738     property_->SetDisplayId(to);
2739 }
2740 
UpdateOccupiedAreaChangeInfo(const sptr<OccupiedAreaChangeInfo> & info)2741 void WindowImpl::UpdateOccupiedAreaChangeInfo(const sptr<OccupiedAreaChangeInfo>& info)
2742 {
2743     WLOGFI("Window Update OccupiedArea, id: %{public}u", property_->GetWindowId());
2744     NotifyOccupiedAreaChange(info);
2745 }
2746 
UpdateActiveStatus(bool isActive)2747 void WindowImpl::UpdateActiveStatus(bool isActive)
2748 {
2749     WLOGFD("window active status: %{public}d, id: %{public}u", isActive, property_->GetWindowId());
2750     if (isActive) {
2751         NotifyAfterActive();
2752     } else {
2753         NotifyAfterInactive();
2754     }
2755 }
2756 
NotifyScreenshot()2757 void WindowImpl::NotifyScreenshot()
2758 {
2759     auto screenshotListeners = GetListeners<IScreenshotListener>();
2760     for (auto& screenshotListener : screenshotListeners) {
2761         if (screenshotListener.GetRefPtr() != nullptr) {
2762             screenshotListener.GetRefPtr()->OnScreenshot();
2763         }
2764     }
2765 }
2766 
NotifyTouchOutside()2767 void WindowImpl::NotifyTouchOutside()
2768 {
2769     auto touchOutsideListeners = GetListeners<ITouchOutsideListener>();
2770     for (auto& touchOutsideListener : touchOutsideListeners) {
2771         if (touchOutsideListener.GetRefPtr() != nullptr) {
2772             touchOutsideListener.GetRefPtr()->OnTouchOutside();
2773         }
2774     }
2775 }
2776 
NotifyTouchDialogTarget()2777 void WindowImpl::NotifyTouchDialogTarget()
2778 {
2779     SingletonContainer::Get<WindowAdapter>().ProcessPointDown(property_->GetWindowId());
2780     auto dialogTargetTouchListeners = GetListeners<IDialogTargetTouchListener>();
2781     for (auto& dialogTargetTouchListener : dialogTargetTouchListeners) {
2782         if (dialogTargetTouchListener.GetRefPtr() != nullptr) {
2783             dialogTargetTouchListener.GetRefPtr()->OnDialogTargetTouch();
2784         }
2785     }
2786 }
2787 
NotifyDestroy()2788 void WindowImpl::NotifyDestroy()
2789 {
2790     auto dialogDeathRecipientListener = GetListener<IDialogDeathRecipientListener>();
2791     if (dialogDeathRecipientListener.GetRefPtr() != nullptr) {
2792         dialogDeathRecipientListener.GetRefPtr()->OnDialogDeathRecipient();
2793     }
2794 }
2795 
NotifyForeground()2796 void WindowImpl::NotifyForeground()
2797 {
2798     NotifyAfterForeground();
2799 }
2800 
NotifyBackground()2801 void WindowImpl::NotifyBackground()
2802 {
2803     NotifyAfterBackground();
2804 }
2805 
TransformSurfaceNode(const Transform & trans)2806 void WindowImpl::TransformSurfaceNode(const Transform& trans)
2807 {
2808     if (surfaceNode_ == nullptr) {
2809         return;
2810     }
2811     surfaceNode_->SetPivotX(trans.pivotX_);
2812     surfaceNode_->SetPivotY(trans.pivotY_);
2813     surfaceNode_->SetScaleX(trans.scaleX_);
2814     surfaceNode_->SetScaleY(trans.scaleY_);
2815     surfaceNode_->SetTranslateX(trans.translateX_);
2816     surfaceNode_->SetTranslateY(trans.translateY_);
2817     surfaceNode_->SetTranslateZ(trans.translateZ_);
2818     surfaceNode_->SetRotationX(trans.rotationX_);
2819     surfaceNode_->SetRotationY(trans.rotationY_);
2820     surfaceNode_->SetRotation(trans.rotationZ_);
2821 }
2822 
UpdateZoomTransform(const Transform & trans,bool isDisplayZoomOn)2823 void WindowImpl::UpdateZoomTransform(const Transform& trans, bool isDisplayZoomOn)
2824 {
2825     WLOGFD("%{public}s zoomTrans, pivotX:%{public}f, pivotY:%{public}f, scaleX:%{public}f, scaleY:%{public}f"
2826         ", transX:%{public}f, transY:%{public}f, transZ:%{public}f, rotateX:%{public}f, rotateY:%{public}f "
2827         "rotateZ:%{public}f", property_->GetWindowName().c_str(), trans.pivotX_, trans.pivotY_, trans.scaleX_,
2828         trans.scaleY_, trans.translateX_, trans.translateY_, trans.translateZ_, trans.rotationX_,
2829         trans.rotationY_, trans.rotationZ_);
2830     property_->SetZoomTransform(trans);
2831     property_->SetDisplayZoomState(isDisplayZoomOn);
2832 }
2833 
ClearListenersById(uint32_t winId)2834 void WindowImpl::ClearListenersById(uint32_t winId)
2835 {
2836     std::lock_guard<std::recursive_mutex> lock(globalMutex_);
2837     ClearUselessListeners(screenshotListeners_, winId);
2838     ClearUselessListeners(touchOutsideListeners_, winId);
2839     ClearUselessListeners(dialogTargetTouchListeners_, winId);
2840     ClearUselessListeners(lifecycleListeners_, winId);
2841     ClearUselessListeners(windowChangeListeners_, winId);
2842     ClearUselessListeners(avoidAreaChangeListeners_, winId);
2843     ClearUselessListeners(occupiedAreaChangeListeners_, winId);
2844     ClearUselessListeners(dialogDeathRecipientListener_, winId);
2845 }
2846 
NotifySizeChange(Rect rect,WindowSizeChangeReason reason)2847 void WindowImpl::NotifySizeChange(Rect rect, WindowSizeChangeReason reason)
2848 {
2849     auto windowChangeListeners = GetListeners<IWindowChangeListener>();
2850     for (auto& listener : windowChangeListeners) {
2851         if (listener.GetRefPtr() != nullptr) {
2852             listener.GetRefPtr()->OnSizeChange(rect, reason);
2853         }
2854     }
2855 }
2856 
NotifyAvoidAreaChange(const sptr<AvoidArea> & avoidArea,AvoidAreaType type)2857 void WindowImpl::NotifyAvoidAreaChange(const sptr<AvoidArea>& avoidArea, AvoidAreaType type)
2858 {
2859     auto avoidAreaChangeListeners = GetListeners<IAvoidAreaChangedListener>();
2860     for (auto& listener : avoidAreaChangeListeners) {
2861         if (listener.GetRefPtr() != nullptr) {
2862             listener.GetRefPtr()->OnAvoidAreaChanged(*avoidArea, type);
2863         }
2864     }
2865 }
2866 
NotifyDisplayMoveChange(DisplayId from,DisplayId to)2867 void WindowImpl::NotifyDisplayMoveChange(DisplayId from, DisplayId to)
2868 {
2869     auto displayMoveListeners = GetListeners<IDisplayMoveListener>();
2870     for (auto& listener : displayMoveListeners) {
2871         if (listener.GetRefPtr() != nullptr) {
2872             listener.GetRefPtr()->OnDisplayMove(from, to);
2873         }
2874     }
2875 }
2876 
NotifyModeChange(WindowMode mode)2877 void WindowImpl::NotifyModeChange(WindowMode mode)
2878 {
2879     auto windowChangeListeners = GetListeners<IWindowChangeListener>();
2880     for (auto& listener : windowChangeListeners) {
2881         if (listener.GetRefPtr() != nullptr) {
2882             listener.GetRefPtr()->OnModeChange(mode);
2883         }
2884     }
2885 }
2886 
NotifyOccupiedAreaChange(const sptr<OccupiedAreaChangeInfo> & info)2887 void WindowImpl::NotifyOccupiedAreaChange(const sptr<OccupiedAreaChangeInfo>& info)
2888 {
2889     auto occupiedAreaChangeListeners = GetListeners<IOccupiedAreaChangeListener>();
2890     for (auto& listener : occupiedAreaChangeListeners) {
2891         if (listener.GetRefPtr() != nullptr) {
2892             listener.GetRefPtr()->OnSizeChange(info);
2893         }
2894     }
2895 }
2896 
SetNeedRemoveWindowInputChannel(bool needRemoveWindowInputChannel)2897 void WindowImpl::SetNeedRemoveWindowInputChannel(bool needRemoveWindowInputChannel)
2898 {
2899     needRemoveWindowInputChannel_ = needRemoveWindowInputChannel;
2900 }
2901 
GetSystemAlarmWindowDefaultSize(Rect defaultRect)2902 Rect WindowImpl::GetSystemAlarmWindowDefaultSize(Rect defaultRect)
2903 {
2904     auto display = SingletonContainer::IsDestroyed() ? nullptr :
2905         SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
2906     if (display == nullptr) {
2907         WLOGFE("get display failed displayId:%{public}" PRIu64", window id:%{public}u", property_->GetDisplayId(),
2908             property_->GetWindowId());
2909         return defaultRect;
2910     }
2911     uint32_t width = static_cast<uint32_t>(display->GetWidth());
2912     uint32_t height = static_cast<uint32_t>(display->GetHeight());
2913     WLOGFI("width:%{public}u, height:%{public}u, displayId:%{public}" PRIu64"",
2914         width, height, property_->GetDisplayId());
2915     Rect rect;
2916     uint32_t alarmWidth = static_cast<uint32_t>((static_cast<float>(width) *
2917         SYSTEM_ALARM_WINDOW_WIDTH_RATIO));
2918     uint32_t alarmHeight = static_cast<uint32_t>((static_cast<float>(height) *
2919         SYSTEM_ALARM_WINDOW_HEIGHT_RATIO));
2920 
2921     rect = { static_cast<int32_t>((width - alarmWidth) / 2), static_cast<int32_t>((height - alarmHeight) / 2),
2922                 alarmWidth, alarmHeight }; // divided by 2 to middle the window
2923     return rect;
2924 }
2925 
SetDefaultOption()2926 void WindowImpl::SetDefaultOption()
2927 {
2928     switch (property_->GetWindowType()) {
2929         case WindowType::WINDOW_TYPE_STATUS_BAR:
2930         case WindowType::WINDOW_TYPE_NAVIGATION_BAR:
2931         case WindowType::WINDOW_TYPE_VOLUME_OVERLAY:
2932         case WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT: {
2933             property_->SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
2934             property_->SetFocusable(false);
2935             break;
2936         }
2937         case WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW: {
2938             property_->SetRequestRect(GetSystemAlarmWindowDefaultSize(property_->GetRequestRect()));
2939             property_->SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
2940             break;
2941         }
2942         case WindowType::WINDOW_TYPE_KEYGUARD: {
2943             RemoveWindowFlag(WindowFlag::WINDOW_FLAG_NEED_AVOID);
2944             property_->SetWindowMode(WindowMode::WINDOW_MODE_FULLSCREEN);
2945             break;
2946         }
2947         case WindowType::WINDOW_TYPE_DRAGGING_EFFECT: {
2948             property_->SetWindowFlags(0);
2949             break;
2950         }
2951         case WindowType::WINDOW_TYPE_APP_COMPONENT: {
2952             property_->SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
2953             property_->SetAnimationFlag(static_cast<uint32_t>(WindowAnimation::NONE));
2954             break;
2955         }
2956         case WindowType::WINDOW_TYPE_TOAST:
2957         case WindowType::WINDOW_TYPE_FLOAT:
2958         case WindowType::WINDOW_TYPE_FLOAT_CAMERA:
2959         case WindowType::WINDOW_TYPE_VOICE_INTERACTION:
2960         case WindowType::WINDOW_TYPE_LAUNCHER_DOCK:
2961         case WindowType::WINDOW_TYPE_SEARCHING_BAR:
2962         case WindowType::WINDOW_TYPE_SCREENSHOT:
2963         case WindowType::WINDOW_TYPE_DIALOG: {
2964             property_->SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
2965             break;
2966         }
2967         case WindowType::WINDOW_TYPE_BOOT_ANIMATION:
2968         case WindowType::WINDOW_TYPE_POINTER: {
2969             property_->SetFocusable(false);
2970             break;
2971         }
2972         case WindowType::WINDOW_TYPE_DOCK_SLICE: {
2973             property_->SetWindowMode(WindowMode::WINDOW_MODE_FLOATING);
2974             property_->SetFocusable(false);
2975             break;
2976         }
2977         default:
2978             break;
2979     }
2980 }
2981 
IsWindowValid() const2982 bool WindowImpl::IsWindowValid() const
2983 {
2984     bool res = ((state_ > WindowState::STATE_INITIAL) && (state_ < WindowState::STATE_BOTTOM));
2985     if (!res) {
2986         WLOGFI("window is already destroyed or not created! id: %{public}u", GetWindowId());
2987     }
2988     return res;
2989 }
2990 
IsLayoutFullScreen() const2991 bool WindowImpl::IsLayoutFullScreen() const
2992 {
2993     uint32_t flags = GetWindowFlags();
2994     auto mode = GetMode();
2995     bool needAvoid = (flags & static_cast<uint32_t>(WindowFlag::WINDOW_FLAG_NEED_AVOID));
2996     return (mode == WindowMode::WINDOW_MODE_FULLSCREEN && !needAvoid);
2997 }
2998 
IsFullScreen() const2999 bool WindowImpl::IsFullScreen() const
3000 {
3001     auto statusProperty = GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_STATUS_BAR);
3002     auto naviProperty = GetSystemBarPropertyByType(WindowType::WINDOW_TYPE_NAVIGATION_BAR);
3003     return (IsLayoutFullScreen() && !statusProperty.enable_ && !naviProperty.enable_);
3004 }
3005 
SetRequestedOrientation(Orientation orientation)3006 void WindowImpl::SetRequestedOrientation(Orientation orientation)
3007 {
3008     if (property_->GetRequestedOrientation() == orientation) {
3009         return;
3010     }
3011     property_->SetRequestedOrientation(orientation);
3012     if (state_ == WindowState::STATE_SHOWN) {
3013         UpdateProperty(PropertyChangeAction::ACTION_UPDATE_ORIENTATION);
3014     }
3015 }
3016 
GetRequestedOrientation()3017 Orientation WindowImpl::GetRequestedOrientation()
3018 {
3019     return property_->GetRequestedOrientation();
3020 }
3021 
SetTouchHotAreas(const std::vector<Rect> & rects)3022 WMError WindowImpl::SetTouchHotAreas(const std::vector<Rect>& rects)
3023 {
3024     std::vector<Rect> lastTouchHotAreas;
3025     property_->GetTouchHotAreas(lastTouchHotAreas);
3026 
3027     property_->SetTouchHotAreas(rects);
3028     WMError result = UpdateProperty(PropertyChangeAction::ACTION_UPDATE_TOUCH_HOT_AREA);
3029     if (result != WMError::WM_OK) {
3030         property_->SetTouchHotAreas(lastTouchHotAreas);
3031     }
3032     return result;
3033 }
GetRequestedTouchHotAreas(std::vector<Rect> & rects) const3034 void WindowImpl::GetRequestedTouchHotAreas(std::vector<Rect>& rects) const
3035 {
3036     property_->GetTouchHotAreas(rects);
3037 }
3038 
SetAPPWindowLabel(const std::string & label)3039 WMError WindowImpl::SetAPPWindowLabel(const std::string& label)
3040 {
3041     if (uiContent_ == nullptr) {
3042         WLOGFE("uicontent is empty");
3043         return WMError::WM_ERROR_NULLPTR;
3044     }
3045     uiContent_->SetAppWindowTitle(label);
3046     return WMError::WM_OK;
3047 }
3048 
SetAPPWindowIcon(const std::shared_ptr<Media::PixelMap> & icon)3049 WMError WindowImpl::SetAPPWindowIcon(const std::shared_ptr<Media::PixelMap>& icon)
3050 {
3051     if (icon == nullptr) {
3052         WLOGFE("window icon is empty");
3053         return WMError::WM_ERROR_NULLPTR;
3054     }
3055     if (uiContent_ == nullptr) {
3056         WLOGFE("uicontent is empty");
3057         return WMError::WM_ERROR_NULLPTR;
3058     }
3059     uiContent_->SetAppWindowIcon(icon);
3060     return WMError::WM_OK;
3061 }
CheckCameraFloatingWindowMultiCreated(WindowType type)3062 bool WindowImpl::CheckCameraFloatingWindowMultiCreated(WindowType type)
3063 {
3064     if (type != WindowType::WINDOW_TYPE_FLOAT_CAMERA) {
3065         return false;
3066     }
3067 
3068     for (auto& winPair : windowMap_) {
3069         if (winPair.second.second->GetType() == WindowType::WINDOW_TYPE_FLOAT_CAMERA) {
3070             return true;
3071         }
3072     }
3073     uint32_t accessTokenId = static_cast<uint32_t>(IPCSkeleton::GetCallingTokenID());
3074     property_->SetAccessTokenId(accessTokenId);
3075     WLOGFI("Create camera float window, accessTokenId = %{public}u", accessTokenId);
3076     return false;
3077 }
3078 
SetCornerRadius(float cornerRadius)3079 WMError WindowImpl::SetCornerRadius(float cornerRadius)
3080 {
3081     WLOGFI("[Client] Window %{public}s set corner radius %{public}f", name_.c_str(), cornerRadius);
3082     if (MathHelper::LessNotEqual(cornerRadius, 0.0)) {
3083         return WMError::WM_ERROR_INVALID_PARAM;
3084     }
3085     surfaceNode_->SetCornerRadius(cornerRadius);
3086     RSTransaction::FlushImplicitTransaction();
3087     return WMError::WM_OK;
3088 }
3089 
SetShadowRadius(float radius)3090 WMError WindowImpl::SetShadowRadius(float radius)
3091 {
3092     if (!Permission::IsSystemCalling()) {
3093         WLOGFE("set shadow radius permission denied!");
3094         return WMError::WM_ERROR_INVALID_PERMISSION;
3095     }
3096     WLOGFI("[Client] Window %{public}s set shadow radius %{public}f", name_.c_str(), radius);
3097     if (MathHelper::LessNotEqual(radius, 0.0)) {
3098         return WMError::WM_ERROR_INVALID_PARAM;
3099     }
3100     surfaceNode_->SetShadowRadius(radius);
3101     RSTransaction::FlushImplicitTransaction();
3102     return WMError::WM_OK;
3103 }
3104 
SetShadowColor(std::string color)3105 WMError WindowImpl::SetShadowColor(std::string color)
3106 {
3107     if (!Permission::IsSystemCalling()) {
3108         WLOGFE("set shadow color permission denied!");
3109         return WMError::WM_ERROR_INVALID_PERMISSION;
3110     }
3111     WLOGFI("[Client] Window %{public}s set shadow color %{public}s", name_.c_str(), color.c_str());
3112     uint32_t colorValue;
3113     if (!ColorParser::Parse(color, colorValue)) {
3114         return WMError::WM_ERROR_INVALID_PARAM;
3115     }
3116     surfaceNode_->SetShadowColor(colorValue);
3117     RSTransaction::FlushImplicitTransaction();
3118     return WMError::WM_OK;
3119 }
3120 
SetShadowOffsetX(float offsetX)3121 void WindowImpl::SetShadowOffsetX(float offsetX)
3122 {
3123     if (!Permission::IsSystemCalling()) {
3124         WLOGFE("set shadow offset x permission denied!");
3125         return;
3126     }
3127     WLOGFI("[Client] Window %{public}s set shadow offsetX %{public}f", name_.c_str(), offsetX);
3128     surfaceNode_->SetShadowOffsetX(offsetX);
3129     RSTransaction::FlushImplicitTransaction();
3130 }
3131 
SetShadowOffsetY(float offsetY)3132 void WindowImpl::SetShadowOffsetY(float offsetY)
3133 {
3134     if (!Permission::IsSystemCalling()) {
3135         WLOGFE("set shadow offset y permission denied!");
3136         return;
3137     }
3138     WLOGFI("[Client] Window %{public}s set shadow offsetY %{public}f", name_.c_str(), offsetY);
3139     surfaceNode_->SetShadowOffsetY(offsetY);
3140     RSTransaction::FlushImplicitTransaction();
3141 }
3142 
SetBlur(float radius)3143 WMError WindowImpl::SetBlur(float radius)
3144 {
3145     if (!Permission::IsSystemCalling()) {
3146         WLOGFE("set blur permission denied!");
3147         return WMError::WM_ERROR_INVALID_PERMISSION;
3148     }
3149     WLOGFI("[Client] Window %{public}s set blur radius %{public}f", name_.c_str(), radius);
3150     if (MathHelper::LessNotEqual(radius, 0.0)) {
3151         return WMError::WM_ERROR_INVALID_PARAM;
3152     }
3153     surfaceNode_->SetFilter(RSFilter::CreateBlurFilter(radius, radius));
3154     RSTransaction::FlushImplicitTransaction();
3155     return WMError::WM_OK;
3156 }
3157 
SetBackdropBlur(float radius)3158 WMError WindowImpl::SetBackdropBlur(float radius)
3159 {
3160     if (!Permission::IsSystemCalling()) {
3161         WLOGFE("set backdrop blur permission denied!");
3162         return WMError::WM_ERROR_INVALID_PERMISSION;
3163     }
3164     WLOGFI("[Client] Window %{public}s set backdrop blur radius %{public}f", name_.c_str(), radius);
3165     if (MathHelper::LessNotEqual(radius, 0.0)) {
3166         return WMError::WM_ERROR_INVALID_PARAM;
3167     }
3168     surfaceNode_->SetBackgroundFilter(RSFilter::CreateBlurFilter(radius, radius));
3169     RSTransaction::FlushImplicitTransaction();
3170     return WMError::WM_OK;
3171 }
3172 
SetBackdropBlurStyle(WindowBlurStyle blurStyle)3173 WMError WindowImpl::SetBackdropBlurStyle(WindowBlurStyle blurStyle)
3174 {
3175     if (!Permission::IsSystemCalling()) {
3176         WLOGFE("set backdrop blur style permission denied!");
3177         return WMError::WM_ERROR_INVALID_PERMISSION;
3178     }
3179     WLOGFI("[Client] Window %{public}s set backdrop blur style %{public}u", name_.c_str(), blurStyle);
3180     if (blurStyle < WindowBlurStyle::WINDOW_BLUR_OFF || blurStyle > WindowBlurStyle::WINDOW_BLUR_THICK) {
3181         return WMError::WM_ERROR_INVALID_PARAM;
3182     }
3183 
3184     if (blurStyle == WindowBlurStyle::WINDOW_BLUR_OFF) {
3185         surfaceNode_->SetBackgroundFilter(nullptr);
3186     } else {
3187         auto display = SingletonContainer::IsDestroyed() ? nullptr :
3188             SingletonContainer::Get<DisplayManager>().GetDisplayById(property_->GetDisplayId());
3189         if (display == nullptr) {
3190             WLOGFE("get display failed displayId:%{public}" PRIu64", window id:%{public}u", property_->GetDisplayId(),
3191                 property_->GetWindowId());
3192             return WMError::WM_ERROR_INVALID_PARAM;
3193         }
3194         surfaceNode_->SetBackgroundFilter(RSFilter::CreateMaterialFilter(static_cast<int>(blurStyle),
3195                                                                          display->GetVirtualPixelRatio()));
3196     }
3197     RSTransaction::FlushImplicitTransaction();
3198     return WMError::WM_OK;
3199 }
3200 
NotifyMemoryLevel(int32_t level) const3201 WMError WindowImpl::NotifyMemoryLevel(int32_t level) const
3202 {
3203     WLOGFI("[Client] Window id: %{public}u, notify memory level: %{public}d", property_->GetWindowId(), level);
3204     if (uiContent_ == nullptr) {
3205         WLOGFE("[Client] Window %{public}s notify memory level failed, because uicontent is null.", name_.c_str());
3206         return WMError::WM_ERROR_NULLPTR;
3207     }
3208     // notify memory level
3209     uiContent_->NotifyMemoryLevel(level);
3210     return WMError::WM_OK;
3211 }
3212 
IsAllowHaveSystemSubWindow()3213 bool WindowImpl::IsAllowHaveSystemSubWindow()
3214 {
3215     auto windowType = property_->GetWindowType();
3216     if (WindowHelper::IsSystemSubWindow(windowType) ||
3217         WindowHelper::IsSubWindow(windowType) ||
3218         windowType == WindowType::WINDOW_TYPE_DIALOG) {
3219         WLOGFI("the window of type %{public}u is limited to add a system sub window", windowType);
3220         return false;
3221     }
3222     return true;
3223 }
3224 } // namespace Rosen
3225 } // namespace OHOS
3226