• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 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 "key_subscriber_handler.h"
17 
18 #include "app_state_observer.h"
19 #include "bytrace_adapter.h"
20 #include "call_manager_client.h"
21 #include "display_event_monitor.h"
22 #include "device_event_monitor.h"
23 #include "dfx_hisysevent.h"
24 #include "display_event_monitor.h"
25 #include "event_log_helper.h"
26 #include "input_event_data_transformation.h"
27 #include "input_event_handler.h"
28 #include "key_auto_repeat.h"
29 #include "key_monitor_manager.h"
30 #ifdef SHORTCUT_KEY_MANAGER_ENABLED
31 #include "key_shortcut_manager.h"
32 #endif // SHORTCUT_KEY_MANAGER_ENABLED
33 #include "setting_datashare.h"
34 #include "util_ex.h"
35 #include "want.h"
36 #include "tablet_subscriber_handler.h"
37 
38 #undef MMI_LOG_DOMAIN
39 #define MMI_LOG_DOMAIN MMI_LOG_HANDLER
40 #undef MMI_LOG_TAG
41 #define MMI_LOG_TAG "KeySubscriberHandler"
42 
43 namespace OHOS {
44 namespace MMI {
45 namespace {
46 constexpr uint32_t MAX_PRE_KEY_COUNT { 4 };
47 constexpr int32_t REMOVE_OBSERVER { -2 };
48 constexpr int32_t UNOBSERVED { -1 };
49 constexpr int32_t ACTIVE_EVENT { 2 };
50 std::shared_ptr<OHOS::Telephony::CallManagerClient> callManagerClientPtr = nullptr;
51 const std::string CALL_BEHAVIOR_KEY { "incall_power_button_behavior" };
52 const std::string SETTINGS_DATA_SYSTEM_URI {
53     "datashare:///com.ohos.settingsdata/entry/settingsdata/USER_SETTINGSDATA_100?Proxy=true" };
54 const char* SETTINGS_DATA_EXT_URI {
55     "datashare:///com.ohos.USER_SETTINGSDATA_100.DataAbility" };
56 } // namespace
57 
58 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
HandleKeyEvent(const std::shared_ptr<KeyEvent> keyEvent)59 void KeySubscriberHandler::HandleKeyEvent(const std::shared_ptr<KeyEvent> keyEvent)
60 {
61     CHKPV(keyEvent);
62     if (OnSubscribeKeyEvent(keyEvent)) {
63         if (DISPLAY_MONITOR->GetScreenStatus() == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF) {
64             auto monitorHandler = InputHandler->GetMonitorHandler();
65             CHKPV(monitorHandler);
66             keyEvent->SetFourceMonitorFlag(true);
67 #ifndef OHOS_BUILD_EMULATOR
68             monitorHandler->OnHandleEvent(keyEvent);
69 #endif // OHOS_BUILD_EMULATOR
70             keyEvent->SetFourceMonitorFlag(false);
71         }
72         if (EventLogHelper::IsBetaVersion() && !keyEvent->HasFlag(InputEvent::EVENT_FLAG_PRIVACY_MODE)) {
73             MMI_HILOGD("Subscribe keyEvent filter success. keyCode:%d", keyEvent->GetKeyCode());
74         } else {
75             MMI_HILOGD("Subscribe keyEvent filter success. keyCode:%{private}d", keyEvent->GetKeyCode());
76         }
77         BytraceAdapter::StartBytrace(keyEvent, BytraceAdapter::KEY_SUBSCRIBE_EVENT);
78         DfxHisysevent::ReportKeyEvent("subcriber");
79         return;
80     }
81     CHKPV(nextHandler_);
82     nextHandler_->HandleKeyEvent(keyEvent);
83 }
84 #endif // OHOS_BUILD_ENABLE_KEYBOARD
85 
86 #ifdef OHOS_BUILD_ENABLE_POINTER
HandlePointerEvent(const std::shared_ptr<PointerEvent> pointerEvent)87 void KeySubscriberHandler::HandlePointerEvent(const std::shared_ptr<PointerEvent> pointerEvent)
88 {
89     CHKPV(pointerEvent);
90     CHKPV(nextHandler_);
91     nextHandler_->HandlePointerEvent(pointerEvent);
92 }
93 #endif // OHOS_BUILD_ENABLE_POINTER
94 
95 #ifdef OHOS_BUILD_ENABLE_TOUCH
HandleTouchEvent(const std::shared_ptr<PointerEvent> pointerEvent)96 void KeySubscriberHandler::HandleTouchEvent(const std::shared_ptr<PointerEvent> pointerEvent)
97 {
98     CHKPV(pointerEvent);
99     TABLET_SCRIBER_HANDLER->HandleTabletEvent(pointerEvent);
100     CHKPV(nextHandler_);
101     nextHandler_->HandleTouchEvent(pointerEvent);
102 }
103 #endif // OHOS_BUILD_ENABLE_TOUCH
104 
SubscribeKeyEvent(SessionPtr sess,int32_t subscribeId,std::shared_ptr<KeyOption> keyOption)105 int32_t KeySubscriberHandler::SubscribeKeyEvent(
106     SessionPtr sess, int32_t subscribeId, std::shared_ptr<KeyOption> keyOption)
107 {
108     CALL_DEBUG_ENTER;
109     if (subscribeId < 0) {
110         MMI_HILOGE("Invalid subscribe");
111         return RET_ERR;
112     }
113     CHKPR(sess, ERROR_NULL_POINTER);
114     CHKPR(keyOption, ERROR_NULL_POINTER);
115     uint32_t preKeySize = keyOption->GetPreKeys().size();
116     if (preKeySize > MAX_PRE_KEY_COUNT) {
117         MMI_HILOGE("Leave, preKeySize:%{public}u", preKeySize);
118         return RET_ERR;
119     }
120 
121     for (const auto &keyCode : keyOption->GetPreKeys()) {
122         MMI_HILOGD("keyOption->prekey:%{private}d", keyCode);
123     }
124     MMI_HILOGI("SubscribeId:%{public}d, finalKey:%{private}d,"
125         "isFinalKeyDown:%{public}s, finalKeyDownDuration:%{public}d, pid:%{public}d",
126         subscribeId, keyOption->GetFinalKey(), keyOption->IsFinalKeyDown() ? "true" : "false",
127         keyOption->GetFinalKeyDownDuration(), sess->GetPid());
128     DfxHisysevent::ReportSubscribeKeyEvent(subscribeId, keyOption->GetFinalKey(),
129         sess->GetProgramName(), sess->GetPid());
130     auto subscriber = std::make_shared<Subscriber>(subscribeId, sess, keyOption);
131     if (keyGestureMgr_.ShouldIntercept(keyOption)) {
132         auto ret = AddKeyGestureSubscriber(subscriber, keyOption);
133         if (ret != RET_OK) {
134             MMI_HILOGE("AddKeyGestureSubscriber fail, error:%{public}d", ret);
135             DfxHisysevent::ReportFailSubscribeKey("SubscribeKeyEvent", sess->GetProgramName(),
136                 keyOption->GetFinalKey(), DfxHisysevent::KEY_ERROR_CODE::ERROR_RETURN_VALUE);
137             return ret;
138         }
139     } else {
140         auto ret = AddSubscriber(subscriber, keyOption, true);
141         if (ret != RET_OK) {
142             MMI_HILOGE("AddSubscriber fail, error:%{public}d", ret);
143             DfxHisysevent::ReportFailSubscribeKey("SubscribeKeyEvent", sess->GetProgramName(),
144                 keyOption->GetFinalKey(), DfxHisysevent::KEY_ERROR_CODE::ERROR_RETURN_VALUE);
145             return ret;
146         }
147     }
148     InitSessionDeleteCallback();
149     return RET_OK;
150 }
151 
UnsubscribeKeyEvent(SessionPtr sess,int32_t subscribeId)152 int32_t KeySubscriberHandler::UnsubscribeKeyEvent(SessionPtr sess, int32_t subscribeId)
153 {
154     CHKPR(sess, ERROR_NULL_POINTER);
155     MMI_HILOGI("SubscribeId:%{public}d, pid:%{public}d", subscribeId, sess->GetPid());
156     int32_t ret = RemoveSubscriber(sess, subscribeId, true);
157     if (ret != RET_OK) {
158         ret = RemoveKeyGestureSubscriber(sess, subscribeId);
159     }
160     if (ret == RET_ERR) {
161         DfxHisysevent::ReportFailSubscribeKey("UnsubscribeKeyEvent", sess->GetProgramName(),
162             subscribeId, DfxHisysevent::KEY_ERROR_CODE::ERROR_RETURN_VALUE);
163     }
164     return ret;
165 }
166 
RemoveSubscriber(SessionPtr sess,int32_t subscribeId,bool isSystem)167 int32_t KeySubscriberHandler::RemoveSubscriber(SessionPtr sess, int32_t subscribeId, bool isSystem)
168 {
169     CALL_DEBUG_ENTER;
170     std::lock_guard<std::mutex> lock(subscriberMapMutex_);
171     for (auto iter = subscriberMap_.begin(); iter != subscriberMap_.end(); iter++) {
172         auto &subscribers = iter->second;
173         for (auto it = subscribers.begin(); it != subscribers.end(); it++) {
174             if ((*it)->id_ == subscribeId && (*it)->sess_ == sess) {
175                 ClearTimer(*it);
176                 auto option = (*it)->keyOption_;
177                 CHKPR(option, ERROR_NULL_POINTER);
178 #ifdef SHORTCUT_KEY_MANAGER_ENABLED
179                 if (isSystem) {
180                     KEY_SHORTCUT_MGR->UnregisterSystemKey((*it)->shortcutId_);
181                 } else {
182                     KEY_SHORTCUT_MGR->UnregisterHotKey((*it)->shortcutId_);
183                 }
184 #endif // SHORTCUT_KEY_MANAGER_ENABLED
185                 MMI_HILOGI("SubscribeId:%{public}d, finalKey:%{private}d, isFinalKeyDown:%{public}s,"
186                     "finalKeyDownDuration:%{public}d, pid:%{public}d", subscribeId, option->GetFinalKey(),
187                     option->IsFinalKeyDown() ? "true" : "false", option->GetFinalKeyDownDuration(), sess->GetPid());
188                 subscribers.erase(it);
189                 DfxHisysevent::ReportUnSubscribeKeyEvent(subscribeId, option->GetFinalKey(),
190                     sess->GetProgramName(), sess->GetPid());
191                 return RET_OK;
192             }
193         }
194     }
195     return RET_ERR;
196 }
197 
AddKeyGestureSubscriber(std::shared_ptr<Subscriber> subscriber,std::shared_ptr<KeyOption> keyOption)198 int32_t KeySubscriberHandler::AddKeyGestureSubscriber(
199     std::shared_ptr<Subscriber> subscriber, std::shared_ptr<KeyOption> keyOption)
200 {
201     CALL_INFO_TRACE;
202     CHKPR(subscriber, RET_ERR);
203     CHKPR(subscriber->sess_, RET_ERR);
204     subscriber->timerId_ = keyGestureMgr_.AddKeyGesture(subscriber->sess_->GetPid(), keyOption,
205         [this, subscriber](std::shared_ptr<KeyEvent> keyEvent) {
206             NotifySubscriber(keyEvent, subscriber);
207         });
208     if (subscriber->timerId_ < 0) {
209         MMI_HILOGE("AddKeyGesture fail, error:%{public}d", subscriber->timerId_);
210         return RET_ERR;
211     }
212     MMI_HILOGI("Handler(%{public}d) of key gesture was added", subscriber->timerId_);
213     PrintKeyOption(keyOption);
214     for (auto &iter : keyGestures_) {
215         if (IsEqualKeyOption(keyOption, iter.first)) {
216             iter.second.push_back(subscriber);
217             return RET_OK;
218         }
219     }
220     keyGestures_[keyOption] = { subscriber };
221     return RET_OK;
222 }
223 
RemoveKeyGestureSubscriber(SessionPtr sess,int32_t subscribeId)224 int32_t KeySubscriberHandler::RemoveKeyGestureSubscriber(SessionPtr sess, int32_t subscribeId)
225 {
226     CALL_INFO_TRACE;
227     for (auto iter = keyGestures_.begin(); iter != keyGestures_.end(); ++iter) {
228         auto &subscribers = iter->second;
229 
230         for (auto innerIter = subscribers.begin(); innerIter != subscribers.end(); ++innerIter) {
231             auto subscriber = *innerIter;
232 
233             if ((subscriber->id_ != subscribeId) || (subscriber->sess_ != sess)) {
234                 continue;
235             }
236             MMI_HILOGI("Removing handler(%{public}d) of key gesture", subscriber->timerId_);
237             keyGestureMgr_.RemoveKeyGesture(subscriber->timerId_);
238             auto option = subscriber->keyOption_;
239             MMI_HILOGI("SubscribeId:%{public}d, finalKey:%{private}d, isFinalKeyDown:%{public}s,"
240                 "finalKeyDownDuration:%{public}d, pid:%{public}d", subscribeId, option->GetFinalKey(),
241                 option->IsFinalKeyDown() ? "true" : "false", option->GetFinalKeyDownDuration(), sess->GetPid());
242             subscribers.erase(innerIter);
243             return RET_OK;
244         }
245     }
246     return RET_ERR;
247 }
248 
249 #ifdef SHORTCUT_KEY_MANAGER_ENABLED
RegisterSystemKey(std::shared_ptr<KeyOption> option,int32_t session,std::function<void (std::shared_ptr<KeyEvent>)> callback)250 int32_t KeySubscriberHandler::RegisterSystemKey(std::shared_ptr<KeyOption> option,
251     int32_t session, std::function<void(std::shared_ptr<KeyEvent>)> callback)
252 {
253     KeyShortcutManager::SystemShortcutKey sysKey {
254         .modifiers = option->GetPreKeys(),
255         .finalKey = option->GetFinalKey(),
256         .longPressTime = option->GetFinalKeyDownDuration(),
257         .triggerType = (option->IsFinalKeyDown() ? KeyShortcutManager::SHORTCUT_TRIGGER_TYPE_DOWN :
258                                                    KeyShortcutManager::SHORTCUT_TRIGGER_TYPE_UP),
259         .session = session,
260         .callback = callback,
261     };
262     if (KeyShortcutManager::IsModifier(sysKey.finalKey) &&
263         !sysKey.modifiers.empty() &&
264         std::all_of(sysKey.modifiers.cbegin(), sysKey.modifiers.cend(),
265             [](auto key) {
266                 return KeyShortcutManager::IsModifier(key);
267             })) {
268         sysKey.modifiers.insert(sysKey.finalKey);
269         sysKey.finalKey = KeyShortcutManager::SHORTCUT_PURE_MODIFIERS;
270     }
271     return KEY_SHORTCUT_MGR->RegisterSystemKey(sysKey);
272 }
273 
RegisterHotKey(std::shared_ptr<KeyOption> option,int32_t session,std::function<void (std::shared_ptr<KeyEvent>)> callback)274 int32_t KeySubscriberHandler::RegisterHotKey(std::shared_ptr<KeyOption> option,
275     int32_t session, std::function<void(std::shared_ptr<KeyEvent>)> callback)
276 {
277     KeyShortcutManager::HotKey hotKey {
278         .modifiers = option->GetPreKeys(),
279         .finalKey = option->GetFinalKey(),
280         .longPressTime = option->GetFinalKeyDownDuration(),
281         .session = session,
282         .callback = callback,
283     };
284     return KEY_SHORTCUT_MGR->RegisterHotKey(hotKey);
285 }
286 
UnregisterSystemKey(int32_t shortcutId)287 void KeySubscriberHandler::UnregisterSystemKey(int32_t shortcutId)
288 {
289     KEY_SHORTCUT_MGR->UnregisterSystemKey(shortcutId);
290 }
291 
UnregisterHotKey(int32_t shortcutId)292 void KeySubscriberHandler::UnregisterHotKey(int32_t shortcutId)
293 {
294     KEY_SHORTCUT_MGR->UnregisterHotKey(shortcutId);
295 }
296 
DeleteShortcutId(std::shared_ptr<Subscriber> subscriber)297 void KeySubscriberHandler::DeleteShortcutId(std::shared_ptr<Subscriber> subscriber)
298 {
299     if (subscriber->isSystem) {
300         UnregisterSystemKey(subscriber->shortcutId_);
301     } else {
302         UnregisterHotKey(subscriber->shortcutId_);
303     }
304 }
305 #endif // SHORTCUT_KEY_MANAGER_ENABLED
306 
SubscribeHotkey(SessionPtr sess,int32_t subscribeId,std::shared_ptr<KeyOption> keyOption)307 int32_t KeySubscriberHandler::SubscribeHotkey(
308     SessionPtr sess, int32_t subscribeId, std::shared_ptr<KeyOption> keyOption)
309 {
310     CHKPR(sess, ERROR_NULL_POINTER);
311     CHKPR(keyOption, ERROR_NULL_POINTER);
312     uint32_t preKeySize = keyOption->GetPreKeys().size();
313     if (preKeySize > MAX_PRE_KEY_COUNT) {
314         MMI_HILOGE("Leave, preKeySize:%{public}u", preKeySize);
315         return RET_ERR;
316     }
317     for (const auto &keyCode : keyOption->GetPreKeys()) {
318         MMI_HILOGD("keyOption->prekey:%{private}d", keyCode);
319     }
320     MMI_HILOGI("SubscribeId:%{public}d, finalKey:%{private}d,"
321         "isFinalKeyDown:%{public}s, finalKeyDownDuration:%{public}d, pid:%{public}d",
322         subscribeId, keyOption->GetFinalKey(), keyOption->IsFinalKeyDown() ? "true" : "false",
323         keyOption->GetFinalKeyDownDuration(), sess->GetPid());
324     auto subscriber = std::make_shared<Subscriber>(subscribeId, sess, keyOption);
325     auto ret = AddSubscriber(subscriber, keyOption, false);
326     if (ret != RET_OK) {
327         MMI_HILOGE("AddSubscriber fail, error:%{public}d", ret);
328         DfxHisysevent::ReportFailSubscribeKey("SubscribeHotkey", sess->GetProgramName(),
329             keyOption->GetFinalKey(), DfxHisysevent::KEY_ERROR_CODE::ERROR_RETURN_VALUE);
330         return ret;
331     }
332     InitSessionDeleteCallback();
333     return RET_OK;
334 }
335 
UnsubscribeHotkey(SessionPtr sess,int32_t subscribeId)336 int32_t KeySubscriberHandler::UnsubscribeHotkey(SessionPtr sess, int32_t subscribeId)
337 {
338     CHKPR(sess, ERROR_NULL_POINTER);
339     MMI_HILOGI("SubscribeId:%{public}d, pid:%{public}d", subscribeId, sess->GetPid());
340     int32_t ret = RemoveSubscriber(sess, subscribeId, false);
341     if (ret != RET_OK) {
342         MMI_HILOGW("No hot key subscription(%{public}d, No.%{public}d)", sess->GetPid(), subscribeId);
343         DfxHisysevent::ReportFailSubscribeKey("UnsubscribeHotkey", sess->GetProgramName(),
344             subscribeId, DfxHisysevent::KEY_ERROR_CODE::ERROR_RETURN_VALUE);
345     }
346     return ret;
347 }
348 
AddSubscriber(std::shared_ptr<Subscriber> subscriber,std::shared_ptr<KeyOption> option,bool isSystem)349 int32_t KeySubscriberHandler::AddSubscriber(std::shared_ptr<Subscriber> subscriber,
350     std::shared_ptr<KeyOption> option, bool isSystem)
351 {
352     CALL_DEBUG_ENTER;
353     CHKPR(subscriber, RET_ERR);
354     CHKPR(option, RET_ERR);
355     PrintKeyOption(option);
356 #ifdef SHORTCUT_KEY_MANAGER_ENABLED
357     CHKPR(subscriber->sess_, RET_ERR);
358     if (isSystem) {
359         subscriber->isSystem = true;
360         subscriber->shortcutId_ = RegisterSystemKey(option, subscriber->sess_->GetPid(),
361             [this, subscriber](std::shared_ptr<KeyEvent> keyEvent) {
362                 NotifySubscriber(keyEvent, subscriber);
363             });
364     } else {
365         subscriber->isSystem = false;
366         subscriber->shortcutId_ = RegisterHotKey(option, subscriber->sess_->GetPid(),
367             [this, subscriber](std::shared_ptr<KeyEvent> keyEvent) {
368                 NotifySubscriber(keyEvent, subscriber);
369             });
370     }
371     if (subscriber->shortcutId_ < 0) {
372         MMI_HILOGE("Register shortcut fail, error:%{public}d", subscriber->shortcutId_);
373         return subscriber->shortcutId_;
374     }
375 #endif // SHORTCUT_KEY_MANAGER_ENABLED
376     std::lock_guard<std::mutex> lock(subscriberMapMutex_);
377     for (auto &iter : subscriberMap_) {
378         if (IsEqualKeyOption(option, iter.first)) {
379             MMI_HILOGI("Add subscriber Id:%{public}d, pid:%{public}d", subscriber->id_, subscriber->sess_->GetPid());
380             iter.second.push_back(std::move(subscriber));
381             MMI_HILOGD("Subscriber size:%{public}zu", iter.second.size());
382             return RET_OK;
383         }
384     }
385     MMI_HILOGI("Add subscriber Id:%{public}d", subscriber->id_);
386     subscriberMap_[option] = {subscriber};
387     return RET_OK;
388 }
389 
IsEqualKeyOption(std::shared_ptr<KeyOption> newOption,std::shared_ptr<KeyOption> oldOption)390 bool KeySubscriberHandler::IsEqualKeyOption(std::shared_ptr<KeyOption> newOption,
391     std::shared_ptr<KeyOption> oldOption)
392 {
393     CALL_DEBUG_ENTER;
394     CHKPF(newOption);
395     CHKPF(oldOption);
396     if (!IsEqualPreKeys(newOption->GetPreKeys(), oldOption->GetPreKeys())) {
397         MMI_HILOGD("Pre key not match");
398         return false;
399     }
400     if (newOption->GetFinalKey() != oldOption->GetFinalKey()) {
401         MMI_HILOGD("Final key not match");
402         return false;
403     }
404     if (newOption->IsFinalKeyDown() != oldOption->IsFinalKeyDown()) {
405         MMI_HILOGD("Is final key down not match");
406         return false;
407     }
408     if (newOption->GetFinalKeyDownDuration() != oldOption->GetFinalKeyDownDuration()) {
409         MMI_HILOGD("Final key down duration not match");
410         return false;
411     }
412     if (newOption->GetFinalKeyUpDelay() != oldOption->GetFinalKeyUpDelay()) {
413         MMI_HILOGD("Is final key up delay not match");
414         return false;
415     }
416     MMI_HILOGD("Key option match");
417     return true;
418 }
419 
GetForegroundPids(std::set<int32_t> & pids)420 void KeySubscriberHandler::GetForegroundPids(std::set<int32_t> &pids)
421 {
422     CALL_DEBUG_ENTER;
423     std::vector<AppExecFwk::AppStateData> list = APP_OBSERVER_MGR->GetForegroundAppData();
424     for (auto iter = list.begin(); iter != list.end(); iter++) {
425         MMI_HILOGD("Foreground process pid:%{public}d", (*iter).pid);
426         pids.insert((*iter).pid);
427     }
428 }
429 
EnableCombineKey(bool enable)430 int32_t KeySubscriberHandler::EnableCombineKey(bool enable)
431 {
432     enableCombineKey_ = enable;
433     MMI_HILOGI("Enable combineKey is successful in subscribe handler, enable:%{public}d", enable);
434     return RET_OK;
435 }
436 
IsFunctionKey(const std::shared_ptr<KeyEvent> keyEvent)437 bool KeySubscriberHandler::IsFunctionKey(const std::shared_ptr<KeyEvent> keyEvent)
438 {
439     MMI_HILOGD("Is Funciton Key In");
440     if (keyEvent->GetKeyCode() == KeyEvent::KEYCODE_BRIGHTNESS_DOWN
441         || keyEvent->GetKeyCode() == KeyEvent::KEYCODE_BRIGHTNESS_UP) {
442         return true;
443     }
444     if (keyEvent->GetKeyCode() == KeyEvent::KEYCODE_VOLUME_UP
445         || keyEvent->GetKeyCode() == KeyEvent::KEYCODE_VOLUME_DOWN
446         || keyEvent->GetKeyCode() == KeyEvent::KEYCODE_VOLUME_MUTE) {
447         return true;
448     }
449     if (keyEvent->GetKeyCode() == KeyEvent::KEYCODE_MUTE
450         || keyEvent->GetKeyCode() == KeyEvent::KEYCODE_SWITCHVIDEOMODE
451         || keyEvent->GetKeyCode() == KeyEvent::KEYCODE_MEDIA_RECORD) {
452         return true;
453     }
454     return false;
455 }
456 
IsEnableCombineKey(const std::shared_ptr<KeyEvent> keyEvent)457 bool KeySubscriberHandler::IsEnableCombineKey(const std::shared_ptr<KeyEvent> keyEvent)
458 {
459     CHKPF(keyEvent);
460     if (enableCombineKey_) {
461         return true;
462     }
463     if (IsFunctionKey(keyEvent)) {
464         auto items = keyEvent->GetKeyItems();
465         return items.size() != 1 ? enableCombineKey_ : true;
466     }
467     if (keyEvent->GetKeyCode() == KeyEvent::KEYCODE_POWER) {
468         auto items = keyEvent->GetKeyItems();
469         if (items.size() != 1) {
470             return enableCombineKey_;
471         }
472         return true;
473     }
474     if (keyEvent->GetKeyCode() == KeyEvent::KEYCODE_DPAD_RIGHT ||
475         keyEvent->GetKeyCode() == KeyEvent::KEYCODE_DPAD_LEFT) {
476         if (EventLogHelper::IsBetaVersion() && !keyEvent->HasFlag(InputEvent::EVENT_FLAG_PRIVACY_MODE)) {
477             MMI_HILOGD("Subscriber mulit swipe keycode is:%d", keyEvent->GetKeyCode());
478         } else {
479             MMI_HILOGD("Subscriber mulit swipe keycode is:%{private}d", keyEvent->GetKeyCode());
480         }
481         return IsEnableCombineKeySwipe(keyEvent);
482     }
483     if (keyEvent->GetKeyCode() == KeyEvent::KEYCODE_R) {
484         return IsEnableCombineKeyRecord(keyEvent);
485     }
486     if (keyEvent->GetKeyCode() == KeyEvent::KEYCODE_L) {
487         for (const auto &item : keyEvent->GetKeyItems()) {
488             int32_t keyCode = item.GetKeyCode();
489             if (keyCode != KeyEvent::KEYCODE_L && keyCode != KeyEvent::KEYCODE_META_LEFT &&
490                 keyCode != KeyEvent::KEYCODE_META_RIGHT) {
491                 return enableCombineKey_;
492             }
493         }
494         return true;
495     }
496     if (!InterceptByVm(keyEvent)) {
497         return true;
498     }
499 
500     return enableCombineKey_;
501 }
502 
IsEnableCombineKeySwipe(const std::shared_ptr<KeyEvent> keyEvent)503 bool KeySubscriberHandler::IsEnableCombineKeySwipe(const std::shared_ptr<KeyEvent> keyEvent)
504 {
505     for (const auto &item : keyEvent->GetKeyItems()) {
506         int32_t keyCode = item.GetKeyCode();
507         if (keyCode != KeyEvent::KEYCODE_CTRL_LEFT && keyCode != KeyEvent::KEYCODE_META_LEFT &&
508             keyCode != KeyEvent::KEYCODE_DPAD_RIGHT && keyCode != KeyEvent::KEYCODE_CTRL_RIGHT &&
509             keyCode != KeyEvent::KEYCODE_DPAD_LEFT) {
510             return enableCombineKey_;
511         }
512     }
513     return true;
514 }
515 
IsEnableCombineKeyRecord(const std::shared_ptr<KeyEvent> keyEvent)516 bool KeySubscriberHandler::IsEnableCombineKeyRecord(const std::shared_ptr<KeyEvent> keyEvent)
517 {
518     for (const auto &item : keyEvent->GetKeyItems()) {
519         int32_t keyCode = item.GetKeyCode();
520         if (keyCode != KeyEvent::KEYCODE_SHIFT_LEFT && keyCode != KeyEvent::KEYCODE_META_LEFT &&
521             keyCode != KeyEvent::KEYCODE_SHIFT_RIGHT && keyCode != KeyEvent::KEYCODE_META_RIGHT &&
522             keyCode != KeyEvent::KEYCODE_R) {
523             return enableCombineKey_;
524         }
525     }
526     return true;
527 }
528 
InterceptByVm(const std::shared_ptr<KeyEvent> keyEvt)529 bool KeySubscriberHandler::InterceptByVm(const std::shared_ptr<KeyEvent> keyEvt)
530 {
531     // logo + leftShift + E is used by sceneboard, do not intercept by vm
532     const std::vector<int32_t> LOGO_LEFTSHIFT_E = {
533         KeyEvent::KEYCODE_META_LEFT, KeyEvent::KEYCODE_SHIFT_LEFT, KeyEvent::KEYCODE_E};
534     size_t waitMatchCnt{LOGO_LEFTSHIFT_E.size()};
535     if (keyEvt->GetKeyItems().size() != waitMatchCnt) {
536         return true;
537     }
538     for (auto &&keyItem : keyEvt->GetKeyItems()) {
539         for (auto &&k : LOGO_LEFTSHIFT_E) {
540             if (keyItem.GetKeyCode() == k) {
541                 --waitMatchCnt;
542                 break;
543             };
544         }
545     }
546     if (waitMatchCnt == 0) {
547         return false;
548     }
549     return true;
550 }
551 
PublishKeyPressCommonEvent(std::shared_ptr<KeyEvent> keyEvent)552 void KeySubscriberHandler::PublishKeyPressCommonEvent(std::shared_ptr<KeyEvent> keyEvent)
553 {
554     OHOS::AAFwk::Want want;
555     want.SetAction("multimodal.event.MUTE_KEY_PRESS");
556     want.SetParam("keyCode", keyEvent->GetKeyCode());
557     EventFwk::CommonEventPublishInfo publishInfo;
558     std::vector<std::string> permissionVec {"ohos.permission.NOTIFICATION_CONTROLLER"};
559     publishInfo.SetSubscriberPermissions(permissionVec);
560     EventFwk::CommonEventData commonData {want};
561     EventFwk::CommonEventManager::PublishCommonEvent(commonData, publishInfo);
562 }
563 
HandleRingMute(std::shared_ptr<KeyEvent> keyEvent)564 bool KeySubscriberHandler::HandleRingMute(std::shared_ptr<KeyEvent> keyEvent)
565 {
566     CALL_DEBUG_ENTER;
567     CHKPF(keyEvent);
568     if (keyEvent->GetKeyCode() != KeyEvent::KEYCODE_VOLUME_DOWN &&
569         keyEvent->GetKeyCode() != KeyEvent::KEYCODE_VOLUME_UP &&
570         keyEvent->GetKeyCode() != KeyEvent::KEYCODE_POWER) {
571         MMI_HILOGD("There is no need to set mute");
572         return false;
573     }
574     int32_t ret = -1;
575     PublishKeyPressCommonEvent(keyEvent);
576     if (DEVICE_MONITOR->GetCallState() == StateType::CALL_STATUS_INCOMING ||
577         DEVICE_MONITOR->GetCallState() == StateType::CALL_STATUS_WAITING) {
578         if (callManagerClientPtr == nullptr) {
579             callManagerClientPtr = DelayedSingleton<OHOS::Telephony::CallManagerClient>::GetInstance();
580             if (callManagerClientPtr == nullptr) {
581                 MMI_HILOGE("CallManager init fail");
582                 return false;
583             }
584             auto begin = std::chrono::high_resolution_clock::now();
585             callManagerClientPtr->Init(OHOS::TELEPHONY_CALL_MANAGER_SYS_ABILITY_ID);
586             auto durationMS = std::chrono::duration_cast<std::chrono::milliseconds>(
587                 std::chrono::high_resolution_clock::now() - begin).count();
588 #ifdef OHOS_BUILD_ENABLE_DFX_RADAR
589             DfxHisysevent::ReportApiCallTimes(ApiDurationStatistics::Api::TELEPHONY_CALL_MGR_INIT, durationMS);
590 #endif // OHOS_BUILD_ENABLE_DFX_RADAR
591         }
592         if (!DEVICE_MONITOR->GetHasHandleRingMute()) {
593             auto begin = std::chrono::high_resolution_clock::now();
594             ret = callManagerClientPtr->MuteRinger();
595             auto durationMS = std::chrono::duration_cast<std::chrono::milliseconds>(
596                 std::chrono::high_resolution_clock::now() - begin).count();
597 #ifdef OHOS_BUILD_ENABLE_DFX_RADAR
598             DfxHisysevent::ReportApiCallTimes(ApiDurationStatistics::Api::TELEPHONY_CALL_MGR_MUTE_RINGER, durationMS);
599 #endif // OHOS_BUILD_ENABLE_DFX_RADAR
600             if (ret != ERR_OK) {
601                 MMI_HILOGE("Set mute fail, ret:%{public}d", ret);
602                 return false;
603             }
604             MMI_HILOGW("Set mute success");
605             DEVICE_MONITOR->SetHasHandleRingMute(true);
606             if (keyEvent->GetKeyCode() == KeyEvent::KEYCODE_POWER) {
607                 needSkipPowerKeyUp_ = true;
608             }
609             return true;
610         } else {
611             if (keyEvent->GetKeyCode() != KeyEvent::KEYCODE_POWER) {
612                 MMI_HILOGI("Set mute success, block volumeKey");
613                 return true;
614             }
615         }
616     }
617     return false;
618 }
619 
OnSubscribeKeyEvent(std::shared_ptr<KeyEvent> keyEvent)620 bool KeySubscriberHandler::OnSubscribeKeyEvent(std::shared_ptr<KeyEvent> keyEvent)
621 {
622     CALL_DEBUG_ENTER;
623     CHKPF(keyEvent);
624     if (HandleRingMute(keyEvent)) {
625         MMI_HILOGI("Mute Ring in subscribe keyEvent");
626         RemoveSubscriberTimer(keyEvent);
627         return true;
628     }
629     if (HandleCallEnded(keyEvent)) {
630         MMI_HILOGI("Call Ended in subscribe keyEvent");
631         return true;
632     }
633     if (!IsEnableCombineKey(keyEvent)) {
634         MMI_HILOGI("Combine key is taken over in subscribe keyEvent");
635         return false;
636     }
637     if (keyGestureMgr_.Intercept(keyEvent)) {
638         MMI_HILOGD("Key gesture recognized");
639         return true;
640     }
641     if (KEY_MONITOR_MGR->Intercept(keyEvent)) {
642         MMI_HILOGD("Key monitor intercept (KC:%{private}d, KA:%{public}d)",
643             keyEvent->GetKeyCode(), keyEvent->GetKeyAction());
644         return true;
645     }
646     if (IsRepeatedKeyEvent(keyEvent)) {
647         MMI_HILOGD("Repeat KeyEvent, skip");
648         return true;
649     }
650     return ProcessKeyEvent(keyEvent);
651 }
652 
ProcessKeyEvent(std::shared_ptr<KeyEvent> keyEvent)653 bool KeySubscriberHandler::ProcessKeyEvent(std::shared_ptr<KeyEvent> keyEvent)
654 {
655     keyEvent_ = KeyEvent::Clone(keyEvent);
656     int32_t keyAction = keyEvent->GetKeyAction();
657     if (EventLogHelper::IsBetaVersion() && !keyEvent->HasFlag(InputEvent::EVENT_FLAG_PRIVACY_MODE)) {
658         MMI_HILOGD("keyCode:%d, keyAction:%{public}s", keyEvent->GetKeyCode(), KeyEvent::ActionToString(keyAction));
659     } else {
660         MMI_HILOGD("keyCode:%{private}d, keyAction:%{public}s",
661             keyEvent->GetKeyCode(), KeyEvent::ActionToString(keyAction));
662     }
663     if (needSkipPowerKeyUp_ && keyEvent->GetKeyCode() == KeyEvent::KEYCODE_POWER
664         && keyAction == KeyEvent::KEY_ACTION_UP) {
665         MMI_HILOGD("Skip power key up");
666         needSkipPowerKeyUp_ = false;
667         return true;
668     }
669     for (const auto &keyCode : keyEvent->GetPressedKeys()) {
670         if (EventLogHelper::IsBetaVersion() && !keyEvent->HasFlag(InputEvent::EVENT_FLAG_PRIVACY_MODE)) {
671             MMI_HILOGD("Pressed KeyCode:%d", keyCode);
672         } else {
673             MMI_HILOGD("Pressed KeyCode:%{private}d", keyCode);
674         }
675     }
676     bool handled = false;
677     if (keyAction == KeyEvent::KEY_ACTION_DOWN) {
678         handled = HandleKeyDown(keyEvent);
679     } else if (keyAction == KeyEvent::KEY_ACTION_UP) {
680         hasEventExecuting_ = false;
681         handled = HandleKeyUp(keyEvent);
682     } else if (keyAction == KeyEvent::KEY_ACTION_CANCEL) {
683         hasEventExecuting_ = false;
684         DfxHisysevent::ReportKeyEvent("cancel");
685         handled = HandleKeyCancel(keyEvent);
686     } else {
687         MMI_HILOGW("keyAction exception");
688     }
689     return handled;
690 }
691 
OnSessionDelete(SessionPtr sess)692 void KeySubscriberHandler::OnSessionDelete(SessionPtr sess)
693 {
694     CALL_DEBUG_ENTER;
695     CHKPV(sess);
696     {
697         std::lock_guard<std::mutex> lock(subscriberMapMutex_);
698         for (auto iter = subscriberMap_.begin(); iter != subscriberMap_.end(); iter++) {
699             auto &subscribers = iter->second;
700             for (auto it = subscribers.begin(); it != subscribers.end();) {
701                 if ((*it)->sess_ == sess) {
702                     ClearTimer(*it);
703 #ifdef SHORTCUT_KEY_MANAGER_ENABLED
704                     DeleteShortcutId(*it);
705 #endif // SHORTCUT_KEY_MANAGER_ENABLED
706                     subscribers.erase(it++);
707                     continue;
708                 }
709                 ++it;
710             }
711         }
712     }
713     for (auto iter = keyGestures_.begin(); iter != keyGestures_.end();) {
714         auto &subscribers = iter->second;
715         for (auto inner = subscribers.begin(); inner != subscribers.end();) {
716             auto subscriber = *inner;
717             if (subscriber->sess_ == sess) {
718                 MMI_HILOGI("Removing key-gesture handler(%{public}d) on subscriber(%{public}d) dying",
719                     subscriber->timerId_, sess->GetPid());
720                 keyGestureMgr_.RemoveKeyGesture(subscriber->timerId_);
721                 auto option = subscriber->keyOption_;
722                 MMI_HILOGI("SubscribeId:%{public}d, finalKey:%{private}d, isFinalKeyDown:%{public}s,"
723                     "finalKeyDownDuration:%{public}d, pid:%{public}d", subscriber->id_, option->GetFinalKey(),
724                     option->IsFinalKeyDown() ? "true" : "false", option->GetFinalKeyDownDuration(), sess->GetPid());
725                 inner = subscribers.erase(inner);
726             } else {
727                 ++inner;
728             }
729         }
730         if (subscribers.empty()) {
731             iter = keyGestures_.erase(iter);
732         } else {
733             ++iter;
734         }
735     }
736 }
737 
IsPreKeysMatch(const std::set<int32_t> & preKeys,const std::vector<int32_t> & pressedKeys) const738 bool KeySubscriberHandler::IsPreKeysMatch(const std::set<int32_t> &preKeys,
739                                           const std::vector<int32_t> &pressedKeys) const
740 {
741     if (preKeys.size() == 0) {
742         MMI_HILOGD("The preKeys is empty");
743         return true;
744     }
745 
746     if (preKeys.size() != pressedKeys.size()) {
747         MMI_HILOGE("The size of preKeys is not match");
748         return false;
749     }
750 
751     for (const auto &pressedKey : pressedKeys) {
752         auto it = std::find(preKeys.begin(), preKeys.end(), pressedKey);
753         if (it == preKeys.end()) {
754             MMI_HILOGE("Cant't find the pressedKey");
755             return false;
756         }
757     }
758 
759     return true;
760 }
761 
IsEqualPreKeys(const std::set<int32_t> & preKeys,const std::set<int32_t> & pressedKeys)762 bool KeySubscriberHandler::IsEqualPreKeys(const std::set<int32_t> &preKeys, const std::set<int32_t> &pressedKeys)
763 {
764     if (preKeys.size() != pressedKeys.size()) {
765         MMI_HILOGD("Pre key size not equal");
766         return false;
767     }
768 
769     for (const auto &pressedKey : pressedKeys) {
770         auto it = std::find(preKeys.begin(), preKeys.end(), pressedKey);
771         if (it == preKeys.end()) {
772             return false;
773         }
774     }
775     MMI_HILOGD("Equal prekeys");
776     return true;
777 }
778 
IsMatchForegroundPid(std::list<std::shared_ptr<Subscriber>> subs,std::set<int32_t> foregroundPids)779 bool KeySubscriberHandler::IsMatchForegroundPid(std::list<std::shared_ptr<Subscriber>> subs,
780     std::set<int32_t> foregroundPids)
781 {
782     CALL_DEBUG_ENTER;
783     isForegroundExits_ = false;
784     foregroundPids_.clear();
785     for (const auto &item : subs) {
786         CHKPF(item);
787         auto sess = item->sess_;
788         CHKPF(sess);
789         if (foregroundPids.find(sess->GetPid()) != foregroundPids.end()) {
790             MMI_HILOGD("Subscriber foregroundPid:%{public}d", sess->GetPid());
791             foregroundPids_.insert(sess->GetPid());
792             isForegroundExits_ = true;
793         }
794     }
795     MMI_HILOGD("The isForegroundExits_:%{public}d, foregroundPids:%{public}zu",
796         isForegroundExits_, foregroundPids_.size());
797     return isForegroundExits_;
798 }
799 
NotifyKeyDownSubscriber(const std::shared_ptr<KeyEvent> & keyEvent,std::shared_ptr<KeyOption> keyOption,std::list<std::shared_ptr<Subscriber>> & subscribers,bool & handled)800 void KeySubscriberHandler::NotifyKeyDownSubscriber(const std::shared_ptr<KeyEvent> &keyEvent,
801     std::shared_ptr<KeyOption> keyOption, std::list<std::shared_ptr<Subscriber>> &subscribers, bool &handled)
802 {
803     CALL_DEBUG_ENTER;
804     CHKPV(keyEvent);
805     CHKPV(keyOption);
806     MMI_HILOGD("Notify key down subscribers size:%{public}zu", subscribers.size());
807     if (keyOption->GetFinalKeyDownDuration() <= 0) {
808         NotifyKeyDownRightNow(keyEvent, subscribers,  keyOption->IsRepeat(), handled);
809     } else {
810         NotifyKeyDownDelay(keyEvent, subscribers, handled);
811     }
812 }
NotifyKeyDownRightNow(const std::shared_ptr<KeyEvent> & keyEvent,std::list<std::shared_ptr<Subscriber>> & subscribers,bool isRepeat,bool & handled)813 void KeySubscriberHandler::NotifyKeyDownRightNow(const std::shared_ptr<KeyEvent> &keyEvent,
814     std::list<std::shared_ptr<Subscriber>> &subscribers, bool isRepeat, bool &handled)
815 {
816     CALL_DEBUG_ENTER;
817     MMI_HILOGD("The subscribe list size is %{public}zu", subscribers.size());
818     for (auto &subscriber : subscribers) {
819         CHKPC(subscriber);
820         auto sess = subscriber->sess_;
821         CHKPC(sess);
822         if (!isForegroundExits_ || keyEvent->GetKeyCode() == KeyEvent::KEYCODE_POWER ||
823             foregroundPids_.find(sess->GetPid()) != foregroundPids_.end()) {
824             MMI_HILOGD("keyOption->GetFinalKeyDownDuration() <= 0");
825             if (!isRepeat && keyEvent->GetKeyCode() == KeyRepeat->GetRepeatKeyCode()) {
826                 MMI_HILOGD("Subscribers do not need to repeat events");
827                 handled = true;
828                 continue;
829             }
830             NotifySubscriber(keyEvent, subscriber);
831             handled = true;
832         }
833     }
834 }
835 
NotifyKeyDownDelay(const std::shared_ptr<KeyEvent> & keyEvent,std::list<std::shared_ptr<Subscriber>> & subscribers,bool & handled)836 void KeySubscriberHandler::NotifyKeyDownDelay(const std::shared_ptr<KeyEvent> &keyEvent,
837     std::list<std::shared_ptr<Subscriber>> &subscribers, bool &handled)
838 {
839     CALL_DEBUG_ENTER;
840     MMI_HILOGD("The subscribe list size is %{public}zu", subscribers.size());
841     for (auto &subscriber : subscribers) {
842         CHKPC(subscriber);
843         auto sess = subscriber->sess_;
844         CHKPC(sess);
845         if (!isForegroundExits_ || keyEvent->GetKeyCode() == KeyEvent::KEYCODE_POWER ||
846             foregroundPids_.find(sess->GetPid()) != foregroundPids_.end()) {
847             MMI_HILOGD("Add timer");
848             if (!AddTimer(subscriber, keyEvent)) {
849                 MMI_HILOGE("Add time failed, subscriberId:%{public}d", subscriber->id_);
850                 continue;
851             }
852             handled = true;
853         }
854     }
855 }
856 
NotifyKeyUpSubscriber(const std::shared_ptr<KeyEvent> & keyEvent,std::list<std::shared_ptr<Subscriber>> subscribers,bool & handled)857 void KeySubscriberHandler::NotifyKeyUpSubscriber(const std::shared_ptr<KeyEvent> &keyEvent,
858     std::list<std::shared_ptr<Subscriber>> subscribers, bool &handled)
859 {
860     CALL_DEBUG_ENTER;
861     MMI_HILOGD("Subscribers size:%{public}zu", subscribers.size());
862     for (auto &subscriber : subscribers) {
863         CHKPC(subscriber);
864         auto sess = subscriber->sess_;
865         CHKPC(sess);
866         if (!isForegroundExits_ || foregroundPids_.find(sess->GetPid()) != foregroundPids_.end()) {
867             HandleKeyUpWithDelay(keyEvent, subscriber);
868             handled = true;
869         }
870     }
871 }
872 
NotifySubscriber(std::shared_ptr<KeyEvent> keyEvent,const std::shared_ptr<Subscriber> & subscriber)873 void KeySubscriberHandler::NotifySubscriber(std::shared_ptr<KeyEvent> keyEvent,
874     const std::shared_ptr<Subscriber> &subscriber) __attribute__((no_sanitize("cfi")))
875 {
876     CALL_DEBUG_ENTER;
877     CHKPV(keyEvent);
878     CHKPV(subscriber);
879 #ifdef SHORTCUT_KEY_RULES_ENABLED
880     if (keyEvent->GetKeyCode() != KeyEvent::KEYCODE_POWER) {
881         CHKPV(subscriber->keyOption_);
882         KEY_SHORTCUT_MGR->MarkShortcutConsumed(*subscriber->keyOption_);
883     }
884 #endif // SHORTCUT_KEY_RULES_ENABLED
885     auto udsServerPtr = InputHandler->GetUDSServer();
886     CHKPV(udsServerPtr);
887     if (keyEvent->GetKeyCode() == KeyEvent::KEYCODE_POWER) {
888         DfxHisysevent::ReportPowerInfo(keyEvent, OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC);
889     }
890     SubscriberNotifyNap(subscriber);
891     NetPacket pkt(MmiMessageId::ON_SUBSCRIBE_KEY);
892     InputEventDataTransformation::KeyEventToNetPacket(keyEvent, pkt);
893     auto sess = subscriber->sess_;
894     CHKPV(sess);
895     int32_t fd = sess->GetFd();
896     pkt << fd << subscriber->id_;
897     if (!EventLogHelper::IsBetaVersion()) {
898         MMI_HILOGI("Notify subscriber id:%{public}d, pid:%{public}d", subscriber->id_, sess->GetPid());
899     } else {
900         if (EventLogHelper::IsBetaVersion() && !keyEvent->HasFlag(InputEvent::EVENT_FLAG_PRIVACY_MODE)) {
901             MMI_HILOGI("Notify subscriber id:%{public}d, keycode:%d, pid:%{public}d",
902                 subscriber->id_, keyEvent->GetKeyCode(), sess->GetPid());
903         } else {
904             MMI_HILOGI("Notify subscriber id:%{public}d, keycode:%{private}d, pid:%{public}d",
905                 subscriber->id_, keyEvent->GetKeyCode(), sess->GetPid());
906         }
907     }
908     if (pkt.ChkRWError()) {
909         MMI_HILOGE("Packet write dispatch subscriber failed");
910         return;
911     }
912     if (!udsServerPtr->SendMsg(fd, pkt)) {
913         MMI_HILOGE("Leave, server dispatch subscriber failed");
914         return;
915     }
916 }
917 
AddTimer(const std::shared_ptr<Subscriber> & subscriber,const std::shared_ptr<KeyEvent> & keyEvent)918 bool KeySubscriberHandler::AddTimer(const std::shared_ptr<Subscriber> &subscriber,
919                                     const std::shared_ptr<KeyEvent> &keyEvent)
920 {
921     CALL_DEBUG_ENTER;
922     CHKPF(keyEvent);
923     CHKPF(subscriber);
924 
925     if (subscriber->timerId_ >= 0) {
926         MMI_HILOGW("Leave, timer already added, it may have been added by injection");
927         return true;
928     }
929 
930     auto &keyOption = subscriber->keyOption_;
931     bool isKeyDown = keyOption->IsFinalKeyDown();
932     int32_t duration = isKeyDown ? keyOption->GetFinalKeyDownDuration() : keyOption->GetFinalKeyUpDelay();
933     if (duration <= 0) {
934         MMI_HILOGE("Leave, duration <= 0");
935         return true;
936     }
937 
938     if (!CloneKeyEvent(keyEvent)) {
939         MMI_HILOGE("Leave, cloneKeyEvent failed");
940         return false;
941     }
942 
943     std::weak_ptr<Subscriber> weakSubscriber = subscriber;
944     subscriber->timerId_ = TimerMgr->AddTimer(duration, 1, [this, weakSubscriber] () {
945         MMI_HILOGD("Timer callback");
946         auto subscriber = weakSubscriber.lock();
947         CHKPV(subscriber);
948         subscriber->timerId_ = -1;
949         OnTimer(subscriber);
950     });
951 
952     if (subscriber->timerId_ < 0) {
953         MMI_HILOGE("Leave, addTimer failed");
954         return false;
955     }
956     subscriber->keyEvent_ = keyEvent_;
957     hasEventExecuting_ = true;
958     MMI_HILOGD("Leave, add timer success, subscribeId:%{public}d,"
959         "duration:%{public}d, timerId:%{public}d",
960         subscriber->id_, duration, subscriber->timerId_);
961     return true;
962 }
963 
ClearSubscriberTimer(std::list<std::shared_ptr<Subscriber>> subscribers)964 void KeySubscriberHandler::ClearSubscriberTimer(std::list<std::shared_ptr<Subscriber>> subscribers)
965 {
966     CALL_DEBUG_ENTER;
967     MMI_HILOGD("Clear subscriber timer size:%{public}zu", subscribers.size());
968     for (auto &subscriber : subscribers) {
969         CHKPC(subscriber);
970         ClearTimer(subscriber);
971     }
972 }
973 
ClearTimer(const std::shared_ptr<Subscriber> & subscriber)974 void KeySubscriberHandler::ClearTimer(const std::shared_ptr<Subscriber> &subscriber)
975 {
976     CALL_DEBUG_ENTER;
977     CHKPV(subscriber);
978 
979     if (subscriber->timerId_ < 0) {
980         MMI_HILOGD("Leave, subscribeId:%{public}d, null timerId < 0", subscriber->id_);
981         return;
982     }
983 
984     TimerMgr->RemoveTimer(subscriber->timerId_);
985     auto timerId = subscriber->timerId_;
986     subscriber->keyEvent_.reset();
987     subscriber->timerId_ = -1;
988     hasEventExecuting_ = false;
989     MMI_HILOGD("subscribeId:%{public}d, timerId:%{public}d", subscriber->id_, timerId);
990 }
991 
OnTimer(const std::shared_ptr<Subscriber> subscriber)992 void KeySubscriberHandler::OnTimer(const std::shared_ptr<Subscriber> subscriber)
993 {
994     CALL_DEBUG_ENTER;
995     CHKPV(subscriber);
996     subscriber->timerId_ = -1;
997     if (subscriber->keyEvent_ == nullptr) {
998         MMI_HILOGE("Leave, subscriber->keyEvent is nullptr, subscribeId:%{public}d", subscriber->id_);
999         return;
1000     }
1001 
1002     NotifySubscriber(subscriber->keyEvent_, subscriber);
1003     subscriber->keyEvent_.reset();
1004     MMI_HILOGD("subscribeId:%{public}d", subscriber->id_);
1005 }
1006 
InitSessionDeleteCallback()1007 bool KeySubscriberHandler::InitSessionDeleteCallback()
1008 {
1009     CALL_DEBUG_ENTER;
1010     if (callbackInitialized_) {
1011         MMI_HILOGD("Session delete callback has already been initialized");
1012         return true;
1013     }
1014     auto udsServerPtr = InputHandler->GetUDSServer();
1015     CHKPF(udsServerPtr);
1016     std::function<void(SessionPtr)> callback =
1017         [this] (SessionPtr sess) { return this->OnSessionDelete(sess); };
1018     udsServerPtr->AddSessionDeletedCallback(callback);
1019     callbackInitialized_ = true;
1020     return true;
1021 }
1022 
HandleKeyDown(const std::shared_ptr<KeyEvent> & keyEvent)1023 bool KeySubscriberHandler::HandleKeyDown(const std::shared_ptr<KeyEvent> &keyEvent)
1024 {
1025     CALL_DEBUG_ENTER;
1026     CHKPF(keyEvent);
1027 #ifdef SHORTCUT_KEY_RULES_ENABLED
1028     KEY_SHORTCUT_MGR->ResetCheckState();
1029 #endif // SHORTCUT_KEY_RULES_ENABLED
1030     bool handled = false;
1031     auto keyCode = keyEvent->GetKeyCode();
1032     std::vector<int32_t> pressedKeys = keyEvent->GetPressedKeys();
1033     RemoveKeyCode(keyCode, pressedKeys);
1034     std::set<int32_t> pids;
1035     GetForegroundPids(pids);
1036     MMI_HILOGI("Foreground pid size:%{public}zu", pids.size());
1037     std::lock_guard<std::mutex> lock(subscriberMapMutex_);
1038     for (auto &iter : subscriberMap_) {
1039         auto keyOption = iter.first;
1040         auto subscribers = iter.second;
1041         PrintKeyOption(keyOption);
1042         IsMatchForegroundPid(subscribers, pids);
1043         if (!keyOption->IsFinalKeyDown()) {
1044             MMI_HILOGD("!keyOption->IsFinalKeyDown()");
1045             continue;
1046         }
1047         if (keyCode != keyOption->GetFinalKey()) {
1048             MMI_HILOGD("keyCode != keyOption->GetFinalKey()");
1049             ClearSubscriberTimer(subscribers);
1050             continue;
1051         }
1052         if (!IsPreKeysMatch(keyOption->GetPreKeys(), pressedKeys)) {
1053             MMI_HILOGD("preKeysMatch failed");
1054             ClearSubscriberTimer(subscribers);
1055             continue;
1056         }
1057         NotifyKeyDownSubscriber(keyEvent, keyOption, subscribers, handled);
1058     }
1059     MMI_HILOGD("Handle key down:%{public}s", handled ? "true" : "false");
1060     return handled;
1061 }
1062 
SubscriberNotifyNap(const std::shared_ptr<Subscriber> subscriber)1063 void KeySubscriberHandler::SubscriberNotifyNap(const std::shared_ptr<Subscriber> subscriber)
1064 {
1065     CALL_DEBUG_ENTER;
1066     CHKPV(subscriber);
1067     int32_t state = NapProcess::GetInstance()->GetNapClientPid();
1068     if (state == REMOVE_OBSERVER || state == UNOBSERVED) {
1069         MMI_HILOGD("Nap client status:%{public}d", state);
1070         return;
1071     }
1072 
1073     auto sess = subscriber->sess_;
1074     CHKPV(sess);
1075     OHOS::MMI::NapProcess::NapStatusData napData;
1076     napData.pid = sess->GetPid();
1077     napData.uid = sess->GetUid();
1078     napData.bundleName = sess->GetProgramName();
1079     if (NapProcess::GetInstance()->IsNeedNotify(napData)) {
1080         int32_t syncState = ACTIVE_EVENT;
1081         NapProcess::GetInstance()->AddMmiSubscribedEventData(napData, syncState);
1082         NapProcess::GetInstance()->NotifyBundleName(napData, syncState);
1083     }
1084 }
1085 
HandleKeyUp(const std::shared_ptr<KeyEvent> & keyEvent)1086 bool KeySubscriberHandler::HandleKeyUp(const std::shared_ptr<KeyEvent> &keyEvent)
1087 {
1088 #ifdef SHORTCUT_KEY_RULES_ENABLED
1089     if (KEY_SHORTCUT_MGR->HaveShortcutConsumed(keyEvent) || !KEY_SHORTCUT_MGR->IsCheckUpShortcut(keyEvent)) {
1090         return false;
1091     }
1092 #endif // SHORTCUT_KEY_RULES_ENABLED
1093     bool handled = false;
1094     auto keyCode = keyEvent->GetKeyCode();
1095     std::vector<int32_t> pressedKeys = keyEvent->GetPressedKeys();
1096     RemoveKeyCode(keyCode, pressedKeys);
1097     std::set<int32_t> pids;
1098     GetForegroundPids(pids);
1099     std::lock_guard<std::mutex> lock(subscriberMapMutex_);
1100     for (auto &iter : subscriberMap_) {
1101         auto keyOption = iter.first;
1102         auto subscribers = iter.second;
1103         PrintKeyOption(keyOption);
1104         IsMatchForegroundPid(subscribers, pids);
1105         if (keyOption->IsFinalKeyDown()) {
1106             MMI_HILOGD("keyOption->IsFinalKeyDown()");
1107             ClearSubscriberTimer(subscribers);
1108             continue;
1109         }
1110         if (keyCode != keyOption->GetFinalKey()) {
1111             MMI_HILOGD("keyCode != keyOption->GetFinalKey()");
1112             continue;
1113         }
1114         if (!IsPreKeysMatch(keyOption->GetPreKeys(), pressedKeys)) {
1115             MMI_HILOGD("PreKeysMatch failed");
1116             continue;
1117         }
1118         auto duration = keyOption->GetFinalKeyDownDuration();
1119         if (duration <= 0) {
1120             NotifyKeyUpSubscriber(keyEvent, subscribers, handled);
1121             continue;
1122         }
1123         std::optional<KeyEvent::KeyItem> keyItem = keyEvent->GetKeyItem();
1124         CHK_KEY_ITEM(keyItem);
1125         if (keyEvent->GetActionTime() - keyItem->GetDownTime() >= MS2US(duration)) {
1126             MMI_HILOGE("upTime - downTime >= duration");
1127             continue;
1128         }
1129         NotifyKeyUpSubscriber(keyEvent, subscribers, handled);
1130     }
1131     MMI_HILOGD("Handle key up:%{public}s", handled ? "true" : "false");
1132     return handled;
1133 }
1134 
HandleKeyCancel(const std::shared_ptr<KeyEvent> & keyEvent)1135 bool KeySubscriberHandler::HandleKeyCancel(const std::shared_ptr<KeyEvent> &keyEvent)
1136 {
1137     CALL_DEBUG_ENTER;
1138     CHKPF(keyEvent);
1139     std::lock_guard<std::mutex> lock(subscriberMapMutex_);
1140     for (auto &iter : subscriberMap_) {
1141         auto keyOption = iter.first;
1142         auto subscribers = iter.second;
1143         for (auto &subscriber : subscribers) {
1144             PrintKeyUpLog(subscriber);
1145             ClearTimer(subscriber);
1146         }
1147     }
1148     return false;
1149 }
1150 
1151 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
IsKeyEventSubscribed(int32_t keyCode,int32_t trrigerType)1152 bool KeySubscriberHandler::IsKeyEventSubscribed(int32_t keyCode, int32_t trrigerType)
1153 {
1154     CALL_DEBUG_ENTER;
1155     std::lock_guard<std::mutex> lock(subscriberMapMutex_);
1156     for (const auto &iter : subscriberMap_) {
1157         auto keyOption = iter.first;
1158         auto subscribers = iter.second;
1159         MMI_HILOGD("keyOption->finalKey:%{private}d, keyOption->isFinalKeyDown:%{public}s, "
1160             "keyOption->finalKeyDownDuration:%{public}d",
1161             keyOption->GetFinalKey(), keyOption->IsFinalKeyDown() ? "true" : "false",
1162             keyOption->GetFinalKeyDownDuration());
1163         int32_t keyAction = KeyEvent::KEY_ACTION_UP;
1164         if (keyOption->IsFinalKeyDown()) {
1165             MMI_HILOGD("keyOption is final key down");
1166             keyAction = KeyEvent::KEY_ACTION_DOWN;
1167         }
1168         if (keyCode == keyOption->GetFinalKey() && trrigerType == keyAction && subscribers.size() > 0) {
1169             MMI_HILOGD("Current key event is subscribed");
1170             return true;
1171         }
1172     }
1173     return false;
1174 }
1175 #endif // OHOS_BUILD_ENABLE_KEYBOARD
1176 
CloneKeyEvent(std::shared_ptr<KeyEvent> keyEvent)1177 bool KeySubscriberHandler::CloneKeyEvent(std::shared_ptr<KeyEvent> keyEvent)
1178 {
1179     CHKPF(keyEvent);
1180     if (keyEvent_ == nullptr) {
1181         MMI_HILOGW("keyEvent_ is nullptr");
1182         keyEvent_ = KeyEvent::Clone(keyEvent);
1183     }
1184     CHKPF(keyEvent_);
1185     return true;
1186 }
1187 
RemoveKeyCode(int32_t keyCode,std::vector<int32_t> & keyCodes)1188 void KeySubscriberHandler::RemoveKeyCode(int32_t keyCode, std::vector<int32_t> &keyCodes)
1189 {
1190     for (auto it = keyCodes.begin(); it != keyCodes.end(); ++it) {
1191         if (*it == keyCode) {
1192             keyCodes.erase(it);
1193             return;
1194         }
1195     }
1196 }
1197 
IsRepeatedKeyEvent(std::shared_ptr<KeyEvent> keyEvent)1198 bool KeySubscriberHandler::IsRepeatedKeyEvent(std::shared_ptr<KeyEvent> keyEvent)
1199 {
1200     CHKPF(keyEvent);
1201     if (!hasEventExecuting_) {
1202         return false;
1203     }
1204 
1205     CHKPF(keyEvent_);
1206     if (keyEvent->GetKeyCode() != keyEvent_->GetKeyCode()) {
1207         return false;
1208     }
1209 
1210     if (keyEvent->GetKeyAction() != keyEvent_->GetKeyAction()) {
1211         return false;
1212     }
1213 
1214     if (keyEvent->GetKeyItems().size() != keyEvent_->GetKeyItems().size()) {
1215         return false;
1216     }
1217 
1218     for (const auto &item : keyEvent->GetKeyItems()) {
1219         int32_t keyCode = item.GetKeyCode();
1220         bool findResult = false;
1221         for (const auto &item1 : keyEvent_->GetKeyItems()) {
1222             if (keyCode == item1.GetKeyCode()) {
1223                 findResult = true;
1224                 break;
1225             }
1226         }
1227         if (!findResult) {
1228             return false;
1229         }
1230     }
1231     return true;
1232 }
1233 
RemoveSubscriberKeyUpTimer(int32_t keyCode)1234 void KeySubscriberHandler::RemoveSubscriberKeyUpTimer(int32_t keyCode)
1235 {
1236     {
1237         std::lock_guard<std::mutex> lock(subscriberMapMutex_);
1238         for (auto iter = subscriberMap_.begin(); iter != subscriberMap_.end(); iter++) {
1239             auto &subscribers = iter->second;
1240             for (auto it = subscribers.begin(); it != subscribers.end(); it++) {
1241                 if (((*it)->timerId_ >= 0) && ((*it)->keyOption_->GetFinalKey() == keyCode)) {
1242                     ClearTimer(*it);
1243                 }
1244             }
1245         }
1246     }
1247     keyGestureMgr_.ResetAll();
1248 }
1249 
HandleKeyUpWithDelay(std::shared_ptr<KeyEvent> keyEvent,const std::shared_ptr<Subscriber> & subscriber)1250 void KeySubscriberHandler::HandleKeyUpWithDelay(std::shared_ptr<KeyEvent> keyEvent,
1251     const std::shared_ptr<Subscriber> &subscriber)
1252 {
1253     auto keyUpDelay = subscriber->keyOption_->GetFinalKeyUpDelay();
1254     if (keyUpDelay <= 0) {
1255         NotifySubscriber(keyEvent, subscriber);
1256     } else {
1257         if (!AddTimer(subscriber, keyEvent)) {
1258             MMI_HILOGE("Leave, add timer failed");
1259         }
1260     }
1261 }
1262 
PrintKeyOption(const std::shared_ptr<KeyOption> keyOption)1263 void KeySubscriberHandler::PrintKeyOption(const std::shared_ptr<KeyOption> keyOption)
1264 {
1265     CHKPV(keyOption);
1266     MMI_HILOGD("keyOption->finalKey:%{private}d,keyOption->isFinalKeyDown:%{public}s, "
1267         "keyOption->finalKeyDownDuration:%{public}d, keyOption->isRepeat:%{public}s",
1268         keyOption->GetFinalKey(), keyOption->IsFinalKeyDown() ? "true" : "false",
1269         keyOption->GetFinalKeyDownDuration(), keyOption->IsRepeat() ? "true" : "false");
1270     for (const auto &keyCode : keyOption->GetPreKeys()) {
1271         MMI_HILOGD("keyOption->prekey:%{private}d", keyCode);
1272     }
1273 }
1274 
PrintKeyUpLog(const std::shared_ptr<Subscriber> & subscriber)1275 void KeySubscriberHandler::PrintKeyUpLog(const std::shared_ptr<Subscriber> &subscriber)
1276 {
1277     CHKPV(subscriber);
1278     auto &keyOption = subscriber->keyOption_;
1279     MMI_HILOGD("subscribeId:%{public}d, keyOption->finalKey:%{private}d,"
1280         "keyOption->isFinalKeyDown:%{public}s, keyOption->finalKeyDownDuration:%{public}d,"
1281         "keyOption->finalKeyUpDelay:%{public}d",
1282         subscriber->id_, keyOption->GetFinalKey(), keyOption->IsFinalKeyDown() ? "true" : "false",
1283         keyOption->GetFinalKeyDownDuration(), keyOption->GetFinalKeyUpDelay());
1284     for (const auto &keyCode : keyOption->GetPreKeys()) {
1285         MMI_HILOGD("keyOption->prekey:%{private}d", keyCode);
1286     }
1287 }
1288 
Dump(int32_t fd,const std::vector<std::string> & args)1289 void KeySubscriberHandler::Dump(int32_t fd, const std::vector<std::string> &args)
1290 {
1291     CALL_DEBUG_ENTER;
1292     mprintf(fd, "Subscriber information:\t");
1293     mprintf(fd, "subscribers: count = %zu", CountSubscribers());
1294     for (const auto &item : foregroundPids_) {
1295         mprintf(fd, "Foreground Pids: %d", item);
1296     }
1297     mprintf(fd, "enableCombineKey: %s | isForegroundExits: %s | needSkipPowerKeyUp: %s \t",
1298             enableCombineKey_ ? "true" : "false", isForegroundExits_ ? "true" : "false",
1299             needSkipPowerKeyUp_ ? "true" : "false");
1300     {
1301         std::lock_guard<std::mutex> lock(subscriberMapMutex_);
1302         DumpSubscribers(fd, subscriberMap_);
1303     }
1304     DumpSubscribers(fd, keyGestures_);
1305 }
1306 
CountSubscribers() const1307 size_t KeySubscriberHandler::CountSubscribers() const
1308 {
1309     size_t total { 0 };
1310 
1311     for (auto &item : subscriberMap_) {
1312         total += item.second.size();
1313     }
1314     for (auto &item : keyGestures_) {
1315         total += item.second.size();
1316     }
1317     return total;
1318 }
1319 
DumpSubscribers(int32_t fd,const SubscriberCollection & collection) const1320 void KeySubscriberHandler::DumpSubscribers(int32_t fd, const SubscriberCollection &collection) const
1321 {
1322     for (auto iter = collection.begin(); iter != collection.end(); ++iter) {
1323         auto &subscribers = iter->second;
1324         for (auto item = subscribers.begin(); item != subscribers.end(); ++item) {
1325             DumpSubscriber(fd, *item);
1326         }
1327     }
1328 }
1329 
DumpSubscriber(int32_t fd,std::shared_ptr<Subscriber> subscriber) const1330 void KeySubscriberHandler::DumpSubscriber(int32_t fd, std::shared_ptr<Subscriber> subscriber) const
1331 {
1332     CHKPV(subscriber);
1333     SessionPtr session = subscriber->sess_;
1334     CHKPV(session);
1335     std::shared_ptr<KeyOption> keyOption = subscriber->keyOption_;
1336     CHKPV(keyOption);
1337     std::set<int32_t> preKeys = keyOption->GetPreKeys();
1338     std::ostringstream sPrekeys;
1339     if (auto keyIter = preKeys.cbegin(); keyIter != preKeys.cend()) {
1340         sPrekeys << *keyIter;
1341         for (++keyIter; keyIter != preKeys.cend(); ++keyIter) {
1342             sPrekeys << "," << *keyIter;
1343         }
1344     }
1345     mprintf(fd,
1346             "Subscriber ID:%d | Pid:%d | Uid:%d | Fd:%d | Prekeys:[%s] | FinalKey:%d | "
1347             "FinalKeyDownDuration:%d | IsFinalKeyDown:%s | IsRepeat:%s | ProgramName:%s",
1348             subscriber->id_, session->GetPid(), session->GetUid(), session->GetFd(),
1349             sPrekeys.str().c_str(), keyOption->GetFinalKey(), keyOption->GetFinalKeyDownDuration(),
1350             keyOption->IsFinalKeyDown() ? "true" : "false", keyOption->IsRepeat() ? "true" : "false",
1351             session->GetProgramName().c_str());
1352 }
1353 
RemoveSubscriberTimer(std::shared_ptr<KeyEvent> keyEvent)1354 void KeySubscriberHandler::RemoveSubscriberTimer(std::shared_ptr<KeyEvent> keyEvent)
1355 {
1356     CALL_INFO_TRACE;
1357     CHKPV(keyEvent);
1358     auto keyCode = keyEvent->GetKeyCode();
1359     std::vector<int32_t> pressedKeys = keyEvent->GetPressedKeys();
1360     RemoveKeyCode(keyCode, pressedKeys);
1361     std::set<int32_t> pids;
1362     GetForegroundPids(pids);
1363     MMI_HILOGI("Foreground pid size:%{public}zu", pids.size());
1364     std::lock_guard<std::mutex> lock(subscriberMapMutex_);
1365     for (auto &iter : subscriberMap_) {
1366         auto keyOption = iter.first;
1367         auto subscribers = iter.second;
1368         PrintKeyOption(keyOption);
1369         IsMatchForegroundPid(subscribers, pids);
1370         ClearSubscriberTimer(subscribers);
1371     }
1372 }
1373 
HandleCallEnded(std::shared_ptr<KeyEvent> keyEvent)1374 bool KeySubscriberHandler::HandleCallEnded(std::shared_ptr<KeyEvent> keyEvent)
1375 {
1376     CALL_DEBUG_ENTER;
1377     CHKPF(keyEvent);
1378     if (!callBahaviorState_) {
1379         MMI_HILOGE("CallBehaviorState is false");
1380         return false;
1381     }
1382     if (keyEvent->GetKeyCode() != KeyEvent::KEYCODE_POWER ||
1383         keyEvent->GetKeyAction() != KeyEvent::KEY_ACTION_DOWN) {
1384         MMI_HILOGE("This key event no need to CallEnded");
1385         return false;
1386     }
1387     std::string screenStatus = DISPLAY_MONITOR->GetScreenStatus();
1388     if (screenStatus != EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON) {
1389         MMI_HILOGI("The current screen is not on, so not allow end call");
1390         return false;
1391     }
1392     int32_t ret = DEVICE_MONITOR->GetCallState();
1393     MMI_HILOGE("Current call state:%{public}d", ret);
1394 
1395     switch (ret) {
1396         case StateType::CALL_STATUS_HOLDING:
1397         case StateType::CALL_STATUS_ALERTING:
1398         case StateType::CALL_STATUS_ANSWERED:
1399         case StateType::CALL_STATUS_ACTIVE:
1400         case StateType::CALL_STATUS_DIALING: {
1401             HangUpCallProcess();
1402             needSkipPowerKeyUp_ = true;
1403             return true;
1404         }
1405         case StateType::CALL_STATUS_WAITING:
1406         case StateType::CALL_STATUS_INCOMING: {
1407             RejectCallProcess();
1408             needSkipPowerKeyUp_ = true;
1409             return true;
1410         }
1411         case StateType::CALL_STATUS_IDLE:
1412         case StateType::CALL_STATUS_DISCONNECTING:
1413         case StateType::CALL_STATUS_DISCONNECTED:
1414         default: {
1415             MMI_HILOGE("This state no need to CallEnded");
1416             return false;
1417         }
1418     }
1419 }
1420 
HangUpCallProcess()1421 void KeySubscriberHandler::HangUpCallProcess()
1422 {
1423     if (callManagerClientPtr == nullptr) {
1424         callManagerClientPtr = DelayedSingleton<OHOS::Telephony::CallManagerClient>::GetInstance();
1425         if (callManagerClientPtr == nullptr) {
1426             MMI_HILOGE("CallManager init fail");
1427             return;
1428         }
1429         callManagerClientPtr->Init(OHOS::TELEPHONY_CALL_MANAGER_SYS_ABILITY_ID);
1430     }
1431     int32_t ret = -1;
1432     auto begin = std::chrono::high_resolution_clock::now();
1433     ret = callManagerClientPtr->HangUpCall(0);
1434     auto durationMS = std::chrono::duration_cast<std::chrono::milliseconds>(
1435     std::chrono::high_resolution_clock::now() - begin).count();
1436 #ifdef OHOS_BUILD_ENABLE_DFX_RADAR
1437     DfxHisysevent::ReportApiCallTimes(ApiDurationStatistics::Api::TELEPHONY_CALL_MGR_HANG_UP_CALL, durationMS);
1438 #endif // OHOS_BUILD_ENABLE_DFX_RADAR
1439     if (ret != ERR_OK) {
1440         MMI_HILOGE("HangUpCall fail, ret:%{public}d", ret);
1441         return;
1442     }
1443     MMI_HILOGI("HangUpCall success");
1444 }
1445 
RejectCallProcess()1446 void KeySubscriberHandler::RejectCallProcess()
1447 {
1448     if (callManagerClientPtr == nullptr) {
1449         callManagerClientPtr = DelayedSingleton<OHOS::Telephony::CallManagerClient>::GetInstance();
1450         if (callManagerClientPtr == nullptr) {
1451             MMI_HILOGE("CallManagerClient GetInstance fail");
1452             return;
1453         }
1454         callManagerClientPtr->Init(OHOS::TELEPHONY_CALL_MANAGER_SYS_ABILITY_ID);
1455     }
1456     int32_t ret = -1;
1457     auto begin = std::chrono::high_resolution_clock::now();
1458     ret = callManagerClientPtr->RejectCall(0, false, u"");
1459     auto durationMS = std::chrono::duration_cast<std::chrono::milliseconds>(
1460     std::chrono::high_resolution_clock::now() - begin).count();
1461 #ifdef OHOS_BUILD_ENABLE_DFX_RADAR
1462     DfxHisysevent::ReportApiCallTimes(ApiDurationStatistics::Api::TELEPHONY_CALL_MGR_REJECT_CALL, durationMS);
1463 #endif // OHOS_BUILD_ENABLE_DFX_RADAR
1464     if (ret != ERR_OK) {
1465         MMI_HILOGE("RejectCall fail, ret:%{public}d", ret);
1466         return;
1467     }
1468     MMI_HILOGI("RejectCall success");
1469 }
1470 
InitDataShareListener()1471 void KeySubscriberHandler::InitDataShareListener()
1472 {
1473     SettingObserver::UpdateFunc func = [&](const std::string& key) {
1474         bool statusValue = false;
1475         int32_t ret = -1;
1476         ret = SettingDataShare::GetInstance(MULTIMODAL_INPUT_SERVICE_ID).GetBoolValue(key, statusValue,
1477             SETTINGS_DATA_SYSTEM_URI);
1478         if (ret != RET_OK) {
1479             MMI_HILOGE("Get incall_power_button_behavior state fail:%{public}d", ret);
1480             return;
1481         }
1482         MMI_HILOGE("Get incall_power_button_behavior state success:%{public}d", statusValue);
1483         callBahaviorState_ = statusValue;
1484     };
1485 
1486     func(CALL_BEHAVIOR_KEY);
1487 
1488     auto saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1489     CHKPV(saManager);
1490     auto remoteObj = saManager->GetSystemAbility(MULTIMODAL_INPUT_SERVICE_ID);
1491     CHKPV(remoteObj);
1492 
1493     std::pair<int, std::shared_ptr<DataShare::DataShareHelper>> ret =
1494         DataShare::DataShareHelper::Create(remoteObj, SETTINGS_DATA_SYSTEM_URI, SETTINGS_DATA_EXT_URI);
1495     MMI_HILOGE("Create data_share helper, ret=%{public}d", ret.first);
1496 
1497     if (ret.first == ERR_OK) {
1498         std::shared_ptr<DataShare::DataShareHelper> helper = ret.second;
1499         auto uri = Uri(SETTINGS_DATA_SYSTEM_URI + "&key=" + CALL_BEHAVIOR_KEY);
1500         sptr<SettingObserver> statusObserver = SettingDataShare::GetInstance(MULTIMODAL_INPUT_SERVICE_ID).
1501             CreateObserver(CALL_BEHAVIOR_KEY, func);
1502         CHKPV(statusObserver);
1503         helper->RegisterObserver(uri, statusObserver);
1504     }
1505 }
1506 } // namespace MMI
1507 } // namespace OHOS
1508