• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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 "power_mgr_service.h"
17 
18 #include <datetime_ex.h>
19 #include <file_ex.h>
20 #include <hisysevent.h>
21 #include <if_system_ability_manager.h>
22 #include "input_manager.h"
23 #include <ipc_skeleton.h>
24 #include <iservice_registry.h>
25 #include <string_ex.h>
26 #include <system_ability_definition.h>
27 #include <unistd.h>
28 
29 #include "display_manager.h"
30 #include "permission.h"
31 #include "power_common.h"
32 #include "power_mgr_dumper.h"
33 #include "ui_service_mgr_client.h"
34 #include "watchdog.h"
35 
36 namespace OHOS {
37 namespace PowerMgr {
38 namespace {
39 const std::string POWERMGR_SERVICE_NAME = "PowerMgrService";
40 const std::string TASK_RUNNINGLOCK_UNLOCK = "RunningLock_UnLock";
41 const std::string REASON_POWER_KEY = "power_key";
42 constexpr int UI_DIALOG_POWER_WIDTH_NARROW = 400;
43 constexpr int UI_DIALOG_POWER_HEIGHT_NARROW = 240;
44 constexpr int UI_DEFAULT_WIDTH = 2560;
45 constexpr int UI_DEFAULT_HEIGHT = 1600;
46 constexpr int UI_DEFAULT_BUTTOM_CLIP = 50 * 2; // 48vp
47 constexpr int UI_HALF = 2;
48 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
49 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(pms.GetRefPtr());
50 }
51 
52 using namespace MMI;
53 using namespace Msdp;
54 
PowerMgrService()55 PowerMgrService::PowerMgrService() : SystemAbility(POWER_MANAGER_SERVICE_ID, true) {}
56 
~PowerMgrService()57 PowerMgrService::~PowerMgrService() {}
58 
OnStart()59 void PowerMgrService::OnStart()
60 {
61     POWER_HILOGI(MODULE_SERVICE, "OnStart enter.");
62     if (ready_) {
63         POWER_HILOGE(MODULE_SERVICE, "OnStart is ready, nothing to do.");
64         return;
65     }
66 
67     if (!Init()) {
68         POWER_HILOGE(MODULE_SERVICE, "OnStart call init fail");
69         return;
70     }
71     if (!Publish(DelayedSpSingleton<PowerMgrService>::GetInstance())) {
72         POWER_HILOGE(MODULE_SERVICE, "OnStart register to system ability manager failed.");
73         return;
74     }
75     ready_ = true;
76     POWER_HILOGI(MODULE_SERVICE, "OnStart and add system ability success.");
77 }
78 
Init()79 bool PowerMgrService::Init()
80 {
81     POWER_HILOGI(MODULE_SERVICE, "Init start");
82 
83     if (!eventRunner_) {
84         eventRunner_ = AppExecFwk::EventRunner::Create(POWERMGR_SERVICE_NAME);
85         if (eventRunner_ == nullptr) {
86             POWER_HILOGE(MODULE_SERVICE, "Init failed due to create EventRunner");
87             return false;
88         }
89     }
90 
91     if (!handler_) {
92         handler_ = std::make_shared<PowermsEventHandler>(eventRunner_, pms);
93         std::string handlerName("PowerMgrEventHandler");
94         HiviewDFX::Watchdog::GetInstance().AddThread(handlerName, handler_, WATCH_DOG_DELAY_MS);
95     }
96 
97     if (!runningLockMgr_) {
98         runningLockMgr_ = std::make_shared<RunningLockMgr>(pms);
99     }
100     if (!runningLockMgr_->Init()) {
101         POWER_HILOGE(MODULE_SERVICE, "OnStart init fail");
102         return false;
103     }
104     if (!PowerStateMachineInit()) {
105         POWER_HILOGE(MODULE_SERVICE, "power state machine init fail!");
106     }
107     if (DelayedSpSingleton<PowerSaveMode>::GetInstance()) {
108         powerModeModule_.EnableMode(powerModeModule_.GetModeItem());
109     } else {
110         POWER_HILOGE(MODULE_SERVICE, "power mode init fail!");
111     }
112     handler_->SendEvent(PowermsEventHandler::INIT_KEY_MONITOR_MSG, 0, INIT_KEY_MONITOR_DELAY_MS);
113     POWER_HILOGI(MODULE_SERVICE, "Init success");
114     return true;
115 }
116 
PowerStateMachineInit()117 bool PowerMgrService::PowerStateMachineInit()
118 {
119     if (powerStateMachine_ == nullptr) {
120         powerStateMachine_ = std::make_shared<PowerStateMachine>(pms);
121         if (!(powerStateMachine_->Init())) {
122             POWER_HILOGE(MODULE_SERVICE, "power state machine start fail!");
123             return false;
124         }
125     }
126     if (powerMgrNotify_ == nullptr) {
127         powerMgrNotify_ = std::make_shared<PowerMgrNotify>();
128         powerMgrNotify_->RegisterPublishEvents();
129     }
130     return true;
131 }
132 
133 class InputCallback : public IInputEventConsumer {
134     virtual void OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const;
135     virtual void OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const;
136     virtual void OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const;
137 };
138 
OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const139 void InputCallback::OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const
140 {
141     POWER_HILOGE(MODULE_SERVICE, "OnInputEvent keyEvent");
142     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
143     if (pms == nullptr) {
144         return;
145     }
146     pms->HandleKeyEvent(keyEvent->GetKeyCode());
147 }
148 
OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const149 void InputCallback::OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const
150 {
151     POWER_HILOGE(MODULE_SERVICE, "OnInputEvent pointerEvent");
152     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
153     if (pms == nullptr) {
154         return;
155     }
156     int32_t type = pointerEvent->GetSourceType();
157     pms->HandlePointEvent(type);
158 }
159 
OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const160 void InputCallback::OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const
161 {
162     POWER_HILOGE(MODULE_SERVICE, "OnInputEvent axisEvent");
163     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
164     if (pms == nullptr) {
165         return;
166     }
167 }
168 
KeyMonitorInit()169 void PowerMgrService::KeyMonitorInit()
170 {
171     POWER_HILOGI(MODULE_SERVICE, "KeyMonitorInit");
172     std::shared_ptr<OHOS::MMI::KeyOption> keyOption = std::make_shared<OHOS::MMI::KeyOption>();
173     std::set<int32_t> preKeys;
174 
175     keyOption->SetPreKeys(preKeys);
176     keyOption->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_POWER);
177     keyOption->SetFinalKeyDown(true);
178     keyOption->SetFinalKeyDownDuration(LONG_PRESS_DELAY_MS);
179     powerkeyLongPressId_ = InputManager::GetInstance()->SubscribeKeyEvent(keyOption,
180         [this](std::shared_ptr<OHOS::MMI::KeyEvent> keyEvent) {
181             POWER_HILOGI(MODULE_SERVICE, "Receive long press powerkey");
182             handler_->SendEvent(PowermsEventHandler::SHUTDOWN_REQUEST_MSG);
183     });
184     if (powerkeyLongPressId_ < 0) {
185         POWER_HILOGI(MODULE_SERVICE, "SubscribeKeyEvent failed: %{public}d", powerkeyLongPressId_);
186         handler_->SendEvent(PowermsEventHandler::INIT_KEY_MONITOR_MSG, 0, INIT_KEY_MONITOR_DELAY_MS);
187         return;
188     }
189 
190     keyOption.reset();
191     keyOption = std::make_shared<OHOS::MMI::KeyOption>();
192     keyOption->SetPreKeys(preKeys);
193     keyOption->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_POWER);
194     keyOption->SetFinalKeyDown(true);
195     keyOption->SetFinalKeyDownDuration(0);
196     powerkeyShortPressId_ = InputManager::GetInstance()->SubscribeKeyEvent(keyOption,
197         [this](std::shared_ptr<OHOS::MMI::KeyEvent> keyEvent) {
198             POWER_HILOGI(MODULE_SERVICE, "Receive short press powerkey");
199             powerkeyPressed_ = true;
200             if (dialogId_ >= 0) {
201                 POWER_HILOGI(MODULE_SERVICE, "Cancel dialog when short press");
202                 Ace::UIServiceMgrClient::GetInstance()->CancelDialog(dialogId_);
203                 dialogId_ = -1;
204             }
205             handler_->SendEvent(PowermsEventHandler::POWER_KEY_TIMEOUT_MSG, 0, POWER_KEY_PRESS_DELAY_MS);
206     });
207 
208     keyOption.reset();
209     keyOption = std::make_shared<OHOS::MMI::KeyOption>();
210     keyOption->SetPreKeys(preKeys);
211     keyOption->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_POWER);
212     keyOption->SetFinalKeyDown(false);
213     keyOption->SetFinalKeyDownDuration(0);
214     powerkeyReleaseId_ = InputManager::GetInstance()->SubscribeKeyEvent(keyOption,
215         [this](std::shared_ptr<OHOS::MMI::KeyEvent> keyEvent) {
216             powerkeyPressed_ = false;
217             this->HandlePowerKeyUp();
218     });
219 
220     keyOption.reset();
221     keyOption = std::make_shared<OHOS::MMI::KeyOption>();
222     keyOption->SetPreKeys(preKeys);
223     keyOption->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_F1);
224     keyOption->SetFinalKeyDown(true);
225     keyOption->SetFinalKeyDownDuration(0);
226     doubleClickId_ = InputManager::GetInstance()->SubscribeKeyEvent(keyOption,
227         [this](std::shared_ptr<OHOS::MMI::KeyEvent> keyEvent) {
228             POWER_HILOGI(MODULE_SERVICE, "Receive double click");
229             this->HandleKeyEvent(keyEvent->GetKeyCode());
230     });
231 
232     std::shared_ptr<InputCallback> callback = std::make_shared<InputCallback>();
233     monitorId_ = InputManager::GetInstance()->AddMonitor(std::static_pointer_cast<IInputEventConsumer>(callback));
234 }
235 
KeyMonitorCancel()236 void PowerMgrService::KeyMonitorCancel()
237 {
238     POWER_HILOGI(MODULE_SERVICE, "KeyMonitorCancel");
239     InputManager* inputManager = InputManager::GetInstance();
240     if (inputManager == nullptr) {
241         POWER_HILOGI(MODULE_SERVICE, "inputManager is NULL");
242         return;
243     }
244     if (powerkeyLongPressId_ >= 0) {
245         inputManager->UnsubscribeKeyEvent(powerkeyLongPressId_);
246     }
247     if (powerkeyShortPressId_ >= 0) {
248         inputManager->UnsubscribeKeyEvent(powerkeyShortPressId_);
249     }
250     if (powerkeyReleaseId_ >= 0) {
251         inputManager->UnsubscribeKeyEvent(powerkeyReleaseId_);
252     }
253     if (doubleClickId_ >= 0) {
254         inputManager->UnsubscribeKeyEvent(doubleClickId_);
255     }
256     if (monitorId_ >= 0) {
257         inputManager->RemoveMonitor(monitorId_);
258     }
259 }
260 
261 class DeviceStatusCallback : public DeviceStatusAgent::DeviceStatusAgentEvent {
262 public:
~DeviceStatusCallback()263     virtual ~DeviceStatusCallback() {};
264     bool OnEventResult(const DevicestatusDataUtils::DevicestatusData& devicestatusData) override;
265 };
266 
OnEventResult(const DevicestatusDataUtils::DevicestatusData & devicestatusData)267 bool DeviceStatusCallback::OnEventResult(const DevicestatusDataUtils::DevicestatusData& devicestatusData)
268 {
269     POWER_HILOGI(MODULE_SERVICE, "DeviceStatusCallback OnEventResult");
270     if (devicestatusData.type != DevicestatusDataUtils::DevicestatusType::TYPE_LID_OPEN) {
271         POWER_HILOGI(MODULE_SERVICE, "OnEventResult, wrong type: %{public}d", devicestatusData.type);
272         return false;
273     }
274     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
275     if (pms == nullptr) {
276         return false;
277     }
278     int64_t now = static_cast<int64_t>(time(0));
279     if (devicestatusData.value == DevicestatusDataUtils::DevicestatusValue::VALUE_EXIT) {
280         POWER_HILOGI(MODULE_SERVICE, "OnEventResult lid close");
281         pms->SuspendDevice(now, SuspendDeviceType::SUSPEND_DEVICE_REASON_LID_SWITCH, false);
282     } else if (devicestatusData.value == DevicestatusDataUtils::DevicestatusValue::VALUE_ENTER) {
283         POWER_HILOGI(MODULE_SERVICE, "OnEventResult lid open");
284         std::string reason = "lid open";
285         pms->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_LID, reason);
286     }
287     return true;
288 }
289 
DeviceStatusMonitorInit()290 void PowerMgrService::DeviceStatusMonitorInit()
291 {
292     POWER_HILOGI(MODULE_SERVICE, "DeviceStatusMonitorInit");
293     deviceStatusAgent_ = std::make_shared<DeviceStatusAgent>();
294     std::shared_ptr<DeviceStatusCallback> agentEvent = std::make_shared<DeviceStatusCallback>();
295     int32_t ret = deviceStatusAgent_->SubscribeAgentEvent(
296         DevicestatusDataUtils::DevicestatusType::TYPE_LID_OPEN,
297         agentEvent);
298     POWER_HILOGI(MODULE_SERVICE, "SubscribeAgentEvent for device state: %{public}d", ret);
299 }
300 
HandleShutdownRequest()301 void PowerMgrService::HandleShutdownRequest()
302 {
303     POWER_HILOGI(MODULE_SERVICE, "HandleShutdown");
304     if (dialogId_ >= 0) {
305         POWER_HILOGI(MODULE_SERVICE, "dialog is already showing");
306         return;
307     }
308     // show dialog
309     std::string params;
310     int pos_x;
311     int pos_y;
312     int width;
313     int height;
314     bool wideScreen;
315     GetDisplayPosition(pos_x, pos_y, width, height, wideScreen);
316     if (wideScreen) {
317         params = "{\"shutdownButton\":\"Power Off\", " \
318             "\"rebootButton\":\"Restart\", \"cancelButton\":\"Cancel\"}";
319     } else {
320         params = "{\"deviceType\":\"phone\", \"shutdownButton\":\"Power Off\", " \
321             "\"rebootButton\":\"Restart\", \"cancelButton\":\"Cancel\"}";
322     }
323     int32_t errCode = Ace::UIServiceMgrClient::GetInstance()->ShowDialog(
324         "power_dialog",
325         params,
326         OHOS::Rosen::WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW,
327         pos_x,
328         pos_y,
329         width,
330         height,
331         [this](int32_t id, const std::string& event, const std::string& params) {
332             POWER_HILOGI(MODULE_SERVICE, "Dialog callback: %{public}s, %{public}s",
333                 event.c_str(), params.c_str());
334             if (event == "EVENT_SHUTDOWN") {
335                 this->ShutDownDevice(REASON_POWER_KEY);
336             } else if (event == "EVENT_REBOOT") {
337                 this->RebootDevice(REASON_POWER_KEY);
338             } else if (event == "EVENT_CANCEL") {
339                 Ace::UIServiceMgrClient::GetInstance()->CancelDialog(id);
340                 this->dialogId_ = -1;
341             }
342         },
343         &dialogId_);
344     POWER_HILOGI(MODULE_SERVICE, "show dialog is %{public}d, dialogId=%{public}d", errCode, dialogId_);
345     if (!IsScreenOn()) {
346         POWER_HILOGI(MODULE_SERVICE, "wakeup when display off");
347         int64_t now = static_cast<int64_t>(time(0));
348         this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_POWER_BUTTON, REASON_POWER_KEY);
349     }
350     return;
351 }
352 
HandlePowerKeyUp()353 void PowerMgrService::HandlePowerKeyUp()
354 {
355     POWER_HILOGI(MODULE_SERVICE, "Receive release powerkey");
356 
357     if (dialogId_ >= 0 || this->shutdownService_.IsShuttingDown()) {
358         POWER_HILOGI(MODULE_SERVICE, "System is shutting down");
359         return;
360     }
361     int64_t now = static_cast<int64_t>(time(0));
362     if (this->IsScreenOn()) {
363         this->SuspendDevice(now, SuspendDeviceType::SUSPEND_DEVICE_REASON_POWER_BUTTON, false);
364     } else {
365         this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_POWER_BUTTON, REASON_POWER_KEY);
366     }
367 }
368 
HandleKeyEvent(int32_t keyCode)369 void PowerMgrService::HandleKeyEvent(int32_t keyCode)
370 {
371     POWER_HILOGI(MODULE_SERVICE, "HandleKeyEvent: %{public}d", keyCode);
372     int64_t now = static_cast<int64_t>(time(0));
373     if (IsScreenOn()) {
374         this->RefreshActivity(now, UserActivityType::USER_ACTIVITY_TYPE_BUTTON, false);
375     } else {
376         if (keyCode == KeyEvent::KEYCODE_F1) {
377             POWER_HILOGI(MODULE_SERVICE, "wakeup by double click");
378             std::string reason = "double click";
379             reason.append(std::to_string(keyCode));
380             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_DOUBLE_CLICK, reason);
381         } else if (keyCode >= KeyEvent::KEYCODE_0
382             && keyCode <= KeyEvent::KEYCODE_NUMPAD_RIGHT_PAREN) {
383             POWER_HILOGI(MODULE_SERVICE, "wakeup by keyboard");
384             std::string reason = "keyboard:";
385             reason.append(std::to_string(keyCode));
386             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_KEYBOARD, reason);
387         }
388     }
389 }
390 
HandlePointEvent(int32_t type)391 void PowerMgrService::HandlePointEvent(int32_t type)
392 {
393     POWER_HILOGI(MODULE_SERVICE, "HandlePointEvent: %{public}d", type);
394     int64_t now = static_cast<int64_t>(time(0));
395     if (this->IsScreenOn()) {
396         this->RefreshActivity(now, UserActivityType::USER_ACTIVITY_TYPE_TOUCH, false);
397     } else {
398         if (type == PointerEvent::SOURCE_TYPE_MOUSE) {
399             std::string reason = "mouse click";
400             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_MOUSE, reason);
401         }
402     }
403 }
404 
NotifyDisplayActionDone(uint32_t event)405 void PowerMgrService::NotifyDisplayActionDone(uint32_t event)
406 {
407     POWER_HILOGI(MODULE_SERVICE, "NotifyDisplayActionDone: %{public}d", event);
408     handler_->RemoveEvent(PowermsEventHandler::POWER_KEY_TIMEOUT_MSG);
409 }
410 
HandlePowerKeyTimeout()411 void PowerMgrService::HandlePowerKeyTimeout()
412 {
413     POWER_HILOGI(MODULE_SERVICE, "HandlePowerKeyTimeout");
414     std::string message = "POWER KEY TIMEOUT ";
415     if (powerkeyPressed_) {
416         message.append("WITHOUT KEY UP");
417     } else {
418         message.append("BUT DISPLAY NOT FINISHED");
419     }
420     HiviewDFX::HiSysEvent::Write(HiviewDFX::HiSysEvent::Domain::POWERMGR, "SCREEN_ON_TIMEOUT",
421         HiviewDFX::HiSysEvent::EventType::FAULT,
422         "PID", IPCSkeleton::GetCallingPid(),
423         "UID", IPCSkeleton::GetCallingUid(),
424         "PACKAGE_NAME", "",
425         "PROCESS_NAME", "",
426         "MSG", message.c_str());
427     POWER_HILOGI(MODULE_SERVICE, "PowerKey press Timeout");
428 }
429 
OnStop()430 void PowerMgrService::PowerMgrService::OnStop()
431 {
432     POWER_HILOGI(MODULE_SERVICE, "stop service");
433     if (!ready_) {
434         return;
435     }
436     powerStateMachine_->CancelDelayTimer(
437         PowermsEventHandler::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
438     powerStateMachine_->CancelDelayTimer(
439         PowermsEventHandler::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
440     powerStateMachine_->CancelDelayTimer(
441         PowermsEventHandler::CHECK_USER_ACTIVITY_SLEEP_TIMEOUT_MSG);
442     handler_->RemoveEvent(PowermsEventHandler::POWER_KEY_TIMEOUT_MSG);
443 
444     KeyMonitorCancel();
445     eventRunner_.reset();
446     handler_.reset();
447     ready_ = false;
448 }
449 
Dump(int32_t fd,const std::vector<std::u16string> & args)450 int32_t PowerMgrService::Dump(int32_t fd, const std::vector<std::u16string>& args)
451 {
452     POWER_HILOGI(MODULE_SERVICE, "Dump service");
453     std::vector<std::string> argsInStr;
454     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr),
455         [](const std::u16string &arg) {
456         std::string ret = Str16ToStr8(arg);
457         POWER_HILOGI(MODULE_SERVICE, "arg: %{public}s", ret.c_str());
458         return ret;
459     });
460     std::string result;
461     PowerMgrDumper::Dump(argsInStr, result);
462     if (!SaveStringToFd(fd, result)) {
463         POWER_HILOGE(MODULE_SERVICE, "PowerMgrService::Dump failed, save to fd failed.");
464         POWER_HILOGE(MODULE_SERVICE, "Dump Info:\n");
465         POWER_HILOGE(MODULE_SERVICE, "%{public}s", result.c_str());
466         return ERR_OK;
467     }
468     return ERR_OK;
469 }
470 
RebootDevice(const std::string & reason)471 void PowerMgrService::RebootDevice(const std::string& reason)
472 {
473     std::lock_guard lock(mutex_);
474     pid_t pid = IPCSkeleton::GetCallingPid();
475     auto uid = IPCSkeleton::GetCallingUid();
476     if (reason.find("updater") != std::string::npos) {
477         if (!Permission::CheckCallingPermission("ohos.permission.REBOOT_RECOVERY")) {
478             POWER_HILOGE(MODULE_SERVICE,
479                 "%{public}s Request failed, %{public}d permission check fail",
480                 __func__, pid);
481             return;
482         }
483     } else {
484         if (!Permission::CheckIsSystemAppByUid(uid)
485             && !Permission::CheckCallingPermission("ohos.permission.REBOOT")) {
486             POWER_HILOGE(MODULE_SERVICE,
487                 "%{public}s Request failed, %{public}d permission check fail",
488                 __func__, pid);
489             return;
490         }
491     }
492     POWER_HILOGI(MODULE_SERVICE, "Cancel auto sleep timer");
493     powerStateMachine_->CancelDelayTimer(
494         PowermsEventHandler::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
495     powerStateMachine_->CancelDelayTimer(
496         PowermsEventHandler::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
497     powerStateMachine_->CancelDelayTimer(
498         PowermsEventHandler::CHECK_USER_ACTIVITY_SLEEP_TIMEOUT_MSG);
499 
500     POWER_HILOGI(MODULE_SERVICE, "PID: %{public}d Call %{public}s !", pid, __func__);
501     shutdownService_.Reboot(reason);
502 }
503 
ShutDownDevice(const std::string & reason)504 void PowerMgrService::ShutDownDevice(const std::string& reason)
505 {
506     std::lock_guard lock(mutex_);
507     pid_t pid  = IPCSkeleton::GetCallingPid();
508     auto uid = IPCSkeleton::GetCallingUid();
509     if (!Permission::CheckIsSystemAppByUid(uid)
510         && !Permission::CheckCallingPermission("ohos.permission.REBOOT")) {
511         POWER_HILOGE(MODULE_SERVICE,
512             "%{public}s Request failed, %{public}d permission check fail",
513             __func__, pid);
514         return;
515     }
516     POWER_HILOGI(MODULE_SERVICE, "Cancel auto sleep timer");
517     powerStateMachine_->CancelDelayTimer(
518         PowermsEventHandler::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
519     powerStateMachine_->CancelDelayTimer(
520         PowermsEventHandler::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
521     powerStateMachine_->CancelDelayTimer(
522         PowermsEventHandler::CHECK_USER_ACTIVITY_SLEEP_TIMEOUT_MSG);
523 
524     POWER_HILOGI(MODULE_SERVICE, "PID: %{public}d Call %{public}s !", pid, __func__);
525     shutdownService_.Shutdown(reason);
526 }
527 
SuspendDevice(int64_t callTimeMs,SuspendDeviceType reason,bool suspendImmed)528 void PowerMgrService::SuspendDevice(int64_t callTimeMs,
529     SuspendDeviceType reason,
530     bool suspendImmed)
531 {
532     std::lock_guard lock(mutex_);
533     auto uid = IPCSkeleton::GetCallingUid();
534     if (!Permission::CheckIsSystemAppByUid(uid)) {
535         POWER_HILOGE(MODULE_SERVICE,
536             "%{public}s Request failed, illegal calling uid %{public}d.",
537             __func__, uid);
538         return;
539     }
540     if (shutdownService_.IsShuttingDown()) {
541         POWER_HILOGI(MODULE_SERVICE, "System is shutting down, can't suspend");
542         return;
543     }
544     pid_t pid = IPCSkeleton::GetCallingPid();
545     powerStateMachine_->SuspendDeviceInner(pid, callTimeMs, reason, suspendImmed);
546 }
547 
WakeupDevice(int64_t callTimeMs,WakeupDeviceType reason,const std::string & details)548 void PowerMgrService::WakeupDevice(int64_t callTimeMs,
549     WakeupDeviceType reason,
550     const std::string& details)
551 {
552     std::lock_guard lock(mutex_);
553     auto uid = IPCSkeleton::GetCallingUid();
554     if (!Permission::CheckIsSystemAppByUid(uid)) {
555         POWER_HILOGE(MODULE_SERVICE,
556             "%{public}s Request failed, illegal calling uid %{public}d.",
557             __func__, uid);
558         return;
559     }
560     pid_t pid = IPCSkeleton::GetCallingPid();
561     powerStateMachine_->WakeupDeviceInner(pid, callTimeMs, reason, details, "OHOS");
562 }
563 
RefreshActivity(int64_t callTimeMs,UserActivityType type,bool needChangeBacklight)564 void PowerMgrService::RefreshActivity(int64_t callTimeMs,
565     UserActivityType type,
566     bool needChangeBacklight)
567 {
568     std::lock_guard lock(mutex_);
569     auto uid = IPCSkeleton::GetCallingUid();
570     if (!Permission::CheckIsSystemAppByUid(uid)
571         && !Permission::CheckCallingPermission("ohos.permission.REFRESH_USER_ACTION")) {
572         POWER_HILOGE(MODULE_SERVICE,
573             "%{public}s Request failed, illegal calling uid %{public}d.",
574             __func__, uid);
575         return;
576     }
577     pid_t pid = IPCSkeleton::GetCallingPid();
578     powerStateMachine_->RefreshActivityInner(pid, callTimeMs, type, needChangeBacklight);
579 }
580 
GetState()581 PowerState PowerMgrService::GetState()
582 {
583     std::lock_guard lock(mutex_);
584     POWER_HILOGI(MODULE_SERVICE, "GetState");
585     return powerStateMachine_->GetState();
586 }
587 
IsScreenOn()588 bool PowerMgrService::IsScreenOn()
589 {
590     std::lock_guard lock(mutex_);
591     POWER_HILOGI(MODULE_SERVICE, "IsScreenOn");
592     return powerStateMachine_->IsScreenOn();
593 }
594 
ForceSuspendDevice(int64_t callTimeMs)595 bool PowerMgrService::ForceSuspendDevice(int64_t callTimeMs)
596 {
597     std::lock_guard lock(mutex_);
598     auto uid = IPCSkeleton::GetCallingUid();
599     if (!Permission::CheckIsSystemAppByUid(uid)) {
600         POWER_HILOGE(MODULE_SERVICE,
601             "%{public}s Request failed, illegal calling uid %{public}d.",
602             __func__, uid);
603         return false;
604     }
605     if (shutdownService_.IsShuttingDown()) {
606         POWER_HILOGI(MODULE_SERVICE, "System is shutting down, can't force suspend");
607         return false;
608     }
609     pid_t pid = IPCSkeleton::GetCallingPid();
610     return powerStateMachine_->ForceSuspendDeviceInner(pid, callTimeMs);
611 }
612 
FillUserIPCInfo(UserIPCInfo & userIPCinfo)613 inline void PowerMgrService::FillUserIPCInfo(UserIPCInfo &userIPCinfo)
614 {
615     userIPCinfo.pid = IPCSkeleton::GetCallingPid();
616     userIPCinfo.uid = IPCSkeleton::GetCallingUid();
617 }
618 
CreateRunningLock(const sptr<IRemoteObject> & token,const RunningLockInfo & runningLockInfo)619 void PowerMgrService::CreateRunningLock(const sptr<IRemoteObject>& token,
620     const RunningLockInfo& runningLockInfo)
621 {
622     std::lock_guard lock(lockMutex_);
623     auto uid = IPCSkeleton::GetCallingUid();
624     if (!Permission::CheckIsSystemAppByUid(uid)
625         && !Permission::CheckCallingPermission("ohos.permission.RUNNING_LOCK")) {
626         POWER_HILOGE(MODULE_SERVICE,
627             "%{public}s Request failed, %{public}d permission check fail",
628             __func__, uid);
629         return;
630     }
631 
632     POWER_HILOGI(MODULE_SERVICE, "%{public}s :name = %s, type = %d", __func__,
633         runningLockInfo.name.c_str(), runningLockInfo.type);
634 
635     UserIPCInfo userIPCInfo;
636     FillUserIPCInfo(userIPCInfo);
637     runningLockMgr_->CreateRunningLock(token, runningLockInfo, userIPCInfo);
638 }
639 
ReleaseRunningLock(const sptr<IRemoteObject> & token)640 void PowerMgrService::ReleaseRunningLock(const sptr<IRemoteObject>& token)
641 {
642     std::lock_guard lock(lockMutex_);
643     auto uid = IPCSkeleton::GetCallingUid();
644     if (!Permission::CheckIsSystemAppByUid(uid)
645         && !Permission::CheckCallingPermission("ohos.permission.RUNNING_LOCK")) {
646         POWER_HILOGE(MODULE_SERVICE,
647             "%{public}s Request failed, %{public}d permission check fail",
648             __func__, uid);
649         return;
650     }
651 
652     POWER_HILOGI(MODULE_SERVICE, "%{public}s called.", __func__);
653     runningLockMgr_->ReleaseLock(token);
654 }
655 
IsRunningLockTypeSupported(uint32_t type)656 bool PowerMgrService::IsRunningLockTypeSupported(uint32_t type)
657 {
658     std::lock_guard lock(lockMutex_);
659     if (type >= static_cast<uint32_t>(RunningLockType::RUNNINGLOCK_BUTT)) {
660         return false;
661     }
662     return true;
663 }
664 
Lock(const sptr<IRemoteObject> & token,const RunningLockInfo & runningLockInfo,uint32_t timeOutMS)665 void PowerMgrService::Lock(const sptr<IRemoteObject>& token,
666     const RunningLockInfo& runningLockInfo,
667     uint32_t timeOutMS)
668 {
669     std::lock_guard lock(lockMutex_);
670     auto uid = IPCSkeleton::GetCallingUid();
671     if (!Permission::CheckIsSystemAppByUid(uid)
672         && !Permission::CheckCallingPermission("ohos.permission.RUNNING_LOCK")) {
673         POWER_HILOGE(MODULE_SERVICE,
674             "%{public}s Request failed, %{public}d permission check fail",
675             __func__, uid);
676         return;
677     }
678 
679     POWER_HILOGI(MODULE_SERVICE,
680         "%{public}s :timeOutMS = %{public}d, name = %{public}s, type = %{public}d",
681         __func__,
682         timeOutMS,
683         runningLockInfo.name.c_str(),
684         runningLockInfo.type);
685 
686     UserIPCInfo userIPCInfo;
687     FillUserIPCInfo(userIPCInfo);
688     runningLockMgr_->Lock(token, runningLockInfo, userIPCInfo, timeOutMS);
689 }
690 
UnLock(const sptr<IRemoteObject> & token)691 void PowerMgrService::UnLock(const sptr<IRemoteObject>& token)
692 {
693     std::lock_guard lock(lockMutex_);
694     auto uid = IPCSkeleton::GetCallingUid();
695     if (!Permission::CheckIsSystemAppByUid(uid)
696         && !Permission::CheckCallingPermission("ohos.permission.RUNNING_LOCK")) {
697         POWER_HILOGE(MODULE_SERVICE,
698             "%{public}s Request failed, %{public}d permission check fail",
699             __func__, uid);
700         return;
701     }
702 
703     POWER_HILOGI(MODULE_SERVICE, "%{public}s called.", __func__);
704     runningLockMgr_->UnLock(token);
705 }
706 
ForceUnLock(const sptr<IRemoteObject> & token)707 void PowerMgrService::ForceUnLock(const sptr<IRemoteObject>& token)
708 {
709     std::lock_guard lock(lockMutex_);
710     POWER_HILOGI(MODULE_SERVICE, "%{public}s called.", __func__);
711     runningLockMgr_->UnLock(token);
712     runningLockMgr_->ReleaseLock(token);
713 }
714 
IsUsed(const sptr<IRemoteObject> & token)715 bool PowerMgrService::IsUsed(const sptr<IRemoteObject>& token)
716 {
717     std::lock_guard lock(lockMutex_);
718     POWER_HILOGI(MODULE_SERVICE, "%{public}s called.", __func__);
719     return runningLockMgr_->IsUsed(token);
720 }
721 
NotifyRunningLockChanged(bool isUnLock)722 void PowerMgrService::NotifyRunningLockChanged(bool isUnLock)
723 {
724     if (isUnLock) {
725         // When unlock we try to suspend
726         if (!runningLockMgr_->ExistValidRunningLock()
727             && !powerStateMachine_->IsScreenOn()) {
728             // runninglock is empty and Screen is off,
729             // so we try to suspend device from Z side.
730             POWER_HILOGI(MODULE_SERVICE,
731                 "%{public}s :RunningLock is empty, try to suspend from Z Side!",
732                 __func__);
733             powerStateMachine_->SuspendDeviceInner(getpid(), GetTickCount(),
734                 SuspendDeviceType::SUSPEND_DEVICE_REASON_MIN, true, true);
735         }
736     }
737 }
738 
SetWorkTriggerList(const sptr<IRemoteObject> & token,const WorkTriggerList & workTriggerList)739 void PowerMgrService::SetWorkTriggerList(const sptr<IRemoteObject>& token,
740     const WorkTriggerList& workTriggerList)
741 {
742     std::lock_guard lock(lockMutex_);
743     auto uid = IPCSkeleton::GetCallingUid();
744     if (!Permission::CheckIsSystemAppByUid(uid)
745         && !Permission::CheckCallingPermission("ohos.permission.RUNNING_LOCK")) {
746         POWER_HILOGE(MODULE_SERVICE,
747             "%{public}s Request failed, %{public}d permission check fail",
748             __func__, uid);
749         return;
750     }
751 
752     POWER_HILOGI(MODULE_SERVICE, "%{public}s called.", __func__);
753     runningLockMgr_->SetWorkTriggerList(token, workTriggerList);
754 }
755 
ProxyRunningLock(bool proxyLock,pid_t uid,pid_t pid)756 void PowerMgrService::ProxyRunningLock(bool proxyLock, pid_t uid, pid_t pid)
757 {
758     std::lock_guard lock(lockMutex_);
759     auto calllingUid = IPCSkeleton::GetCallingUid();
760     if (!Permission::CheckIsSystemAppByUid(uid)) {
761         POWER_HILOGE(MODULE_SERVICE,
762             "%{public}s Request failed, illegal calling uid %{public}d.",
763             __func__,
764             calllingUid);
765         return;
766     }
767     runningLockMgr_->ProxyRunningLock(proxyLock, uid, pid);
768 }
769 
RegisterPowerStateCallback(const sptr<IPowerStateCallback> & callback)770 void PowerMgrService::RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
771 {
772     std::lock_guard lock(mutex_);
773     auto uid = IPCSkeleton::GetCallingUid();
774     if (!Permission::CheckIsSystemAppByUid(uid)
775         && !Permission::CheckCallingPermission("ohos.permission.POWER_MANAGER")) {
776         POWER_HILOGE(MODULE_SERVICE,
777             "%{public}s Request failed, %{public}d permission check fail",
778             __func__, uid);
779         return;
780     }
781     powerStateMachine_->RegisterPowerStateCallback(callback);
782 }
783 
UnRegisterPowerStateCallback(const sptr<IPowerStateCallback> & callback)784 void PowerMgrService::UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
785 {
786     std::lock_guard lock(mutex_);
787     auto uid = IPCSkeleton::GetCallingUid();
788     if (!Permission::CheckIsSystemAppByUid(uid)
789         && !Permission::CheckCallingPermission("ohos.permission.POWER_MANAGER")) {
790         POWER_HILOGE(MODULE_SERVICE,
791             "%{public}s Request failed, %{public}d permission check fail",
792             __func__, uid);
793         return;
794     }
795     powerStateMachine_->UnRegisterPowerStateCallback(callback);
796 }
797 
RegisterShutdownCallback(IShutdownCallback::ShutdownPriority priority,const sptr<IShutdownCallback> & callback)798 void PowerMgrService::RegisterShutdownCallback(IShutdownCallback::ShutdownPriority priority,
799     const sptr<IShutdownCallback>& callback)
800 {
801     std::lock_guard lock(mutex_);
802     auto uid = IPCSkeleton::GetCallingUid();
803     if (!Permission::CheckIsSystemAppByUid(uid)) {
804         POWER_HILOGE(MODULE_SERVICE, "Register failed, %{public}d fail", uid);
805         return;
806     }
807     POWER_HILOGE(MODULE_SERVICE, "Register shutdown callback: %{public}d", uid);
808     shutdownService_.AddShutdownCallback(priority, callback);
809 }
810 
UnRegisterShutdownCallback(const sptr<IShutdownCallback> & callback)811 void PowerMgrService::UnRegisterShutdownCallback(const sptr<IShutdownCallback>& callback)
812 {
813     std::lock_guard lock(mutex_);
814     auto uid = IPCSkeleton::GetCallingUid();
815     if (!Permission::CheckIsSystemAppByUid(uid)) {
816         POWER_HILOGE(MODULE_SERVICE, "UnRegister failed, %{public}d fail", uid);
817         return;
818     }
819     POWER_HILOGE(MODULE_SERVICE, "UnRegister shutdown callback: %{public}d", uid);
820     shutdownService_.DelShutdownCallback(callback);
821 }
822 
RegisterPowerModeCallback(const sptr<IPowerModeCallback> & callback)823 void PowerMgrService::RegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback)
824 {
825     std::lock_guard lock(mutex_);
826     auto uid = IPCSkeleton::GetCallingUid();
827     if (!Permission::CheckIsSystemAppByUid(uid)) {
828         POWER_HILOGE(MODULE_SERVICE, "Register failed, %{public}d fail", uid);
829         return;
830     }
831     POWER_HILOGE(MODULE_SERVICE, "Register power mode callback: %{public}d", uid);
832     powerModeModule_.AddPowerModeCallback(callback);
833 }
834 
UnRegisterPowerModeCallback(const sptr<IPowerModeCallback> & callback)835 void PowerMgrService::UnRegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback)
836 {
837     std::lock_guard lock(mutex_);
838     auto uid = IPCSkeleton::GetCallingUid();
839     if (!Permission::CheckIsSystemAppByUid(uid)) {
840         POWER_HILOGE(MODULE_SERVICE, "UnRegister failed, %{public}d fail", uid);
841         return;
842     }
843     POWER_HILOGE(MODULE_SERVICE, "UnRegister power mode callback: %{public}d", uid);
844     powerModeModule_.DelPowerModeCallback(callback);
845 }
846 
SetDisplaySuspend(bool enable)847 void PowerMgrService::SetDisplaySuspend(bool enable)
848 {
849     std::lock_guard lock(mutex_);
850     auto uid = IPCSkeleton::GetCallingUid();
851     if (!Permission::CheckIsSystemAppByUid(uid)) {
852         POWER_HILOGE(MODULE_SERVICE, "SetDisplaySuspend failed, %{public}d fail", uid);
853         return;
854     }
855     powerStateMachine_->SetDisplaySuspend(enable);
856 }
857 
SetDeviceMode(const uint32_t & mode)858 void PowerMgrService::SetDeviceMode(const uint32_t& mode)
859 {
860     std::lock_guard lock(mutex_);
861     pid_t pid = IPCSkeleton::GetCallingPid();
862     auto uid = IPCSkeleton::GetCallingUid();
863     POWER_HILOGI(MODULE_SERVICE, "PID: %{public}d Call %{public}s !", pid, __func__);
864     if (!Permission::CheckIsSystemAppByUid(uid)
865         && !Permission::CheckCallingPermission("ohos.permission.POWER_OPTIMIZATION")) {
866         POWER_HILOGE(MODULE_SERVICE,
867             "%{public}s Request failed, %{public}d permission check fail",
868             __func__, uid);
869         return;
870     }
871     powerModeModule_.SetModeItem(mode);
872 }
873 
GetDeviceMode()874 uint32_t PowerMgrService::GetDeviceMode()
875 {
876     std::lock_guard lock(mutex_);
877     pid_t pid = IPCSkeleton::GetCallingPid();
878     POWER_HILOGI(MODULE_SERVICE, "PID: %{public}d Call %{public}s !", pid, __func__);
879     return powerModeModule_.GetModeItem();
880 }
881 
ShellDump(const std::vector<std::string> & args,uint32_t argc)882 std::string PowerMgrService::ShellDump(const std::vector<std::string>& args, uint32_t argc)
883 {
884     std::lock_guard lock(mutex_);
885     pid_t pid = IPCSkeleton::GetCallingPid();
886     POWER_HILOGI(MODULE_SERVICE, "PID: %{public}d Call %{public}s !", pid, __func__);
887 
888     std::string result;
889     bool ret = PowerMgrDumper::Dump(args, result);
890     POWER_HILOGI(MODULE_SERVICE, "PowerMgrDumper :%{public}d", ret);
891     return result;
892 }
893 
GetDisplayPosition(int32_t & offsetX,int32_t & offsetY,int32_t & width,int32_t & height,bool & wideScreen)894 void PowerMgrService::GetDisplayPosition(
895     int32_t& offsetX, int32_t& offsetY, int32_t& width, int32_t& height, bool& wideScreen)
896 {
897     wideScreen = true;
898     auto display = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
899     if (display == nullptr) {
900         POWER_HILOGI(MODULE_SERVICE, "dialog GetDefaultDisplay fail, try again.");
901         display = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
902     }
903 
904     if (display != nullptr) {
905         POWER_HILOGI(MODULE_SERVICE, "display size: %{public}d x %{public}d",
906             display->GetWidth(), display->GetHeight());
907         if (display->GetWidth() < display->GetHeight()) {
908             POWER_HILOGI(MODULE_SERVICE, "share dialog narrow.");
909             const int NARROW_WIDTH_N = 3;
910             const int NARROW_WIDTH_D = 4;
911             const int NARROW_HEIGHT_RATE = 8;
912             wideScreen = false;
913             width = display->GetWidth() * NARROW_WIDTH_N / NARROW_WIDTH_D;
914             height = display->GetHeight() / NARROW_HEIGHT_RATE;
915         } else {
916             POWER_HILOGI(MODULE_SERVICE, "share dialog wide.");
917             const int NARROW_WIDTH_N = 1;
918             const int NARROW_WIDTH_D = 3;
919             const int NARROW_HEIGHT_RATE = 6;
920             wideScreen = true;
921             width = display->GetWidth() * NARROW_WIDTH_N / NARROW_WIDTH_D;
922             height = display->GetHeight() / NARROW_HEIGHT_RATE;
923         }
924         offsetX = (display->GetWidth() - width) / UI_HALF;
925         offsetY = display->GetHeight() - height - UI_DEFAULT_BUTTOM_CLIP;
926     } else {
927         POWER_HILOGI(MODULE_SERVICE, "dialog get display fail, use default wide.");
928         wideScreen = false;
929         width = UI_DIALOG_POWER_WIDTH_NARROW;
930         height = UI_DIALOG_POWER_HEIGHT_NARROW;
931         offsetX = (UI_DEFAULT_WIDTH - width) / UI_HALF;
932         offsetY = UI_DEFAULT_HEIGHT - height - UI_DEFAULT_BUTTOM_CLIP;
933     }
934     POWER_HILOGI(MODULE_SERVICE, "GetDisplayPosition: %{public}d, %{public}d (%{public}d x %{public}d)",
935         offsetX, offsetY, width, height);
936 }
937 } // namespace PowerMgr
938 } // namespace OHOS
939