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