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