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 #include <hisysevent.h>
20 #include <input_manager.h>
21 #include <ipc_skeleton.h>
22 #include <securec.h>
23 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
24 #include <dlfcn.h>
25 #endif
26 #include "json/json.h"
27 #include "permission.h"
28 #include "power_errors.h"
29 #include "power_log.h"
30 #include "power_mgr_service.h"
31 #include "power_state_callback_stub.h"
32 #include "setting_helper.h"
33 #include "suspend_controller.h"
34 #include "system_suspend_controller.h"
35 
36 namespace OHOS {
37 namespace PowerMgr {
38 using namespace OHOS::MMI;
39 namespace {
40 sptr<SettingObserver> g_wakeupSourcesKeyObserver = nullptr;
41 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
42 const int32_t ERR_FAILED = -1;
43 #endif
44 
45 constexpr int32_t WAKEUP_LOCK_TIMEOUT_MS = 5000;
46 constexpr int32_t COLLABORATION_REMOTE_DEVICE_ID = 0xAAAAAAFF;
47 }
48 std::mutex WakeupController::sourceUpdateMutex_;
49 
50 /** WakeupController Implement */
WakeupController(std::shared_ptr<PowerStateMachine> & stateMachine)51 WakeupController::WakeupController(std::shared_ptr<PowerStateMachine>& stateMachine)
52 {
53     stateMachine_ = stateMachine;
54 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
55     std::shared_ptr<InputCallback> callback = std::make_shared<InputCallback>();
56     if (monitorId_ < 0) {
57         monitorId_ = InputManager::GetInstance()->AddMonitor(std::static_pointer_cast<IInputEventConsumer>(callback));
58     }
59 #endif
60     eventHandleMap_.emplace(WakeupDeviceType::WAKEUP_DEVICE_KEYBOARD, 0);
61     eventHandleMap_.emplace(WakeupDeviceType::WAKEUP_DEVICE_MOUSE, 0);
62     eventHandleMap_.emplace(WakeupDeviceType::WAKEUP_DEVICE_TOUCHPAD, 0);
63     eventHandleMap_.emplace(WakeupDeviceType::WAKEUP_DEVICE_PEN, 0);
64     eventHandleMap_.emplace(WakeupDeviceType::WAKEUP_DEVICE_TOUCH_SCREEN, 0);
65     eventHandleMap_.emplace(WakeupDeviceType::WAKEUP_DEVICE_SINGLE_CLICK, 0);
66 }
67 
~WakeupController()68 WakeupController::~WakeupController()
69 {
70 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
71     InputManager* inputManager = InputManager::GetInstance();
72     if (monitorId_ >= 0) {
73         inputManager->RemoveMonitor(monitorId_);
74     }
75 #endif
76     UnregisterSettingsObserver();
77 }
78 
Init()79 void WakeupController::Init()
80 {
81     std::lock_guard lock(monitorMutex_);
82     std::shared_ptr<WakeupSources> sources = WakeupSourceParser::ParseSources();
83     sourceList_ = sources->GetSourceList();
84     if (sourceList_.empty()) {
85         POWER_HILOGE(FEATURE_WAKEUP, "InputManager is null");
86         return;
87     }
88 
89     for (auto source = sourceList_.begin(); source != sourceList_.end(); source++) {
90         POWER_HILOGI(FEATURE_WAKEUP, "registered type=%{public}u", (*source).GetReason());
91 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
92             SetOriginSettingValue((*source));
93 #endif
94         std::shared_ptr<WakeupMonitor> monitor = WakeupMonitor::CreateMonitor(*source);
95         if (monitor != nullptr && monitor->Init()) {
96             POWER_HILOGI(FEATURE_WAKEUP, "monitor init success, type=%{public}u", (*source).GetReason());
97             monitor->RegisterListener([this](WakeupDeviceType reason) { this->ControlListener(reason); });
98             monitorMap_.emplace(monitor->GetReason(), monitor);
99         }
100     }
101     RegisterSettingsObserver();
102 }
103 
Cancel()104 void WakeupController::Cancel()
105 {
106     for (auto monitor = monitorMap_.begin(); monitor != monitorMap_.end(); monitor++) {
107         monitor->second->Cancel();
108     }
109     monitorMap_.clear();
110 }
111 
RegisterSettingsObserver()112 void WakeupController::RegisterSettingsObserver()
113 {
114     if (g_wakeupSourcesKeyObserver) {
115         POWER_HILOGE(FEATURE_POWER_STATE, "wakeup sources key observer is already registered");
116         return;
117     }
118     SettingObserver::UpdateFunc updateFunc = [&](const std::string&) {
119         std::lock_guard lock(monitorMutex_);
120         POWER_HILOGI(COMP_SVC, "start setting string update");
121         std::string jsonStr = SettingHelper::GetSettingWakeupSources();
122         std::shared_ptr<WakeupSources> sources = WakeupSourceParser::ParseSources(jsonStr);
123         if (sources->GetParseErrorFlag()) {
124             POWER_HILOGI(FEATURE_WAKEUP, "Parse failed, call GetWakeupSourcesByConfig again");
125             sources = WakeupSourceParser::ParseSources(WakeupSourceParser::GetWakeupSourcesByConfig());
126         }
127         std::vector<WakeupSource> updateSourceList = sources->GetSourceList();
128         if (updateSourceList.size() == 0) {
129             return;
130         }
131         sourceList_ = updateSourceList;
132         POWER_HILOGI(COMP_SVC, "start updateListener");
133         Cancel();
134         uint32_t id = 0;
135         for (auto source = sourceList_.begin(); source != sourceList_.end(); source++, id++) {
136             std::shared_ptr<WakeupMonitor> monitor = WakeupMonitor::CreateMonitor(*source);
137             POWER_HILOGI(FEATURE_WAKEUP, "UpdateFunc CreateMonitor[%{public}u] reason=%{public}d",
138                 id, source->GetReason());
139             if (monitor != nullptr && monitor->Init()) {
140                 monitor->RegisterListener([this](WakeupDeviceType reason) { this->ControlListener(reason); });
141                 monitorMap_.emplace(monitor->GetReason(), monitor);
142             }
143         }
144     };
145     g_wakeupSourcesKeyObserver = SettingHelper::RegisterSettingWakeupSourcesObserver(updateFunc);
146     POWER_HILOGI(FEATURE_POWER_STATE, "register setting observer fin");
147 }
148 
UnregisterSettingsObserver()149 void WakeupController::UnregisterSettingsObserver()
150 {
151     if (g_wakeupSourcesKeyObserver) {
152         SettingHelper::UnregisterSettingObserver(g_wakeupSourcesKeyObserver);
153         g_wakeupSourcesKeyObserver = nullptr;
154     }
155 }
156 
157 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
SetOriginSettingValue(WakeupSource & source)158 void WakeupController::SetOriginSettingValue(WakeupSource& source)
159 {
160     if (source.GetReason() == WakeupDeviceType::WAKEUP_DEVICE_DOUBLE_CLICK) {
161         if (SettingHelper::IsWakeupDoubleSettingValid() == false) {
162             POWER_HILOGI(COMP_SVC, "the origin doubleClick_enable is: %{public}d", source.IsEnable());
163             SettingHelper::SetSettingWakeupDouble(source.IsEnable());
164             SetWakeupDoubleClickSensor(source.IsEnable());
165             return;
166         }
167 
168         auto enable = SettingHelper::GetSettingWakeupDouble();
169         SetWakeupDoubleClickSensor(enable);
170     } else if (source.GetReason() == WakeupDeviceType::WAKEUP_DEVICE_PICKUP) {
171         if (!SettingHelper::IsWakeupPickupSettingValid()) {
172             POWER_HILOGI(FEATURE_WAKEUP, "GetReason_WAKEUP_DEVICE_PICKUP,source enable=%{public}d", source.IsEnable());
173             SettingHelper::SetSettingWakeupPickup(source.IsEnable());
174             PickupConnectMotionConfig(source.IsEnable());
175             return;
176         }
177 
178         auto enable = SettingHelper::GetSettingWakeupPickup();
179         PickupConnectMotionConfig(enable);
180     }
181 }
182 
ChangeWakeupSourceConfig(bool updateEnable)183 void WakeupController::ChangeWakeupSourceConfig(bool updateEnable)
184 {
185     std::lock_guard lock(sourceUpdateMutex_);
186     std::string jsonStr = SettingHelper::GetSettingWakeupSources();
187     if (jsonStr.empty()) {
188         POWER_HILOGE(COMP_SVC, "there is no such configuration file available");
189         return;
190     }
191     POWER_HILOGI(COMP_SVC, "the origin ccmJson is: %{public}s", jsonStr.c_str());
192     Json::Value root;
193     Json::Reader reader;
194     if (!reader.parse(jsonStr.data(), jsonStr.data() + jsonStr.size(), root)) {
195         POWER_HILOGE(COMP_SVC, "json parse error");
196         return;
197     }
198     if (root["touchscreen"].isNull()) {
199         POWER_HILOGE(COMP_SVC, "this touchscreenNode is empty");
200         return;
201     }
202     if (root["touchscreen"]["enable"].isNull()) {
203         POWER_HILOGE(COMP_SVC, "the touchscreenNode is empty");
204         return;
205     }
206     if (!root["touchscreen"]["enable"].isBool()) {
207         POWER_HILOGE(COMP_SVC, "the origin touchscreenEnable value is invalid");
208         return;
209     }
210     bool originEnable = root["touchscreen"]["enable"].asBool();
211     if (originEnable == updateEnable) {
212         POWER_HILOGI(COMP_SVC, "no need change jsonConfig value");
213         return;
214     }
215 
216     root["touchscreen"]["enable"] = updateEnable;
217     POWER_HILOGI(COMP_SVC, "the new doubleJsonConfig is: %{public}s", root.toStyledString().c_str());
218     SettingHelper::SetSettingWakeupSources(root.toStyledString());
219 }
220 
221 static const char* SET_WAKEUP_DOUBLE_CLICK_SENSOR = "SetWakeupDoubleClickSensor";
222 static const char* POWER_DOUBLE_CLICK_PATH = "/system/lib64/libpower_manager_ext.z.so";
223 typedef int32_t(*Func)(bool);
SetWakeupDoubleClickSensor(bool enable)224 int32_t WakeupController::SetWakeupDoubleClickSensor(bool enable)
225 {
226     POWER_HILOGI(COMP_SVC, "enter SetWakeupDoubleClickSensor");
227     void *handler = dlopen(POWER_DOUBLE_CLICK_PATH, RTLD_LAZY | RTLD_NODELETE);
228     if (handler == nullptr) {
229         POWER_HILOGE(FEATURE_SHUTDOWN, "Dlopen failed, reason : %{public}s", dlerror());
230         return ERR_FAILED;
231     }
232 
233     Func PowerDoubleClickFlag = (Func)dlsym(handler, SET_WAKEUP_DOUBLE_CLICK_SENSOR);
234     if (PowerDoubleClickFlag == nullptr) {
235         POWER_HILOGE(FEATURE_SHUTDOWN, "find function failed, reason : %{public}s", dlerror());
236         dlclose(handler);
237         return ERR_FAILED;
238     }
239     auto resCode = PowerDoubleClickFlag(enable);
240     dlclose(handler);
241     return resCode;
242 }
243 
244 static const char* SET_WAKEUP_MOTION_SUBSCRIBER_CONFIG = "PickupMotionSubscriber";
245 static const char* SET_WAKEUP_MOTION_UNSUBSCRIBER_CONFIG = "PickupMotionUnsubscriber";
246 static const char* POWER_MANAGER_EXT_PATH = "/system/lib64/libpower_manager_ext.z.so";
247 typedef void(*FuncSubscriber)();
248 typedef void(*FuncUnsubscriber)();
249 
PickupConnectMotionConfig(bool databaseSwitchValue)250 void WakeupController::PickupConnectMotionConfig(bool databaseSwitchValue)
251 {
252     POWER_HILOGI(COMP_SVC, "open enter PickupConnectMotionConfig");
253     if (databaseSwitchValue) {
254         void *subscriberHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
255         if (subscriberHandler == nullptr) {
256             POWER_HILOGE(COMP_SVC, "Dlopen failed, reason : %{public}s", dlerror());
257             return;
258         }
259         FuncSubscriber powerPickupMotionSubscriberFlag = reinterpret_cast<FuncSubscriber>(dlsym(subscriberHandler,
260             SET_WAKEUP_MOTION_SUBSCRIBER_CONFIG));
261         if (powerPickupMotionSubscriberFlag == nullptr) {
262             POWER_HILOGE(COMP_SVC, "find Subscriber function failed, reason : %{public}s", dlerror());
263             dlclose(subscriberHandler);
264             return;
265         }
266         powerPickupMotionSubscriberFlag();
267         POWER_HILOGI(COMP_SVC, "powerservice enable powerPickupMotionSubscriberFlag isSettingEnable=%{public}d",
268             databaseSwitchValue);
269         dlclose(subscriberHandler);
270         POWER_HILOGI(COMP_SVC, "open to close PickupMotionSubscriberConfig");
271     } else {
272         void *unsubscriberHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
273         if (unsubscriberHandler == nullptr) {
274             POWER_HILOGE(COMP_SVC, "Dlopen failed, reason : %{public}s", dlerror());
275             return;
276         }
277         FuncUnsubscriber powerPickupMotionUnsubscriberFlag = reinterpret_cast<FuncUnsubscriber>(dlsym(
278             unsubscriberHandler, SET_WAKEUP_MOTION_UNSUBSCRIBER_CONFIG));
279         if (powerPickupMotionUnsubscriberFlag == nullptr) {
280             POWER_HILOGE(COMP_SVC, "find Unsubscriber function failed, reason : %{public}s", dlerror());
281             dlclose(unsubscriberHandler);
282             return;
283         }
284         powerPickupMotionUnsubscriberFlag();
285         POWER_HILOGI(COMP_SVC, "powerservice disable powerPickupMotionUnsubscriberFlag isSettingEnable=%{public}d",
286             databaseSwitchValue);
287         dlclose(unsubscriberHandler);
288         POWER_HILOGI(COMP_SVC, "open to close PickupMotionSubscriberConfig");
289     }
290 }
291 
ChangePickupWakeupSourceConfig(bool updataEnable)292 void WakeupController::ChangePickupWakeupSourceConfig(bool updataEnable)
293 {
294     std::lock_guard lock(sourceUpdateMutex_);
295     std::string jsonStr = SettingHelper::GetSettingWakeupSources();
296     if (jsonStr.empty()) {
297         POWER_HILOGE(COMP_SVC, "there is no such configuration file available");
298         return;
299     }
300     POWER_HILOGI(COMP_SVC, "%{public}s(%{public}d)", __func__, updataEnable);
301     Json::Value root;
302     Json::Reader reader;
303     reader.parse(jsonStr, root);
304     if (!reader.parse(jsonStr, root)) {
305         POWER_HILOGE(COMP_SVC, "Failed to parse json string");
306         return;
307     }
308     if (root["pickup"].isNull()) {
309         POWER_HILOGE(COMP_SVC, "this pickNode is empty");
310         return;
311     }
312     if (root["pickup"]["enable"].isNull()) {
313         POWER_HILOGE(COMP_SVC, "the pickupNode is empty");
314         return;
315     }
316     if (!root["pickup"]["enable"].isBool()) {
317         POWER_HILOGE(COMP_SVC, "the origin pickupEnable value is invalid");
318         return;
319     }
320     bool originEnable = root["pickup"]["enable"].asBool();
321     if (originEnable == updataEnable) {
322         POWER_HILOGI(COMP_SVC, "no need change jsonconfig_value");
323         return;
324     }
325     root["pickup"]["enable"] = updataEnable;
326     POWER_HILOGI(COMP_SVC, "the new pickupJsonConfig is: %{public}s", root.toStyledString().c_str());
327     SettingHelper::SetSettingWakeupSources(root.toStyledString());
328 }
329 #endif
330 
ChangeLidWakeupSourceConfig(bool updataEnable)331 void WakeupController::ChangeLidWakeupSourceConfig(bool updataEnable)
332 {
333     std::lock_guard lock(sourceUpdateMutex_);
334     std::string jsonStr = SettingHelper::GetSettingWakeupSources();
335     POWER_HILOGI(FEATURE_POWER_STATE, "%{public}s", jsonStr.c_str());
336     Json::Value root;
337     Json::Reader reader;
338     reader.parse(jsonStr, root);
339     if (!reader.parse(jsonStr, root)) {
340         POWER_HILOGE(FEATURE_POWER_STATE, "Failed to parse json string");
341         return;
342     }
343     bool originEnable = true;
344     if (root["lid"]["enable"].isBool()) {
345         originEnable = root["lid"]["enable"].asBool();
346     }
347 
348     if (originEnable == updataEnable) {
349         POWER_HILOGI(FEATURE_POWER_STATE, "no need change jsonConfig value");
350         return;
351     }
352     if (root["lid"]["enable"].isBool()) {
353         root["lid"]["enable"] = updataEnable;
354     }
355     SettingHelper::SetSettingWakeupSources(root.toStyledString());
356 }
357 
358 
ExecWakeupMonitorByReason(WakeupDeviceType reason)359 void WakeupController::ExecWakeupMonitorByReason(WakeupDeviceType reason)
360 {
361     FFRTUtils::SubmitTask([this, reason] {
362         std::lock_guard lock(monitorMutex_);
363         if (monitorMap_.find(reason) != monitorMap_.end()) {
364             auto monitor = monitorMap_[reason];
365             monitor->Notify();
366         }
367     });
368 }
369 
Wakeup()370 void WakeupController::Wakeup()
371 {
372     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
373     if (pms == nullptr) {
374         POWER_HILOGE(FEATURE_WAKEUP, "get powerMgrService instance error");
375         return;
376     }
377     auto suspendController = pms->GetSuspendController();
378     if (suspendController == nullptr) {
379         POWER_HILOGE(FEATURE_WAKEUP, "get suspendController instance error");
380         return;
381     }
382     suspendController->StopSleep();
383 }
384 
SleepGuard(const sptr<PowerMgrService> & pms)385 WakeupController::SleepGuard::SleepGuard(const sptr<PowerMgrService>& pms) : pms_(pms)
386 {
387     token_ = new (std::nothrow) RunningLockTokenStub();
388     if (token_ == nullptr) {
389         POWER_HILOGE(COMP_SVC, "create runninglock token failed");
390         return;
391     }
392     RunningLockInfo info = {"SleepGuard", OHOS::PowerMgr::RunningLockType::RUNNINGLOCK_BACKGROUND_TASK};
393     pms_->CreateRunningLock(token_, info);
394     pms_->Lock(token_, WAKEUP_LOCK_TIMEOUT_MS);
395 }
396 
~SleepGuard()397 WakeupController::SleepGuard::~SleepGuard()
398 {
399     if (token_ == nullptr) {
400         POWER_HILOGE(COMP_SVC, "dtor: token_ is nullptr, direct return ");
401         return;
402     }
403     pms_->ReleaseRunningLock(token_);
404 }
405 
406 #ifdef POWER_MANAGER_WAKEUP_ACTION
IsLowCapacityWakeup(WakeupDeviceType reason)407 bool WakeupController::IsLowCapacityWakeup(WakeupDeviceType reason)
408 {
409     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
410     if (pms == nullptr) {
411         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] pms is nullptr");
412         return false;
413     }
414     auto wakeupActionController = pms->GetWakeupActionController();
415     if (wakeupActionController == nullptr) {
416         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] wakeupActionController is nullptr.");
417         return false;
418     }
419     return (reason == WakeupDeviceType::WAKEUP_DEVICE_POWER_BUTTON) &&
420         (wakeupActionController->IsLowCapacityWakeup());
421 }
422 
ProcessLowCapacityWakeup()423 void WakeupController::ProcessLowCapacityWakeup()
424 {
425     POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] processing low capacity wake up begins.");
426     if (stateMachine_->GetState() != PowerState::SLEEP) {
427         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] the current power state is not sleep.");
428         return;
429     }
430     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
431     if (pms == nullptr) {
432         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] pms is nullptr");
433         return;
434     }
435     auto wakeupActionController = pms->GetWakeupActionController();
436     if (wakeupActionController == nullptr) {
437         POWER_HILOGE(FEATURE_WAKEUP, "[UL_POWER] wakeupActionController is nullptr");
438         return;
439     }
440     SleepGuard sleepGuard(pms);
441     Wakeup();
442     auto suspendController = pms->GetSuspendController();
443     if (suspendController != nullptr) {
444         POWER_HILOGI(FEATURE_WAKEUP, "ControlListener TriggerSyncSleepCallback start.");
445         suspendController->TriggerSyncSleepCallback(true);
446     }
447     wakeupActionController->ExecuteByGetReason();
448 }
449 #endif
450 
ControlListener(WakeupDeviceType reason)451 void WakeupController::ControlListener(WakeupDeviceType reason)
452 {
453     std::lock_guard lock(mutex_);
454     if (!Permission::IsSystem()) {
455         return;
456     }
457 #ifdef POWER_MANAGER_WAKEUP_ACTION
458     if (IsLowCapacityWakeup(reason)) {
459         ProcessLowCapacityWakeup();
460         return;
461     }
462 #endif
463 
464 #ifdef POWER_MANAGER_POWER_ENABLE_S4
465     if (!stateMachine_->IsSwitchOpen() || stateMachine_->IsHibernating()) {
466 #else
467     if (!stateMachine_->IsSwitchOpen()) {
468 #endif
469         POWER_HILOGI(FEATURE_WAKEUP, "Switch is closed or hibernating, wakeup control listerner do nothing.");
470         return;
471     }
472     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
473     if ((pms == nullptr || pms->IsScreenOn()) && (reason != WakeupDeviceType::WAKEUP_DEVICE_SWITCH) &&
474         (reason != WakeupDeviceType::WAKEUP_DEVICE_LID)) {
475         POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] The Screen is on, ignore this event: %{public}d", reason);
476         return;
477     }
478     pid_t pid = IPCSkeleton::GetCallingPid();
479     auto uid = IPCSkeleton::GetCallingUid();
480     POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Try to wakeup device, pid=%{public}d, uid=%{public}d", pid, uid);
481     if (stateMachine_->GetState() != PowerState::AWAKE || reason == WakeupDeviceType::WAKEUP_DEVICE_SWITCH ||
482         reason == WakeupDeviceType::WAKEUP_DEVICE_LID) {
483         SleepGuard sleepGuard(pms);
484         Wakeup();
485         SystemSuspendController::GetInstance().Wakeup();
486         POWER_HILOGI(FEATURE_WAKEUP, "wakeup Request: %{public}d", reason);
487         if (stateMachine_->GetState() == PowerState::SLEEP && pms->GetSuspendController() != nullptr) {
488             POWER_HILOGI(FEATURE_WAKEUP, "WakeupController::ControlListener TriggerSyncSleepCallback start.");
489             pms->GetSuspendController()->TriggerSyncSleepCallback(true);
490         }
491         if (!stateMachine_->SetState(PowerState::AWAKE, stateMachine_->GetReasonByWakeType(reason), true)) {
492             POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] setstate wakeup error");
493         }
494     } else {
495         POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] state=%{public}u no transitor", stateMachine_->GetState());
496     }
497 }
498 
499 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
500 /* InputCallback achieve */
501 bool InputCallback::IsRemoteEvent(std::shared_ptr<InputEvent> event) const
502 {
503     return event->GetDeviceId() == COLLABORATION_REMOTE_DEVICE_ID;
504 }
505 
506 bool InputCallback::isKeyboardKeycode(int32_t keyCode) const
507 {
508     if ((keyCode >= KeyEvent::KEYCODE_0 && keyCode <= KeyEvent::KEYCODE_NUMPAD_RIGHT_PAREN
509         && keyCode != KeyEvent::KEYCODE_F1)
510         || (keyCode == KeyEvent::KEYCODE_BRIGHTNESS_DOWN) // F1 hotkey
511         || (keyCode == KeyEvent::KEYCODE_BRIGHTNESS_UP) // F2 hotkey
512         || (keyCode == KeyEvent::KEYCODE_FN) // F3 hotkey
513         || (keyCode == KeyEvent::KEYCODE_VOLUME_MUTE) // F4 hotkey
514         || (keyCode == KeyEvent::KEYCODE_SOUND) // sound
515         || (keyCode == KeyEvent::KEYCODE_MUTE) // F7 hotkey
516         || (keyCode == KeyEvent::KEYCODE_SWITCHVIDEOMODE) // F8 hotkey
517         || (keyCode == KeyEvent::KEYCODE_SEARCH) // F9 hotkey
518         || (keyCode == KeyEvent::KEYCODE_ASSISTANT)) { // assistant
519         return true;
520     }
521     return false;
522 }
523 
524 void InputCallback::OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const
525 {
526     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
527     if (pms == nullptr || keyEvent == nullptr) {
528         POWER_HILOGE(FEATURE_WAKEUP, "get powerMgrService instance error");
529         return;
530     }
531     // ignores remote event
532     if (IsRemoteEvent(keyEvent)) {
533         return;
534     }
535     int64_t now = static_cast<int64_t>(time(nullptr));
536     pms->RefreshActivityInner(now, UserActivityType::USER_ACTIVITY_TYPE_BUTTON, false);
537 
538     PowerState state = pms->GetState();
539     if (state == PowerState::AWAKE || state == PowerState::FREEZE) {
540         return;
541     }
542     std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
543     if (wakeupController == nullptr) {
544         POWER_HILOGE(FEATURE_WAKEUP, "wakeupController is not init");
545         return;
546     }
547 
548     int32_t keyCode = keyEvent->GetKeyCode();
549     WakeupDeviceType wakeupType = WakeupDeviceType::WAKEUP_DEVICE_UNKNOWN;
550     if (keyCode == KeyEvent::KEYCODE_F1) {
551         wakeupType = WakeupDeviceType::WAKEUP_DEVICE_DOUBLE_CLICK;
552     } else if (keyCode == KeyEvent::KEYCODE_STYLUS_SCREEN) {
553         wakeupType = WakeupDeviceType::WAKEUP_DEVICE_PEN;
554     }
555 
556     if (isKeyboardKeycode(keyCode)) {
557         wakeupType = WakeupDeviceType::WAKEUP_DEVICE_KEYBOARD;
558         if (wakeupController->CheckEventReciveTime(wakeupType) ||
559             keyEvent->GetKeyAction() == KeyEvent::KEY_ACTION_UP) {
560             return;
561         }
562     }
563 
564     POWER_HILOGD(FEATURE_WAKEUP, "[UL_POWER] KeyEvent wakeupType=%{public}u, keyCode=%{public}d", wakeupType, keyCode);
565     if (wakeupType != WakeupDeviceType::WAKEUP_DEVICE_UNKNOWN) {
566         wakeupController->ExecWakeupMonitorByReason(wakeupType);
567     }
568 }
569 
570 void InputCallback::OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const
571 {
572     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
573     if (pms == nullptr || pointerEvent == nullptr) {
574         return;
575     }
576     if (!NonWindowEvent(pointerEvent)) {
577         return;
578     }
579     if (IsRemoteEvent(pointerEvent)) {
580         return;
581     }
582     int64_t now = static_cast<int64_t>(time(nullptr));
583     pms->RefreshActivityInner(now, UserActivityType::USER_ACTIVITY_TYPE_TOUCH, false);
584 
585     PowerState state = pms->GetState();
586     if (state == PowerState::AWAKE || state == PowerState::FREEZE) {
587         return;
588     }
589     std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
590     WakeupDeviceType wakeupType = WakeupDeviceType::WAKEUP_DEVICE_UNKNOWN;
591     PointerEvent::PointerItem pointerItem;
592     if (!pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
593         POWER_HILOGI(FEATURE_WAKEUP, "GetPointerItem false");
594     }
595     int32_t deviceType = pointerItem.GetToolType();
596     int32_t sourceType = pointerEvent->GetSourceType();
597     if (deviceType == PointerEvent::TOOL_TYPE_PEN) {
598         wakeupType = WakeupDeviceType::WAKEUP_DEVICE_PEN;
599     } else {
600         switch (sourceType) {
601             case PointerEvent::SOURCE_TYPE_MOUSE:
602                 wakeupType = WakeupDeviceType::WAKEUP_DEVICE_MOUSE;
603                 break;
604             case PointerEvent::SOURCE_TYPE_TOUCHPAD:
605                 wakeupType = WakeupDeviceType::WAKEUP_DEVICE_TOUCHPAD;
606                 break;
607             case PointerEvent::SOURCE_TYPE_TOUCHSCREEN:
608                 wakeupType = WakeupDeviceType::WAKEUP_DEVICE_SINGLE_CLICK;
609                 break;
610             default:
611                 break;
612         }
613     }
614     if (wakeupController->CheckEventReciveTime(wakeupType)) {
615         return;
616     }
617 
618     if (wakeupType != WakeupDeviceType::WAKEUP_DEVICE_UNKNOWN) {
619         POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] PointerEvent wakeupType=%{public}u", wakeupType);
620         wakeupController->ExecWakeupMonitorByReason(wakeupType);
621     }
622 }
623 
624 bool InputCallback::NonWindowEvent(const std::shared_ptr<PointerEvent>& pointerEvent) const
625 {
626     auto action = pointerEvent->GetPointerAction();
627     if (action == PointerEvent::POINTER_ACTION_ENTER_WINDOW ||
628         action == PointerEvent::POINTER_ACTION_LEAVE_WINDOW ||
629         action == PointerEvent::POINTER_ACTION_PULL_IN_WINDOW ||
630         action == PointerEvent::POINTER_ACTION_PULL_OUT_WINDOW) {
631         return false;
632     }
633     return true;
634 }
635 
636 void InputCallback::OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const
637 {
638     POWER_HILOGD(FEATURE_WAKEUP, "AxisEvent");
639     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
640     if (pms == nullptr || axisEvent == nullptr) {
641         return;
642     }
643     int64_t now = static_cast<int64_t>(time(nullptr));
644     pms->RefreshActivityInner(now, UserActivityType::USER_ACTIVITY_TYPE_ACCESSIBILITY, false);
645 }
646 #endif
647 
648 bool WakeupController::CheckEventReciveTime(WakeupDeviceType wakeupType)
649 {
650     // The minimum refreshactivity interval is 100ms!!
651     std::lock_guard lock(eventHandleMutex_);
652     int64_t now = GetTickCount();
653     if (eventHandleMap_.find(wakeupType) != eventHandleMap_.end()) {
654         if ((eventHandleMap_[wakeupType] + MIN_TIME_MS_BETWEEN_MULTIMODEACTIVITIES) > now) {
655             return true;
656         }
657         eventHandleMap_[wakeupType] = now;
658         return false;
659     }
660     return false;
661 }
662 
663 /* WakeupMonitor Implement */
664 
665 std::shared_ptr<WakeupMonitor> WakeupMonitor::CreateMonitor(WakeupSource& source)
666 {
667     WakeupDeviceType reason = source.GetReason();
668     std::shared_ptr<WakeupMonitor> monitor = nullptr;
669     switch (reason) {
670         case WakeupDeviceType::WAKEUP_DEVICE_POWER_BUTTON:
671             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<PowerkeyWakeupMonitor>(source));
672             break;
673         case WakeupDeviceType::WAKEUP_DEVICE_MOUSE:
674             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<MousekeyWakeupMonitor>(source));
675             break;
676         case WakeupDeviceType::WAKEUP_DEVICE_KEYBOARD:
677             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<KeyboardWakeupMonitor>(source));
678             break;
679         case WakeupDeviceType::WAKEUP_DEVICE_PEN:
680             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<PenWakeupMonitor>(source));
681             break;
682         case WakeupDeviceType::WAKEUP_DEVICE_TOUCHPAD:
683             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<TouchpadWakeupMonitor>(source));
684             break;
685         case WakeupDeviceType::WAKEUP_DEVICE_SINGLE_CLICK:
686             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<SingleClickWakeupMonitor>(source));
687             break;
688         case WakeupDeviceType::WAKEUP_DEVICE_DOUBLE_CLICK:
689             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<DoubleClickWakeupMonitor>(source));
690             break;
691         case WakeupDeviceType::WAKEUP_DEVICE_LID:
692             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<LidWakeupMonitor>(source));
693             break;
694         case WakeupDeviceType::WAKEUP_DEVICE_SWITCH:
695             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<SwitchWakeupMonitor>(source));
696             break;
697         case WakeupDeviceType::WAKEUP_DEVICE_PICKUP:
698             monitor = std::static_pointer_cast<WakeupMonitor>(std::make_shared<PickupWakeupMonitor>(source));
699             break;
700         default:
701             POWER_HILOGE(FEATURE_WAKEUP, "CreateMonitor : Invalid reason=%{public}d", reason);
702             break;
703     }
704     return monitor;
705 }
706 
707 /** PowerkeyWakeupMonitor Implement */
708 bool PowerkeyWakeupMonitor::Init()
709 {
710     if (powerkeyShortPressId_ >= 0) {
711         return true;
712     }
713     std::shared_ptr<OHOS::MMI::KeyOption> keyOption = std::make_shared<OHOS::MMI::KeyOption>();
714     std::set<int32_t> preKeys;
715     keyOption.reset();
716     keyOption = std::make_shared<OHOS::MMI::KeyOption>();
717     keyOption->SetPreKeys(preKeys);
718     keyOption->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_POWER);
719     keyOption->SetFinalKeyDown(true);
720     keyOption->SetFinalKeyDownDuration(0);
721     auto weak = weak_from_this();
722     powerkeyShortPressId_ = InputManager::GetInstance()->SubscribeKeyEvent(
723         keyOption, [weak](std::shared_ptr<OHOS::MMI::KeyEvent> keyEvent) {
724             auto strong = weak.lock();
725             if (!strong) {
726                 POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] PowerkeyWakeupMonitor is invaild, return");
727                 return;
728             }
729             POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Received powerkey down");
730 
731             auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
732             if (pms == nullptr) {
733                 return;
734             }
735             pms->RefreshActivityInner(
736                 static_cast<int64_t>(time(nullptr)), UserActivityType::USER_ACTIVITY_TYPE_BUTTON, false);
737             std::shared_ptr<SuspendController> suspendController = pms->GetSuspendController();
738             bool poweroffInterrupted = false;
739             if (PowerKeySuspendMonitor::powerkeyScreenOff_.load()) {
740                 auto stateMachine = pms->GetPowerStateMachine();
741                 if (!stateMachine) {
742                     POWER_HILOGE(FEATURE_WAKEUP, "TryToCancelScreenOff, state machine is nullptr");
743                 } else {
744                     poweroffInterrupted = stateMachine->TryToCancelScreenOff();
745                 }
746             }
747             // sync with the end of powerkey screen off task
748             ffrt::wait({&PowerKeySuspendMonitor::powerkeyScreenOff_});
749             suspendController->RecordPowerKeyDown(poweroffInterrupted);
750             strong->Notify();
751         });
752 
753     POWER_HILOGI(FEATURE_WAKEUP, "powerkey register powerkeyShortPressId_=%{public}d", powerkeyShortPressId_);
754     return powerkeyShortPressId_ >= 0 ? true : false;
755 }
756 
757 void PowerkeyWakeupMonitor::Cancel()
758 {
759     if (powerkeyShortPressId_ >= 0) {
760         POWER_HILOGI(FEATURE_WAKEUP, "UnsubscribeKeyEvent: PowerkeyWakeupMonitor");
761         InputManager::GetInstance()->UnsubscribeKeyEvent(powerkeyShortPressId_);
762     }
763 }
764 
765 /** Keyboard Implement */
766 
767 bool KeyboardWakeupMonitor::Init()
768 {
769     return true;
770 }
771 
772 void KeyboardWakeupMonitor::Cancel() {}
773 
774 /** Mouse Implement */
775 
776 bool MousekeyWakeupMonitor::Init()
777 {
778     return true;
779 }
780 
781 void MousekeyWakeupMonitor::Cancel() {}
782 
783 /** Mouse Implement */
784 
785 bool TouchpadWakeupMonitor::Init()
786 {
787     return true;
788 }
789 
790 void TouchpadWakeupMonitor::Cancel() {}
791 
792 /** Pen Implement */
793 
794 bool PenWakeupMonitor::Init()
795 {
796     return true;
797 }
798 
799 void PenWakeupMonitor::Cancel() {}
800 
801 /** SingleClickWakeupMonitor Implement */
802 
803 bool SingleClickWakeupMonitor::Init()
804 {
805     return true;
806 }
807 
808 void SingleClickWakeupMonitor::Cancel() {}
809 
810 /** DoubleClickWakeupMonitor Implement */
811 
812 bool DoubleClickWakeupMonitor::Init()
813 {
814     return true;
815 }
816 
817 void DoubleClickWakeupMonitor::Cancel() {}
818 
819 /** SwitchWakeupMonitor Implement */
820 
821 bool SwitchWakeupMonitor::Init()
822 {
823     return true;
824 }
825 
826 void SwitchWakeupMonitor::Cancel() {}
827 
828 /** LidWakeupMonitor Implement */
829 
830 bool LidWakeupMonitor::Init()
831 {
832     return true;
833 }
834 
835 void LidWakeupMonitor::Cancel() {}
836 
837 /** PickupWakeupMonitor Implement */
838 
839 bool PickupWakeupMonitor::Init()
840 {
841     return true;
842 }
843 
844 void PickupWakeupMonitor::Cancel() {}
845 } // namespace PowerMgr
846 } // namespace OHOS
847