• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 "wakeup_controller.h"
17 
18 #include <datetime_ex.h>
19 #ifdef POWER_MANAGER_ENABLE_EXTERNAL_SCREEN_MANAGEMENT
20 #include <display_manager_lite.h>
21 #endif
22 #include <dlfcn.h>
23 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
24 #include <hisysevent.h>
25 #endif
26 #include <cJSON.h>
27 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
28 #include <input_manager.h>
29 #endif
30 #include <ipc_skeleton.h>
31 #include <securec.h>
32 #include "permission.h"
33 #include "power_cjson_utils.h"
34 #include "power_errors.h"
35 #include "power_log.h"
36 #include "power_mgr_service.h"
37 #include "power_state_callback_stub.h"
38 #include "power_utils.h"
39 #include "setting_helper.h"
40 #include "suspend_controller.h"
41 #include "system_suspend_controller.h"
42 #include "customized_screen_event_rules.h"
43 #include "singleton.h"
44 
45 namespace OHOS {
46 namespace PowerMgr {
47 using namespace OHOS::MMI;
48 namespace {
49 sptr<SettingObserver> g_wakeupSourcesKeyObserver = nullptr;
50 #ifdef POWER_DOUBLECLICK_ENABLE
51 const int32_t ERR_FAILED = -1;
52 #endif
53 constexpr int32_t EVENT_INTERVAL_MS = 1000;
54 constexpr int32_t WAKEUP_LOCK_TIMEOUT_MS = 5000;
55 constexpr int32_t COLLABORATION_REMOTE_DEVICE_ID = 0xAAAAAAFF;
56 constexpr int32_t OTHER_SYSTEM_DEVICE_ID = 0xAAAAAAFE;
57 }
58 std::mutex WakeupController::sourceUpdateMutex_;
59 
60 /** WakeupController Implement */
WakeupController(std::shared_ptr<PowerStateMachine> & stateMachine)61 WakeupController::WakeupController(std::shared_ptr<PowerStateMachine>& stateMachine)
62 {
63     stateMachine_ = stateMachine;
64 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
65     RegisterMonitor(PowerState::AWAKE);
66 #endif
67     eventHandleMap_.emplace(WakeupDeviceType::WAKEUP_DEVICE_KEYBOARD, 0);
68     eventHandleMap_.emplace(WakeupDeviceType::WAKEUP_DEVICE_MOUSE, 0);
69     eventHandleMap_.emplace(WakeupDeviceType::WAKEUP_DEVICE_TOUCHPAD, 0);
70     eventHandleMap_.emplace(WakeupDeviceType::WAKEUP_DEVICE_PEN, 0);
71     eventHandleMap_.emplace(WakeupDeviceType::WAKEUP_DEVICE_TOUCH_SCREEN, 0);
72     eventHandleMap_.emplace(WakeupDeviceType::WAKEUP_DEVICE_SINGLE_CLICK, 0);
73 }
74 
~WakeupController()75 WakeupController::~WakeupController()
76 {
77 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
78     InputManager* inputManager = InputManager::GetInstance();
79     if (monitorId_ >= 0) {
80         inputManager->UnsubscribeInputActive(monitorId_);
81     }
82 #endif
83     UnregisterSettingsObserver();
84 }
85 
RegisterMonitor(PowerState state)86 void WakeupController::RegisterMonitor(PowerState state)
87 {
88 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
89     constexpr int32_t PARAM_ZERO = 0;
90     static PowerState curState = PowerState::UNKNOWN;
91     POWER_HILOGD(FEATURE_WAKEUP, "RegisterMonitor state: %{public}d -> %{public}d", static_cast<int32_t>(curState),
92         static_cast<int32_t>(state));
93     if (state != PowerState::AWAKE && state != PowerState::INACTIVE) {
94         POWER_HILOGE(FEATURE_WAKEUP, "not setting awake or inactive, return");
95         return;
96     }
97     std::lock_guard lock(mmiMonitorMutex_);
98     if (curState == state) {
99         POWER_HILOGE(FEATURE_WAKEUP, "State not changed, return");
100         return;
101     }
102     InputManager* inputManager = InputManager::GetInstance();
103     if (!inputManager) {
104         POWER_HILOGE(FEATURE_WAKEUP, "inputManager is null");
105         return;
106     }
107     if (monitorId_ >= PARAM_ZERO) {
108         POWER_HILOGE(FEATURE_WAKEUP, "removing monitor id = %{public}d", monitorId_);
109         inputManager->UnsubscribeInputActive(monitorId_);
110     }
111     std::shared_ptr<InputCallback> callback = std::make_shared<InputCallback>();
112     monitorId_ = inputManager->SubscribeInputActive(std::static_pointer_cast<IInputEventConsumer>(callback),
113         state == PowerState::AWAKE ? EVENT_INTERVAL_MS : static_cast<int64_t>(PARAM_ZERO));
114     curState = state;
115     POWER_HILOGD(FEATURE_WAKEUP, "new monitorid = %{public}d, new state = %{public}d", monitorId_,
116         static_cast<int32_t>(curState));
117 #endif
118 }
119 
Init()120 void WakeupController::Init()
121 {
122     std::lock_guard lock(monitorMutex_);
123     std::shared_ptr<WakeupSources> sources = WakeupSourceParser::ParseSources();
124     sourceList_ = sources->GetSourceList();
125     if (sourceList_.empty()) {
126         POWER_HILOGE(FEATURE_WAKEUP, "InputManager is null");
127         return;
128     }
129 
130     for (auto source = sourceList_.begin(); source != sourceList_.end(); source++) {
131         POWER_HILOGI(FEATURE_WAKEUP, "registered type=%{public}u", (*source).GetReason());
132         SetOriginSettingValue((*source));
133         std::shared_ptr<WakeupMonitor> monitor = WakeupMonitor::CreateMonitor(*source);
134         if (monitor != nullptr && monitor->Init()) {
135             POWER_HILOGI(FEATURE_WAKEUP, "monitor init success, type=%{public}u", (*source).GetReason());
136             monitor->RegisterListener([this](WakeupDeviceType reason) { this->ControlListener(reason); });
137             monitorMap_.emplace(monitor->GetReason(), monitor);
138         }
139     }
140     RegisterSettingsObserver();
141 }
142 
Cancel()143 void WakeupController::Cancel()
144 {
145     for (auto monitor = monitorMap_.begin(); monitor != monitorMap_.end(); monitor++) {
146         monitor->second->Cancel();
147     }
148     monitorMap_.clear();
149 }
150 
RegisterSettingsObserver()151 void WakeupController::RegisterSettingsObserver()
152 {
153     if (g_wakeupSourcesKeyObserver) {
154         POWER_HILOGE(FEATURE_POWER_STATE, "wakeup sources key observer is already registered");
155         return;
156     }
157     SettingObserver::UpdateFunc updateFunc = [&](const std::string&) {
158         std::lock_guard lock(monitorMutex_);
159         POWER_HILOGI(COMP_SVC, "start setting string update");
160         std::string jsonStr = SettingHelper::GetSettingWakeupSources();
161         std::shared_ptr<WakeupSources> sources = WakeupSourceParser::ParseSources(jsonStr);
162         if (sources->GetParseErrorFlag()) {
163             POWER_HILOGI(FEATURE_WAKEUP, "Parse failed, call GetWakeupSourcesByConfig again");
164             sources = WakeupSourceParser::ParseSources(WakeupSourceParser::GetWakeupSourcesByConfig());
165         }
166         std::vector<WakeupSource> updateSourceList = sources->GetSourceList();
167         if (updateSourceList.size() == 0) {
168             return;
169         }
170         sourceList_ = updateSourceList;
171         POWER_HILOGI(COMP_SVC, "start updateListener");
172         Cancel();
173         uint32_t id = 0;
174         for (auto source = sourceList_.begin(); source != sourceList_.end(); source++, id++) {
175             std::shared_ptr<WakeupMonitor> monitor = WakeupMonitor::CreateMonitor(*source);
176             POWER_HILOGI(FEATURE_WAKEUP, "UpdateFunc CreateMonitor[%{public}u] reason=%{public}d",
177                 id, source->GetReason());
178             if (monitor != nullptr && monitor->Init()) {
179                 monitor->RegisterListener([this](WakeupDeviceType reason) { this->ControlListener(reason); });
180                 monitorMap_.emplace(monitor->GetReason(), monitor);
181             }
182         }
183     };
184     g_wakeupSourcesKeyObserver = SettingHelper::RegisterSettingWakeupSourcesObserver(updateFunc);
185     POWER_HILOGI(FEATURE_POWER_STATE, "register setting observer fin");
186 }
187 
UnregisterSettingsObserver()188 void WakeupController::UnregisterSettingsObserver()
189 {
190     if (g_wakeupSourcesKeyObserver) {
191         SettingHelper::UnregisterSettingObserver(g_wakeupSourcesKeyObserver);
192         g_wakeupSourcesKeyObserver = nullptr;
193     }
194 }
195 
SetOriginSettingValue(WakeupSource & source)196 void WakeupController::SetOriginSettingValue(WakeupSource& source)
197 {
198 #ifdef POWER_DOUBLECLICK_ENABLE
199     if (source.GetReason() == WakeupDeviceType::WAKEUP_DEVICE_DOUBLE_CLICK) {
200         if (SettingHelper::IsWakeupDoubleSettingValid() == false) {
201             POWER_HILOGI(COMP_SVC, "the origin doubleClick_enable is: %{public}d", source.IsEnable());
202             SettingHelper::SetSettingWakeupDouble(source.IsEnable());
203             SetWakeupDoubleClickSensor(source.IsEnable());
204             return;
205         }
206 
207         auto enable = SettingHelper::GetSettingWakeupDouble();
208         SetWakeupDoubleClickSensor(enable);
209     }
210 #endif
211 #ifdef POWER_PICKUP_ENABLE
212     if (source.GetReason() == WakeupDeviceType::WAKEUP_DEVICE_PICKUP) {
213         if (!SettingHelper::IsWakeupPickupSettingValid()) {
214             POWER_HILOGI(FEATURE_WAKEUP, "GetReason_WAKEUP_DEVICE_PICKUP,source enable=%{public}d", source.IsEnable());
215             SettingHelper::SetSettingWakeupPickup(source.IsEnable());
216             PickupConnectMotionConfig(source.IsEnable());
217             return;
218         }
219 
220         auto enable = SettingHelper::GetSettingWakeupPickup();
221         PickupConnectMotionConfig(enable);
222     }
223 #endif
224 }
225 #ifdef POWER_DOUBLECLICK_ENABLE
ChangeWakeupSourceConfig(bool updateEnable)226 void WakeupController::ChangeWakeupSourceConfig(bool updateEnable)
227 {
228     std::lock_guard lock(sourceUpdateMutex_);
229     std::string jsonStr = SettingHelper::GetSettingWakeupSources();
230     if (jsonStr.empty()) {
231         POWER_HILOGE(COMP_SVC, "there is no such configuration file available");
232         return;
233     }
234     POWER_HILOGI(COMP_SVC, "the origin ccmJson is: %{public}s", jsonStr.c_str());
235     WakeupParseJsonConfig(updateEnable, jsonStr);
236 }
237 
WakeupParseJsonConfig(bool updateEnable,std::string & jsonStr)238 void WakeupController::WakeupParseJsonConfig(bool updateEnable, std::string& jsonStr)
239 {
240     cJSON* root = cJSON_Parse(jsonStr.c_str());
241     if (!root) {
242         POWER_HILOGE(COMP_SVC, "json parse error");
243         return;
244     }
245     if (!cJSON_IsObject(root)) {
246         POWER_HILOGW(COMP_SVC, "json root is not an object");
247         cJSON_Delete(root);
248         return;
249     }
250     cJSON* touchscreenNode = cJSON_GetObjectItemCaseSensitive(root, "touchscreen");
251     if (!PowerMgrJsonUtils::IsValidJsonObject(touchscreenNode)) {
252         POWER_HILOGE(COMP_SVC, "this touchscreenNode is empty");
253         cJSON_Delete(root);
254         return;
255     }
256     cJSON* enableNode = cJSON_GetObjectItemCaseSensitive(touchscreenNode, "enable");
257     if (!PowerMgrJsonUtils::IsValidJsonBool(enableNode)) {
258         POWER_HILOGE(COMP_SVC, "the touchscreenNode enable value is invalid");
259         cJSON_Delete(root);
260         return;
261     }
262     bool originEnable = cJSON_IsTrue(enableNode);
263     if (originEnable == updateEnable) {
264         POWER_HILOGI(COMP_SVC, "no need change jsonConfig value");
265         cJSON_Delete(root);
266         return;
267     }
268     cJSON_SetBoolValue(enableNode, updateEnable ? 1 : 0);
269     char* jsonUpdatedStr = cJSON_Print(root);
270     if (!jsonUpdatedStr) {
271         POWER_HILOGI(COMP_SVC, "Failed to print cJSON to string");
272         cJSON_Delete(root);
273         return;
274     }
275     POWER_HILOGI(COMP_SVC, "the new doubleJsonConfig is: %{public}s", jsonUpdatedStr);
276     std::string jsonConfig = std::string(jsonUpdatedStr);
277     SettingHelper::SetSettingWakeupSources(jsonConfig);
278     cJSON_free(jsonUpdatedStr);
279     cJSON_Delete(root);
280 }
281 
282 static const char* POWER_MANAGER_EXT_PATH = "libpower_manager_ext.z.so";
283 static const char* SET_WAKEUP_DOUBLE_CLICK_SENSOR = "SetWakeupDoubleClickSensor";
284 typedef int32_t(*Func)(bool);
SetWakeupDoubleClickSensor(bool enable)285 int32_t WakeupController::SetWakeupDoubleClickSensor(bool enable)
286 {
287     POWER_HILOGI(COMP_SVC, "enter SetWakeupDoubleClickSensor");
288     void *handler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
289     if (handler == nullptr) {
290         POWER_HILOGE(COMP_SVC, "Dlopen failed, reason : %{public}s", dlerror());
291         return ERR_FAILED;
292     }
293 
294     Func PowerDoubleClickFlag = (Func)dlsym(handler, SET_WAKEUP_DOUBLE_CLICK_SENSOR);
295     if (PowerDoubleClickFlag == nullptr) {
296         POWER_HILOGE(COMP_SVC, "find function failed, reason : %{public}s", dlerror());
297         dlclose(handler);
298         return ERR_FAILED;
299     }
300     auto resCode = PowerDoubleClickFlag(enable);
301     dlclose(handler);
302     return resCode;
303 }
304 #endif
305 #ifdef POWER_PICKUP_ENABLE
306 static const char* SET_WAKEUP_MOTION_SUBSCRIBER_CONFIG = "PickupMotionSubscriber";
307 static const char* SET_WAKEUP_MOTION_UNSUBSCRIBER_CONFIG = "PickupMotionUnsubscriber";
308 typedef void(*FuncSubscriber)();
309 typedef void(*FuncUnsubscriber)();
310 
PickupConnectMotionConfig(bool databaseSwitchValue)311 void WakeupController::PickupConnectMotionConfig(bool databaseSwitchValue)
312 {
313     POWER_HILOGI(COMP_SVC, "open enter PickupConnectMotionConfig");
314     if (databaseSwitchValue) {
315         void *subscriberHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
316         if (subscriberHandler == nullptr) {
317             POWER_HILOGE(COMP_SVC, "Dlopen failed, reason : %{public}s", dlerror());
318             return;
319         }
320         FuncSubscriber powerPickupMotionSubscriberFlag = reinterpret_cast<FuncSubscriber>(dlsym(subscriberHandler,
321             SET_WAKEUP_MOTION_SUBSCRIBER_CONFIG));
322         if (powerPickupMotionSubscriberFlag == nullptr) {
323             POWER_HILOGE(COMP_SVC, "find Subscriber function failed, reason : %{public}s", dlerror());
324             dlclose(subscriberHandler);
325             return;
326         }
327         powerPickupMotionSubscriberFlag();
328         POWER_HILOGI(COMP_SVC, "powerservice enable powerPickupMotionSubscriberFlag isSettingEnable=%{public}d",
329             databaseSwitchValue);
330         dlclose(subscriberHandler);
331         POWER_HILOGI(COMP_SVC, "open to close PickupMotionSubscriberConfig");
332     } else {
333         void *unsubscriberHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
334         if (unsubscriberHandler == nullptr) {
335             POWER_HILOGE(COMP_SVC, "Dlopen failed, reason : %{public}s", dlerror());
336             return;
337         }
338         FuncUnsubscriber powerPickupMotionUnsubscriberFlag = reinterpret_cast<FuncUnsubscriber>(dlsym(
339             unsubscriberHandler, SET_WAKEUP_MOTION_UNSUBSCRIBER_CONFIG));
340         if (powerPickupMotionUnsubscriberFlag == nullptr) {
341             POWER_HILOGE(COMP_SVC, "find Unsubscriber function failed, reason : %{public}s", dlerror());
342             dlclose(unsubscriberHandler);
343             return;
344         }
345         powerPickupMotionUnsubscriberFlag();
346         POWER_HILOGI(COMP_SVC, "powerservice disable powerPickupMotionUnsubscriberFlag isSettingEnable=%{public}d",
347             databaseSwitchValue);
348         dlclose(unsubscriberHandler);
349         POWER_HILOGI(COMP_SVC, "open to close PickupMotionSubscriberConfig");
350     }
351 }
352 
ChangePickupWakeupSourceConfig(bool updataEnable)353 void WakeupController::ChangePickupWakeupSourceConfig(bool updataEnable)
354 {
355     std::lock_guard lock(sourceUpdateMutex_);
356     std::string jsonStr = SettingHelper::GetSettingWakeupSources();
357     if (jsonStr.empty()) {
358         POWER_HILOGE(COMP_SVC, "there is no such configuration file available");
359         return;
360     }
361     PickupWakeupParseJsonConfig(updataEnable, jsonStr);
362 }
363 
PickupWakeupParseJsonConfig(bool updataEnable,std::string & jsonStr)364 void WakeupController::PickupWakeupParseJsonConfig(bool updataEnable, std::string& jsonStr)
365 {
366     POWER_HILOGI(COMP_SVC, "%{public}s(%{public}d)", __func__, updataEnable);
367     cJSON* root = cJSON_Parse(jsonStr.c_str());
368     if (!root) {
369         POWER_HILOGE(COMP_SVC, "Failed to parse json string");
370         return;
371     }
372     if (!cJSON_IsObject(root)) {
373         POWER_HILOGW(COMP_SVC, "json root is not an object");
374         cJSON_Delete(root);
375         return;
376     }
377     cJSON* pickupNode = cJSON_GetObjectItemCaseSensitive(root, "pickup");
378     if (!PowerMgrJsonUtils::IsValidJsonObject(pickupNode)) {
379         POWER_HILOGE(COMP_SVC, "this pickNode is empty");
380         cJSON_Delete(root);
381         return;
382     }
383     cJSON* enableNode = cJSON_GetObjectItemCaseSensitive(pickupNode, "enable");
384     if (!PowerMgrJsonUtils::IsValidJsonBool(enableNode)) {
385         POWER_HILOGE(COMP_SVC, "the pickupNode enable value is invalid");
386         cJSON_Delete(root);
387         return;
388     }
389     bool originEnable = cJSON_IsTrue(enableNode);
390     if (originEnable == updataEnable) {
391         POWER_HILOGI(COMP_SVC, "no need change jsonconfig_value");
392         cJSON_Delete(root);
393         return;
394     }
395     cJSON_SetBoolValue(enableNode, updataEnable ? 1 : 0);
396     char* jsonUpdatedStr = cJSON_Print(root);
397     if (!jsonUpdatedStr) {
398         POWER_HILOGI(COMP_SVC, "Failed to print cJSON to string");
399         cJSON_Delete(root);
400         return;
401     }
402     POWER_HILOGI(COMP_SVC, "the new pickupJsonConfig is: %{public}s", jsonUpdatedStr);
403     std::string jsonConfig = std::string(jsonUpdatedStr);
404     SettingHelper::SetSettingWakeupSources(jsonConfig);
405     cJSON_free(jsonUpdatedStr);
406     cJSON_Delete(root);
407 }
408 #endif
409 
ChangeLidWakeupSourceConfig(bool updataEnable)410 void WakeupController::ChangeLidWakeupSourceConfig(bool updataEnable)
411 {
412     std::lock_guard lock(sourceUpdateMutex_);
413     std::string jsonStr = SettingHelper::GetSettingWakeupSources();
414     POWER_HILOGI(FEATURE_POWER_STATE, "%{public}s", jsonStr.c_str());
415     LidWakeupParseJsonConfig(updataEnable, jsonStr);
416 }
417 
LidWakeupParseJsonConfig(bool updataEnable,std::string & jsonStr)418 void WakeupController::LidWakeupParseJsonConfig(bool updataEnable, std::string& jsonStr)
419 {
420     cJSON* root = cJSON_Parse(jsonStr.c_str());
421     if (!root) {
422         POWER_HILOGE(FEATURE_POWER_STATE, "Failed to parse json string");
423         return;
424     }
425     if (!cJSON_IsObject(root)) {
426         POWER_HILOGW(FEATURE_POWER_STATE, "json root is not an object");
427         cJSON_Delete(root);
428         return;
429     }
430     cJSON* lidNode = cJSON_GetObjectItemCaseSensitive(root, "lid");
431     if (!PowerMgrJsonUtils::IsValidJsonObject(lidNode)) {
432         POWER_HILOGE(FEATURE_POWER_STATE, "this lidNode is empty or not an object");
433         cJSON_Delete(root);
434         return;
435     }
436     bool originEnable = true;
437     cJSON* enableNode = cJSON_GetObjectItemCaseSensitive(lidNode, "enable");
438     if (PowerMgrJsonUtils::IsValidJsonBool(enableNode)) {
439         originEnable = cJSON_IsTrue(enableNode);
440     }
441     if (originEnable == updataEnable) {
442         POWER_HILOGI(FEATURE_POWER_STATE, "no need change jsonConfig value");
443         cJSON_Delete(root);
444         return;
445     }
446 
447     if (PowerMgrJsonUtils::IsValidJsonBool(enableNode)) {
448         cJSON_SetBoolValue(enableNode, updataEnable ? 1 : 0);
449     }
450     char* jsonUpdatedStr = cJSON_Print(root);
451     if (!jsonUpdatedStr) {
452         POWER_HILOGI(COMP_SVC, "Failed to print cJSON to string");
453         cJSON_Delete(root);
454         return;
455     }
456     std::string jsonConfig = std::string(jsonUpdatedStr);
457     SettingHelper::SetSettingWakeupSources(jsonConfig);
458     cJSON_free(jsonUpdatedStr);
459     cJSON_Delete(root);
460 }
461 
ExecWakeupMonitorByReason(WakeupDeviceType reason)462 void WakeupController::ExecWakeupMonitorByReason(WakeupDeviceType reason)
463 {
464     FFRTUtils::SubmitTask([this, reason] {
465         std::lock_guard lock(monitorMutex_);
466         if (monitorMap_.find(reason) != monitorMap_.end()) {
467             auto monitor = monitorMap_[reason];
468             monitor->Notify();
469         }
470     });
471 }
472 
Wakeup()473 void WakeupController::Wakeup()
474 {
475     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
476     if (pms == nullptr) {
477         POWER_HILOGE(FEATURE_WAKEUP, "get powerMgrService instance error");
478         return;
479     }
480     auto suspendController = pms->GetSuspendController();
481     if (suspendController == nullptr) {
482         POWER_HILOGE(FEATURE_WAKEUP, "get suspendController instance error");
483         return;
484     }
485     suspendController->StopSleep();
486 }
487 
SleepGuard(const sptr<PowerMgrService> & pms)488 WakeupController::SleepGuard::SleepGuard(const sptr<PowerMgrService>& pms) : pms_(pms)
489 {
490     token_ = new (std::nothrow) RunningLockTokenStub();
491     if (token_ == nullptr) {
492         POWER_HILOGE(COMP_SVC, "create runninglock token failed");
493         return;
494     }
495     RunningLockInfo info = {"SleepGuard", OHOS::PowerMgr::RunningLockType::RUNNINGLOCK_BACKGROUND_TASK};
496     pms_->CreateRunningLock(token_, info);
497     pms_->Lock(token_, WAKEUP_LOCK_TIMEOUT_MS);
498 }
499 
~SleepGuard()500 WakeupController::SleepGuard::~SleepGuard()
501 {
502     if (token_ == nullptr) {
503         POWER_HILOGE(COMP_SVC, "dtor: token_ is nullptr, direct return ");
504         return;
505     }
506     pms_->ReleaseRunningLock(token_);
507 }
508 
509 #ifdef POWER_MANAGER_WAKEUP_ACTION
IsLowCapacityWakeup(WakeupDeviceType reason)510 bool WakeupController::IsLowCapacityWakeup(WakeupDeviceType reason)
511 {
512     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
513     if (pms == nullptr) {
514         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] pms is nullptr");
515         return false;
516     }
517     auto wakeupActionController = pms->GetWakeupActionController();
518     if (wakeupActionController == nullptr) {
519         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] wakeupActionController is nullptr.");
520         return false;
521     }
522     return (reason == WakeupDeviceType::WAKEUP_DEVICE_POWER_BUTTON) &&
523         (wakeupActionController->IsLowCapacityWakeup());
524 }
525 
ProcessLowCapacityWakeup()526 void WakeupController::ProcessLowCapacityWakeup()
527 {
528     POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] processing low capacity wake up begins.");
529     if (stateMachine_->GetState() != PowerState::SLEEP) {
530         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] the current power state is not sleep.");
531         return;
532     }
533     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
534     if (pms == nullptr) {
535         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] pms is nullptr");
536         return;
537     }
538     auto wakeupActionController = pms->GetWakeupActionController();
539     if (wakeupActionController == nullptr) {
540         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] wakeupActionController is nullptr");
541         return;
542     }
543     SleepGuard sleepGuard(pms);
544     Wakeup();
545     auto suspendController = pms->GetSuspendController();
546     if (suspendController != nullptr) {
547         POWER_HILOGI(FEATURE_WAKEUP, "ControlListener TriggerSyncSleepCallback start.");
548         suspendController->TriggerSyncSleepCallback(true);
549     }
550     wakeupActionController->ExecuteByGetReason();
551 }
552 #endif
553 
HandleWakeup(const sptr<PowerMgrService> & pms,WakeupDeviceType reason)554 void WakeupController::HandleWakeup(const sptr<PowerMgrService>& pms, WakeupDeviceType reason)
555 {
556 #ifdef POWER_MANAGER_ENABLE_EXTERNAL_SCREEN_MANAGEMENT
557     if (IsPowerOnInernalScreenOnlyScene(reason)) {
558         ProcessPowerOnInternalScreenOnly(pms, reason);
559         return;
560     }
561 #endif
562 
563     pid_t pid = IPCSkeleton::GetCallingPid();
564     auto uid = IPCSkeleton::GetCallingUid();
565     POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Try to wakeup device, pid=%{public}d, uid=%{public}d", pid, uid);
566     if (stateMachine_->GetState() != PowerState::AWAKE || reason == WakeupDeviceType::WAKEUP_DEVICE_SWITCH ||
567         reason == WakeupDeviceType::WAKEUP_DEVICE_LID) {
568         SleepGuard sleepGuard(pms);
569         Wakeup();
570         SystemSuspendController::GetInstance().Wakeup();
571         POWER_HILOGI(FEATURE_WAKEUP, "wakeup Request: %{public}d", reason);
572         if (!stateMachine_->SetState(PowerState::AWAKE, stateMachine_->GetReasonByWakeType(reason), true)) {
573             POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] setstate wakeup error");
574         }
575         auto suspendController = pms->GetSuspendController();
576         if (suspendController != nullptr && stateMachine_->GetState() == PowerState::AWAKE) {
577             POWER_HILOGI(FEATURE_WAKEUP, "WakeupController::ControlListener TriggerSyncSleepCallback start.");
578             suspendController->TriggerSyncSleepCallback(true);
579         }
580 #ifdef POWER_MANAGER_ENABLE_EXTERNAL_SCREEN_MANAGEMENT
581         if (suspendController != nullptr && stateMachine_->GetExternalScreenNumber() > 0 &&
582             !stateMachine_->IsSwitchOpenByPath()) {
583             suspendController->PowerOffInternalScreen(SuspendDeviceType::SUSPEND_DEVICE_REASON_SWITCH);
584         }
585 #endif
586     } else {
587         POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] state=%{public}u no transitor", stateMachine_->GetState());
588     }
589 }
590 
ControlListener(WakeupDeviceType reason)591 void WakeupController::ControlListener(WakeupDeviceType reason)
592 {
593     std::lock_guard lock(mutex_);
594     if (!Permission::IsSystem()) {
595         return;
596     }
597 
598     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
599     if (pms == nullptr) {
600         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] get PowerMgrService instance error");
601         return;
602     }
603 
604     if (NeedToSkipCurrentWakeup(pms, reason)) {
605         return;
606     }
607 
608     HandleWakeup(pms, reason);
609 }
610 
611 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
612 /* InputCallback achieve */
isRemoteEvent(std::shared_ptr<InputEvent> event) const613 bool InputCallback::isRemoteEvent(std::shared_ptr<InputEvent> event) const
614 {
615     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
616     bool isCollaborationEvent =
617         pms && pms->IsCollaborationState() && event->GetDeviceId() == COLLABORATION_REMOTE_DEVICE_ID;
618     bool isFromOtherSource = event->GetDeviceId() == OTHER_SYSTEM_DEVICE_ID;
619     return isCollaborationEvent || isFromOtherSource;
620 }
621 
isKeyboardKeycode(int32_t keyCode) const622 bool InputCallback::isKeyboardKeycode(int32_t keyCode) const
623 {
624     if ((keyCode >= KeyEvent::KEYCODE_0 && keyCode <= KeyEvent::KEYCODE_NUMPAD_RIGHT_PAREN
625         && keyCode != KeyEvent::KEYCODE_F1)
626         || (keyCode == KeyEvent::KEYCODE_BRIGHTNESS_DOWN) // F1 hotkey
627         || (keyCode == KeyEvent::KEYCODE_BRIGHTNESS_UP) // F2 hotkey
628         || (keyCode == KeyEvent::KEYCODE_FN) // F3 hotkey
629         || (keyCode == KeyEvent::KEYCODE_VOLUME_MUTE) // F4 hotkey
630         || (keyCode == KeyEvent::KEYCODE_SOUND) // sound
631         || (keyCode == KeyEvent::KEYCODE_MUTE) // F7 hotkey
632         || (keyCode == KeyEvent::KEYCODE_SWITCHVIDEOMODE) // F8 hotkey
633         || (keyCode == KeyEvent::KEYCODE_SEARCH) // F9 hotkey
634         || (keyCode == KeyEvent::KEYCODE_ASSISTANT)) { // assistant
635         return true;
636     }
637     return false;
638 }
639 
OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const640 void InputCallback::OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const
641 {
642     if (!keyEvent) {
643         POWER_HILOGE(FEATURE_WAKEUP, "keyEvent is null");
644         return;
645     }
646     POWER_HILOGD(FEATURE_WAKEUP, "input keyEvent event received, action = %{public}d", keyEvent->GetAction());
647     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
648     if (pms == nullptr) {
649         POWER_HILOGE(FEATURE_WAKEUP, "get powerMgrService instance error");
650         return;
651     }
652     // ignores remote event
653     if (isRemoteEvent(keyEvent)) {
654         POWER_HILOGE(FEATURE_WAKEUP, "is remote event, ignore");
655         return;
656     }
657     int64_t now = static_cast<int64_t>(time(nullptr));
658     pms->RefreshActivityInner(now, UserActivityType::USER_ACTIVITY_TYPE_BUTTON, false);
659     PowerState state = pms->GetState();
660     if (state == PowerState::AWAKE || state == PowerState::FREEZE) {
661         return;
662     }
663     std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
664     if (wakeupController == nullptr) {
665         POWER_HILOGE(FEATURE_WAKEUP, "wakeupController is not init");
666         return;
667     }
668     int32_t keyCode = keyEvent->GetKeyCode();
669     WakeupDeviceType wakeupType = WakeupDeviceType::WAKEUP_DEVICE_UNKNOWN;
670     if (keyCode == KeyEvent::KEYCODE_F1) {
671         wakeupType = WakeupDeviceType::WAKEUP_DEVICE_DOUBLE_CLICK;
672     } else if (keyCode == KeyEvent::KEYCODE_STYLUS_SCREEN) {
673         wakeupType = WakeupDeviceType::WAKEUP_DEVICE_PEN;
674     } else if (keyCode == KeyEvent::KEYCODE_WAKEUP) {
675         wakeupType = WakeupDeviceType::WAKEUP_DEVICE_TP_TOUCH;
676     }
677     if (isKeyboardKeycode(keyCode)) {
678         wakeupType = WakeupDeviceType::WAKEUP_DEVICE_KEYBOARD;
679         if (wakeupController->CheckEventReciveTime(wakeupType) ||
680             keyEvent->GetKeyAction() == KeyEvent::KEY_ACTION_UP) {
681             return;
682         }
683     }
684     POWER_HILOGD(FEATURE_WAKEUP, "[UL_POWER] KeyEvent wakeupType=%{public}u, keyCode=%{public}d", wakeupType, keyCode);
685     if (wakeupType != WakeupDeviceType::WAKEUP_DEVICE_UNKNOWN) {
686         wakeupController->ExecWakeupMonitorByReason(wakeupType);
687     }
688 }
689 
TouchEventAfterScreenOn(std::shared_ptr<PointerEvent> pointerEvent,PowerState state) const690 bool InputCallback::TouchEventAfterScreenOn(std::shared_ptr<PointerEvent> pointerEvent, PowerState state) const
691 {
692     if (state == PowerState::AWAKE || state == PowerState::FREEZE) {
693 #ifdef POWER_MANAGER_ENABLE_WATCH_CUSTOMIZED_SCREEN_COMMON_EVENT_RULES
694         int32_t sourceType1 = pointerEvent->GetSourceType();
695         if (sourceType1 == PointerEvent::POINTER_ACTION_DOWN) {
696             DelayedSingleton<CustomizedScreenEventRules>::GetInstance()->NotifyOperateEventAfterScreenOn();
697         }
698 #endif
699         return true;
700     }
701     return false;
702 }
703 
DetermineWakeupDeviceType(int32_t deviceType,int32_t sourceType) const704 WakeupDeviceType InputCallback::DetermineWakeupDeviceType(int32_t deviceType, int32_t sourceType) const
705 {
706     WakeupDeviceType wakeupType = WakeupDeviceType::WAKEUP_DEVICE_UNKNOWN;
707     if (deviceType == PointerEvent::TOOL_TYPE_PEN) {
708         wakeupType = WakeupDeviceType::WAKEUP_DEVICE_PEN;
709     } else {
710         switch (sourceType) {
711             case PointerEvent::SOURCE_TYPE_MOUSE:
712                 wakeupType = WakeupDeviceType::WAKEUP_DEVICE_MOUSE;
713                 break;
714             case PointerEvent::SOURCE_TYPE_TOUCHPAD:
715                 wakeupType = WakeupDeviceType::WAKEUP_DEVICE_TOUCHPAD;
716                 break;
717             case PointerEvent::SOURCE_TYPE_TOUCHSCREEN:
718                 wakeupType = WakeupDeviceType::WAKEUP_DEVICE_SINGLE_CLICK;
719                 break;
720             default:
721                 break;
722         }
723     }
724     return wakeupType;
725 }
726 
OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const727 void InputCallback::OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const
728 {
729     if (!pointerEvent) {
730         POWER_HILOGE(FEATURE_WAKEUP, "pointerEvent is null");
731         return;
732     }
733     POWER_HILOGD(FEATURE_WAKEUP, "input pointer event received, action = %{public}d", pointerEvent->GetPointerAction());
734     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
735     if (pms == nullptr) {
736         return;
737     }
738     if (!NonWindowEvent(pointerEvent)) {
739         POWER_HILOGE(FEATURE_WAKEUP, "generated by window event, ignore");
740         return;
741     }
742     if (isRemoteEvent(pointerEvent)) {
743         POWER_HILOGE(FEATURE_WAKEUP, "is remote event, ignore");
744         return;
745     }
746     int64_t now = static_cast<int64_t>(time(nullptr));
747     pms->RefreshActivityInner(now, UserActivityType::USER_ACTIVITY_TYPE_TOUCH, false);
748     PowerState state = pms->GetState();
749     if (TouchEventAfterScreenOn(pointerEvent, state)) {
750         return;
751     }
752     std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
753     WakeupDeviceType wakeupType = WakeupDeviceType::WAKEUP_DEVICE_UNKNOWN;
754     PointerEvent::PointerItem pointerItem;
755     if (!pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
756         POWER_HILOGI(FEATURE_WAKEUP, "GetPointerItem false");
757     }
758     int32_t deviceType = pointerItem.GetToolType();
759     int32_t sourceType = pointerEvent->GetSourceType();
760     wakeupType = DetermineWakeupDeviceType(deviceType, sourceType);
761     if (wakeupController->CheckEventReciveTime(wakeupType)) {
762         return;
763     }
764     if (wakeupType != WakeupDeviceType::WAKEUP_DEVICE_UNKNOWN) {
765         POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] PointerEvent wakeupType=%{public}u", wakeupType);
766         wakeupController->ExecWakeupMonitorByReason(wakeupType);
767     }
768 }
769 
NonWindowEvent(const std::shared_ptr<PointerEvent> & pointerEvent) const770 bool InputCallback::NonWindowEvent(const std::shared_ptr<PointerEvent>& pointerEvent) const
771 {
772     auto action = pointerEvent->GetPointerAction();
773     if (action == PointerEvent::POINTER_ACTION_ENTER_WINDOW ||
774         action == PointerEvent::POINTER_ACTION_LEAVE_WINDOW ||
775         action == PointerEvent::POINTER_ACTION_PULL_IN_WINDOW ||
776         action == PointerEvent::POINTER_ACTION_PULL_OUT_WINDOW) {
777         return false;
778     }
779     return true;
780 }
781 
OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const782 void InputCallback::OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const
783 {
784     if (!axisEvent) {
785         POWER_HILOGE(FEATURE_WAKEUP, "axisEvent is null");
786         return;
787     }
788     POWER_HILOGD(FEATURE_WAKEUP, "input axisEvent event received, action = %{public}d", axisEvent->GetAction());
789     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
790     if (pms == nullptr) {
791         return;
792     }
793     int64_t now = static_cast<int64_t>(time(nullptr));
794     pms->RefreshActivityInner(now, UserActivityType::USER_ACTIVITY_TYPE_ACCESSIBILITY, false);
795 }
796 #endif
797 
CheckEventReciveTime(WakeupDeviceType wakeupType)798 bool WakeupController::CheckEventReciveTime(WakeupDeviceType wakeupType)
799 {
800     // The minimum refreshactivity interval is 100ms!!
801     std::lock_guard lock(eventHandleMutex_);
802     int64_t now = GetTickCount();
803     if (eventHandleMap_.find(wakeupType) != eventHandleMap_.end()) {
804         if ((eventHandleMap_[wakeupType] + MIN_TIME_MS_BETWEEN_MULTIMODEACTIVITIES) > now) {
805             return true;
806         }
807         eventHandleMap_[wakeupType] = now;
808         return false;
809     }
810     return false;
811 }
812 
813 #ifdef POWER_MANAGER_ENABLE_EXTERNAL_SCREEN_MANAGEMENT
PowerOnInternalScreen(WakeupDeviceType type)814 void WakeupController::PowerOnInternalScreen(WakeupDeviceType type)
815 {
816     stateMachine_->SetInternalScreenDisplayState(DisplayState::DISPLAY_ON, stateMachine_->GetReasonByWakeType(type));
817 }
818 
PowerOnAllScreens(WakeupDeviceType type)819 void WakeupController::PowerOnAllScreens(WakeupDeviceType type)
820 {
821 #ifdef POWER_MANAGER_POWER_ENABLE_S4
822     if (stateMachine_->IsHibernating()) {
823         POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Do not power all the screen while hibernating");
824         return;
825     }
826 #endif
827 
828     auto changeReason = stateMachine_->GetReasonByWakeType(type);
829     auto dmsReason = PowerUtils::GetDmsReasonByPowerReason(changeReason);
830     bool ret =
831         Rosen::ScreenManagerLite::GetInstance().SetScreenPowerForAll(Rosen::ScreenPowerState::POWER_ON, dmsReason);
832     POWER_HILOGI(FEATURE_WAKEUP, "Power on all screens, reason = %{public}u, ret = %{public}d", dmsReason, ret);
833 }
834 
IsPowerOnInernalScreenOnlyScene(WakeupDeviceType reason) const835 bool WakeupController::IsPowerOnInernalScreenOnlyScene(WakeupDeviceType reason) const
836 {
837     // switch action 0 menas only doing poweroff when closing switch
838     if (reason == WakeupDeviceType::WAKEUP_DEVICE_SWITCH && stateMachine_->GetSwitchAction() == 0 &&
839         stateMachine_->GetExternalScreenNumber() > 0 && stateMachine_->IsScreenOn()) {
840         return true;
841     }
842     return false;
843 }
844 
ProcessPowerOnInternalScreenOnly(const sptr<PowerMgrService> & pms,WakeupDeviceType reason)845 void WakeupController::ProcessPowerOnInternalScreenOnly(const sptr<PowerMgrService>& pms, WakeupDeviceType reason)
846 {
847     FFRTTask powerOnInternalScreenTask = [this, pms, reason]() {
848         POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Power on internal screen only when external screen is on");
849         PowerOnInternalScreen(reason);
850         pms->RefreshActivity(GetTickCount(), UserActivityType::USER_ACTIVITY_TYPE_SWITCH, false);
851     };
852     stateMachine_->SetDelayTimer(0, PowerStateMachine::SET_INTERNAL_SCREEN_STATE_MSG, powerOnInternalScreenTask);
853 }
854 #endif
855 
NeedToSkipCurrentWakeup(const sptr<PowerMgrService> & pms,WakeupDeviceType reason) const856 bool WakeupController::NeedToSkipCurrentWakeup(const sptr<PowerMgrService>& pms, WakeupDeviceType reason) const
857 {
858     bool skipWakeup = false;
859 #ifdef POWER_MANAGER_ENABLE_LID_CHECK
860     skipWakeup = PowerMgrService::isInLidMode_;
861 #else
862     skipWakeup = !stateMachine_->IsSwitchOpen();
863 #endif
864 #ifdef POWER_MANAGER_ENABLE_EXTERNAL_SCREEN_MANAGEMENT
865     skipWakeup = skipWakeup &&
866         (stateMachine_->GetExternalScreenNumber() <= 0 || !stateMachine_->IsOnlySecondDisplayModeSupported());
867 #endif
868     if (skipWakeup) {
869         POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Switch is closed, skip current wakeup reason: %{public}u", reason);
870 #ifdef POWER_MANAGER_ENABLE_WATCH_CUSTOMIZED_SCREEN_COMMON_EVENT_RULES
871         DelayedSingleton<CustomizedScreenEventRules>::GetInstance()->NotifyScreenOnEventAgain(reason);
872 #endif
873         return true;
874     }
875 
876 #ifdef POWER_MANAGER_POWER_ENABLE_S4
877     skipWakeup = stateMachine_->IsHibernating();
878     if (skipWakeup) {
879         POWER_HILOGI(
880             FEATURE_WAKEUP, "[UL_POWER] Device is hibernating, skip current wakeup reason: %{public}u", reason);
881         return true;
882     }
883 #endif
884 
885     skipWakeup = (pms->IsScreenOn()) && (reason != WakeupDeviceType::WAKEUP_DEVICE_SWITCH) &&
886         (reason != WakeupDeviceType::WAKEUP_DEVICE_LID);
887     if (skipWakeup) {
888         POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Screen is on, skip current wakeup reason: %{public}u", reason);
889         return true;
890     }
891 
892     return false;
893 }
894 
895 /* WakeupMonitor Implement */
896 
CreateMonitor(WakeupSource & source)897 std::shared_ptr<WakeupMonitor> WakeupMonitor::CreateMonitor(WakeupSource& source)
898 {
899     WakeupDeviceType reason = source.GetReason();
900     std::shared_ptr<WakeupMonitor> monitor = nullptr;
901     switch (reason) {
902         case WakeupDeviceType::WAKEUP_DEVICE_POWER_BUTTON:
903             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<PowerkeyWakeupMonitor>(source));
904             break;
905         case WakeupDeviceType::WAKEUP_DEVICE_MOUSE:
906             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<MousekeyWakeupMonitor>(source));
907             break;
908         case WakeupDeviceType::WAKEUP_DEVICE_KEYBOARD:
909             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<KeyboardWakeupMonitor>(source));
910             break;
911         case WakeupDeviceType::WAKEUP_DEVICE_PEN:
912             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<PenWakeupMonitor>(source));
913             break;
914         case WakeupDeviceType::WAKEUP_DEVICE_TOUCHPAD:
915             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<TouchpadWakeupMonitor>(source));
916             break;
917         case WakeupDeviceType::WAKEUP_DEVICE_SINGLE_CLICK:
918             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<SingleClickWakeupMonitor>(source));
919             break;
920         case WakeupDeviceType::WAKEUP_DEVICE_DOUBLE_CLICK:
921             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<DoubleClickWakeupMonitor>(source));
922             break;
923         case WakeupDeviceType::WAKEUP_DEVICE_LID:
924             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<LidWakeupMonitor>(source));
925             break;
926         case WakeupDeviceType::WAKEUP_DEVICE_SWITCH:
927             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<SwitchWakeupMonitor>(source));
928             break;
929         case WakeupDeviceType::WAKEUP_DEVICE_PICKUP:
930             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<PickupWakeupMonitor>(source));
931             break;
932         case WakeupDeviceType::WAKEUP_DEVICE_TP_TOUCH:
933             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<TPTouchWakeupMonitor>(source));
934             break;
935         default:
936             POWER_HILOGE(FEATURE_WAKEUP, "CreateMonitor : Invalid reason=%{public}d", reason);
937             break;
938     }
939     return monitor;
940 }
941 
942 /** PowerkeyWakeupMonitor Implement */
Init()943 bool PowerkeyWakeupMonitor::Init()
944 {
945 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
946     if (powerkeyShortPressId_ >= 0) {
947         return true;
948     }
949     std::shared_ptr<OHOS::MMI::KeyOption> keyOption = std::make_shared<OHOS::MMI::KeyOption>();
950     std::set<int32_t> preKeys;
951     keyOption.reset();
952     keyOption = std::make_shared<OHOS::MMI::KeyOption>();
953     keyOption->SetPreKeys(preKeys);
954     keyOption->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_POWER);
955     keyOption->SetFinalKeyDown(true);
956     keyOption->SetFinalKeyDownDuration(0);
957     auto inputManager = InputManager::GetInstance();
958     if (!inputManager) {
959         POWER_HILOGE(FEATURE_WAKEUP, "PowerkeyWakeupMonitorInit inputManager is null");
960         return false;
961     }
962     std::weak_ptr<PowerkeyWakeupMonitor> weak = weak_from_this();
963     powerkeyShortPressId_ = inputManager->SubscribeKeyEvent(
964         keyOption, [weak](std::shared_ptr<OHOS::MMI::KeyEvent> keyEvent) {
965             std::shared_ptr<PowerkeyWakeupMonitor> strong = weak.lock();
966             if (!strong) {
967                 POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] PowerkeyWakeupMonitor is invaild, return");
968                 return;
969             }
970 
971             strong->ReceivePowerkeyCallback(keyEvent);
972         });
973 
974     POWER_HILOGI(FEATURE_WAKEUP, "powerkey register powerkeyShortPressId_=%{public}d", powerkeyShortPressId_);
975     return powerkeyShortPressId_ >= 0 ? true : false;
976 #else
977     return false;
978 #endif
979 }
980 
ReceivePowerkeyCallback(std::shared_ptr<OHOS::MMI::KeyEvent> keyEvent)981 void PowerkeyWakeupMonitor::ReceivePowerkeyCallback(std::shared_ptr<OHOS::MMI::KeyEvent> keyEvent)
982 {
983 #ifndef POWER_MANAGER_ALLOW_INTERRUPTING_POWERKEY_OFF
984     ffrt::wait({&PowerKeySuspendMonitor::powerkeyScreenOff_});
985 #endif
986     POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Received powerkey down");
987 
988     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
989     if (pms == nullptr) {
990         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] PowerMgrService is nullptr");
991         return;
992     }
993     int64_t now = static_cast<int64_t>(time(nullptr));
994     pms->RefreshActivityInner(now, UserActivityType::USER_ACTIVITY_TYPE_BUTTON, false);
995 
996     std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
997     if (wakeupController == nullptr) {
998         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] wakeupController is nullptr");
999         return;
1000     }
1001     std::shared_ptr<SuspendController> suspendController = pms->GetSuspendController();
1002     if (suspendController == nullptr) {
1003         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] suspendController is nullptr");
1004         return;
1005     }
1006 
1007 #ifdef POWER_MANAGER_WAKEUP_ACTION
1008     if (wakeupController->IsLowCapacityWakeup(reason)) {
1009         wakeupController->ProcessLowCapacityWakeup();
1010         suspendController->SetLowCapacityPowerKeyFlag(true);
1011         return;
1012     }
1013     suspendController->SetLowCapacityPowerKeyFlag(false);
1014 #endif
1015 
1016     bool poweroffInterrupted = false;
1017     if (PowerKeySuspendMonitor::powerkeyScreenOff_.load()) {
1018         auto stateMachine = pms->GetPowerStateMachine();
1019         if (!stateMachine) {
1020             POWER_HILOGE(FEATURE_WAKEUP, "TryToCancelScreenOff, state machine is nullptr");
1021         } else {
1022             poweroffInterrupted = stateMachine->TryToCancelScreenOff();
1023         }
1024     }
1025     // sync with the end of powerkey screen off task
1026     ffrt::wait({&PowerKeySuspendMonitor::powerkeyScreenOff_});
1027     suspendController->RecordPowerKeyDown(poweroffInterrupted);
1028     Notify();
1029 }
1030 
Cancel()1031 void PowerkeyWakeupMonitor::Cancel()
1032 {
1033 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
1034     auto inputManager = InputManager::GetInstance();
1035     if (!inputManager) {
1036         POWER_HILOGE(FEATURE_WAKEUP, "PowerkeyWakeupMonitorCancel inputManager is null");
1037         return;
1038     }
1039     if (powerkeyShortPressId_ >= 0) {
1040         POWER_HILOGI(FEATURE_WAKEUP, "UnsubscribeKeyEvent: PowerkeyWakeupMonitor");
1041         inputManager->UnsubscribeKeyEvent(powerkeyShortPressId_);
1042     }
1043 #endif
1044 }
1045 
1046 /** Keyboard Implement */
1047 
Init()1048 bool KeyboardWakeupMonitor::Init()
1049 {
1050     return true;
1051 }
1052 
Cancel()1053 void KeyboardWakeupMonitor::Cancel() {}
1054 
1055 /** Mouse Implement */
1056 
Init()1057 bool MousekeyWakeupMonitor::Init()
1058 {
1059     return true;
1060 }
1061 
Cancel()1062 void MousekeyWakeupMonitor::Cancel() {}
1063 
1064 /** Mouse Implement */
1065 
Init()1066 bool TouchpadWakeupMonitor::Init()
1067 {
1068     return true;
1069 }
1070 
Cancel()1071 void TouchpadWakeupMonitor::Cancel() {}
1072 
1073 /** Pen Implement */
1074 
Init()1075 bool PenWakeupMonitor::Init()
1076 {
1077     return true;
1078 }
1079 
Cancel()1080 void PenWakeupMonitor::Cancel() {}
1081 
1082 /** SingleClickWakeupMonitor Implement */
1083 
Init()1084 bool SingleClickWakeupMonitor::Init()
1085 {
1086     return true;
1087 }
1088 
Cancel()1089 void SingleClickWakeupMonitor::Cancel() {}
1090 
1091 /** DoubleClickWakeupMonitor Implement */
1092 
Init()1093 bool DoubleClickWakeupMonitor::Init()
1094 {
1095     return true;
1096 }
1097 
Cancel()1098 void DoubleClickWakeupMonitor::Cancel() {}
1099 
1100 /** SwitchWakeupMonitor Implement */
1101 
Init()1102 bool SwitchWakeupMonitor::Init()
1103 {
1104     return true;
1105 }
1106 
Cancel()1107 void SwitchWakeupMonitor::Cancel() {}
1108 
1109 /** LidWakeupMonitor Implement */
1110 
Init()1111 bool LidWakeupMonitor::Init()
1112 {
1113     return true;
1114 }
1115 
Cancel()1116 void LidWakeupMonitor::Cancel() {}
1117 
1118 /** PickupWakeupMonitor Implement */
1119 
Init()1120 bool PickupWakeupMonitor::Init()
1121 {
1122     return true;
1123 }
1124 
Cancel()1125 void PickupWakeupMonitor::Cancel() {}
1126 
1127 /** TPTouchWakeupMonitor Implement */
1128 
Init()1129 bool TPTouchWakeupMonitor::Init()
1130 {
1131     return true;
1132 }
1133 
Cancel()1134 void TPTouchWakeupMonitor::Cancel() {}
1135 } // namespace PowerMgr
1136 } // namespace OHOS
1137