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_manager_service.h"
17 
18 #include <thread>
19 
20 #include <ability_manager_client.h>
21 #include <cinttypes>
22 #include <chrono>
23 #include <hisysevent.h>
24 #include <hitrace_meter.h>
25 #include <ipc_skeleton.h>
26 #include <parameters.h>
27 #include <rs_iwindow_animation_controller.h>
28 #include "scene_board_judgement.h"
29 #include <system_ability_definition.h>
30 #include <sstream>
31 #include "xcollie/watchdog.h"
32 
33 #include "color_parser.h"
34 #include "display_manager_service_inner.h"
35 #include "dm_common.h"
36 #include "drag_controller.h"
37 #include "memory_guard.h"
38 #include "minimize_app.h"
39 #include "permission.h"
40 #include "persistent_storage.h"
41 #include "remote_animation.h"
42 #include "singleton_container.h"
43 #include "starting_window.h"
44 #include "ui/rs_ui_director.h"
45 #include "window_helper.h"
46 #include "window_inner_manager.h"
47 #include "window_layout_policy.h"
48 #include "window_manager_agent_controller.h"
49 #include "window_manager_hilog.h"
50 #include "wm_common.h"
51 #include "wm_math.h"
52 
53 namespace OHOS {
54 namespace Rosen {
55 namespace {
56 constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, HILOG_DOMAIN_WINDOW, "WMS"};
57 }
58 WM_IMPLEMENT_SINGLE_INSTANCE(WindowManagerService)
59 
60 const bool REGISTER_RESULT = SceneBoardJudgement::IsSceneBoardEnabled() ? false :
61     SystemAbility::MakeAndRegisterAbility(&SingletonContainer::Get<WindowManagerService>());
62 const std::string BOOTEVENT_WMS_READY = "bootevent.wms.ready";
63 
WindowManagerService()64 WindowManagerService::WindowManagerService() : SystemAbility(WINDOW_MANAGER_SERVICE_ID, true),
65     rsInterface_(RSInterfaces::GetInstance()),
66     windowShowPerformReport_(new PerformReporter("SHOW_WINDOW_TIME", {20, 35, 50}))
67 {
68     windowRoot_ = new WindowRoot(
__anon02364d230202(Event event, const sptr<IRemoteObject>& remoteObject) 69         [this](Event event, const sptr<IRemoteObject>& remoteObject) { OnWindowEvent(event, remoteObject); });
70     inputWindowMonitor_ = new InputWindowMonitor(windowRoot_);
71     windowController_ = new WindowController(windowRoot_, inputWindowMonitor_);
72     dragController_ = new DragController(windowRoot_);
73     windowDumper_ = new WindowDumper(windowRoot_);
74     freezeDisplayController_ = new FreezeController();
75     windowCommonEvent_ = std::make_shared<WindowCommonEvent>();
76     startingOpen_ = system::GetParameter("persist.window.sw.enabled", "1") == "1"; // startingWin default enabled
77     windowGroupMgr_ = new WindowGroupMgr(windowRoot_);
78     if (SceneBoardJudgement::IsSceneBoardEnabled()) {
79         return;
80     }
81     runner_ = AppExecFwk::EventRunner::Create(name_);
82     handler_ = std::make_shared<AppExecFwk::EventHandler>(runner_);
83     snapshotController_ = new SnapshotController(windowRoot_, handler_);
84     int ret = HiviewDFX::Watchdog::GetInstance().AddThread(name_, handler_);
85     if (ret != 0) {
86         WLOGFE("Add watchdog thread failed");
87     }
__anon02364d230302() 88     handler_->PostTask([]() { MemoryGuard cacheGuard; }, "WindowManagerService:cacheGuard", 0,
89         AppExecFwk::EventQueue::Priority::IMMEDIATE);
90     // init RSUIDirector, it will handle animation callback
91     rsUiDirector_ = RSUIDirector::Create();
__anon02364d230402(const std::function<void()>& task, uint32_t delay) 92     rsUiDirector_->SetUITaskRunner([this](const std::function<void()>& task, uint32_t delay) {
93         PostAsyncTask(task, "WindowManagerService:cacheGuard", delay);
94     });
95     rsUiDirector_->Init(false);
96 }
97 
OnStart()98 void WindowManagerService::OnStart()
99 {
100     WLOGI("start");
101     if (!Init()) {
102         WLOGFE("Init failed");
103         return;
104     }
105     WindowInnerManager::GetInstance().Start(system::GetParameter("persist.window.holder.enable", "0") == "1");
106     WindowInnerManager::GetInstance().StartWindowInfoReportLoop();
107     WindowInnerManager::GetInstance().SetWindowRoot(windowRoot_);
108     sptr<IDisplayChangeListener> listener = new DisplayChangeListener();
109     DisplayManagerServiceInner::GetInstance().RegisterDisplayChangeListener(listener);
110 
111     sptr<IWindowInfoQueriedListener> windowInfoQueriedListener = new WindowInfoQueriedListener();
112     DisplayManagerServiceInner::GetInstance().RegisterWindowInfoQueriedListener(windowInfoQueriedListener);
113     system::SetParameter(BOOTEVENT_WMS_READY.c_str(), "true");
114     AddSystemAbilityListener(RENDER_SERVICE);
115     AddSystemAbilityListener(ABILITY_MGR_SERVICE_ID);
116     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
117     sptr<WindowManagerService> wms = this;
118     wms->IncStrongRef(nullptr);
119     if (!Publish(sptr<WindowManagerService>(this))) {
120         WLOGFE("Publish failed");
121     }
122     WLOGI("end");
123 }
124 
PostAsyncTask(Task task,const std::string & taskName,uint32_t delay)125 void WindowManagerService::PostAsyncTask(Task task, const std::string& taskName, uint32_t delay)
126 {
127     if (handler_) {
128         bool ret = handler_->PostTask(task, "wms:" + taskName, delay, AppExecFwk::EventQueue::Priority::IMMEDIATE);
129         if (!ret) {
130             WLOGFE("EventHandler PostTask Failed");
131         }
132     }
133 }
134 
PostVoidSyncTask(Task task,const std::string & taskName)135 void WindowManagerService::PostVoidSyncTask(Task task, const std::string& taskName)
136 {
137     if (handler_) {
138         bool ret = handler_->PostSyncTask(task, "wms:" + taskName, AppExecFwk::EventQueue::Priority::IMMEDIATE);
139         if (!ret) {
140             WLOGFE("EventHandler PostVoidSyncTask Failed");
141         }
142     }
143 }
144 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)145 void WindowManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
146 {
147     WLOGI("systemAbilityId: %{public}d, start", systemAbilityId);
148     switch (systemAbilityId) {
149         case RENDER_SERVICE:
150             WLOGI("RENDER_SERVICE");
151             InitWithRanderServiceAdded();
152             break;
153         case ABILITY_MGR_SERVICE_ID:
154             WLOGI("ABILITY_MGR_SERVICE_ID");
155             InitWithAbilityManagerServiceAdded();
156             break;
157         case COMMON_EVENT_SERVICE_ID:
158             WLOGI("COMMON_EVENT_SERVICE_ID");
159             windowCommonEvent_->SubscriberEvent();
160             break;
161         case MULTIMODAL_INPUT_SERVICE_ID:
162             WLOGI("MULTIMODAL_INPUT_SERVICE_ID");
163             SetWindowInputEventConsumer();
164             break;
165         default:
166             WLOGFW("unhandled sysabilityId: %{public}d", systemAbilityId);
167             break;
168     }
169     WLOGI("systemAbilityId: %{public}d, end", systemAbilityId);
170 }
171 
SetWindowInputEventConsumer()172 void WindowManagerService::SetWindowInputEventConsumer()
173 {
174     WindowInnerManager::GetInstance().SetInputEventConsumer();
175 }
176 
OnAccountSwitched(int accountId)177 void WindowManagerService::OnAccountSwitched(int accountId)
178 {
179     auto task = [this, accountId]() {
180         windowRoot_->RemoveSingleUserWindowNodes(accountId);
181     };
182     PostAsyncTask(task, "OnAccountSwitched");
183     WLOGI("called");
184 }
185 
WindowVisibilityChangeCallback(std::shared_ptr<RSOcclusionData> occlusionData)186 void WindowManagerService::WindowVisibilityChangeCallback(std::shared_ptr<RSOcclusionData> occlusionData)
187 {
188     WLOGI("NotifyWindowVisibilityChange: enter");
189     std::weak_ptr<RSOcclusionData> weak(occlusionData);
190     auto task = [this, weak]() {
191         auto weakOcclusionData = weak.lock();
192         if (weakOcclusionData == nullptr) {
193             WLOGFE("weak occlusionData is nullptr");
194             return;
195         }
196         windowRoot_->NotifyWindowVisibilityChange(weakOcclusionData);
197     };
198     PostVoidSyncTask(task, "WindowVisibilityChangeCallback");
199 }
200 
InitWithRanderServiceAdded()201 void WindowManagerService::InitWithRanderServiceAdded()
202 {
203     auto windowVisibilityChangeCb =
204         [this](std::shared_ptr<RSOcclusionData> occlusionData) { this->WindowVisibilityChangeCallback(occlusionData); };
205     WLOGI("RegisterWindowVisibilityChangeCallback");
206     if (rsInterface_.RegisterOcclusionChangeCallback(windowVisibilityChangeCb) != WM_OK) {
207         WLOGFE("RegisterWindowVisibilityChangeCallback failed");
208     }
209 }
210 
InitWithAbilityManagerServiceAdded()211 void WindowManagerService::InitWithAbilityManagerServiceAdded()
212 {
213     if (snapshotController_ == nullptr) {
214         snapshotController_ = new SnapshotController(windowRoot_, handler_);
215     }
216     WLOGI("RegisterSnapshotHandler");
217     if (AAFwk::AbilityManagerClient::GetInstance()->RegisterSnapshotHandler(snapshotController_) != ERR_OK) {
218         WLOGFE("RegisterSnapshotHandler failed");
219     }
220 
221     if (wmsHandler_ == nullptr) {
222         wmsHandler_ = new WindowManagerServiceHandler();
223     }
224     WLOGI("RegisterWindowManagerServiceHandler");
225     bool animaEnabled = RemoteAnimation::CheckAnimationController();
226     if (AAFwk::AbilityManagerClient::GetInstance()->RegisterWindowManagerServiceHandler(
227         wmsHandler_, animaEnabled) != ERR_OK) {
228         WLOGFE("RegisterWindowManagerServiceHandler failed");
229     }
230 }
231 
NotifyWindowTransition(sptr<AAFwk::AbilityTransitionInfo> from,sptr<AAFwk::AbilityTransitionInfo> to,bool & animaEnabled)232 void WindowManagerServiceHandler::NotifyWindowTransition(
233     sptr<AAFwk::AbilityTransitionInfo> from, sptr<AAFwk::AbilityTransitionInfo> to, bool& animaEnabled)
234 {
235     sptr<WindowTransitionInfo> fromInfo = nullptr;
236     sptr<WindowTransitionInfo> toInfo = nullptr;
237     if (from) { // if exists, transition to window transition info
238         fromInfo = new WindowTransitionInfo(from);
239     }
240     if (to) {
241         toInfo = new WindowTransitionInfo(to);
242     }
243     animaEnabled = RemoteAnimation::CheckAnimationController();
244     WindowManagerService::GetInstance().NotifyWindowTransition(fromInfo, toInfo, false);
245 }
246 
NotifyAnimationAbilityDied(sptr<AAFwk::AbilityTransitionInfo> info)247 void WindowManagerServiceHandler::NotifyAnimationAbilityDied(sptr<AAFwk::AbilityTransitionInfo> info)
248 {
249     sptr<WindowTransitionInfo> windowTransitionInfo = new WindowTransitionInfo(info);
250     WindowManagerService::GetInstance().NotifyAnimationAbilityDied(windowTransitionInfo);
251 }
252 
GetFocusWindow(sptr<IRemoteObject> & abilityToken)253 int32_t WindowManagerServiceHandler::GetFocusWindow(sptr<IRemoteObject>& abilityToken)
254 {
255     return static_cast<int32_t>(WindowManagerService::GetInstance().GetFocusWindowInfo(abilityToken));
256 }
257 
StartingWindow(sptr<AAFwk::AbilityTransitionInfo> info,std::shared_ptr<Media::PixelMap> pixelMap)258 void WindowManagerServiceHandler::StartingWindow(
259     sptr<AAFwk::AbilityTransitionInfo> info, std::shared_ptr<Media::PixelMap> pixelMap)
260 {
261     sptr<WindowTransitionInfo> windowInfo = new WindowTransitionInfo(info);
262     WLOGI("hot start is called");
263     WindowManagerService::GetInstance().StartingWindow(windowInfo, pixelMap, false);
264 }
265 
StartingWindow(sptr<AAFwk::AbilityTransitionInfo> info,std::shared_ptr<Media::PixelMap> pixelMap,uint32_t bgColor)266 void WindowManagerServiceHandler::StartingWindow(
267     sptr<AAFwk::AbilityTransitionInfo> info, std::shared_ptr<Media::PixelMap> pixelMap, uint32_t bgColor)
268 {
269     sptr<WindowTransitionInfo> windowInfo = new WindowTransitionInfo(info);
270     WLOGI("cold start is called");
271     WindowManagerService::GetInstance().StartingWindow(windowInfo, pixelMap, true, bgColor);
272 }
273 
CancelStartingWindow(sptr<IRemoteObject> abilityToken)274 void WindowManagerServiceHandler::CancelStartingWindow(sptr<IRemoteObject> abilityToken)
275 {
276     WLOGI("WindowManagerServiceHandler CancelStartingWindow!");
277     WindowManagerService::GetInstance().CancelStartingWindow(abilityToken);
278 }
279 
MoveMissionsToForeground(const std::vector<int32_t> & missionIds,int32_t topMissionId)280 int32_t WindowManagerServiceHandler::MoveMissionsToForeground(const std::vector<int32_t>& missionIds,
281     int32_t topMissionId)
282 {
283     WLOGD("WindowManagerServiceHandler MoveMissionsToForeground!");
284     return static_cast<int32_t>(WindowManagerService::GetInstance().MoveMissionsToForeground(missionIds, topMissionId));
285 }
286 
MoveMissionsToBackground(const std::vector<int32_t> & missionIds,std::vector<int32_t> & result)287 int32_t WindowManagerServiceHandler::MoveMissionsToBackground(const std::vector<int32_t>& missionIds,
288     std::vector<int32_t>& result)
289 {
290     WLOGD("WindowManagerServiceHandler MoveMissionsToBackground!");
291     return static_cast<int32_t>(WindowManagerService::GetInstance().MoveMissionsToBackground(missionIds, result));
292 }
293 
Init()294 bool WindowManagerService::Init()
295 {
296     WLOGI("Init start");
297     if (WindowManagerConfig::LoadConfigXml()) {
298         if (WindowManagerConfig::GetConfig().IsMap()) {
299             WindowManagerConfig::DumpConfig(*WindowManagerConfig::GetConfig().mapValue_);
300         }
301         ConfigureWindowManagerService();
302         StartingWindow::SetAnimationConfig(WindowNodeContainer::GetAnimationConfigRef());
303     }
304     if (PersistentStorage::HasKey("maximize_state", PersistentStorageType::MAXIMIZE_STATE)) {
305         int32_t storageMode = -1;
306         PersistentStorage::Get("maximize_state", storageMode, PersistentStorageType::MAXIMIZE_STATE);
307         if (storageMode == static_cast<int32_t>(MaximizeMode::MODE_AVOID_SYSTEM_BAR) ||
308             storageMode == static_cast<int32_t>(MaximizeMode::MODE_FULL_FILL)) {
309             maximizeMode_ = static_cast<MaximizeMode>(storageMode);
310         }
311     }
312     WindowSystemEffect::SetWindowRoot(windowRoot_);
313     WLOGI("Init success");
314     return true;
315 }
316 
Dump(int fd,const std::vector<std::u16string> & args)317 int WindowManagerService::Dump(int fd, const std::vector<std::u16string>& args)
318 {
319     if (windowDumper_ == nullptr) {
320         windowDumper_ = new WindowDumper(windowRoot_);
321     }
322     WLOGFI("Pid : %{public}d", IPCSkeleton::GetCallingPid());
323     auto task = [this, fd, &args]() {
324         return static_cast<int>(windowDumper_->Dump(fd, args));
325     };
326     return PostSyncTask(task, "Dump");
327 }
328 
ConfigureWindowManagerService()329 void WindowManagerService::ConfigureWindowManagerService()
330 {
331     const auto& config = WindowManagerConfig::GetConfig();
332     WindowManagerConfig::ConfigItem item = config["decor"];
333     if (item.IsMap()) {
334         ConfigDecor(item);
335     }
336     item = config["minimizeByOther"].GetProp("enable");
337     if (item.IsBool()) {
338         MinimizeApp::SetMinimizedByOtherConfig(item.boolValue_);
339     }
340     item = config["stretchable"].GetProp("enable");
341     if (item.IsBool()) {
342         systemConfig_.isStretchable_ = item.boolValue_;
343     }
344     item = config["defaultWindowMode"];
345     if (item.IsInts()) {
346         auto numbers = *item.intsValue_;
347         if (numbers.size() == 1 &&
348             (numbers[0] == static_cast<int32_t>(WindowMode::WINDOW_MODE_FULLSCREEN) ||
349              numbers[0] == static_cast<int32_t>(WindowMode::WINDOW_MODE_FLOATING))) {
350             systemConfig_.defaultWindowMode_ = static_cast<WindowMode>(static_cast<uint32_t>(numbers[0]));
351             StartingWindow::SetDefaultWindowMode(systemConfig_.defaultWindowMode_);
352         }
353     }
354     item = config["dragFrameGravity"];
355     if (item.IsInts()) {
356         auto numbers = *item.intsValue_;
357         if (numbers.size() == 1
358             && (numbers[0] == static_cast<int32_t>(Gravity::RESIZE)
359             || numbers[0] == static_cast<int32_t>(Gravity::TOP_LEFT))) {
360             windowController_->SetDragFrameGravity(static_cast<int32_t>(numbers[0]));
361         }
362     }
363     item = config["remoteAnimation"].GetProp("enable");
364     if (item.IsBool()) {
365         RemoteAnimation::isRemoteAnimationEnable_ = item.boolValue_;
366     }
367     item = config["maxAppWindowNumber"];
368     if (item.IsInts()) {
369         auto numbers = *item.intsValue_;
370         if (numbers.size() == 1 && numbers[0] > 0) {
371             windowRoot_->SetMaxAppWindowNumber(static_cast<uint32_t>(numbers[0]));
372         }
373     }
374     item = config["modeChangeHotZones"];
375     if (item.IsInts()) {
376         ConfigHotZones(*item.intsValue_);
377     }
378     item = config["splitRatios"];
379     if (item.IsFloats()) {
380         windowRoot_->SetSplitRatios(*item.floatsValue_);
381     }
382     item = config["exitSplitRatios"];
383     if (item.IsFloats()) {
384         windowRoot_->SetExitSplitRatios(*item.floatsValue_);
385     }
386     item = config["windowAnimation"];
387     if (item.IsMap()) {
388         ConfigWindowAnimation(item);
389     }
390     item = config["keyboardAnimation"];
391     if (item.IsMap()) {
392         ConfigKeyboardAnimation(item);
393     }
394     item = config["startWindowTransitionAnimation"];
395     if (item.IsMap()) {
396         ConfigStartingWindowAnimation(item);
397     }
398     item = config["windowEffect"];
399     if (item.IsMap()) {
400         ConfigWindowEffect(item);
401     }
402     item = config["floatingBottomPosY"];
403     if (item.IsInts()) {
404         auto numbers = *item.intsValue_;
405         if (numbers.size() == 1 && numbers[0] > 0) {
406             WindowLayoutPolicy::SetCascadeRectBottomPosYLimit(static_cast<uint32_t>(numbers[0]));
407         }
408     }
409     item = config["configMainFloatingWindowAbove"].GetProp("enable");
410     if (item.IsBool()) {
411         WindowNodeContainer::SetConfigMainFloatingWindowAbove(item.boolValue_);
412     }
413     item = config["maxMainFloatingWindowNumber"];
414     if (item.IsInts()) {
415         auto numbers = *item.intsValue_;
416         if (numbers.size() == 1 && numbers[0] > 0) {
417             WindowNodeContainer::SetMaxMainFloatingWindowNumber(static_cast<uint32_t>(numbers[0]));
418         }
419     }
420     item = config["maxFloatingWindowSize"];
421     if (item.IsInts()) {
422         auto numbers = *item.intsValue_;
423         if (numbers.size() == 1 && numbers[0] > 0) {
424             WindowLayoutPolicy::SetMaxFloatingWindowSize(static_cast<uint32_t>(numbers[0]));
425         }
426     }
427     item = config["defaultMaximizeMode"];
428     if (item.IsInts()) {
429         auto numbers = *item.intsValue_;
430         if (numbers.size() == 1 &&
431             (numbers[0] == static_cast<int32_t>(MaximizeMode::MODE_AVOID_SYSTEM_BAR) ||
432             numbers[0] == static_cast<int32_t>(MaximizeMode::MODE_FULL_FILL))) {
433             maximizeMode_ = static_cast<MaximizeMode>(numbers[0]);
434         }
435     }
436     item = config["uiType"];
437     if (item.IsString()) {
438         systemConfig_.uiType_ = item.stringValue_;
439         StartingWindow::uiType_ = item.stringValue_;
440         WindowNodeContainer::uiType_ = item.stringValue_;
441     }
442     item = config["supportTypeFloatWindow"].GetProp("enable");
443     if (item.IsBool()) {
444         systemConfig_.supportTypeFloatWindow_ = item.boolValue_;
445     }
446 }
447 
ConfigHotZones(const std::vector<int> & numbers)448 void WindowManagerService::ConfigHotZones(const std::vector<int>& numbers)
449 {
450     if (numbers.size() == 3) { // 3 hot zones
451         hotZonesConfig_.fullscreenRange_ = static_cast<uint32_t>(numbers[0]); // 0 fullscreen
452         hotZonesConfig_.primaryRange_ = static_cast<uint32_t>(numbers[1]);    // 1 primary
453         hotZonesConfig_.secondaryRange_ = static_cast<uint32_t>(numbers[2]);  // 2 secondary
454         hotZonesConfig_.isModeChangeHotZoneConfigured_ = true;
455     }
456 }
457 
ConfigDecor(const WindowManagerConfig::ConfigItem & decorConfig)458 void WindowManagerService::ConfigDecor(const WindowManagerConfig::ConfigItem& decorConfig)
459 {
460     WindowManagerConfig::ConfigItem item = decorConfig.GetProp("enable");
461     if (item.IsBool()) {
462         systemConfig_.isSystemDecorEnable_ = item.boolValue_;
463         std::vector<std::string> supportedModes;
464         item = decorConfig["supportedMode"];
465         if (item.IsStrings()) {
466             systemConfig_.decorWindowModeSupportType_ = 0;
467             supportedModes = *item.stringsValue_;
468         }
469         for (auto mode : supportedModes) {
470             if (mode == "fullscreen") {
471                 systemConfig_.decorWindowModeSupportType_ |= WindowModeSupport::WINDOW_MODE_SUPPORT_FULLSCREEN;
472             } else if (mode == "floating") {
473                 systemConfig_.decorWindowModeSupportType_ |= WindowModeSupport::WINDOW_MODE_SUPPORT_FLOATING;
474             } else if (mode == "pip") {
475                 systemConfig_.decorWindowModeSupportType_ |= WindowModeSupport::WINDOW_MODE_SUPPORT_PIP;
476             } else if (mode == "split") {
477                 systemConfig_.decorWindowModeSupportType_ |= WindowModeSupport::WINDOW_MODE_SUPPORT_SPLIT_PRIMARY |
478                     WindowModeSupport::WINDOW_MODE_SUPPORT_SPLIT_SECONDARY;
479             } else {
480                 WLOGFW("Invalid supporedMode");
481                 systemConfig_.decorWindowModeSupportType_ = WindowModeSupport::WINDOW_MODE_SUPPORT_ALL;
482                 break;
483             }
484         }
485     }
486 }
487 
ConfigWindowAnimation(const WindowManagerConfig::ConfigItem & animeConfig)488 void WindowManagerService::ConfigWindowAnimation(const WindowManagerConfig::ConfigItem& animeConfig)
489 {
490     auto& windowAnimationConfig = WindowNodeContainer::GetAnimationConfigRef().windowAnimationConfig_;
491     WindowManagerConfig::ConfigItem item = animeConfig["timing"];
492     if (item.IsMap() && item.mapValue_->count("curve")) {
493         windowAnimationConfig.animationTiming_.timingCurve_ = CreateCurve(item["curve"]);
494     }
495     item = animeConfig["timing"]["duration"];
496     if (item.IsInts()) {
497         auto numbers = *item.intsValue_;
498         if (numbers.size() == 1) { // duration
499             windowAnimationConfig.animationTiming_.timingProtocol_ =
500                 RSAnimationTimingProtocol(numbers[0]);
501         }
502     }
503     item = animeConfig["scale"];
504     if (item.IsFloats()) {
505         auto numbers = *item.floatsValue_;
506         if (numbers.size() == 1) { // 1 xy scale
507             windowAnimationConfig.scale_.x_ =
508             windowAnimationConfig.scale_.y_ = numbers[0]; // 0 xy scale
509         } else if (numbers.size() == 2) { // 2 x,y sclae
510             windowAnimationConfig.scale_.x_ = numbers[0]; // 0 x scale
511             windowAnimationConfig.scale_.y_ = numbers[1]; // 1 y scale
512         } else if (numbers.size() == 3) { // 3 x,y,z scale
513             windowAnimationConfig.scale_ = Vector3f(&numbers[0]);
514         }
515     }
516     item = animeConfig["rotation"];
517     if (item.IsFloats() && item.floatsValue_->size() == 4) { // 4 (axix,angle)
518         windowAnimationConfig.rotation_ = Vector4f(item.floatsValue_->data());
519     }
520     item = animeConfig["translate"];
521     if (item.IsFloats()) {
522         auto numbers = *item.floatsValue_;
523         if (numbers.size() == 2) { // 2 translate xy
524             windowAnimationConfig.translate_.x_ = numbers[0]; // 0 translate x
525             windowAnimationConfig.translate_.y_ = numbers[1]; // 1 translate y
526         } else if (numbers.size() == 3) { // 3 translate xyz
527             windowAnimationConfig.translate_.x_ = numbers[0]; // 0 translate x
528             windowAnimationConfig.translate_.y_ = numbers[1]; // 1 translate y
529             windowAnimationConfig.translate_.z_ = numbers[2]; // 2 translate z
530         }
531     }
532     item = animeConfig["opacity"];
533     if (item.IsFloats()) {
534         auto numbers = *item.floatsValue_;
535         numbers.size() == 1 ? (windowAnimationConfig.opacity_ = numbers[0]) : float();
536     }
537 }
538 
ConfigKeyboardAnimation(const WindowManagerConfig::ConfigItem & animeConfig)539 void WindowManagerService::ConfigKeyboardAnimation(const WindowManagerConfig::ConfigItem& animeConfig)
540 {
541     auto& animationConfig = WindowNodeContainer::GetAnimationConfigRef();
542     WindowManagerConfig::ConfigItem inItem = animeConfig["animationIn"]["timing"];
543     if (inItem.IsMap() && inItem.mapValue_ != nullptr && inItem.mapValue_->count("curve")) {
544         CreateKeyboardCurve(inItem, animationConfig.keyboardAnimationIn_, systemConfig_.animationIn_);
545     }
546 
547     WindowManagerConfig::ConfigItem outItem = animeConfig["animationOut"]["timing"];
548     if (outItem.IsMap() && outItem.mapValue_ != nullptr && outItem.mapValue_->count("curve")) {
549         CreateKeyboardCurve(outItem, animationConfig.keyboardAnimationOut_, systemConfig_.animationOut_);
550     }
551     WLOGFI("curveIn:[%{public}s, %{public}u], curveOut:[%{public}s, %{public}u]",
552         systemConfig_.animationIn_.curveType_.c_str(), systemConfig_.animationIn_.duration_,
553         systemConfig_.animationOut_.curveType_.c_str(), systemConfig_.animationOut_.duration_);
554 }
555 
ConfigStartingWindowAnimation(const WindowManagerConfig::ConfigItem & animeConfig)556 void WindowManagerService::ConfigStartingWindowAnimation(const WindowManagerConfig::ConfigItem& animeConfig)
557 {
558     WindowManagerConfig::ConfigItem item = animeConfig.GetProp("enable");
559     if (item.IsBool()) {
560         StartingWindow::transAnimateEnable_ = item.boolValue_;
561     }
562     auto& startWinAnimationConfig = WindowNodeContainer::GetAnimationConfigRef().startWinAnimationConfig_;
563     item = animeConfig["timing"];
564     if (item.IsMap() && item.mapValue_->count("curve")) {
565         startWinAnimationConfig.timingCurve_ = CreateCurve(item["curve"]);
566     }
567     item = animeConfig["timing"]["duration"];
568     if (item.IsInts()) {
569         auto numbers = *item.intsValue_;
570         if (numbers.size() == 1) { // duration
571             startWinAnimationConfig.timingProtocol_ = RSAnimationTimingProtocol(numbers[0]);
572         }
573     }
574     item = animeConfig["opacityStart"];
575     if (item.IsFloats()) {
576         auto numbers = *item.floatsValue_;
577         numbers.size() == 1 ? (startWinAnimationConfig.opacityStart_ = numbers[0]) : float();
578     }
579     item = animeConfig["opacityEnd"];
580     if (item.IsFloats()) {
581         auto numbers = *item.floatsValue_;
582         numbers.size() == 1 ? (startWinAnimationConfig.opacityEnd_ = numbers[0]) : float();
583     }
584 }
585 
ConfigAppWindowCornerRadius(const WindowManagerConfig::ConfigItem & item,float & out)586 bool WindowManagerService::ConfigAppWindowCornerRadius(const WindowManagerConfig::ConfigItem& item, float& out)
587 {
588     std::map<std::string, float> stringToCornerRadius = {
589         {"off", 0.0f}, {"defaultCornerRadiusXS", 4.0f}, {"defaultCornerRadiusS", 8.0f},
590         {"defaultCornerRadiusM", 12.0f}, {"defaultCornerRadiusL", 16.0f}, {"defaultCornerRadiusXL", 24.0f}
591     };
592 
593     if (item.IsString()) {
594         auto value = item.stringValue_;
595         if (stringToCornerRadius.find(value) != stringToCornerRadius.end()) {
596             out = stringToCornerRadius[value];
597             return true;
598         }
599     }
600     return false;
601 }
602 
ConfigAppWindowShadow(const WindowManagerConfig::ConfigItem & shadowConfig,WindowShadowParameters & outShadow)603 bool WindowManagerService::ConfigAppWindowShadow(const WindowManagerConfig::ConfigItem& shadowConfig,
604     WindowShadowParameters& outShadow)
605 {
606     WindowManagerConfig::ConfigItem item = shadowConfig["elevation"];
607     if (item.IsFloats()) {
608         auto elevation = *item.floatsValue_;
609         if (elevation.size() != 1 || MathHelper::LessNotEqual(elevation[0], 0.0)) {
610             return false;
611         }
612         outShadow.elevation_ = elevation[0];
613     }
614 
615     item = shadowConfig["color"];
616     if (item.IsString()) {
617         auto color = item.stringValue_;
618         uint32_t colorValue;
619         if (!ColorParser::Parse(color, colorValue)) {
620             return false;
621         }
622         outShadow.color_ = color;
623     }
624 
625     item = shadowConfig["offsetX"];
626     if (item.IsFloats()) {
627         auto offsetX = *item.floatsValue_;
628         if (offsetX.size() != 1) {
629             return false;
630         }
631         outShadow.offsetX_ = offsetX[0];
632     }
633 
634     item = shadowConfig["offsetY"];
635     if (item.IsFloats()) {
636         auto offsetY = *item.floatsValue_;
637         if (offsetY.size() != 1) {
638             return false;
639         }
640         outShadow.offsetY_ = offsetY[0];
641     }
642 
643     item = shadowConfig["alpha"];
644     if (item.IsFloats()) {
645         auto alpha = *item.floatsValue_;
646         if (alpha.size() != 1 ||
647             (MathHelper::LessNotEqual(alpha[0], 0.0) && MathHelper::GreatNotEqual(alpha[0], 1.0))) {
648             return false;
649         }
650         outShadow.alpha_ = alpha[0];
651     }
652 
653     item = shadowConfig["radius"];
654     if (item.IsFloats()) {
655         auto radius = *item.floatsValue_;
656         if (radius.size() != 1 || MathHelper::LessNotEqual(radius[0], 0.0)) {
657             return false;
658         }
659         outShadow.radius_ = radius[0];
660     }
661 
662     return true;
663 }
664 
ConfigWindowEffect(const WindowManagerConfig::ConfigItem & effectConfig)665 void WindowManagerService::ConfigWindowEffect(const WindowManagerConfig::ConfigItem& effectConfig)
666 {
667     AppWindowEffectConfig config;
668     AppWindowEffectConfig systemEffectConfig;
669     // config corner radius
670     WindowManagerConfig::ConfigItem item = effectConfig["appWindows"]["cornerRadius"];
671     if (item.IsMap()) {
672         if (ConfigAppWindowCornerRadius(item["fullScreen"], config.fullScreenCornerRadius_) &&
673             ConfigAppWindowCornerRadius(item["split"], config.splitCornerRadius_) &&
674             ConfigAppWindowCornerRadius(item["float"], config.floatCornerRadius_)) {
675             systemEffectConfig = config;
676         }
677     }
678 
679     // config shadow
680     item = effectConfig["appWindows"]["shadow"]["focused"];
681     if (item.IsMap()) {
682         if (ConfigAppWindowShadow(item, config.focusedShadow_)) {
683             systemEffectConfig.focusedShadow_ = config.focusedShadow_;
684         }
685     }
686 
687     item = effectConfig["appWindows"]["shadow"]["unfocused"];
688     if (item.IsMap()) {
689         if (ConfigAppWindowShadow(item, config.unfocusedShadow_)) {
690             systemEffectConfig.unfocusedShadow_ = config.unfocusedShadow_;
691         }
692     }
693     WindowSystemEffect::SetWindowSystemEffectConfig(systemEffectConfig);
694 }
695 
CreateKeyboardCurve(const WindowManagerConfig::ConfigItem & config,AnimationConfig::KeyboardAnimation & animateConfig,KeyboardAnimationCurve & sysCurveConfig)696 void WindowManagerService::CreateKeyboardCurve(const WindowManagerConfig::ConfigItem& config,
697     AnimationConfig::KeyboardAnimation& animateConfig, KeyboardAnimationCurve& sysCurveConfig)
698 {
699     // parse curve params
700     const WindowManagerConfig::ConfigItem& curveConfig = config["curve"];
701     static std::map<std::string, RSAnimationTimingCurve> curveMap = {
702         { "easeOut",           RSAnimationTimingCurve::EASE_OUT },
703         { "ease",              RSAnimationTimingCurve::EASE },
704         { "easeIn",            RSAnimationTimingCurve::EASE_IN },
705         { "easeInOut",         RSAnimationTimingCurve::EASE_IN_OUT },
706         { "default",           RSAnimationTimingCurve::DEFAULT },
707         { "linear",            RSAnimationTimingCurve::LINEAR },
708         { "spring",            RSAnimationTimingCurve::SPRING },
709         { "interactiveSpring", RSAnimationTimingCurve::INTERACTIVE_SPRING }
710     };
711     RSAnimationTimingCurve curve = RSAnimationTimingCurve::EASE_OUT;
712     std::string keyboardCurveName = "easeOut";
713     std::vector<float> keyboardCurveParams = {};
714     const auto& nameItem = curveConfig.GetProp("name");
715     if (nameItem.IsString()) {
716         std::string name = nameItem.stringValue_;
717         if (name == "cubic" && curveConfig.IsFloats() && curveConfig.floatsValue_ != nullptr &&
718             curveConfig.floatsValue_->size() == 4) { // 4: param size
719             const auto& numbers = *curveConfig.floatsValue_;
720             keyboardCurveName = name;
721             keyboardCurveParams.assign(numbers.begin(), numbers.end());
722             curve = RSAnimationTimingCurve::CreateCubicCurve(
723                 numbers[0],  // 0 ctrlX1
724                 numbers[1],  // 1 ctrlY1
725                 numbers[2],  // 2 ctrlX2
726                 numbers[3]); // 3 ctrlY2
727         } else {
728             auto iter = curveMap.find(name);
729             if (iter != curveMap.end()) {
730                 keyboardCurveName = name;
731                 curve = iter->second;
732             }
733         }
734     }
735     animateConfig.curve_ = curve;
736     sysCurveConfig.curveType_ = keyboardCurveName;
737     sysCurveConfig.curveParams_.assign(keyboardCurveParams.begin(), keyboardCurveParams.end());
738 
739     // parse curve duration
740     const WindowManagerConfig::ConfigItem& duration = config["duration"];
741     if (duration.IsInts() && duration.intsValue_ != nullptr) {
742         auto numbers = *duration.intsValue_;
743         if (numbers.size() == 1) { // duration
744             animateConfig.duration_ = RSAnimationTimingProtocol(numbers[0]);
745             sysCurveConfig.duration_ = static_cast<uint32_t>(numbers[0]);
746         }
747     }
748 }
749 
CreateCurve(const WindowManagerConfig::ConfigItem & curveConfig)750 RSAnimationTimingCurve WindowManagerService::CreateCurve(const WindowManagerConfig::ConfigItem& curveConfig)
751 {
752     static std::map<std::string, RSAnimationTimingCurve> curveMap = {
753         { "easeOut",           RSAnimationTimingCurve::EASE_OUT },
754         { "ease",              RSAnimationTimingCurve::EASE },
755         { "easeIn",            RSAnimationTimingCurve::EASE_IN },
756         { "easeInOut",         RSAnimationTimingCurve::EASE_IN_OUT },
757         { "default",           RSAnimationTimingCurve::DEFAULT },
758         { "linear",            RSAnimationTimingCurve::LINEAR },
759         { "spring",            RSAnimationTimingCurve::SPRING },
760         { "interactiveSpring", RSAnimationTimingCurve::INTERACTIVE_SPRING }
761     };
762 
763     RSAnimationTimingCurve curve = RSAnimationTimingCurve::EASE_OUT;
764     const auto& nameItem = curveConfig.GetProp("name");
765     if (nameItem.IsString()) {
766         std::string name = nameItem.stringValue_;
767         if (name == "cubic" && curveConfig.IsFloats() && curveConfig.floatsValue_ != nullptr &&
768             curveConfig.floatsValue_->size() == 4) { // 4 curve parameter
769             const auto& numbers = *curveConfig.floatsValue_;
770             curve = RSAnimationTimingCurve::CreateCubicCurve(
771                 numbers[0],  // 0 ctrlX1
772                 numbers[1],  // 1 ctrlY1
773                 numbers[2],  // 2 ctrlX2
774                 numbers[3]); // 3 ctrlY2
775         } else {
776             if (auto iter = curveMap.find(name); iter != curveMap.end()) {
777                 curve = iter->second;
778             }
779         }
780     }
781     return curve;
782 }
783 
OnStop()784 void WindowManagerService::OnStop()
785 {
786     windowCommonEvent_->UnSubscriberEvent();
787     WindowInnerManager::GetInstance().Stop();
788     WLOGI("ready to stop service.");
789 }
790 
NotifyWindowTransition(sptr<WindowTransitionInfo> & fromInfo,sptr<WindowTransitionInfo> & toInfo,bool isFromClient)791 WMError WindowManagerService::NotifyWindowTransition(
792     sptr<WindowTransitionInfo>& fromInfo, sptr<WindowTransitionInfo>& toInfo, bool isFromClient)
793 {
794     if (!isFromClient) {
795         WLOGI("NotifyWindowTransition asynchronously.");
796         auto task = [this, fromInfo, toInfo]() mutable {
797             return windowController_->NotifyWindowTransition(fromInfo, toInfo);
798         };
799         PostAsyncTask(task, "NotifyWindowTransition");
800         return WMError::WM_OK;
801     } else {
802         WLOGI("NotifyWindowTransition synchronously.");
803         auto task = [this, &fromInfo, &toInfo]() {
804             return windowController_->NotifyWindowTransition(fromInfo, toInfo);
805         };
806         return PostSyncTask(task, "NotifyWindowTransition");
807     }
808 }
809 
NotifyAnimationAbilityDied(sptr<WindowTransitionInfo> info)810 void WindowManagerService::NotifyAnimationAbilityDied(sptr<WindowTransitionInfo> info)
811 {
812     auto task = [this, info]() mutable {
813         return RemoteAnimation::NotifyAnimationAbilityDied(info);
814     };
815     PostAsyncTask(task, "NotifyAnimationAbilityDied");
816 }
817 
GetFocusWindowInfo(sptr<IRemoteObject> & abilityToken)818 WMError WindowManagerService::GetFocusWindowInfo(sptr<IRemoteObject>& abilityToken)
819 {
820     auto task = [this, &abilityToken]() {
821         return windowController_->GetFocusWindowInfo(abilityToken);
822     };
823     return PostSyncTask(task, "GetFocusWindowInfo");
824 }
825 
StartingWindow(sptr<WindowTransitionInfo> info,std::shared_ptr<Media::PixelMap> pixelMap,bool isColdStart,uint32_t bkgColor)826 void WindowManagerService::StartingWindow(sptr<WindowTransitionInfo> info, std::shared_ptr<Media::PixelMap> pixelMap,
827     bool isColdStart, uint32_t bkgColor)
828 {
829     if (!startingOpen_) {
830         WLOGI("startingWindow not open!");
831         return;
832     }
833     if (info) {
834         info->isSystemCalling_ = Permission::IsSystemCalling();
835     }
836     auto task = [this, info, pixelMap, isColdStart, bkgColor]() {
837         windowController_->StartingWindow(info, pixelMap, bkgColor, isColdStart);
838     };
839     PostAsyncTask(task, "StartingWindow");
840 }
841 
CancelStartingWindow(sptr<IRemoteObject> abilityToken)842 void WindowManagerService::CancelStartingWindow(sptr<IRemoteObject> abilityToken)
843 {
844     WLOGI("begin");
845     if (!startingOpen_) {
846         WLOGI("startingWindow not open!");
847         return;
848     }
849     auto task = [this, abilityToken]() {
850         windowController_->CancelStartingWindow(abilityToken);
851     };
852     PostAsyncTask(task, "CancelStartingWindow");
853 }
854 
MoveMissionsToForeground(const std::vector<int32_t> & missionIds,int32_t topMissionId)855 WMError WindowManagerService::MoveMissionsToForeground(const std::vector<int32_t>& missionIds, int32_t topMissionId)
856 {
857     if (windowGroupMgr_) {
858         auto task = [this, &missionIds, topMissionId]() {
859             WMError res = windowGroupMgr_->MoveMissionsToForeground(missionIds, topMissionId);
860             // no need to return inner error to caller
861             if (res > WMError::WM_ERROR_NEED_REPORT_BASE) {
862                 return res;
863             }
864             return WMError::WM_OK;
865         };
866         return PostSyncTask(task, "MoveMissionsToForeground");
867     }
868     return WMError::WM_ERROR_NULLPTR;
869 }
870 
MoveMissionsToBackground(const std::vector<int32_t> & missionIds,std::vector<int32_t> & result)871 WMError WindowManagerService::MoveMissionsToBackground(const std::vector<int32_t>& missionIds,
872     std::vector<int32_t>& result)
873 {
874     if (windowGroupMgr_) {
875         auto task = [this, &missionIds, &result]() {
876             WMError res = windowGroupMgr_->MoveMissionsToBackground(missionIds, result);
877             // no need to return wms inner error to caller
878             if (res > WMError::WM_ERROR_NEED_REPORT_BASE) {
879                 return res;
880             }
881             return WMError::WM_OK;
882         };
883         return PostSyncTask(task, "MoveMissionsToBackground");
884     }
885     return WMError::WM_ERROR_NULLPTR;
886 }
887 
888 
CheckAnimationPermission(const sptr<WindowProperty> & property) const889 bool WindowManagerService::CheckAnimationPermission(const sptr<WindowProperty>& property) const
890 {
891     WindowType type = property->GetWindowType();
892     // If the animation type is NONE or the window type is WINDOW_TYPE_INPUT_METHOD_FLOAT
893     if (property->GetAnimationFlag() == static_cast<uint32_t>(WindowAnimation::NONE) ||
894         type == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT) {
895         return true;
896     }
897     // If the animation type is DEFAULT and the window type is AppWindow
898     if (property->GetAnimationFlag() == static_cast<uint32_t>(WindowAnimation::DEFAULT) &&
899         WindowHelper::IsAppWindow(type)) {
900         return true;
901     }
902     // If the animation type is CUSTOM
903     if (Permission::IsSystemCalling() || Permission::IsStartByHdcd()) {
904         WLOGFD("check IsSystemCalling permission success, show with animation calling.");
905         return true;
906     }
907     WLOGFE("check animation permission failed");
908     return false;
909 }
910 
CheckSystemWindowPermission(const sptr<WindowProperty> & property) const911 bool WindowManagerService::CheckSystemWindowPermission(const sptr<WindowProperty>& property) const
912 {
913     WindowType type = property->GetWindowType();
914     if (!WindowHelper::IsSystemWindow(type)) {
915         // type is not system
916         return true;
917     }
918     if ((type == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT || type == WindowType::WINDOW_TYPE_INPUT_METHOD_STATUS_BAR)
919         && Permission::IsStartByInputMethod()) {
920         // WINDOW_TYPE_INPUT_METHOD_FLOAT counld be created by input method app
921         WLOGFD("check create permission success, input method app create input method window.");
922         return true;
923     }
924     if (type == WindowType::WINDOW_TYPE_DRAGGING_EFFECT || type == WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW ||
925         type == WindowType::WINDOW_TYPE_TOAST || type == WindowType::WINDOW_TYPE_DIALOG) {
926         // some system types counld be created by normal app
927         return true;
928     }
929     if (type == WindowType::WINDOW_TYPE_FLOAT &&
930         Permission::CheckCallingPermission("ohos.permission.SYSTEM_FLOAT_WINDOW")) {
931         // WINDOW_TYPE_FLOAT counld be created by normal app with the corresponding permission
932         WLOGFD("check create permission success, normal app create float window with request permission.");
933         return true;
934     }
935     if (Permission::IsSystemCalling() || Permission::IsStartByHdcd()) {
936         WLOGFD("check create permission success, create with system calling.");
937         return true;
938     }
939     WLOGFE("check system window permission failed.");
940     return false;
941 }
942 
CreateWindow(sptr<IWindow> & window,sptr<WindowProperty> & property,const std::shared_ptr<RSSurfaceNode> & surfaceNode,uint32_t & windowId,sptr<IRemoteObject> token)943 WMError WindowManagerService::CreateWindow(sptr<IWindow>& window, sptr<WindowProperty>& property,
944     const std::shared_ptr<RSSurfaceNode>& surfaceNode, uint32_t& windowId, sptr<IRemoteObject> token)
945 {
946     if (!window || property == nullptr || surfaceNode == nullptr || !window->AsObject()) {
947         WLOGFE("window is invalid");
948         return WMError::WM_ERROR_NULLPTR;
949     }
950     if (!CheckSystemWindowPermission(property)) {
951         WLOGFE("create system window permission denied!");
952         return WMError::WM_ERROR_NOT_SYSTEM_APP;
953     }
954     int pid = IPCSkeleton::GetCallingRealPid();
955     int uid = IPCSkeleton::GetCallingUid();
956     property->isSystemCalling_ = Permission::IsSystemCalling();
957     auto task = [this, pid, uid, &window, &property, &surfaceNode, &windowId, &token]() {
958         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "wms:CreateWindow(%u)", windowId);
959         return windowController_->CreateWindow(window, property, surfaceNode, windowId, token, pid, uid);
960     };
961     WMError ret = PostSyncTask(task, "CreateWindow");
962     accessTokenIdMaps_.insert(std::pair(windowId, IPCSkeleton::GetCallingTokenID()));
963     return ret;
964 }
965 
AddWindow(sptr<WindowProperty> & property)966 WMError WindowManagerService::AddWindow(sptr<WindowProperty>& property)
967 {
968     if (property == nullptr) {
969         WLOGFE("property is nullptr");
970         return WMError::WM_ERROR_NULLPTR;
971     }
972     if (!CheckSystemWindowPermission(property) || !CheckAnimationPermission(property)) {
973         WLOGFE("add window permission denied!");
974         return WMError::WM_ERROR_NOT_SYSTEM_APP;
975     }
976     auto task = [this, &property]() {
977         windowShowPerformReport_->start();
978         Rect rect = property->GetRequestRect();
979         uint32_t windowId = property->GetWindowId();
980         WLOGI("[WMS] Add: %{public}5d %{public}4d %{public}4d %{public}4d [%{public}4d %{public}4d " \
981             "%{public}4d %{public}4d]", windowId, property->GetWindowType(), property->GetWindowMode(),
982             property->GetWindowFlags(), rect.posX_, rect.posY_, rect.width_, rect.height_);
983         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "wms:AddWindow(%u)", windowId);
984         WMError res = windowController_->AddWindowNode(property);
985         if (property->GetWindowType() == WindowType::WINDOW_TYPE_DRAGGING_EFFECT) {
986             dragController_->StartDrag(windowId);
987         }
988         if (res == WMError::WM_OK) {
989             windowShowPerformReport_->end();
990         }
991         return res;
992     };
993     return PostSyncTask(task, "AddWindow");
994 }
995 
RemoveWindow(uint32_t windowId,bool isFromInnerkits)996 WMError WindowManagerService::RemoveWindow(uint32_t windowId, bool isFromInnerkits)
997 {
998     if (!isFromInnerkits && !Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
999         WLOGFE("remove window permission denied!");
1000         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1001     }
1002     if (!accessTokenIdMaps_.isExist(windowId, IPCSkeleton::GetCallingTokenID())) {
1003         WLOGI("Operation rejected");
1004         return WMError::WM_ERROR_INVALID_OPERATION;
1005     }
1006     auto task = [this, windowId]() {
1007         WLOGI("[WMS] Remove: %{public}u", windowId);
1008         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "wms:RemoveWindow(%u)", windowId);
1009         WindowInnerManager::GetInstance().NotifyWindowRemovedOrDestroyed(windowId);
1010         WMError res = windowController_->RecoverInputEventToClient(windowId);
1011         if (res != WMError::WM_OK) {
1012             return res;
1013         }
1014         return windowController_->RemoveWindowNode(windowId);
1015     };
1016     return PostSyncTask(task, "RemoveWindow");
1017 }
1018 
DestroyWindow(uint32_t windowId,bool onlySelf)1019 WMError WindowManagerService::DestroyWindow(uint32_t windowId, bool onlySelf)
1020 {
1021     if (!accessTokenIdMaps_.isExistAndRemove(windowId, IPCSkeleton::GetCallingTokenID())) {
1022         WLOGI("Operation rejected");
1023         return WMError::WM_ERROR_INVALID_OPERATION;
1024     }
1025     auto task = [this, windowId, onlySelf]() {
1026         auto node = windowRoot_->GetWindowNode(windowId);
1027         if (node == nullptr) {
1028             return WMError::WM_ERROR_NULLPTR;
1029         }
1030         node->stateMachine_.SetDestroyTaskParam(onlySelf);
1031         auto func = [this, windowId]() {
1032             WLOGI("[WMS] Destroy: %{public}u", windowId);
1033             HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "wms:DestroyWindow(%u)", windowId);
1034             WindowInnerManager::GetInstance().NotifyWindowRemovedOrDestroyed(windowId);
1035             windowGroupMgr_->OnWindowDestroyed(windowId);
1036             auto node = windowRoot_->GetWindowNode(windowId);
1037             if (node == nullptr) {
1038                 return WMError::WM_OK;
1039             }
1040             if (node->GetWindowType() == WindowType::WINDOW_TYPE_DRAGGING_EFFECT) {
1041                 dragController_->FinishDrag(windowId);
1042             }
1043             return windowController_->DestroyWindow(windowId, node->stateMachine_.GetDestroyTaskParam());
1044         };
1045         if (RemoteAnimation::IsRemoteAnimationEnabledAndFirst(node->GetDisplayId()) &&
1046             node->stateMachine_.IsRemoteAnimationPlaying()) {
1047             WLOGI("SetDestroyTask id:%{public}u", node->GetWindowId());
1048             node->stateMachine_.SetDestroyTask(func);
1049             return WMError::WM_OK;
1050         }
1051         WLOGI("DestroyWindow windowId: %{public}u, name:%{public}s state: %{public}u",
1052             node->GetWindowId(), node->GetWindowName().c_str(),
1053             static_cast<uint32_t>(node->stateMachine_.GetCurrentState()));
1054         return func();
1055     };
1056     return PostSyncTask(task, "DestroyWindow");
1057 }
1058 
RequestFocus(uint32_t windowId)1059 WMError WindowManagerService::RequestFocus(uint32_t windowId)
1060 {
1061     auto task = [this, windowId]() {
1062         WLOGI("[WMS] RequestFocus: %{public}u", windowId);
1063         return windowController_->RequestFocus(windowId);
1064     };
1065     return PostSyncTask(task, "RequestFocus");
1066 }
1067 
GetAvoidAreaByType(uint32_t windowId,AvoidAreaType avoidAreaType)1068 AvoidArea WindowManagerService::GetAvoidAreaByType(uint32_t windowId, AvoidAreaType avoidAreaType)
1069 {
1070     auto task = [this, windowId, avoidAreaType]() {
1071         WLOGI("[WMS] GetAvoidAreaByType: %{public}u, Type: %{public}u", windowId,
1072             static_cast<uint32_t>(avoidAreaType));
1073         return windowController_->GetAvoidAreaByType(windowId, avoidAreaType);
1074     };
1075     return PostSyncTask(task, "GetAvoidAreaByType");
1076 }
1077 
RegisterWindowManagerAgent(WindowManagerAgentType type,const sptr<IWindowManagerAgent> & windowManagerAgent)1078 WMError WindowManagerService::RegisterWindowManagerAgent(WindowManagerAgentType type,
1079     const sptr<IWindowManagerAgent>& windowManagerAgent)
1080 {
1081     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
1082         WLOGFE("register windowManager agent permission denied!");
1083         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1084     }
1085     if ((windowManagerAgent == nullptr) || (windowManagerAgent->AsObject() == nullptr)) {
1086         WLOGFE("windowManagerAgent is null");
1087         return WMError::WM_ERROR_NULLPTR;
1088     }
1089     auto task = [this, &windowManagerAgent, type]() {
1090         WMError ret = WindowManagerAgentController::GetInstance().RegisterWindowManagerAgent(windowManagerAgent, type);
1091         if (type == WindowManagerAgentType::WINDOW_MANAGER_AGENT_TYPE_SYSTEM_BAR) { // if system bar, notify once
1092             windowController_->NotifySystemBarTints();
1093         }
1094         return ret;
1095     };
1096     return PostSyncTask(task, "RegisterWindowManagerAgent");
1097 }
1098 
UnregisterWindowManagerAgent(WindowManagerAgentType type,const sptr<IWindowManagerAgent> & windowManagerAgent)1099 WMError WindowManagerService::UnregisterWindowManagerAgent(WindowManagerAgentType type,
1100     const sptr<IWindowManagerAgent>& windowManagerAgent)
1101 {
1102     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
1103         WLOGFE("unregister windowManager agent permission denied!");
1104         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1105     }
1106     if ((windowManagerAgent == nullptr) || (windowManagerAgent->AsObject() == nullptr)) {
1107         WLOGFE("windowManagerAgent is null");
1108         return WMError::WM_ERROR_NULLPTR;
1109     }
1110     auto task = [this, &windowManagerAgent, type]() {
1111         return WindowManagerAgentController::GetInstance().UnregisterWindowManagerAgent(windowManagerAgent, type);
1112     };
1113     return PostSyncTask(task, "UnregisterWindowManagerAgent");
1114 }
1115 
SetWindowAnimationController(const sptr<RSIWindowAnimationController> & controller)1116 WMError WindowManagerService::SetWindowAnimationController(const sptr<RSIWindowAnimationController>& controller)
1117 {
1118     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
1119         WLOGFE("set window animation controller permission denied!");
1120         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1121     }
1122     if (controller == nullptr) {
1123         WLOGFE("RSWindowAnimation: Failed to set window animation controller, controller is null!");
1124         return WMError::WM_ERROR_NULLPTR;
1125     }
1126 
1127     sptr<AgentDeathRecipient> deathRecipient = new AgentDeathRecipient(
1128         [this](sptr<IRemoteObject>& remoteObject) {
1129             auto task = [&remoteObject]() {
1130                 RemoteAnimation::OnRemoteDie(remoteObject);
1131             };
1132             PostVoidSyncTask(task, "OnRemoteDie");
1133         }
1134     );
1135     controller->AsObject()->AddDeathRecipient(deathRecipient);
1136     RemoteAnimation::SetWindowControllerAndRoot(windowController_, windowRoot_);
1137     RemoteAnimation::SetMainTaskHandler(handler_);
1138     auto task = [this, &controller]() {
1139         WMError ret = windowController_->SetWindowAnimationController(controller);
1140         RemoteAnimation::SetAnimationFirst(system::GetParameter("persist.window.af.enabled", "1") == "1");
1141         return ret;
1142     };
1143     return PostSyncTask(task, "SetWindowAnimationController");
1144 }
1145 
OnWindowEvent(Event event,const sptr<IRemoteObject> & remoteObject)1146 void WindowManagerService::OnWindowEvent(Event event, const sptr<IRemoteObject>& remoteObject)
1147 {
1148     if (event == Event::REMOTE_DIED) {
1149         auto task = [this, &remoteObject]() {
1150             uint32_t windowId = windowRoot_->GetWindowIdByObject(remoteObject);
1151             auto node = windowRoot_->GetWindowNode(windowId);
1152             if (node == nullptr) {
1153                 WLOGFD("window node is nullptr, REMOTE_DIED no need to destroy");
1154                 return;
1155             }
1156             WLOGI("window %{public}u received REMOTE_DIED", windowId);
1157             node->stateMachine_.SetDestroyTaskParam(true);
1158             auto func = [this, windowId]() {
1159                 auto node = windowRoot_->GetWindowNode(windowId);
1160                 if (node == nullptr) {
1161                     WLOGFD("window node is nullptr");
1162                     return;
1163                 }
1164                 if (node->GetWindowType() == WindowType::WINDOW_TYPE_DRAGGING_EFFECT) {
1165                     dragController_->FinishDrag(windowId);
1166                 }
1167                 WindowInnerManager::GetInstance().NotifyWindowRemovedOrDestroyed(windowId);
1168                 windowGroupMgr_->OnWindowDestroyed(windowId);
1169                 windowController_->DestroyWindow(windowId, node->stateMachine_.GetDestroyTaskParam());
1170             };
1171 
1172             if (node->GetWindowType() == WindowType::WINDOW_TYPE_DESKTOP) {
1173                 RemoteAnimation::OnRemoteDie(remoteObject);
1174             }
1175             if (RemoteAnimation::IsRemoteAnimationEnabledAndFirst(node->GetDisplayId()) &&
1176                 node->stateMachine_.IsRemoteAnimationPlaying()) {
1177                 WLOGI("set destroy task windowId:%{public}u", node->GetWindowId());
1178                 node->stateMachine_.SetDestroyTask(func);
1179                 handler_->PostTask(func, "destroyTimeOutTask", 6000); // 6000 is time out 6s
1180                 return;
1181             }
1182             func();
1183         };
1184         PostVoidSyncTask(task, "OnWindowEvent");
1185     }
1186 }
1187 
NotifyDisplayStateChange(DisplayId defaultDisplayId,sptr<DisplayInfo> displayInfo,const std::map<DisplayId,sptr<DisplayInfo>> & displayInfoMap,DisplayStateChangeType type)1188 void WindowManagerService::NotifyDisplayStateChange(DisplayId defaultDisplayId, sptr<DisplayInfo> displayInfo,
1189     const std::map<DisplayId, sptr<DisplayInfo>>& displayInfoMap, DisplayStateChangeType type)
1190 {
1191     HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "wms:NotifyDisplayStateChange(%u)", type);
1192     DisplayId displayId = (displayInfo == nullptr) ? DISPLAY_ID_INVALID : displayInfo->GetDisplayId();
1193     if (type == DisplayStateChangeType::FREEZE) {
1194         freezeDisplayController_->FreezeDisplay(displayId);
1195     } else if (type == DisplayStateChangeType::UNFREEZE) {
1196         freezeDisplayController_->UnfreezeDisplay(displayId);
1197         /*
1198          * Set 'InnerInputManager Listener' to MMI, ensure that the listener
1199          * for move/drag won't be replaced by freeze-display-window
1200          */
1201         WindowInnerManager::GetInstance().SetInputEventConsumer();
1202     } else {
1203         auto task = [this, defaultDisplayId, displayInfo, displayInfoMap, type]() mutable {
1204             windowController_->NotifyDisplayStateChange(defaultDisplayId, displayInfo, displayInfoMap, type);
1205             windowGroupMgr_->OnDisplayStateChange(defaultDisplayId, displayInfo, displayInfoMap, type);
1206         };
1207         PostAsyncTask(task, "NotifyDisplayStateChange");
1208     }
1209 }
1210 
OnDisplayStateChange(DisplayId defaultDisplayId,sptr<DisplayInfo> displayInfo,const std::map<DisplayId,sptr<DisplayInfo>> & displayInfoMap,DisplayStateChangeType type)1211 void DisplayChangeListener::OnDisplayStateChange(DisplayId defaultDisplayId, sptr<DisplayInfo> displayInfo,
1212     const std::map<DisplayId, sptr<DisplayInfo>>& displayInfoMap, DisplayStateChangeType type)
1213 {
1214     WindowManagerService::GetInstance().NotifyDisplayStateChange(defaultDisplayId, displayInfo, displayInfoMap, type);
1215 }
1216 
OnScreenshot(DisplayId displayId)1217 void DisplayChangeListener::OnScreenshot(DisplayId displayId)
1218 {
1219     WindowManagerService::GetInstance().OnScreenshot(displayId);
1220 }
1221 
NotifyServerReadyToMoveOrDrag(uint32_t windowId,sptr<WindowProperty> & windowProperty,sptr<MoveDragProperty> & moveDragProperty)1222 void WindowManagerService::NotifyServerReadyToMoveOrDrag(uint32_t windowId, sptr<WindowProperty>& windowProperty,
1223     sptr<MoveDragProperty>& moveDragProperty)
1224 {
1225     if (windowProperty == nullptr || moveDragProperty == nullptr) {
1226         WLOGFE("windowProperty or moveDragProperty is invalid");
1227         return;
1228     }
1229 
1230     auto task = [this, windowId, windowProperty, moveDragProperty]() mutable {
1231         if (moveDragProperty->startDragFlag_ || moveDragProperty->startMoveFlag_) {
1232             bool res = WindowInnerManager::GetInstance().NotifyServerReadyToMoveOrDrag(windowId,
1233                 windowProperty, moveDragProperty);
1234             if (!res) {
1235                 WLOGFE("invalid operation");
1236                 return;
1237             }
1238             windowController_->InterceptInputEventToServer(windowId);
1239         }
1240         windowController_->NotifyServerReadyToMoveOrDrag(windowId, moveDragProperty);
1241     };
1242     PostAsyncTask(task, "NotifyServerReadyToMoveOrDrag");
1243 }
1244 
ProcessPointDown(uint32_t windowId,bool isPointDown)1245 void WindowManagerService::ProcessPointDown(uint32_t windowId, bool isPointDown)
1246 {
1247     auto task = [this, windowId, isPointDown]() {
1248         windowController_->ProcessPointDown(windowId, isPointDown);
1249     };
1250     PostAsyncTask(task, "ProcessPointDown");
1251 }
1252 
ProcessPointUp(uint32_t windowId)1253 void WindowManagerService::ProcessPointUp(uint32_t windowId)
1254 {
1255     auto task = [this, windowId]() {
1256         WindowInnerManager::GetInstance().NotifyWindowEndUpMovingOrDragging(windowId);
1257         windowController_->RecoverInputEventToClient(windowId);
1258         windowController_->ProcessPointUp(windowId);
1259     };
1260     PostAsyncTask(task, "ProcessPointUp");
1261 }
1262 
NotifyWindowClientPointUp(uint32_t windowId,const std::shared_ptr<MMI::PointerEvent> & pointerEvent)1263 void WindowManagerService::NotifyWindowClientPointUp(uint32_t windowId,
1264     const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
1265 {
1266     auto task = [this, windowId, pointerEvent]() mutable {
1267         windowController_->NotifyWindowClientPointUp(windowId, pointerEvent);
1268     };
1269     PostAsyncTask(task, "NotifyWindowClientPointUp");
1270 }
1271 
MinimizeAllAppWindows(DisplayId displayId)1272 WMError WindowManagerService::MinimizeAllAppWindows(DisplayId displayId)
1273 {
1274     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
1275         WLOGFE("minimize all appWindows permission denied!");
1276         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1277     }
1278     auto task = [this, displayId]() {
1279         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "wms:MinimizeAllAppWindows(%" PRIu64")", displayId);
1280         WLOGI("displayId %{public}" PRIu64"", displayId);
1281         windowController_->MinimizeAllAppWindows(displayId);
1282     };
1283     PostAsyncTask(task, "MinimizeAllAppWindows");
1284     return WMError::WM_OK;
1285 }
1286 
ToggleShownStateForAllAppWindows()1287 WMError WindowManagerService::ToggleShownStateForAllAppWindows()
1288 {
1289     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
1290         WLOGFE("toggle shown state for all appwindows permission denied!");
1291         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1292     }
1293     auto task = [this]() {
1294         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "wms:ToggleShownStateForAllAppWindows");
1295         return windowController_->ToggleShownStateForAllAppWindows();
1296     };
1297     PostAsyncTask(task, "ToggleShownStateForAllAppWindows");
1298     return WMError::WM_OK;
1299 }
1300 
GetTopWindowId(uint32_t mainWinId,uint32_t & topWinId)1301 WMError WindowManagerService::GetTopWindowId(uint32_t mainWinId, uint32_t& topWinId)
1302 {
1303     auto task = [this, &topWinId, mainWinId]() {
1304         return windowController_->GetTopWindowId(mainWinId, topWinId);
1305     };
1306     return PostSyncTask(task, "GetTopWindowId");
1307 }
1308 
SetWindowLayoutMode(WindowLayoutMode mode)1309 WMError WindowManagerService::SetWindowLayoutMode(WindowLayoutMode mode)
1310 {
1311     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
1312         WLOGFE("set window layout mode permission denied!");
1313         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1314     }
1315     auto task = [this, mode]() {
1316         WLOGI("layoutMode: %{public}u", mode);
1317         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "wms:SetWindowLayoutMode");
1318         return windowController_->SetWindowLayoutMode(mode);
1319     };
1320     return PostSyncTask(task, "SetWindowLayoutMode");
1321 }
1322 
UpdateProperty(sptr<WindowProperty> & windowProperty,PropertyChangeAction action,bool isAsyncTask)1323 WMError WindowManagerService::UpdateProperty(sptr<WindowProperty>& windowProperty, PropertyChangeAction action,
1324     bool isAsyncTask)
1325 {
1326     if (windowProperty == nullptr) {
1327         WLOGFE("windowProperty is nullptr");
1328         return WMError::WM_ERROR_NULLPTR;
1329     }
1330 
1331     if ((windowProperty->GetWindowFlags() == static_cast<uint32_t>(WindowFlag::WINDOW_FLAG_FORBID_SPLIT_MOVE) ||
1332         action == PropertyChangeAction::ACTION_UPDATE_TRANSFORM_PROPERTY) &&
1333         !Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
1334         WLOGFE("SetForbidSplitMove or SetShowWhenLocked or SetTranform or SetTurnScreenOn permission denied!");
1335         return WMError::WM_ERROR_INVALID_PERMISSION;
1336     }
1337 
1338     WindowType type = windowProperty->GetWindowType();
1339     if (type == WindowType::WINDOW_TYPE_INPUT_METHOD_FLOAT ||
1340         type == WindowType::WINDOW_TYPE_INPUT_METHOD_STATUS_BAR) {
1341         if (!Permission::IsStartByInputMethod()) {
1342             WLOGI("Keyboard only hide by input method it'self, operation rejected.");
1343             return WMError::WM_ERROR_INVALID_OPERATION;
1344         }
1345     } else if (!accessTokenIdMaps_.isExist(windowProperty->GetWindowId(), IPCSkeleton::GetCallingTokenID()) &&
1346         !Permission::IsSystemCalling()) {
1347         WLOGI("Operation rejected");
1348         return WMError::WM_ERROR_INVALID_OPERATION;
1349     }
1350 
1351     if (action == PropertyChangeAction::ACTION_UPDATE_PRIVACY_MODE &&
1352         !Permission::CheckCallingPermission("ohos.permission.PRIVACY_WINDOW")) {
1353         WLOGFE("Set privacy mode permission denied!");
1354         return WMError::WM_ERROR_INVALID_PERMISSION;
1355     }
1356 
1357     windowProperty->isSystemCalling_ = Permission::IsSystemCalling();
1358     if (action == PropertyChangeAction::ACTION_UPDATE_TRANSFORM_PROPERTY) {
1359         auto task = [this, windowProperty, action]() mutable {
1360             windowController_->UpdateProperty(windowProperty, action);
1361             return WMError::WM_OK;
1362         };
1363         return PostSyncTask(task, "UpdateProperty");
1364     }
1365 
1366     if (isAsyncTask || action == PropertyChangeAction::ACTION_UPDATE_RECT) {
1367         auto task = [this, windowProperty, action]() mutable {
1368             HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "wms:UpdateProperty");
1369             WMError res = windowController_->UpdateProperty(windowProperty, action);
1370             if (action == PropertyChangeAction::ACTION_UPDATE_RECT && res == WMError::WM_OK &&
1371                 IsMoveToOrDragMove(windowProperty->GetWindowSizeChangeReason())) {
1372                 dragController_->UpdateDragInfo(windowProperty->GetWindowId());
1373             }
1374         };
1375         PostAsyncTask(task, "UpdateProperty");
1376         return WMError::WM_OK;
1377     }
1378 
1379     auto task = [this, &windowProperty, action]() {
1380         HITRACE_METER_FMT(HITRACE_TAG_WINDOW_MANAGER, "wms:UpdateProperty");
1381         WMError res = windowController_->UpdateProperty(windowProperty, action);
1382         if (action == PropertyChangeAction::ACTION_UPDATE_RECT && res == WMError::WM_OK &&
1383             IsMoveToOrDragMove(windowProperty->GetWindowSizeChangeReason())) {
1384             dragController_->UpdateDragInfo(windowProperty->GetWindowId());
1385         }
1386         return res;
1387     };
1388     return PostSyncTask(task, "UpdateProperty");
1389 }
1390 
SetWindowGravity(uint32_t windowId,WindowGravity gravity,uint32_t percent)1391 WMError WindowManagerService::SetWindowGravity(uint32_t windowId, WindowGravity gravity, uint32_t percent)
1392 {
1393     auto task = [this, windowId, gravity, percent]() {
1394         WMError res = windowController_->SetWindowGravity(windowId, gravity, percent);
1395         return res;
1396     };
1397     return PostSyncTask(task, "SetWindowGravity");
1398 }
1399 
GetAccessibilityWindowInfo(std::vector<sptr<AccessibilityWindowInfo>> & infos)1400 WMError WindowManagerService::GetAccessibilityWindowInfo(std::vector<sptr<AccessibilityWindowInfo>>& infos)
1401 {
1402     if (!Permission::IsSystemServiceCalling()) {
1403         WLOGFE("get accessibility window info permission denied!");
1404         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1405     }
1406     auto task = [this, &infos]() {
1407         return windowController_->GetAccessibilityWindowInfo(infos);
1408     };
1409     return PostSyncTask(task, "GetAccessibilityWindowInfo");
1410 }
1411 
GetUnreliableWindowInfo(int32_t windowId,std::vector<sptr<UnreliableWindowInfo>> & infos)1412 WMError WindowManagerService::GetUnreliableWindowInfo(int32_t windowId,
1413     std::vector<sptr<UnreliableWindowInfo>>& infos)
1414 {
1415     if (!Permission::IsSystemServiceCalling()) {
1416         WLOGFE("get unreliable window info permission denied!");
1417         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1418     }
1419     auto task = [this, windowId, &infos]() {
1420         return windowController_->GetUnreliableWindowInfo(windowId, infos);
1421     };
1422     return PostSyncTask(task, "GetUnreliableWindowInfo");
1423 }
1424 
GetVisibilityWindowInfo(std::vector<sptr<WindowVisibilityInfo>> & infos)1425 WMError WindowManagerService::GetVisibilityWindowInfo(std::vector<sptr<WindowVisibilityInfo>>& infos)
1426 {
1427     auto task = [this, &infos]() {
1428         return windowController_->GetVisibilityWindowInfo(infos);
1429     };
1430     return PostSyncTask(task, "GetVisibilityWindowInfo");
1431 }
1432 
1433 /** @note @window.hierarchy */
RaiseToAppTop(uint32_t windowId)1434 WMError WindowManagerService::RaiseToAppTop(uint32_t windowId)
1435 {
1436     auto task = [this, windowId]() {
1437         return windowController_->RaiseToAppTop(windowId);
1438     };
1439     return PostSyncTask(task, "RaiseToAppTop");
1440 }
1441 
GetSnapshot(int32_t windowId)1442 std::shared_ptr<Media::PixelMap> WindowManagerService::GetSnapshot(int32_t windowId)
1443 {
1444     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
1445         WLOGFE("permission denied!");
1446         return nullptr;
1447     }
1448     auto task = [this, windowId]() {
1449         return windowController_->GetSnapshot(windowId);
1450     };
1451     return PostSyncTask(task, "GetSnapshot");
1452 }
1453 
DispatchKeyEvent(uint32_t windowId,std::shared_ptr<MMI::KeyEvent> event)1454 void WindowManagerService::DispatchKeyEvent(uint32_t windowId, std::shared_ptr<MMI::KeyEvent> event)
1455 {
1456     auto task = [this, windowId, event]() {
1457         windowController_->DispatchKeyEvent(windowId, event);
1458     };
1459     PostVoidSyncTask(task, "DispatchKeyEvent");
1460 }
1461 
NotifyDumpInfoResult(const std::vector<std::string> & info)1462 void WindowManagerService::NotifyDumpInfoResult(const std::vector<std::string>& info)
1463 {
1464     if (windowDumper_) {
1465         windowDumper_->dumpInfoFuture_.SetValue(info);
1466     }
1467 }
1468 
GetWindowAnimationTargets(std::vector<uint32_t> missionIds,std::vector<sptr<RSWindowAnimationTarget>> & targets)1469 WMError WindowManagerService::GetWindowAnimationTargets(std::vector<uint32_t> missionIds,
1470     std::vector<sptr<RSWindowAnimationTarget>>& targets)
1471 {
1472     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
1473         WLOGFE("get window animation targets permission denied!");
1474         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1475     }
1476     auto task = [this, missionIds, &targets]() {
1477         return RemoteAnimation::GetWindowAnimationTargets(missionIds, targets);
1478     };
1479     return PostSyncTask(task, "GetWindowAnimationTargets");
1480 }
1481 
GetSystemConfig(SystemConfig & systemConfig)1482 WMError WindowManagerService::GetSystemConfig(SystemConfig& systemConfig)
1483 {
1484     systemConfig = systemConfig_;
1485     return WMError::WM_OK;
1486 }
1487 
GetModeChangeHotZones(DisplayId displayId,ModeChangeHotZones & hotZones)1488 WMError WindowManagerService::GetModeChangeHotZones(DisplayId displayId, ModeChangeHotZones& hotZones)
1489 {
1490     if (!hotZonesConfig_.isModeChangeHotZoneConfigured_) {
1491         return WMError::WM_DO_NOTHING;
1492     }
1493 
1494     return windowController_->GetModeChangeHotZones(displayId, hotZones, hotZonesConfig_);
1495 }
1496 
MinimizeWindowsByLauncher(std::vector<uint32_t> windowIds,bool isAnimated,sptr<RSIWindowAnimationFinishedCallback> & finishCallback)1497 void WindowManagerService::MinimizeWindowsByLauncher(std::vector<uint32_t> windowIds, bool isAnimated,
1498     sptr<RSIWindowAnimationFinishedCallback>& finishCallback)
1499 {
1500     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
1501         WLOGFE("minimize windows by launcher permission denied!");
1502         return;
1503     }
1504     auto task = [this, windowIds, isAnimated, &finishCallback]() mutable {
1505         windowController_->MinimizeWindowsByLauncher(windowIds, isAnimated, finishCallback);
1506     };
1507     PostVoidSyncTask(task, "MinimizeWindowsByLauncher");
1508 }
1509 
UpdateAvoidAreaListener(uint32_t windowId,bool haveAvoidAreaListener)1510 WMError WindowManagerService::UpdateAvoidAreaListener(uint32_t windowId, bool haveAvoidAreaListener)
1511 {
1512     auto task = [this, windowId, haveAvoidAreaListener]() {
1513         sptr<WindowNode> node = windowRoot_->GetWindowNode(windowId);
1514         if (node == nullptr) {
1515             WLOGFE("get window node failed. win %{public}u", windowId);
1516             return WMError::WM_DO_NOTHING;
1517         }
1518         sptr<WindowNodeContainer> container = windowRoot_->GetWindowNodeContainer(node->GetDisplayId());
1519         if (container == nullptr) {
1520             WLOGFE("get container failed. win %{public}u display %{public}" PRIu64"", windowId, node->GetDisplayId());
1521             return WMError::WM_DO_NOTHING;
1522         }
1523         container->UpdateAvoidAreaListener(node, haveAvoidAreaListener);
1524         return WMError::WM_OK;
1525     };
1526     return PostSyncTask(task, "UpdateAvoidAreaListener");
1527 }
1528 
SetAnchorAndScale(int32_t x,int32_t y,float scale)1529 void WindowManagerService::SetAnchorAndScale(int32_t x, int32_t y, float scale)
1530 {
1531     auto task = [this, x, y, scale]() {
1532         windowController_->SetAnchorAndScale(x, y, scale);
1533     };
1534     PostAsyncTask(task, "SetAnchorAndScale");
1535 }
1536 
SetAnchorOffset(int32_t deltaX,int32_t deltaY)1537 void WindowManagerService::SetAnchorOffset(int32_t deltaX, int32_t deltaY)
1538 {
1539     auto task = [this, deltaX, deltaY]() {
1540         windowController_->SetAnchorOffset(deltaX, deltaY);
1541     };
1542     PostAsyncTask(task, "SetAnchorOffset");
1543 }
1544 
OffWindowZoom()1545 void WindowManagerService::OffWindowZoom()
1546 {
1547     auto task = [this]() {
1548         windowController_->OffWindowZoom();
1549     };
1550     PostAsyncTask(task, "OffWindowZoom");
1551 }
1552 
UpdateRsTree(uint32_t windowId,bool isAdd)1553 WMError WindowManagerService::UpdateRsTree(uint32_t windowId, bool isAdd)
1554 {
1555     auto task = [this, windowId, isAdd]() {
1556         return windowRoot_->UpdateRsTree(windowId, isAdd);
1557     };
1558     return PostSyncTask(task, "UpdateRsTree");
1559 }
1560 
OnScreenshot(DisplayId displayId)1561 void WindowManagerService::OnScreenshot(DisplayId displayId)
1562 {
1563     auto task = [this, displayId]() {
1564         windowController_->OnScreenshot(displayId);
1565     };
1566     PostAsyncTask(task, "OnScreenshot");
1567 }
1568 
BindDialogTarget(uint32_t & windowId,sptr<IRemoteObject> targetToken)1569 WMError WindowManagerService::BindDialogTarget(uint32_t& windowId, sptr<IRemoteObject> targetToken)
1570 {
1571     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
1572         WLOGFE("bind dialog target permission denied!");
1573         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1574     }
1575     auto task = [this, &windowId, targetToken]() {
1576         return windowController_->BindDialogTarget(windowId, targetToken);
1577     };
1578     return PostSyncTask(task, "BindDialogTarget");
1579 }
1580 
HasPrivateWindow(DisplayId displayId,bool & hasPrivateWindow)1581 void WindowManagerService::HasPrivateWindow(DisplayId displayId, bool& hasPrivateWindow)
1582 {
1583     auto task = [this, displayId, &hasPrivateWindow]() mutable {
1584         hasPrivateWindow = windowRoot_->HasPrivateWindow(displayId);
1585     };
1586     PostVoidSyncTask(task, "HasPrivateWindow");
1587     WLOGI("called %{public}u", hasPrivateWindow);
1588 }
1589 
SetGestureNavigaionEnabled(bool enable)1590 WMError WindowManagerService::SetGestureNavigaionEnabled(bool enable)
1591 {
1592     if (!Permission::IsSystemCalling() && !Permission::IsStartByHdcd()) {
1593         WLOGFE("permission denied!");
1594         return WMError::WM_ERROR_NOT_SYSTEM_APP;
1595     }
1596     auto task = [this, enable]() {
1597         return windowRoot_->SetGestureNavigaionEnabled(enable);
1598     };
1599     return PostSyncTask(task, "SetGestureNavigaionEnabled");
1600 }
1601 
HasPrivateWindow(DisplayId displayId,bool & hasPrivateWindow)1602 void WindowInfoQueriedListener::HasPrivateWindow(DisplayId displayId, bool& hasPrivateWindow)
1603 {
1604     WLOGI("called");
1605     WindowManagerService::GetInstance().HasPrivateWindow(displayId, hasPrivateWindow);
1606 }
1607 
SetMaximizeMode(MaximizeMode maximizeMode)1608 void WindowManagerService::SetMaximizeMode(MaximizeMode maximizeMode)
1609 {
1610     maximizeMode_ = maximizeMode;
1611     int32_t storageMode = -1;
1612     if (PersistentStorage::HasKey("maximize_state", PersistentStorageType::MAXIMIZE_STATE)) {
1613         PersistentStorage::Get("maximize_state", storageMode, PersistentStorageType::MAXIMIZE_STATE);
1614         PersistentStorage::Delete("maximize_state", PersistentStorageType::MAXIMIZE_STATE);
1615     }
1616     PersistentStorage::Insert("maximize_state", static_cast<int32_t>(maximizeMode),
1617         PersistentStorageType::MAXIMIZE_STATE);
1618     WLOGI("globalMaximizeMode changed from %{public}d to %{public}d", storageMode, static_cast<int32_t>(maximizeMode));
1619 }
1620 
GetMaximizeMode()1621 MaximizeMode WindowManagerService::GetMaximizeMode()
1622 {
1623     return maximizeMode_;
1624 }
1625 
GetFocusWindowInfo(FocusChangeInfo & focusInfo)1626 void WindowManagerService::GetFocusWindowInfo(FocusChangeInfo& focusInfo)
1627 {
1628     WLOGFD("Get Focus window info in wms");
1629     windowController_->GetFocusWindowInfo(focusInfo);
1630 }
1631 } // namespace Rosen
1632 } // namespace OHOS
1633