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_command_handler.h"
17
18 #include <ostream>
19 #include <sstream>
20
21 #include "cJSON.h"
22 #include "config_policy_utils.h"
23 #include "file_ex.h"
24 #include "system_ability_definition.h"
25
26 #include "ability_manager_client.h"
27 #include "audio_stream_manager.h"
28 #include "bytrace_adapter.h"
29 #include "define_multimodal.h"
30 #include "device_event_monitor.h"
31 #include "dfx_hisysevent.h"
32 #include "display_event_monitor.h"
33 #include "error_multimodal.h"
34 #include "event_log_helper.h"
35 #include "gesturesense_wrapper.h"
36 #include "input_event_data_transformation.h"
37 #include "input_event_handler.h"
38 #include "i_input_windows_manager.h"
39 #include "i_preference_manager.h"
40 #include "key_command_handler_util.h"
41 #include "mmi_log.h"
42 #include "nap_process.h"
43 #include "net_packet.h"
44 #include "pointer_drawing_manager.h"
45 #include "proto.h"
46 #include "setting_datashare.h"
47 #include "stylus_key_handler.h"
48 #include "timer_manager.h"
49 #include "util.h"
50 #include "util_ex.h"
51
52 #undef MMI_LOG_DOMAIN
53 #define MMI_LOG_DOMAIN MMI_LOG_HANDLER
54 #undef MMI_LOG_TAG
55 #define MMI_LOG_TAG "KeyCommandHandler"
56
57 namespace OHOS {
58 namespace MMI {
59 namespace {
60 constexpr float MOVE_TOLERANCE { 3.0f };
61 constexpr float MIN_GESTURE_STROKE_LENGTH { 200.0f };
62 constexpr float MIN_LETTER_GESTURE_SQUARENESS { 0.15f };
63 constexpr float MIN_START_GESTURE { 60.0f };
64 constexpr int32_t POINTER_NUMBER { 2 };
65 constexpr int32_t EVEN_NUMBER { 2 };
66 constexpr int64_t NO_DELAY { 0 };
67 constexpr int64_t FREQUENCY { 1000 };
68 constexpr int64_t TAP_DOWN_INTERVAL_MILLIS { 550000 };
69 constexpr int64_t SOS_INTERVAL_TIMES { 300000 };
70 constexpr int64_t SOS_DELAY_TIMES { 1000000 };
71 constexpr int64_t SOS_COUNT_DOWN_TIMES { 4000000 };
72 constexpr int32_t MAX_TAP_COUNT { 2 };
73 constexpr int32_t ANCO_KNUCKLE_POINTER_ID { 15000 };
74 const std::string AIBASE_BUNDLE_NAME { "com.huawei.hmos.aibase" };
75 const std::string WAKEUP_ABILITY_NAME { "WakeUpExtAbility" };
76 const std::string SCREENSHOT_BUNDLE_NAME { "com.hmos.screenshot" };
77 const std::string SCREENSHOT_ABILITY_NAME { "com.hmos.screenshot.ServiceExtAbility" };
78 const std::string SCREENRECORDER_BUNDLE_NAME { "com.hmos.screenrecorder" };
79 const std::string SOS_BUNDLE_NAME { "com.hmos.emergencycommunication" };
80 const std::string WALLET_BUNDLE_NAME { "com.hmos.walletservice" };
81 constexpr int32_t DEFAULT_VALUE { -1 };
82 constexpr int64_t POWER_ACTION_INTERVAL { 600 };
83 constexpr int64_t SOS_WAIT_TIME { 3000 };
84 } // namespace
85
86 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
HandleKeyEvent(const std::shared_ptr<KeyEvent> keyEvent)87 void KeyCommandHandler::HandleKeyEvent(const std::shared_ptr<KeyEvent> keyEvent)
88 {
89 CHKPV(keyEvent);
90 if (OnHandleEvent(keyEvent)) {
91 if (DISPLAY_MONITOR->GetScreenStatus() == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF) {
92 auto monitorHandler = InputHandler->GetMonitorHandler();
93 CHKPV(monitorHandler);
94 keyEvent->SetFourceMonitorFlag(true);
95 #ifndef OHOS_BUILD_EMULATOR
96 monitorHandler->OnHandleEvent(keyEvent);
97 #endif // OHOS_BUILD_EMULATOR
98 keyEvent->SetFourceMonitorFlag(false);
99 }
100 MMI_HILOGD("The keyEvent start launch an ability, keyCode:%{private}d", keyEvent->GetKeyCode());
101 BytraceAdapter::StartBytrace(keyEvent, BytraceAdapter::KEY_LAUNCH_EVENT);
102 return;
103 }
104 CHKPV(nextHandler_);
105 nextHandler_->HandleKeyEvent(keyEvent);
106 }
107 #endif // OHOS_BUILD_ENABLE_KEYBOARD
108
109 #ifdef OHOS_BUILD_ENABLE_POINTER
HandlePointerEvent(const std::shared_ptr<PointerEvent> pointerEvent)110 void KeyCommandHandler::HandlePointerEvent(const std::shared_ptr<PointerEvent> pointerEvent)
111 {
112 CHKPV(pointerEvent);
113 if (OnHandleEvent(pointerEvent)) {
114 if (EventLogHelper::IsBetaVersion() && !pointerEvent->HasFlag(InputEvent::EVENT_FLAG_PRIVACY_MODE)) {
115 MMI_HILOGD("The pointerEvent start launch an ability, pointAction:%s", pointerEvent->DumpPointerAction());
116 } else {
117 MMI_HILOGD("The pointerEvent start launch an ability, pointAction:%s", pointerEvent->DumpPointerAction());
118 }
119 }
120 CHKPV(nextHandler_);
121 nextHandler_->HandlePointerEvent(pointerEvent);
122 }
123 #endif // OHOS_BUILD_ENABLE_POINTER
124
125 #ifdef OHOS_BUILD_ENABLE_TOUCH
HandleTouchEvent(const std::shared_ptr<PointerEvent> pointerEvent)126 void KeyCommandHandler::HandleTouchEvent(const std::shared_ptr<PointerEvent> pointerEvent)
127 {
128 CHKPV(pointerEvent);
129 CHKPV(nextHandler_);
130 OnHandleTouchEvent(pointerEvent);
131 int32_t id = pointerEvent->GetPointerId();
132 PointerEvent::PointerItem item;
133 pointerEvent->GetPointerItem(id, item);
134 int32_t toolType = item.GetToolType();
135 if (toolType == PointerEvent::TOOL_TYPE_KNUCKLE) {
136 pointerEvent->AddFlag(InputEvent::EVENT_FLAG_NO_INTERCEPT);
137 }
138 nextHandler_->HandleTouchEvent(pointerEvent);
139 }
140 #endif // OHOS_BUILD_ENABLE_TOUCH
141
GetKnuckleSwitchValue()142 bool KeyCommandHandler::GetKnuckleSwitchValue()
143 {
144 return knuckleSwitch_.statusConfigValue;
145 }
146
147 #ifdef OHOS_BUILD_ENABLE_TOUCH
OnHandleTouchEvent(const std::shared_ptr<PointerEvent> touchEvent)148 void KeyCommandHandler::OnHandleTouchEvent(const std::shared_ptr<PointerEvent> touchEvent)
149 {
150 CALL_DEBUG_ENTER;
151 CHKPV(touchEvent);
152 STYLUS_HANDLER->SetLastEventState(false);
153 if (!isParseConfig_) {
154 if (!ParseConfig()) {
155 MMI_HILOGE("Parse configFile failed");
156 return;
157 }
158 isParseConfig_ = true;
159 }
160 if (!isTimeConfig_) {
161 SetKnuckleDoubleTapIntervalTime(DOUBLE_CLICK_INTERVAL_TIME_DEFAULT);
162 isTimeConfig_ = true;
163 }
164 if (!isDistanceConfig_) {
165 distanceDefaultConfig_ = DOUBLE_CLICK_DISTANCE_DEFAULT_CONFIG * VPR_CONFIG;
166 distanceLongConfig_ = DOUBLE_CLICK_DISTANCE_LONG_CONFIG * VPR_CONFIG;
167 SetKnuckleDoubleTapDistance(distanceDefaultConfig_);
168 isDistanceConfig_ = true;
169 }
170
171 switch (touchEvent->GetPointerAction()) {
172 case PointerEvent::POINTER_ACTION_CANCEL:
173 case PointerEvent::POINTER_ACTION_UP: {
174 HandlePointerActionUpEvent(touchEvent);
175 break;
176 }
177 case PointerEvent::POINTER_ACTION_MOVE: {
178 HandlePointerActionMoveEvent(touchEvent);
179 break;
180 }
181 case PointerEvent::POINTER_ACTION_DOWN: {
182 HandlePointerActionDownEvent(touchEvent);
183 break;
184 }
185 default:
186 MMI_HILOGD("Unknown pointer action:%{public}d", touchEvent->GetPointerAction());
187 break;
188 }
189 #ifdef OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
190 HandleKnuckleGestureEvent(touchEvent);
191 #endif // OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
192 }
193
HandlePointerActionDownEvent(const std::shared_ptr<PointerEvent> touchEvent)194 void KeyCommandHandler::HandlePointerActionDownEvent(const std::shared_ptr<PointerEvent> touchEvent)
195 {
196 CALL_DEBUG_ENTER;
197 CHKPV(touchEvent);
198 int32_t id = touchEvent->GetPointerId();
199 PointerEvent::PointerItem item;
200 touchEvent->GetPointerItem(id, item);
201 int32_t toolType = item.GetToolType();
202 MMI_HILOGD("Pointer tool type:%{public}d", toolType);
203 singleKnuckleGesture_.state = false;
204 doubleKnuckleGesture_.state = false;
205 switch (toolType) {
206 #ifdef OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
207 case PointerEvent::TOOL_TYPE_FINGER: {
208 HandleFingerGestureDownEvent(touchEvent);
209 break;
210 }
211 case PointerEvent::TOOL_TYPE_KNUCKLE: {
212 DfxHisysevent::ReportKnuckleClickEvent();
213 HandleKnuckleGestureDownEvent(touchEvent);
214 break;
215 }
216 #endif // OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
217 default: {
218 MMI_HILOGD("Current touch event tool type:%{public}d", toolType);
219 break;
220 }
221 }
222 CheckAndUpdateTappingCountAtDown(touchEvent);
223 }
224
HandlePointerActionMoveEvent(const std::shared_ptr<PointerEvent> touchEvent)225 void KeyCommandHandler::HandlePointerActionMoveEvent(const std::shared_ptr<PointerEvent> touchEvent)
226 {
227 CALL_DEBUG_ENTER;
228 CHKPV(touchEvent);
229 int32_t id = touchEvent->GetPointerId();
230 PointerEvent::PointerItem item;
231 touchEvent->GetPointerItem(id, item);
232 if (!twoFingerGesture_.active) {
233 return;
234 }
235 if (twoFingerGesture_.timerId == -1) {
236 MMI_HILOGD("Two finger gesture timer id is -1");
237 return;
238 }
239 auto pos = std::find_if(std::begin(twoFingerGesture_.touches), std::end(twoFingerGesture_.touches),
240 [id](const auto& item) { return item.id == id; });
241 if (pos == std::end(twoFingerGesture_.touches)) {
242 MMI_HILOGE("Cant't find the pointer id");
243 return;
244 }
245 auto dx = std::abs(pos->x - item.GetDisplayX());
246 auto dy = std::abs(pos->y - item.GetDisplayY());
247 auto moveDistance = sqrt(pow(dx, 2) + pow(dy, 2));
248 if (moveDistance > ConvertVPToPX(TOUCH_MAX_THRESHOLD)) {
249 #ifdef OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
250 MMI_HILOGI("Finger movement distance greater than 20VP, defaultDistance:%{public}d, moveDistance:%{public}f",
251 ConvertVPToPX(TOUCH_MAX_THRESHOLD), moveDistance);
252 StopTwoFingerGesture();
253 #endif // OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
254 }
255 }
256
HandlePointerActionUpEvent(const std::shared_ptr<PointerEvent> touchEvent)257 void KeyCommandHandler::HandlePointerActionUpEvent(const std::shared_ptr<PointerEvent> touchEvent)
258 {
259 CALL_DEBUG_ENTER;
260 CHKPV(touchEvent);
261 int32_t id = touchEvent->GetPointerId();
262 PointerEvent::PointerItem item;
263 touchEvent->GetPointerItem(id, item);
264 int32_t toolType = item.GetToolType();
265 switch (toolType) {
266 #ifdef OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
267 case PointerEvent::TOOL_TYPE_FINGER: {
268 HandleFingerGestureUpEvent(touchEvent);
269 break;
270 }
271 case PointerEvent::TOOL_TYPE_KNUCKLE: {
272 HandleKnuckleGestureUpEvent(touchEvent);
273 break;
274 }
275 #endif // OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
276 default: {
277 MMI_HILOGW("Current touch event tool type:%{public}d", toolType);
278 break;
279 }
280 }
281 }
282 #endif // OHOS_BUILD_ENABLE_TOUCH
283
284 #ifdef OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
HandleFingerGestureDownEvent(const std::shared_ptr<PointerEvent> touchEvent)285 void KeyCommandHandler::HandleFingerGestureDownEvent(const std::shared_ptr<PointerEvent> touchEvent)
286 {
287 CALL_DEBUG_ENTER;
288 if (!twoFingerGesture_.active) {
289 MMI_HILOGD("Two finger gesture is not active");
290 return;
291 }
292 auto num = touchEvent->GetPointerIds().size();
293 if (num == TwoFingerGesture::MAX_TOUCH_NUM) {
294 StartTwoFingerGesture();
295 } else {
296 StopTwoFingerGesture();
297 }
298 if (num > 0 && num <= TwoFingerGesture::MAX_TOUCH_NUM) {
299 int32_t id = touchEvent->GetPointerId();
300 PointerEvent::PointerItem item;
301 touchEvent->GetPointerItem(id, item);
302 twoFingerGesture_.touches[num - 1].id = id;
303 twoFingerGesture_.touches[num - 1].x = item.GetDisplayX();
304 twoFingerGesture_.touches[num - 1].y = item.GetDisplayY();
305 twoFingerGesture_.touches[num - 1].downTime = item.GetDownTime();
306 }
307 }
308
HandleFingerGestureUpEvent(const std::shared_ptr<PointerEvent> touchEvent)309 void KeyCommandHandler::HandleFingerGestureUpEvent(const std::shared_ptr<PointerEvent> touchEvent)
310 {
311 CALL_DEBUG_ENTER;
312 CHKPV(touchEvent);
313 if (!twoFingerGesture_.active) {
314 MMI_HILOGD("Two finger gesture is not active");
315 return;
316 }
317 StopTwoFingerGesture();
318 }
319
HandleKnuckleGestureDownEvent(const std::shared_ptr<PointerEvent> touchEvent)320 void KeyCommandHandler::HandleKnuckleGestureDownEvent(const std::shared_ptr<PointerEvent> touchEvent)
321 {
322 CALL_DEBUG_ENTER;
323 CHKPV(touchEvent);
324 int32_t id = touchEvent->GetPointerId();
325 PointerEvent::PointerItem item;
326 touchEvent->GetPointerItem(id, item);
327 int64_t currentDownTime = item.GetDownTime();
328 if (!lastPointerDownTime_.empty()) {
329 int64_t firstDownTime = lastPointerDownTime_.begin()->second;
330 int64_t lastPointerDownTime = touchEvent->HasFlag(InputEvent::EVENT_FLAG_SIMULATE) ?
331 lastPointerDownTime_[SIMULATE_POINTER_ID] : firstDownTime;
332 int64_t diffTime = currentDownTime - lastPointerDownTime;
333 lastPointerDownTime_[id] = currentDownTime;
334 MMI_HILOGW("Size:%{public}zu, firstDownTime:%{public}" PRId64 ", "
335 "currentDownTime:%{public}" PRId64 ", diffTime:%{public}" PRId64,
336 lastPointerDownTime_.size(), firstDownTime, currentDownTime, diffTime);
337 if (diffTime > TWO_FINGERS_TIME_LIMIT) {
338 MMI_HILOGE("Invalid double knuckle event, pointerId:%{public}d", id);
339 return;
340 }
341 }
342 lastPointerDownTime_[id] = currentDownTime;
343 auto items = touchEvent->GetAllPointerItems();
344 MMI_HILOGI("itemsSize:%{public}zu", items.size());
345 for (const auto &item : items) {
346 if (item.GetToolType() != PointerEvent::TOOL_TYPE_KNUCKLE) {
347 MMI_HILOGW("Touch event tool type:%{public}d not knuckle", item.GetToolType());
348 return;
349 }
350 }
351 if (knuckleSwitch_.statusConfigValue) {
352 MMI_HILOGI("Knuckle switch closed");
353 return;
354 }
355 if (CheckInputMethodArea(touchEvent)) {
356 if (touchEvent->GetPointerAction() == PointerEvent::POINTER_ACTION_DOWN ||
357 touchEvent->GetPointerAction() == PointerEvent::POINTER_ACTION_UP) {
358 MMI_HILOGW("Event skipping inputmethod area");
359 }
360 return;
361 }
362 size_t pointercnt = touchEvent->GetPointerIds().size();
363 if (pointercnt == SINGLE_KNUCKLE_SIZE) {
364 SingleKnuckleGestureProcesser(touchEvent);
365 isDoubleClick_ = false;
366 knuckleCount_++;
367 } else if (pointercnt == DOUBLE_KNUCKLE_SIZE) {
368 DoubleKnuckleGestureProcesser(touchEvent);
369 isDoubleClick_ = true;
370 } else {
371 MMI_HILOGW("Other kunckle pointercnt not process, pointercnt:%{public}zu", pointercnt);
372 }
373 }
374
HandleKnuckleGestureUpEvent(const std::shared_ptr<PointerEvent> touchEvent)375 void KeyCommandHandler::HandleKnuckleGestureUpEvent(const std::shared_ptr<PointerEvent> touchEvent)
376 {
377 CALL_DEBUG_ENTER;
378 CHKPV(touchEvent);
379 int32_t id = touchEvent->GetPointerId();
380 auto it = lastPointerDownTime_.find(id);
381 if (it != lastPointerDownTime_.end()) {
382 MMI_HILOGW("lastPointerDownTime_ has been erased, pointerId:%{public}d", id);
383 lastPointerDownTime_.erase(it);
384 }
385
386 previousUpTime_ = touchEvent->GetActionTime();
387 size_t pointercnt = touchEvent->GetPointerIds().size();
388 if ((pointercnt == SINGLE_KNUCKLE_SIZE) && (!isDoubleClick_)) {
389 singleKnuckleGesture_.lastPointerUpTime = touchEvent->GetActionTime();
390 } else if (pointercnt == DOUBLE_KNUCKLE_SIZE) {
391 doubleKnuckleGesture_.lastPointerUpTime = touchEvent->GetActionTime();
392 } else {
393 MMI_HILOGW("Other kunckle pointercnt not process, pointercnt:%{public}zu", pointercnt);
394 }
395 }
396
SingleKnuckleGestureProcesser(const std::shared_ptr<PointerEvent> touchEvent)397 void KeyCommandHandler::SingleKnuckleGestureProcesser(const std::shared_ptr<PointerEvent> touchEvent)
398 {
399 CALL_DEBUG_ENTER;
400 CHKPV(touchEvent);
401 singleKnuckleGesture_.state = false;
402 KnuckleGestureProcessor(touchEvent, singleKnuckleGesture_, KnuckleType::KNUCKLE_TYPE_SINGLE);
403 }
404
DoubleKnuckleGestureProcesser(const std::shared_ptr<PointerEvent> touchEvent)405 void KeyCommandHandler::DoubleKnuckleGestureProcesser(const std::shared_ptr<PointerEvent> touchEvent)
406 {
407 CALL_DEBUG_ENTER;
408 CHKPV(touchEvent);
409 doubleKnuckleGesture_.state = false;
410 KnuckleGestureProcessor(touchEvent, doubleKnuckleGesture_, KnuckleType::KNUCKLE_TYPE_DOUBLE);
411 }
412
KnuckleGestureProcessor(std::shared_ptr<PointerEvent> touchEvent,KnuckleGesture & knuckleGesture,KnuckleType type)413 void KeyCommandHandler::KnuckleGestureProcessor(std::shared_ptr<PointerEvent> touchEvent,
414 KnuckleGesture &knuckleGesture, KnuckleType type)
415 {
416 CALL_DEBUG_ENTER;
417 CHKPV(touchEvent);
418 if (knuckleGesture.lastPointerDownEvent == nullptr) {
419 MMI_HILOGI("Knuckle gesture first down Event");
420 knuckleGesture.lastPointerDownEvent = touchEvent;
421 UpdateKnuckleGestureInfo(touchEvent, knuckleGesture);
422 return;
423 }
424 int64_t intervalTime = touchEvent->GetActionTime() - knuckleGesture.lastPointerUpTime;
425 bool isTimeIntervalReady = intervalTime > 0 && intervalTime <= downToPrevUpTimeConfig_;
426 float downToPrevDownDistance = AbsDiff(knuckleGesture, touchEvent);
427 bool isDistanceReady = downToPrevDownDistance < downToPrevDownDistanceConfig_;
428 knuckleGesture.downToPrevUpTime = intervalTime;
429 knuckleGesture.doubleClickDistance = downToPrevDownDistance;
430 UpdateKnuckleGestureInfo(touchEvent, knuckleGesture);
431 if (isTimeIntervalReady && (type == KnuckleType::KNUCKLE_TYPE_DOUBLE || isDistanceReady)) {
432 #ifdef OHOS_BUILD_ENABLE_ANCO
433 if (WIN_MGR->IsKnuckleOnAncoWindow(touchEvent)) {
434 knuckleCount_ = 0;
435 SendNotSupportMsg(touchEvent);
436 return;
437 }
438 #endif // OHOS_BUILD_ENABLE_ANCO
439 MMI_HILOGI("Knuckle gesture start launch ability");
440 knuckleCount_ = 0;
441 DfxHisysevent::ReportSingleKnuckleDoubleClickEvent(intervalTime, downToPrevDownDistance);
442 BytraceAdapter::StartLaunchAbility(KeyCommandType::TYPE_FINGERSCENE, knuckleGesture.ability.bundleName);
443 LaunchAbility(knuckleGesture.ability, NO_DELAY);
444 BytraceAdapter::StopLaunchAbility();
445 knuckleGesture.state = true;
446 if (knuckleGesture.ability.bundleName == SCREENRECORDER_BUNDLE_NAME) {
447 DfxHisysevent::ReportScreenRecorderGesture(intervalTime);
448 }
449 ReportKnuckleScreenCapture(touchEvent);
450 } else {
451 if (knuckleCount_ > KNUCKLE_KNOCKS) {
452 knuckleCount_ = 0;
453 MMI_HILOGW("Time ready:%{public}d, distance ready:%{public}d", isTimeIntervalReady, isDistanceReady);
454 if (!isTimeIntervalReady) {
455 DfxHisysevent::ReportFailIfInvalidTime(touchEvent, intervalTime);
456 }
457 if (!isDistanceReady) {
458 DfxHisysevent::ReportFailIfInvalidDistance(touchEvent, downToPrevDownDistance);
459 }
460 }
461 }
462 AdjustTimeIntervalConfigIfNeed(intervalTime);
463 AdjustDistanceConfigIfNeed(downToPrevDownDistance);
464 }
465
SendNotSupportMsg(std::shared_ptr<PointerEvent> touchEvent)466 void KeyCommandHandler::SendNotSupportMsg(std::shared_ptr<PointerEvent> touchEvent)
467 {
468 CALL_DEBUG_ENTER;
469 CHKPV(touchEvent);
470 auto tempEvent = std::make_shared<PointerEvent>(*touchEvent);
471 std::list<PointerEvent::PointerItem> pointerItems = tempEvent->GetAllPointerItems();
472 tempEvent->RemoveAllPointerItems();
473 for (auto &pointerItem : pointerItems) {
474 pointerItem.SetPointerId(ANCO_KNUCKLE_POINTER_ID);
475 pointerItem.SetOriginPointerId(ANCO_KNUCKLE_POINTER_ID);
476 tempEvent->AddPointerItem(pointerItem);
477 }
478 tempEvent->SetPointerAction(PointerEvent::POINTER_ACTION_DOWN);
479 tempEvent->SetPointerId(ANCO_KNUCKLE_POINTER_ID);
480 tempEvent->SetAgentWindowId(tempEvent->GetTargetWindowId());
481 MMI_HILOGI("Send message");
482 auto fd = WIN_MGR->GetClientFd(tempEvent);
483 auto udsServer = InputHandler->GetUDSServer();
484 NetPacket pkt(MmiMessageId::ON_POINTER_EVENT);
485 InputEventDataTransformation::Marshalling(tempEvent, pkt);
486 #ifdef OHOS_BUILD_ENABLE_SECURITY_COMPONENT
487 InputEventDataTransformation::MarshallingEnhanceData(tempEvent, pkt);
488 #endif // OHOS_BUILD_ENABLE_SECURITY_COMPONENT
489 udsServer->SendMsg(fd, pkt);
490
491 tempEvent->SetPointerAction(PointerEvent::POINTER_ACTION_UP);
492 std::list<PointerEvent::PointerItem> tmpPointerItems = tempEvent->GetAllPointerItems();
493 tempEvent->RemoveAllPointerItems();
494 for (auto &pointerItem : tmpPointerItems) {
495 pointerItem.SetPressed(false);
496 tempEvent->AddPointerItem(pointerItem);
497 }
498 NetPacket pktUp(MmiMessageId::ON_POINTER_EVENT);
499 InputEventDataTransformation::Marshalling(tempEvent, pktUp);
500 #ifdef OHOS_BUILD_ENABLE_SECURITY_COMPONENT
501 InputEventDataTransformation::MarshallingEnhanceData(tempEvent, pktUp);
502 #endif // OHOS_BUILD_ENABLE_SECURITY_COMPONENT
503 udsServer->SendMsg(fd, pktUp);
504 }
505
UpdateKnuckleGestureInfo(const std::shared_ptr<PointerEvent> touchEvent,KnuckleGesture & knuckleGesture)506 void KeyCommandHandler::UpdateKnuckleGestureInfo(const std::shared_ptr<PointerEvent> touchEvent,
507 KnuckleGesture &knuckleGesture)
508 {
509 int32_t id = touchEvent->GetPointerId();
510 PointerEvent::PointerItem item;
511 touchEvent->GetPointerItem(id, item);
512 knuckleGesture.lastDownPointer.x = item.GetDisplayX();
513 knuckleGesture.lastDownPointer.y = item.GetDisplayY();
514 knuckleGesture.lastDownPointer.id = touchEvent->GetId();
515 }
516
AdjustTimeIntervalConfigIfNeed(int64_t intervalTime)517 void KeyCommandHandler::AdjustTimeIntervalConfigIfNeed(int64_t intervalTime)
518 {
519 CALL_DEBUG_ENTER;
520 int64_t newTimeConfig;
521 MMI_HILOGI("Down to prev up interval time:%{public}" PRId64 ",config time:%{public}" PRId64"",
522 intervalTime, downToPrevUpTimeConfig_);
523 if (downToPrevUpTimeConfig_ == DOUBLE_CLICK_INTERVAL_TIME_DEFAULT) {
524 if (intervalTime < DOUBLE_CLICK_INTERVAL_TIME_DEFAULT || intervalTime > DOUBLE_CLICK_INTERVAL_TIME_SLOW) {
525 return;
526 }
527 newTimeConfig = DOUBLE_CLICK_INTERVAL_TIME_SLOW;
528 } else if (downToPrevUpTimeConfig_ == DOUBLE_CLICK_INTERVAL_TIME_SLOW) {
529 if (intervalTime > DOUBLE_CLICK_INTERVAL_TIME_DEFAULT) {
530 return;
531 }
532 newTimeConfig = DOUBLE_CLICK_INTERVAL_TIME_DEFAULT;
533 } else {
534 return;
535 }
536 checkAdjustIntervalTimeCount_++;
537 if (checkAdjustIntervalTimeCount_ < MAX_TIME_FOR_ADJUST_CONFIG) {
538 return;
539 }
540 MMI_HILOGI("Adjust new double click interval time:%{public}" PRId64 "", newTimeConfig);
541 downToPrevUpTimeConfig_ = newTimeConfig;
542 checkAdjustIntervalTimeCount_ = 0;
543 }
544
AdjustDistanceConfigIfNeed(float distance)545 void KeyCommandHandler::AdjustDistanceConfigIfNeed(float distance)
546 {
547 CALL_DEBUG_ENTER;
548 float newDistanceConfig;
549 MMI_HILOGI("Down to prev down distance:%{public}f, config distance:%{public}f",
550 distance, downToPrevDownDistanceConfig_);
551 if (IsEqual(downToPrevDownDistanceConfig_, distanceDefaultConfig_)) {
552 if (distance < distanceDefaultConfig_ || distance > distanceLongConfig_) {
553 return;
554 }
555 newDistanceConfig = distanceLongConfig_;
556 } else if (IsEqual(downToPrevDownDistanceConfig_, distanceLongConfig_)) {
557 if (distance > distanceDefaultConfig_) {
558 return;
559 }
560 newDistanceConfig = distanceDefaultConfig_;
561 } else {
562 return;
563 }
564 checkAdjustDistanceCount_++;
565 if (checkAdjustDistanceCount_ < MAX_TIME_FOR_ADJUST_CONFIG) {
566 return;
567 }
568 MMI_HILOGI("Adjust new double click distance:%{public}f", newDistanceConfig);
569 downToPrevDownDistanceConfig_ = newDistanceConfig;
570 checkAdjustDistanceCount_ = 0;
571 }
572
ReportKnuckleScreenCapture(const std::shared_ptr<PointerEvent> touchEvent)573 void KeyCommandHandler::ReportKnuckleScreenCapture(const std::shared_ptr<PointerEvent> touchEvent)
574 {
575 CHKPV(touchEvent);
576 size_t pointercnt = touchEvent->GetPointerIds().size();
577 if (pointercnt == SINGLE_KNUCKLE_SIZE) {
578 DfxHisysevent::ReportScreenCaptureGesture();
579 return;
580 }
581 MMI_HILOGW("Current touch event pointercnt:%{public}zu", pointercnt);
582 }
583
StartTwoFingerGesture()584 void KeyCommandHandler::StartTwoFingerGesture()
585 {
586 CALL_DEBUG_ENTER;
587 twoFingerGesture_.timerId = TimerMgr->AddTimer(twoFingerGesture_.abilityStartDelay, 1, [this]() {
588 twoFingerGesture_.timerId = -1;
589 if (!CheckTwoFingerGestureAction()) {
590 return;
591 }
592 twoFingerGesture_.ability.params["displayX1"] = std::to_string(twoFingerGesture_.touches[0].x);
593 twoFingerGesture_.ability.params["displayY1"] = std::to_string(twoFingerGesture_.touches[0].y);
594 twoFingerGesture_.ability.params["displayX2"] = std::to_string(twoFingerGesture_.touches[1].x);
595 twoFingerGesture_.ability.params["displayY2"] = std::to_string(twoFingerGesture_.touches[1].y);
596 MMI_HILOGI("Start launch ability immediately");
597 BytraceAdapter::StartLaunchAbility(KeyCommandType::TYPE_MULTI_FINGERS, twoFingerGesture_.ability.bundleName);
598 LaunchAbility(twoFingerGesture_.ability, twoFingerGesture_.abilityStartDelay);
599 BytraceAdapter::StopLaunchAbility();
600 });
601 }
602
StopTwoFingerGesture()603 void KeyCommandHandler::StopTwoFingerGesture()
604 {
605 CALL_DEBUG_ENTER;
606 if (twoFingerGesture_.timerId != -1) {
607 TimerMgr->RemoveTimer(twoFingerGesture_.timerId);
608 twoFingerGesture_.timerId = -1;
609 }
610 }
611
CheckTwoFingerGestureAction() const612 bool KeyCommandHandler::CheckTwoFingerGestureAction() const
613 {
614 if (!twoFingerGesture_.active) {
615 MMI_HILOGI("Two fingers active:%{public}d is fasle", twoFingerGesture_.active);
616 return false;
617 }
618
619 auto firstFinger = twoFingerGesture_.touches[0];
620 auto secondFinger = twoFingerGesture_.touches[1];
621
622 auto pressTimeInterval = fabs(firstFinger.downTime - secondFinger.downTime);
623 if (pressTimeInterval > TWO_FINGERS_TIME_LIMIT) {
624 MMI_HILOGI("Two fingers time too long firstdownTime:%{public}" PRId64 ",seconddownTime:%{public}" PRId64,
625 firstFinger.downTime, secondFinger.downTime);
626 return false;
627 }
628
629 #ifdef OHOS_BUILD_ENABLE_TOUCH
630 auto devX = firstFinger.x - secondFinger.x;
631 auto devY = firstFinger.y - secondFinger.y;
632 auto distance = sqrt(pow(devX, 2) + pow(devY, 2));
633 if (distance < ConvertVPToPX(TWO_FINGERS_DISTANCE_LIMIT)) {
634 MMI_HILOGI("Two fingers distance:%{public}f too small", distance);
635 return false;
636 }
637
638 auto displayInfo = WIN_MGR->GetDefaultDisplayInfo();
639 CHKPR(displayInfo, false);
640 auto leftLimit = ConvertVPToPX(TOUCH_LIFT_LIMIT);
641 auto rightLimit = displayInfo->width - ConvertVPToPX(TOUCH_RIGHT_LIMIT);
642 auto topLimit = ConvertVPToPX(TOUCH_TOP_LIMIT);
643 auto bottomLimit = displayInfo->height - ConvertVPToPX(TOUCH_BOTTOM_LIMIT);
644 if (firstFinger.x <= leftLimit || firstFinger.x >= rightLimit ||
645 firstFinger.y <= topLimit || firstFinger.y >= bottomLimit ||
646 secondFinger.x <= leftLimit || secondFinger.x >= rightLimit ||
647 secondFinger.y <= topLimit || secondFinger.y >= bottomLimit) {
648 MMI_HILOGI("any finger out of region");
649 return false;
650 }
651 #endif // OHOS_BUILD_ENABLE_TOUCH
652
653 return true;
654 }
655 #endif // OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
656
657 #ifdef OHOS_BUILD_ENABLE_TOUCH
ConvertVPToPX(int32_t vp) const658 int32_t KeyCommandHandler::ConvertVPToPX(int32_t vp) const
659 {
660 if (vp <= 0) {
661 return 0;
662 }
663 auto displayInfo = WIN_MGR->GetDefaultDisplayInfo();
664 CHKPR(displayInfo, 0);
665 int32_t dpi = displayInfo->dpi;
666 if (dpi <= 0) {
667 return 0;
668 }
669 const int32_t base = 160;
670 return vp * (dpi / base);
671 }
672 #endif // OHOS_BUILD_ENABLE_TOUCH
673
674 #ifdef OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
HandleKnuckleGestureEvent(std::shared_ptr<PointerEvent> touchEvent)675 void KeyCommandHandler::HandleKnuckleGestureEvent(std::shared_ptr<PointerEvent> touchEvent)
676 {
677 CALL_DEBUG_ENTER;
678 CHKPV(touchEvent);
679 if (!CheckKnuckleCondition(touchEvent)) {
680 return;
681 }
682 int32_t touchAction = touchEvent->GetPointerAction();
683 if (IsValidAction(touchAction)) {
684 switch (touchAction) {
685 case PointerEvent::POINTER_ACTION_CANCEL:
686 case PointerEvent::POINTER_ACTION_UP: {
687 HandleKnuckleGestureTouchUp(touchEvent);
688 break;
689 }
690 case PointerEvent::POINTER_ACTION_MOVE: {
691 HandleKnuckleGestureTouchMove(touchEvent);
692 break;
693 }
694 case PointerEvent::POINTER_ACTION_DOWN: {
695 HandleKnuckleGestureTouchDown(touchEvent);
696 break;
697 }
698 default:
699 MMI_HILOGD("Unknown pointer action:%{public}d", touchAction);
700 break;
701 }
702 }
703 }
704
CheckKnuckleCondition(std::shared_ptr<PointerEvent> touchEvent)705 bool KeyCommandHandler::CheckKnuckleCondition(std::shared_ptr<PointerEvent> touchEvent)
706 {
707 CHKPF(touchEvent);
708 PointerEvent::PointerItem item;
709 touchEvent->GetPointerItem(touchEvent->GetPointerId(), item);
710 if (item.GetToolType() != PointerEvent::TOOL_TYPE_KNUCKLE ||
711 touchEvent->GetPointerIds().size() != SINGLE_KNUCKLE_SIZE || singleKnuckleGesture_.state) {
712 MMI_HILOGD("Touch tool type is:%{public}d", item.GetToolType());
713 ResetKnuckleGesture();
714 return false;
715 }
716 auto physicDisplayInfo = WIN_MGR->GetPhysicalDisplay(touchEvent->GetTargetDisplayId());
717 if (physicDisplayInfo != nullptr && physicDisplayInfo->direction != lastDirection_) {
718 lastDirection_ = physicDisplayInfo->direction;
719 if (touchEvent->GetPointerAction() == PointerEvent::POINTER_ACTION_MOVE && !gesturePoints_.empty()) {
720 MMI_HILOGW("The screen has been rotated while knuckle is moving");
721 ResetKnuckleGesture();
722 return false;
723 }
724 }
725 if (knuckleSwitch_.statusConfigValue) {
726 MMI_HILOGI("Knuckle switch closed");
727 return false;
728 }
729 if (CheckInputMethodArea(touchEvent)) {
730 if (touchEvent->GetPointerAction() == PointerEvent::POINTER_ACTION_DOWN ||
731 touchEvent->GetPointerAction() == PointerEvent::POINTER_ACTION_UP) {
732 MMI_HILOGI("In input method area, skip");
733 }
734 return false;
735 }
736 return true;
737 }
738
IsValidAction(int32_t action)739 bool KeyCommandHandler::IsValidAction(int32_t action)
740 {
741 CALL_DEBUG_ENTER;
742 if (action == PointerEvent::POINTER_ACTION_DOWN ||
743 ((action == PointerEvent::POINTER_ACTION_MOVE || action == PointerEvent::POINTER_ACTION_UP ||
744 action == PointerEvent::POINTER_ACTION_CANCEL) && !gesturePoints_.empty())) {
745 return true;
746 }
747 return false;
748 }
749
CalcDrawCoordinate(const DisplayInfo & displayInfo,PointerEvent::PointerItem pointerItem)750 std::pair<int32_t, int32_t> KeyCommandHandler::CalcDrawCoordinate(const DisplayInfo& displayInfo,
751 PointerEvent::PointerItem pointerItem)
752 {
753 CALL_DEBUG_ENTER;
754 double physicalX = pointerItem.GetRawDisplayX();
755 double physicalY = pointerItem.GetRawDisplayY();
756 if (!displayInfo.transform.empty()) {
757 auto displayXY = WIN_MGR->TransformDisplayXY(displayInfo, physicalX, physicalY);
758 physicalX = displayXY.first;
759 physicalY = displayXY.second;
760 }
761 return {static_cast<int32_t>(physicalX), static_cast<int32_t>(physicalY)};
762 }
763
HandleKnuckleGestureTouchDown(std::shared_ptr<PointerEvent> touchEvent)764 void KeyCommandHandler::HandleKnuckleGestureTouchDown(std::shared_ptr<PointerEvent> touchEvent)
765 {
766 CALL_DEBUG_ENTER;
767 CHKPV(touchEvent);
768 ResetKnuckleGesture();
769 isStartBase_ = false;
770 int32_t id = touchEvent->GetPointerId();
771 PointerEvent::PointerItem item;
772 touchEvent->GetPointerItem(id, item);
773 sessionKey_ = "Base" + std::to_string(item.GetDownTime());
774 auto displayInfo = WIN_MGR->GetPhysicalDisplay(touchEvent->GetTargetDisplayId());
775 CHKPV(displayInfo);
776 auto displayXY = CalcDrawCoordinate(*displayInfo, item);
777 gestureLastX_ = displayXY.first;
778 gestureLastY_ = displayXY.second;
779
780 gesturePoints_.emplace_back(gestureLastX_);
781 gesturePoints_.emplace_back(gestureLastY_);
782 gestureTimeStamps_.emplace_back(touchEvent->GetActionTime());
783 }
784
HandleKnuckleGestureTouchMove(std::shared_ptr<PointerEvent> touchEvent)785 void KeyCommandHandler::HandleKnuckleGestureTouchMove(std::shared_ptr<PointerEvent> touchEvent)
786 {
787 CALL_DEBUG_ENTER;
788 CHKPV(touchEvent);
789 PointerEvent::PointerItem item;
790 touchEvent->GetPointerItem(touchEvent->GetPointerId(), item);
791 auto displayInfo = WIN_MGR->GetPhysicalDisplay(touchEvent->GetTargetDisplayId());
792 CHKPV(displayInfo);
793 auto displayXY = CalcDrawCoordinate(*displayInfo, item);
794 float eventX = displayXY.first;
795 float eventY = displayXY.second;
796 float dx = std::abs(eventX - gestureLastX_);
797 float dy = std::abs(eventY - gestureLastY_);
798 if (dx >= MOVE_TOLERANCE || dy >= MOVE_TOLERANCE) {
799 gestureLastX_ = eventX;
800 gestureLastY_ = eventY;
801 gesturePoints_.emplace_back(gestureLastX_);
802 gesturePoints_.emplace_back(gestureLastY_);
803 gestureTimeStamps_.emplace_back(touchEvent->GetActionTime());
804 if (!isStartBase_ && IsMatchedAbility(gesturePoints_, gestureLastX_, gestureLastY_)) {
805 MMI_HILOGI("First time start aility, size:%{public}zu", gesturePoints_.size());
806 ProcessKnuckleGestureTouchUp(NotifyType::REGIONGESTURE);
807 isStartBase_ = true;
808 }
809 if (!isGesturing_) {
810 gestureTrackLength_ += sqrt(dx * dx + dy * dy);
811 if (gestureTrackLength_ > MIN_GESTURE_STROKE_LENGTH) {
812 isGesturing_ = true;
813 }
814 }
815 if (isGesturing_ && !isLetterGesturing_) {
816 auto GetBoundingSquareness = GESTURESENSE_WRAPPER->getBoundingSquareness_;
817 CHKPV(GetBoundingSquareness);
818 auto boundingSquareness = GetBoundingSquareness(gesturePoints_);
819 if (boundingSquareness > MIN_LETTER_GESTURE_SQUARENESS) {
820 isLetterGesturing_ = true;
821 }
822 }
823 }
824 }
825
HandleKnuckleGestureTouchUp(std::shared_ptr<PointerEvent> touchEvent)826 void KeyCommandHandler::HandleKnuckleGestureTouchUp(std::shared_ptr<PointerEvent> touchEvent)
827 {
828 CALL_DEBUG_ENTER;
829 CHKPV(touchEvent);
830 auto touchUp = GESTURESENSE_WRAPPER->touchUp_;
831 CHKPV(touchUp);
832 MMI_HILOGI("Knuckle gesturePoints size:%{public}zu, isGesturing:%{public}d, isLetterGesturing:%{public}d",
833 gesturePoints_.size(), isGesturing_, isLetterGesturing_);
834 NotifyType notifyType = static_cast<NotifyType>(touchUp(gesturePoints_, gestureTimeStamps_,
835 isGesturing_, isLetterGesturing_));
836 #ifdef OHOS_BUILD_ENABLE_ANCO
837 if (WIN_MGR->IsKnuckleOnAncoWindow(touchEvent) && (notifyType == NotifyType::REGIONGESTURE ||
838 notifyType == NotifyType::LETTERGESTURE)) {
839 MMI_HILOGI("Anco single knuckle toast");
840 SendNotSupportMsg(touchEvent);
841 ResetKnuckleGesture();
842 return;
843 }
844 #endif // OHOS_BUILD_ENABLE_ANCO
845 switch (notifyType) {
846 case NotifyType::REGIONGESTURE: {
847 ProcessKnuckleGestureTouchUp(notifyType);
848 drawOSuccTimestamp_ = touchEvent->GetActionTime();
849 ReportRegionGesture();
850 break;
851 }
852 case NotifyType::LETTERGESTURE: {
853 ProcessKnuckleGestureTouchUp(notifyType);
854 drawOFailTimestamp_ = touchEvent->GetActionTime();
855 ReportLetterGesture();
856 break;
857 }
858 default: {
859 MMI_HILOGW("Not a region gesture or letter gesture, notifyType:%{public}d", notifyType);
860 drawOFailTimestamp_ = touchEvent->GetActionTime();
861 ReportIfNeed();
862 break;
863 }
864 }
865 ResetKnuckleGesture();
866 }
867
ProcessKnuckleGestureTouchUp(NotifyType type)868 void KeyCommandHandler::ProcessKnuckleGestureTouchUp(NotifyType type)
869 {
870 Ability ability;
871 ability.abilityType = EXTENSION_ABILITY;
872 if (type == NotifyType::REGIONGESTURE) {
873 ability.abilityName = WAKEUP_ABILITY_NAME;
874 ability.bundleName = AIBASE_BUNDLE_NAME;
875 ability.params.emplace(std::make_pair("shot_type", "smart-shot"));
876 MMI_HILOGI("isStartBase_:%{public}d, sessionKey_:%{public}s", isStartBase_, sessionKey_.c_str());
877 if (!isStartBase_) {
878 ability.params.emplace(std::make_pair("fingerPath", ""));
879 ability.params.emplace(std::make_pair("launch_type", "knuckle_gesture_pre"));
880 } else {
881 ability.params.emplace(std::make_pair("fingerPath", GesturePointsToStr()));
882 ability.params.emplace(std::make_pair("launch_type", "knuckle_gesture"));
883 }
884 ability.params.emplace(std::make_pair("session_id", sessionKey_));
885 } else if (type == NotifyType::LETTERGESTURE) {
886 ability.abilityName = SCREENSHOT_ABILITY_NAME;
887 ability.bundleName = SCREENSHOT_BUNDLE_NAME;
888 ability.params.emplace(std::make_pair("shot_type", "scroll-shot"));
889 ability.params.emplace(std::make_pair("trigger_type", "knuckle"));
890 }
891 LaunchAbility(ability, NO_DELAY);
892 }
893
ResetKnuckleGesture()894 void KeyCommandHandler::ResetKnuckleGesture()
895 {
896 gestureLastX_ = 0.0f;
897 gestureLastY_ = 0.0f;
898 isGesturing_ = false;
899 isLetterGesturing_ = false;
900 gestureTrackLength_ = 0.0f;
901 gesturePoints_.clear();
902 gestureTimeStamps_.clear();
903 }
904
GesturePointsToStr() const905 std::string KeyCommandHandler::GesturePointsToStr() const
906 {
907 auto count = gesturePoints_.size();
908 if (count % EVEN_NUMBER != 0 || count == 0) {
909 MMI_HILOGE("Invalid gesturePoints_ size");
910 return {};
911 }
912 cJSON *jsonArray = cJSON_CreateArray();
913 for (size_t i = 0; i < count; i += EVEN_NUMBER) {
914 cJSON *jsonData = cJSON_CreateObject();
915 cJSON_AddItemToObject(jsonData, "x", cJSON_CreateNumber(gesturePoints_[i]));
916 cJSON_AddItemToObject(jsonData, "y", cJSON_CreateNumber(gesturePoints_[i + 1]));
917 cJSON_AddItemToArray(jsonArray, jsonData);
918 }
919 char *jsonString = cJSON_Print(jsonArray);
920 std::string result = std::string(jsonString);
921 cJSON_Delete(jsonArray);
922 cJSON_free(jsonString);
923 return result;
924 }
925
ReportIfNeed()926 void KeyCommandHandler::ReportIfNeed()
927 {
928 if (!isGesturing_) {
929 return;
930 }
931 DfxHisysevent::ReportKnuckleGestureFaildTimes();
932 DfxHisysevent::ReportKnuckleGestureTrackLength(gestureTrackLength_);
933 DfxHisysevent::ReportKnuckleGestureTrackTime(gestureTimeStamps_);
934 if (isLastGestureSucceed_) {
935 DfxHisysevent::ReportKnuckleGestureFromSuccessToFailTime(drawOFailTimestamp_ - drawOSuccTimestamp_);
936 }
937 isLastGestureSucceed_ = false;
938 }
939
ReportRegionGesture()940 void KeyCommandHandler::ReportRegionGesture()
941 {
942 DfxHisysevent::ReportSmartShotSuccTimes();
943 ReportGestureInfo();
944 }
945
ReportLetterGesture()946 void KeyCommandHandler::ReportLetterGesture()
947 {
948 DfxHisysevent::ReportKnuckleDrawSSuccessTimes();
949 ReportGestureInfo();
950 }
951
ReportGestureInfo()952 void KeyCommandHandler::ReportGestureInfo()
953 {
954 DfxHisysevent::ReportKnuckleGestureTrackLength(gestureTrackLength_);
955 DfxHisysevent::ReportKnuckleGestureTrackTime(gestureTimeStamps_);
956 if (!isLastGestureSucceed_) {
957 DfxHisysevent::ReportKnuckleGestureFromFailToSuccessTime(drawOSuccTimestamp_ - drawOFailTimestamp_);
958 }
959 isLastGestureSucceed_ = true;
960 }
961
IsMatchedAbility(std::vector<float> gesturePoints,float gestureLastX,float gestureLastY)962 bool KeyCommandHandler::IsMatchedAbility(std::vector<float> gesturePoints,
963 float gestureLastX, float gestureLastY)
964 {
965 if (gesturePoints.size() < POINTER_NUMBER) {
966 MMI_HILOGI("gesturePoints_ is empty");
967 return false;
968 }
969 float gestureFirstX = gesturePoints[0];
970 float gestureFirstY = gesturePoints[1];
971 float distance = std::min(std::abs(gestureLastX - gestureFirstX), std::abs(gestureLastY - gestureFirstY));
972 return distance >= MIN_START_GESTURE;
973 }
974 #endif // OHOS_BUILD_ENABLE_GESTURESENSE_WRAPPER
975
ParseConfig()976 bool KeyCommandHandler::ParseConfig()
977 {
978 const char *testPathSuffix = "/etc/multimodalinput/ability_launch_config.json";
979 char buf[MAX_PATH_LEN] = { 0 };
980 char *filePath = GetOneCfgFile(testPathSuffix, buf, MAX_PATH_LEN);
981 std::string defaultConfig = "/system/etc/multimodalinput/ability_launch_config.json";
982 if (filePath == nullptr || filePath[0] == '\0' || strlen(filePath) > MAX_PATH_LEN) {
983 MMI_HILOGD("Can not get customization config file");
984 return ParseJson(defaultConfig);
985 }
986 std::string customConfig = filePath;
987 MMI_HILOGD("The configuration file path:%{private}s", customConfig.c_str());
988 return ParseJson(customConfig) || ParseJson(defaultConfig);
989 }
990
ParseExcludeConfig()991 bool KeyCommandHandler::ParseExcludeConfig()
992 {
993 #ifndef UNIT_TEST
994 const char *testPathSuffix = "/etc/multimodalinput/exclude_keys_config.json";
995 #else
996 const char *testPathSuffix = "/data/test/exclude_keys_config.json";
997 #endif // UNIT_TEST
998 char buf[MAX_PATH_LEN] = { 0 };
999 char *filePath = GetOneCfgFile(testPathSuffix, buf, MAX_PATH_LEN);
1000 #ifndef UNIT_TEST
1001 std::string defaultConfig = "/system/etc/multimodalinput/exclude_keys_config.json";
1002 #else
1003 std::string defaultConfig = "/data/test/exclude_keys_config.json";
1004 #endif // UNIT_TEST
1005 if (filePath == nullptr || filePath[0] == '\0' || strlen(filePath) > MAX_PATH_LEN) {
1006 MMI_HILOGD("Can not get customization exclude_keys_config.json file");
1007 return ParseExcludeJson(defaultConfig);
1008 }
1009 std::string customConfig = filePath;
1010 MMI_HILOGD("The exclude_keys_config.json file path:%s", customConfig.c_str());
1011 return ParseExcludeJson(customConfig) || ParseExcludeJson(defaultConfig);
1012 }
1013
ParseRepeatKeyMaxCount()1014 void KeyCommandHandler::ParseRepeatKeyMaxCount()
1015 {
1016 if (repeatKeys_.empty()) {
1017 maxCount_ = 0;
1018 }
1019 int32_t tempCount = 0;
1020 int64_t tempDelay = 0;
1021 for (RepeatKey& item : repeatKeys_) {
1022 if (item.times > tempCount) {
1023 tempCount = item.times;
1024 }
1025 if (item.delay > tempDelay) {
1026 tempDelay = item.delay;
1027 }
1028 if (item.ability.bundleName == WALLET_BUNDLE_NAME) {
1029 walletLaunchDelayTimes_ = item.delay;
1030 }
1031 }
1032 maxCount_ = tempCount;
1033 intervalTime_ = tempDelay;
1034 }
1035
CheckSpecialRepeatKey(RepeatKey & item,const std::shared_ptr<KeyEvent> keyEvent)1036 bool KeyCommandHandler::CheckSpecialRepeatKey(RepeatKey& item, const std::shared_ptr<KeyEvent> keyEvent)
1037 {
1038 if (item.keyCode != keyEvent->GetKeyCode()) {
1039 return false;
1040 }
1041 if (item.keyCode != KeyEvent::KEYCODE_VOLUME_DOWN) {
1042 return false;
1043 }
1044 std::string bundleName = item.ability.bundleName;
1045 std::string matchName = ".camera";
1046 if (bundleName.find(matchName) == std::string::npos) {
1047 return false;
1048 }
1049 std::string screenStatus = DISPLAY_MONITOR->GetScreenStatus();
1050 bool isScreenLocked = DISPLAY_MONITOR->GetScreenLocked();
1051 if (WIN_MGR->JudgeCaramaInFore() &&
1052 (screenStatus != EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF && isScreenLocked)) {
1053 return true;
1054 }
1055 auto callState = DEVICE_MONITOR->GetCallState();
1056 if (callState == StateType::CALL_STATUS_ACTIVE) {
1057 return true;
1058 }
1059 MMI_HILOGI("ScreenStatus: %{public}s, isScreenLocked: %{public}d", screenStatus.c_str(), isScreenLocked);
1060 if ((screenStatus == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF || isScreenLocked) &&
1061 !IsMusicActivate()) {
1062 return false;
1063 }
1064 return true;
1065 }
1066
ParseJson(const std::string & configFile)1067 bool KeyCommandHandler::ParseJson(const std::string &configFile)
1068 {
1069 CALL_DEBUG_ENTER;
1070 std::string jsonStr = ReadJsonFile(configFile);
1071 if (jsonStr.empty()) {
1072 MMI_HILOGE("Read configFile failed");
1073 return false;
1074 }
1075 JsonParser parser;
1076 parser.json_ = cJSON_Parse(jsonStr.c_str());
1077 if (!cJSON_IsObject(parser.json_)) {
1078 MMI_HILOGE("Parser.json_ is not object");
1079 return false;
1080 }
1081
1082 bool isParseShortKeys = ParseShortcutKeys(parser, shortcutKeys_, businessIds_);
1083 bool isParseSequences = ParseSequences(parser, sequences_);
1084 bool isParseTwoFingerGesture = ParseTwoFingerGesture(parser, twoFingerGesture_);
1085 bool isParseSingleKnuckleGesture = IsParseKnuckleGesture(parser, SINGLE_KNUCKLE_ABILITY, singleKnuckleGesture_);
1086 bool isParseDoubleKnuckleGesture = IsParseKnuckleGesture(parser, DOUBLE_KNUCKLE_ABILITY, doubleKnuckleGesture_);
1087 bool isParseRepeatKeys = ParseRepeatKeys(parser, repeatKeys_, repeatKeyMaxTimes_);
1088 bool isParseMultiFingersTap = ParseMultiFingersTap(parser, TOUCHPAD_TRIP_TAP_ABILITY, threeFingersTap_);
1089 knuckleSwitch_.statusConfig = SETTING_KNUCKLE_SWITCH;
1090 if (!isParseShortKeys && !isParseSequences && !isParseTwoFingerGesture && !isParseSingleKnuckleGesture &&
1091 !isParseDoubleKnuckleGesture && !isParseRepeatKeys && !isParseMultiFingersTap) {
1092 MMI_HILOGE("Parse configFile failed");
1093 return false;
1094 }
1095
1096 Print();
1097 PrintSeq();
1098 return true;
1099 }
1100
ParseExcludeJson(const std::string & configFile)1101 bool KeyCommandHandler::ParseExcludeJson(const std::string &configFile)
1102 {
1103 CALL_DEBUG_ENTER;
1104 std::string jsonStr = ReadJsonFile(configFile);
1105 if (jsonStr.empty()) {
1106 MMI_HILOGE("Read excludeKey configFile failed");
1107 return false;
1108 }
1109 JsonParser parser;
1110 parser.json_ = cJSON_Parse(jsonStr.c_str());
1111 if (!cJSON_IsObject(parser.json_)) {
1112 MMI_HILOGE("Parser.json_ of excludeKey is not object");
1113 return false;
1114 }
1115 bool isParseExcludeKeys = ParseExcludeKeys(parser, excludeKeys_);
1116 if (!isParseExcludeKeys) {
1117 MMI_HILOGE("Parse ExcludeKeys configFile failed");
1118 return false;
1119 }
1120 PrintExcludeKeys();
1121 return true;
1122 }
1123
Print()1124 void KeyCommandHandler::Print()
1125 {
1126 MMI_HILOGI("ShortcutKey count:%{public}zu", shortcutKeys_.size());
1127 int32_t row = 0;
1128 for (const auto &item : shortcutKeys_) {
1129 MMI_HILOGI("row:%{public}d", row++);
1130 auto &shortcutKey = item.second;
1131 for (const auto &prekey : shortcutKey.preKeys) {
1132 MMI_HILOGI("preKey:%d", prekey);
1133 }
1134 MMI_HILOGI("finalKey:%d, keyDownDuration:%{public}d, triggerType:%{public}d,"
1135 " bundleName:%{public}s, abilityName:%{public}s", shortcutKey.finalKey,
1136 shortcutKey.keyDownDuration, shortcutKey.triggerType,
1137 shortcutKey.ability.bundleName.c_str(), shortcutKey.ability.abilityName.c_str());
1138 }
1139 }
1140
PrintExcludeKeys()1141 void KeyCommandHandler::PrintExcludeKeys()
1142 {
1143 size_t keysSize = excludeKeys_.size();
1144 for (size_t i = 0; i < keysSize; i++) {
1145 MMI_HILOGD("keyCode:%d, keyAction:%{public}d, delay:%{public}" PRId64,
1146 excludeKeys_[i].keyCode, excludeKeys_[i].keyAction, excludeKeys_[i].delay);
1147 }
1148 }
1149
PrintSeq()1150 void KeyCommandHandler::PrintSeq()
1151 {
1152 MMI_HILOGI("Sequences count:%{public}zu", sequences_.size());
1153 int32_t row = 0;
1154 for (const auto &item : sequences_) {
1155 MMI_HILOGI("row:%{public}d", row++);
1156 for (const auto& sequenceKey : item.sequenceKeys) {
1157 MMI_HILOGI("keyCode:%d, keyAction:%{public}d, delay:%{public}" PRId64,
1158 sequenceKey.keyCode, sequenceKey.keyAction, sequenceKey.delay);
1159 }
1160 MMI_HILOGI("bundleName:%{public}s, abilityName:%{public}s",
1161 item.ability.bundleName.c_str(), item.ability.abilityName.c_str());
1162 }
1163 }
1164
IsExcludeKey(const std::shared_ptr<KeyEvent> key)1165 bool KeyCommandHandler::IsExcludeKey(const std::shared_ptr<KeyEvent> key)
1166 {
1167 size_t keysSize = excludeKeys_.size();
1168 for (size_t i = 0; i < keysSize; i++) {
1169 if (key->GetKeyCode() == excludeKeys_[i].keyCode) {
1170 if (key->GetKeyAction() == excludeKeys_[i].keyAction) {
1171 return true;
1172 }
1173 }
1174 }
1175 return false;
1176 }
1177
IsEnableCombineKey(const std::shared_ptr<KeyEvent> key)1178 bool KeyCommandHandler::IsEnableCombineKey(const std::shared_ptr<KeyEvent> key)
1179 {
1180 CHKPF(key);
1181 if (enableCombineKey_) {
1182 return true;
1183 }
1184
1185 if (!isParseExcludeConfig_) {
1186 if (!ParseExcludeConfig()) {
1187 MMI_HILOGE("Parse Exclude configFile failed");
1188 return false;
1189 }
1190 isParseExcludeConfig_ = true;
1191 }
1192
1193 if (IsExcludeKey(key)) {
1194 if (EventLogHelper::IsBetaVersion() && !key->HasFlag(InputEvent::EVENT_FLAG_PRIVACY_MODE)) {
1195 MMI_HILOGD("ExcludekeyCode:%d, ExcludekeyAction:%{public}d", key->GetKeyCode(), key->GetKeyAction());
1196 } else {
1197 MMI_HILOGD("ExcludekeyCode:%d, ExcludekeyAction:%{public}d", key->GetKeyCode(), key->GetKeyAction());
1198 }
1199 auto items = key->GetKeyItems();
1200 MMI_HILOGD("KeyItemsSize:%{public}zu", items.size());
1201 if (items.size() != 1) {
1202 return enableCombineKey_;
1203 }
1204 return true;
1205 }
1206 if (key->GetKeyCode() == KeyEvent::KEYCODE_L) {
1207 for (const auto &item : key->GetKeyItems()) {
1208 int32_t keyCode = item.GetKeyCode();
1209 if (keyCode != KeyEvent::KEYCODE_L && keyCode != KeyEvent::KEYCODE_META_LEFT &&
1210 keyCode != KeyEvent::KEYCODE_META_RIGHT) {
1211 return enableCombineKey_;
1212 }
1213 }
1214 return true;
1215 }
1216 return enableCombineKey_;
1217 }
1218
EnableCombineKey(bool enable)1219 int32_t KeyCommandHandler::EnableCombineKey(bool enable)
1220 {
1221 enableCombineKey_ = enable;
1222 MMI_HILOGI("Enable combineKey is successful in keyCommand handler, enable:%{public}d", enable);
1223 return RET_OK;
1224 }
1225
ParseStatusConfigObserver()1226 void KeyCommandHandler::ParseStatusConfigObserver()
1227 {
1228 CALL_DEBUG_ENTER;
1229 for (Sequence& item : sequences_) {
1230 if (item.statusConfig.empty()) {
1231 continue;
1232 }
1233 CreateStatusConfigObserver<Sequence>(item);
1234 }
1235
1236 for (auto& item : shortcutKeys_) {
1237 ShortcutKey &shortcutKey = item.second;
1238 if (shortcutKey.statusConfig.empty()) {
1239 continue;
1240 }
1241 CreateStatusConfigObserver<ShortcutKey>(shortcutKey);
1242 }
1243 }
1244
1245 template <class T>
CreateStatusConfigObserver(T & item)1246 void KeyCommandHandler::CreateStatusConfigObserver(T& item)
1247 {
1248 CALL_DEBUG_ENTER;
1249 SettingObserver::UpdateFunc updateFunc = [&item](const std::string& key) {
1250 bool statusValue = true;
1251 auto ret = SettingDataShare::GetInstance(MULTIMODAL_INPUT_SERVICE_ID)
1252 .GetBoolValue(key, statusValue);
1253 if (ret != RET_OK) {
1254 MMI_HILOGE("Get value from setting date fail");
1255 return;
1256 }
1257 MMI_HILOGI("Config changed key:%s, value:%{public}d", key.c_str(), statusValue);
1258 item.statusConfigValue = statusValue;
1259 };
1260 sptr<SettingObserver> statusObserver = SettingDataShare::GetInstance(MULTIMODAL_INPUT_SERVICE_ID)
1261 .CreateObserver(item.statusConfig, updateFunc);
1262 ErrCode ret = SettingDataShare::GetInstance(MULTIMODAL_INPUT_SERVICE_ID).RegisterObserver(statusObserver);
1263 if (ret != ERR_OK) {
1264 MMI_HILOGE("Register setting observer failed, ret:%{public}d", ret);
1265 statusObserver = nullptr;
1266 }
1267 bool configVlaue = true;
1268 ret = SettingDataShare::GetInstance(MULTIMODAL_INPUT_SERVICE_ID)
1269 .GetBoolValue(item.statusConfig, configVlaue);
1270 if (ret != RET_OK) {
1271 MMI_HILOGE("Get value from setting date fail");
1272 return;
1273 }
1274 MMI_HILOGI("Get value success key:%s, value:%{public}d", item.statusConfig.c_str(), configVlaue);
1275 item.statusConfigValue = configVlaue;
1276 }
1277
CreateKeyEvent(int32_t keyCode,int32_t keyAction,bool isPressed)1278 std::shared_ptr<KeyEvent> KeyCommandHandler::CreateKeyEvent(int32_t keyCode, int32_t keyAction, bool isPressed)
1279 {
1280 CALL_DEBUG_ENTER;
1281 std::shared_ptr<KeyEvent> keyEvent = KeyEvent::Create();
1282 CHKPP(keyEvent);
1283 KeyEvent::KeyItem item;
1284 item.SetKeyCode(keyCode);
1285 item.SetPressed(isPressed);
1286 keyEvent->SetKeyCode(keyCode);
1287 keyEvent->SetKeyAction(keyAction);
1288 keyEvent->AddPressedKeyItems(item);
1289 return keyEvent;
1290 }
1291
PreHandleEvent(const std::shared_ptr<KeyEvent> key)1292 bool KeyCommandHandler::PreHandleEvent(const std::shared_ptr<KeyEvent> key)
1293 {
1294 CHKPF(key);
1295 if (EventLogHelper::IsBetaVersion() && !key->HasFlag(InputEvent::EVENT_FLAG_PRIVACY_MODE)) {
1296 MMI_HILOGD("KeyEvent occured. keyCode:%d, keyAction:%{public}d", key->GetKeyCode(), key->GetKeyAction());
1297 } else {
1298 MMI_HILOGD("KeyEvent occured. keyCode:%d, keyAction:%{public}d", key->GetKeyCode(), key->GetKeyAction());
1299 }
1300 if (!IsEnableCombineKey(key)) {
1301 MMI_HILOGI("Combine key is taken over in key command");
1302 return false;
1303 }
1304 if (!isParseConfig_) {
1305 if (!ParseConfig()) {
1306 MMI_HILOGE("Parse configFile failed");
1307 return false;
1308 }
1309 isParseConfig_ = true;
1310 }
1311 if (!isParseMaxCount_) {
1312 ParseRepeatKeyMaxCount();
1313 isParseMaxCount_ = true;
1314 }
1315 if (key->GetKeyCode() == KeyEvent::KEYCODE_VOLUME_DOWN || key->GetKeyCode() == KeyEvent::KEYCODE_VOLUME_UP) {
1316 lastVolumeDownActionTime_ = key->GetActionTime();
1317 }
1318 return true;
1319 }
1320
PreHandleEvent()1321 bool KeyCommandHandler::PreHandleEvent()
1322 {
1323 CALL_INFO_TRACE;
1324 if (!isParseConfig_) {
1325 if (!ParseConfig()) {
1326 MMI_HILOGE("Parse configFile failed");
1327 return false;
1328 }
1329 isParseConfig_ = true;
1330 }
1331 if (!isParseMaxCount_) {
1332 ParseRepeatKeyMaxCount();
1333 isParseMaxCount_ = true;
1334 }
1335 return true;
1336 }
1337
HandleEvent(const std::shared_ptr<KeyEvent> key)1338 bool KeyCommandHandler::HandleEvent(const std::shared_ptr<KeyEvent> key)
1339 {
1340 CALL_DEBUG_ENTER;
1341 CHKPF(key);
1342 if (!PreHandleEvent(key)) {
1343 return false;
1344 }
1345
1346 if (STYLUS_HANDLER->HandleStylusKey(key)) {
1347 return true;
1348 }
1349
1350 bool shortKeysHandleRet = HandleShortKeys(key);
1351 if (key->GetKeyCode() == KeyEvent::KEYCODE_POWER && key->GetKeyAction() == KeyEvent::KEY_ACTION_UP) {
1352 powerUpTime_ = key->GetActionTime();
1353 }
1354 if (key->GetKeyCode() == KeyEvent::KEYCODE_POWER && key->GetKeyAction() == KeyEvent::KEY_ACTION_DOWN) {
1355 if ((key->GetActionTime() - powerUpTime_) > POWER_ACTION_INTERVAL * FREQUENCY &&
1356 (key->GetActionTime() - sosLaunchTime_) > SOS_WAIT_TIME * FREQUENCY) {
1357 MMI_HILOGI("Set isFreezePowerKey as false");
1358 isFreezePowerKey_ = false;
1359 }
1360 }
1361 if (key->GetKeyCode() == KeyEvent::KEYCODE_POWER && isFreezePowerKey_) {
1362 MMI_HILOGI("Freeze power key");
1363 return true;
1364 }
1365 bool sequencesHandleRet = HandleSequences(key);
1366 if (shortKeysHandleRet) {
1367 launchAbilityCount_ = 0;
1368 isHandleSequence_ = false;
1369 return true;
1370 }
1371 if (sequencesHandleRet) {
1372 isHandleSequence_ = true;
1373 return true;
1374 }
1375 if (key->GetKeyCode() == KeyEvent::KEYCODE_POWER) {
1376 MMI_HILOGI("Handle power key DownStart:%{public}d", isDownStart_);
1377 }
1378 if (key->GetKeyCode() != repeatKey_.keyCode && key->GetKeyAction() == KeyEvent::KEY_ACTION_DOWN) {
1379 MMI_HILOGI("Combination key currentKey:%{public}d, repeatKey:%{public}d",
1380 key->GetKeyCode(), repeatKey_.keyCode);
1381 isDownStart_ = false;
1382 }
1383 if (!isDownStart_) {
1384 HandleRepeatKeys(key);
1385 return false;
1386 } else {
1387 if (HandleRepeatKeys(key)) {
1388 MMI_HILOGI("Handle power key lifting event");
1389 return true;
1390 }
1391 }
1392 count_ = 0;
1393 repeatKeyCountMap_.clear();
1394 isDownStart_ = false;
1395 return false;
1396 }
1397
InitKeyObserver()1398 void KeyCommandHandler::InitKeyObserver()
1399 {
1400 if (!isParseStatusConfig_) {
1401 ParseStatusConfigObserver();
1402 isParseStatusConfig_ = true;
1403 }
1404 if (!isKnuckleSwitchConfig_) {
1405 CreateStatusConfigObserver(knuckleSwitch_);
1406 isKnuckleSwitchConfig_ = true;
1407 }
1408 }
1409
1410 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
OnHandleEvent(const std::shared_ptr<KeyEvent> key)1411 bool KeyCommandHandler::OnHandleEvent(const std::shared_ptr<KeyEvent> key)
1412 {
1413 CALL_DEBUG_ENTER;
1414 CHKPF(key);
1415 HandlePointerVisibleKeys(key);
1416 if (HandleEvent(key)) {
1417 return true;
1418 }
1419
1420 if (specialKeys_.find(key->GetKeyCode()) != specialKeys_.end()) {
1421 HandleSpecialKeys(key->GetKeyCode(), key->GetAction());
1422 return true;
1423 }
1424
1425 if (IsSpecialType(key->GetKeyCode(), SpecialType::SUBSCRIBER_BEFORE_DELAY)) {
1426 auto tmpKey = KeyEvent::Clone(key);
1427 int32_t timerId = TimerMgr->AddTimer(SPECIAL_KEY_DOWN_DELAY, 1, [this, tmpKey] () {
1428 MMI_HILOGD("Timer callback");
1429 auto it = specialTimers_.find(tmpKey->GetKeyCode());
1430 if (it != specialTimers_.end() && !it->second.empty()) {
1431 it->second.pop_front();
1432 }
1433 InputHandler->GetSubscriberHandler()->HandleKeyEvent(tmpKey);
1434 });
1435 if (timerId < 0) {
1436 MMI_HILOGE("Add timer failed");
1437 return false;
1438 }
1439
1440 auto it = specialTimers_.find(key->GetKeyCode());
1441 if (it == specialTimers_.end()) {
1442 std::list<int32_t> timerIds;
1443 timerIds.push_back(timerId);
1444 auto it = specialTimers_.emplace(key->GetKeyCode(), timerIds);
1445 if (!it.second) {
1446 MMI_HILOGE("Keycode duplicated");
1447 return false;
1448 }
1449 } else {
1450 it->second.push_back(timerId);
1451 }
1452 MMI_HILOGD("Add timer success");
1453 return true;
1454 }
1455 return false;
1456 }
1457 #endif // OHOS_BUILD_ENABLE_KEYBOARD
1458
1459 #if defined(OHOS_BUILD_ENABLE_POINTER) || defined(OHOS_BUILD_ENABLE_TOUCH)
OnHandleEvent(const std::shared_ptr<PointerEvent> pointer)1460 bool KeyCommandHandler::OnHandleEvent(const std::shared_ptr<PointerEvent> pointer)
1461 {
1462 CALL_DEBUG_ENTER;
1463 CHKPF(pointer);
1464 STYLUS_HANDLER->SetLastEventState(false);
1465 if (!isParseConfig_) {
1466 if (!ParseConfig()) {
1467 MMI_HILOGE("Parse configFile failed");
1468 return false;
1469 }
1470 isParseConfig_ = true;
1471 }
1472 return HandleMulFingersTap(pointer);
1473 }
1474 #endif // OHOS_BUILD_ENABLE_POINTER || OHOS_BUILD_ENABLE_TOUCH
1475
HandleRepeatKeys(const std::shared_ptr<KeyEvent> keyEvent)1476 bool KeyCommandHandler::HandleRepeatKeys(const std::shared_ptr<KeyEvent> keyEvent)
1477 {
1478 CALL_DEBUG_ENTER;
1479 CHKPF(keyEvent);
1480 if (repeatKeys_.empty()) {
1481 MMI_HILOGD("No sequences configuration data");
1482 return false;
1483 }
1484
1485 bool isLaunched = false;
1486 bool waitRepeatKey = false;
1487
1488 for (RepeatKey& item : repeatKeys_) {
1489 if (CheckSpecialRepeatKey(item, keyEvent)) {
1490 launchAbilityCount_ = 0;
1491 MMI_HILOGI("Skip repeatKey");
1492 return false;
1493 }
1494 if (HandleKeyUpCancel(item, keyEvent)) {
1495 MMI_HILOGI("Cancel repeatKey");
1496 return false;
1497 }
1498 if (HandleRepeatKeyCount(item, keyEvent)) {
1499 break;
1500 }
1501 }
1502
1503 for (RepeatKey& item : repeatKeys_) {
1504 bool isRepeatKey = HandleRepeatKey(item, isLaunched, keyEvent);
1505 if (isRepeatKey) {
1506 waitRepeatKey = true;
1507 }
1508 }
1509 MMI_HILOGI("Handle repeat key, isLaunched:%{public}d, waitRepeatKey:%{public}d",
1510 isLaunched, waitRepeatKey);
1511 return isLaunched || waitRepeatKey;
1512 }
1513
IsMusicActivate()1514 bool KeyCommandHandler::IsMusicActivate()
1515 {
1516 CALL_INFO_TRACE;
1517 std::vector<std::unique_ptr<AudioStandard::AudioRendererChangeInfo>> rendererChangeInfo;
1518 auto ret = AudioStandard::AudioStreamManager::GetInstance()->GetCurrentRendererChangeInfos(rendererChangeInfo);
1519 if (ret != ERR_OK) {
1520 MMI_HILOGE("Check music activate failed, errnoCode is %{public}d", ret);
1521 return false;
1522 }
1523 if (rendererChangeInfo.empty()) {
1524 MMI_HILOGI("Music info empty");
1525 return false;
1526 }
1527 for (const auto &info : rendererChangeInfo) {
1528 if (info->rendererState == AudioStandard::RENDERER_RUNNING &&
1529 (info->rendererInfo.streamUsage != AudioStandard::STREAM_USAGE_ULTRASONIC ||
1530 info->rendererInfo.streamUsage != AudioStandard::STREAM_USAGE_INVALID)) {
1531 MMI_HILOGI("Find music activate");
1532 return true;
1533 }
1534 }
1535 return false;
1536 }
1537
HandleRepeatKeyOwnCount(const RepeatKey & item)1538 void KeyCommandHandler::HandleRepeatKeyOwnCount(const RepeatKey &item)
1539 {
1540 if (item.ability.bundleName == SOS_BUNDLE_NAME) {
1541 if (repeatKeyCountMap_[item.ability.bundleName] == 1) {
1542 if (downActionTime_ - lastVolumeDownActionTime_ > SOS_INTERVAL_TIMES) {
1543 repeatKeyCountMap_[item.ability.bundleName]++;
1544 }
1545 } else if (downActionTime_ - lastDownActionTime_ < item.delay) {
1546 repeatKeyCountMap_[item.ability.bundleName]++;
1547 }
1548 } else if (downActionTime_ - upActionTime_ < item.delay) {
1549 repeatKeyCountMap_[item.ability.bundleName]++;
1550 }
1551 }
1552
HandleRepeatKey(const RepeatKey & item,bool & isLaunched,const std::shared_ptr<KeyEvent> keyEvent)1553 bool KeyCommandHandler::HandleRepeatKey(const RepeatKey &item, bool &isLaunched,
1554 const std::shared_ptr<KeyEvent> keyEvent)
1555 {
1556 CALL_DEBUG_ENTER;
1557 CHKPF(keyEvent);
1558 if (keyEvent->GetKeyCode() != item.keyCode) {
1559 return false;
1560 }
1561 if (!isDownStart_) {
1562 return false;
1563 }
1564 if (keyEvent->GetKeyAction() != KeyEvent::KEY_ACTION_DOWN ||
1565 (count_ > maxCount_ && keyEvent->GetKeyCode() == KeyEvent::KEYCODE_POWER)) {
1566 MMI_HILOGI("isDownStart:%{public}d", isDownStart_);
1567 if (isDownStart_) {
1568 HandleSpecialKeys(keyEvent->GetKeyCode(), keyEvent->GetKeyAction());
1569 }
1570 return true;
1571 }
1572 auto it = repeatKeyCountMap_.find(item.ability.bundleName);
1573 if (it == repeatKeyCountMap_.end()) {
1574 repeatKeyCountMap_.emplace(item.ability.bundleName, 1);
1575 lastDownActionTime_ = downActionTime_;
1576 return true;
1577 }
1578 HandleRepeatKeyOwnCount(item);
1579 lastDownActionTime_ = downActionTime_;
1580 if (repeatKeyCountMap_[item.ability.bundleName] == item.times) {
1581 if (!item.statusConfig.empty()) {
1582 bool statusValue = true;
1583 auto ret = SettingDataShare::GetInstance(MULTIMODAL_INPUT_SERVICE_ID)
1584 .GetBoolValue(item.statusConfig, statusValue);
1585 if (ret != RET_OK) {
1586 MMI_HILOGE("Get value from setting data fail");
1587 return false;
1588 }
1589 if (!statusValue) {
1590 MMI_HILOGE("Get value from setting data, result is false");
1591 return false;
1592 }
1593 }
1594 if (repeatKeyMaxTimes_.find(item.keyCode) != repeatKeyMaxTimes_.end()) {
1595 launchAbilityCount_ = count_;
1596 if (item.times < repeatKeyMaxTimes_[item.keyCode]) {
1597 return HandleRepeatKeyAbility(item, isLaunched, keyEvent, false);
1598 }
1599 return HandleRepeatKeyAbility(item, isLaunched, keyEvent, true);
1600 }
1601 }
1602 if (count_ > item.times && repeatKeyMaxTimes_.find(item.keyCode) != repeatKeyMaxTimes_.end() &&
1603 repeatKeyTimerIds_.find(item.ability.bundleName) != repeatKeyTimerIds_.end()) {
1604 if (count_ < repeatKeyMaxTimes_[item.keyCode] && repeatKeyTimerIds_[item.ability.bundleName] >= 0) {
1605 TimerMgr->RemoveTimer(repeatKeyTimerIds_[item.ability.bundleName]);
1606 repeatKeyTimerIds_.erase(item.ability.bundleName);
1607 return true;
1608 }
1609 }
1610 return true;
1611 }
1612
HandleRepeatKeyAbility(const RepeatKey & item,bool & isLaunched,const std::shared_ptr<KeyEvent> keyEvent,bool isMaxTimes)1613 bool KeyCommandHandler::HandleRepeatKeyAbility(const RepeatKey &item, bool &isLaunched,
1614 const std::shared_ptr<KeyEvent> keyEvent, bool isMaxTimes)
1615 {
1616 if (!isMaxTimes) {
1617 int64_t delaytime = intervalTime_ - (downActionTime_ - upActionTime_);
1618 int32_t timerId = TimerMgr->AddTimer(
1619 delaytime / SECONDS_SYSTEM, 1, [this, item, &isLaunched, keyEvent] () {
1620 LaunchRepeatKeyAbility(item, isLaunched, keyEvent);
1621 auto it = repeatKeyTimerIds_.find(item.ability.bundleName);
1622 if (it != repeatKeyTimerIds_.end()) {
1623 repeatKeyTimerIds_.erase(it);
1624 }
1625 });
1626 if (timerId < 0) {
1627 return false;
1628 }
1629 if (repeatTimerId_ >= 0) {
1630 TimerMgr->RemoveTimer(repeatTimerId_);
1631 repeatTimerId_ = DEFAULT_VALUE;
1632 isHandleSequence_ = false;
1633 }
1634 if (repeatKeyTimerIds_.find(item.ability.bundleName) == repeatKeyTimerIds_.end()) {
1635 repeatKeyTimerIds_.emplace(item.ability.bundleName, timerId);
1636 return true;
1637 }
1638 repeatKeyTimerIds_[item.ability.bundleName] = timerId;
1639 return true;
1640 }
1641 LaunchRepeatKeyAbility(item, isLaunched, keyEvent);
1642 return true;
1643 }
1644
LaunchRepeatKeyAbility(const RepeatKey & item,bool & isLaunched,const std::shared_ptr<KeyEvent> keyEvent)1645 void KeyCommandHandler::LaunchRepeatKeyAbility(const RepeatKey &item, bool &isLaunched,
1646 const std::shared_ptr<KeyEvent> keyEvent)
1647 {
1648 BytraceAdapter::StartLaunchAbility(KeyCommandType::TYPE_REPEAT_KEY, item.ability.bundleName);
1649 LaunchAbility(item.ability);
1650 BytraceAdapter::StopLaunchAbility();
1651 repeatKeyCountMap_.clear();
1652 isLaunched = true;
1653 if (InputHandler->GetSubscriberHandler() != nullptr) {
1654 auto keyEventCancel = std::make_shared<KeyEvent>(*keyEvent);
1655 keyEventCancel->SetKeyAction(KeyEvent::KEY_ACTION_CANCEL);
1656 InputHandler->GetSubscriberHandler()->HandleKeyEvent(keyEventCancel);
1657 }
1658 }
1659
SetIsFreezePowerKey(const std::string pageName)1660 int32_t KeyCommandHandler::SetIsFreezePowerKey(const std::string pageName)
1661 {
1662 CALL_INFO_TRACE;
1663 std::lock_guard<std::mutex> lock(mutex_);
1664 if (pageName != "SosCountdown") {
1665 isFreezePowerKey_ = false;
1666 return RET_OK;
1667 }
1668 isFreezePowerKey_ = true;
1669 sosLaunchTime_ = OHOS::MMI::GetSysClockTime();
1670 count_ = 0;
1671 launchAbilityCount_ = 0;
1672 repeatKeyCountMap_.clear();
1673 if (sosDelayTimerId_ >= 0) {
1674 TimerMgr->RemoveTimer(sosDelayTimerId_);
1675 sosDelayTimerId_ = DEFAULT_VALUE;
1676 }
1677 int32_t timerId = TimerMgr->AddTimer(
1678 SOS_COUNT_DOWN_TIMES / SECONDS_SYSTEM, 1, [this] () {
1679 MMI_HILOGW("Timeout, restore the power button");
1680 isFreezePowerKey_ = false;
1681 });
1682 if (timerId < 0) {
1683 MMI_HILOGE("Add timer failed");
1684 isFreezePowerKey_ = false;
1685 return RET_ERR;
1686 }
1687 return RET_OK;
1688 }
1689
HandleKeyUpCancel(const RepeatKey & item,const std::shared_ptr<KeyEvent> keyEvent)1690 bool KeyCommandHandler::HandleKeyUpCancel(const RepeatKey &item, const std::shared_ptr<KeyEvent> keyEvent)
1691 {
1692 CALL_DEBUG_ENTER;
1693 CHKPF(keyEvent);
1694 if (keyEvent->GetKeyCode() == item.keyCode && keyEvent->GetKeyAction() == KeyEvent::KEY_ACTION_CANCEL) {
1695 isKeyCancel_ = true;
1696 isDownStart_ = false;
1697 count_ = 0;
1698 repeatKeyCountMap_.clear();
1699 return true;
1700 }
1701 return false;
1702 }
1703
HandleRepeatKeyCount(const RepeatKey & item,const std::shared_ptr<KeyEvent> keyEvent)1704 bool KeyCommandHandler::HandleRepeatKeyCount(const RepeatKey &item, const std::shared_ptr<KeyEvent> keyEvent)
1705 {
1706 CALL_DEBUG_ENTER;
1707 CHKPF(keyEvent);
1708
1709 if (keyEvent->GetKeyCode() == item.keyCode && keyEvent->GetKeyAction() == KeyEvent::KEY_ACTION_UP) {
1710 upActionTime_ = keyEvent->GetActionTime();
1711 repeatKey_.keyCode = item.keyCode;
1712 repeatKey_.keyAction = keyEvent->GetKeyAction();
1713 int64_t intervalTime = intervalTime_;
1714 if (item.keyCode == KeyEvent::KEYCODE_POWER) {
1715 intervalTime = intervalTime_ - (upActionTime_ - downActionTime_);
1716 if (walletLaunchDelayTimes_ != 0) {
1717 intervalTime = walletLaunchDelayTimes_;
1718 }
1719 }
1720 MMI_HILOGD("IntervalTime: %{public}" PRId64, intervalTime);
1721 repeatTimerId_ = TimerMgr->AddTimer(intervalTime / SECONDS_SYSTEM, 1, [this] () {
1722 SendKeyEvent();
1723 repeatTimerId_ = -1;
1724 });
1725 if (repeatTimerId_ < 0) {
1726 return false;
1727 }
1728 return true;
1729 }
1730
1731 if (keyEvent->GetKeyCode() == item.keyCode && keyEvent->GetKeyAction() == KeyEvent::KEY_ACTION_DOWN) {
1732 if (repeatKey_.keyCode != item.keyCode) {
1733 count_ = 1;
1734 repeatKey_.keyCode = item.keyCode;
1735 repeatKey_.keyAction = keyEvent->GetKeyAction();
1736 } else {
1737 if (repeatKey_.keyAction == keyEvent->GetKeyAction()) {
1738 MMI_HILOGD("Repeat key, reset down status");
1739 count_ = 0;
1740 isDownStart_ = false;
1741 repeatKeyCountMap_.clear();
1742 return true;
1743 } else {
1744 repeatKey_.keyAction = keyEvent->GetKeyAction();
1745 count_++;
1746 MMI_HILOGD("Repeat count:%{public}d", count_);
1747 }
1748 }
1749 isDownStart_ = true;
1750 downActionTime_ = keyEvent->GetActionTime();
1751 if ((downActionTime_ - upActionTime_) < intervalTime_) {
1752 if (repeatTimerId_ >= 0) {
1753 TimerMgr->RemoveTimer(repeatTimerId_);
1754 repeatTimerId_ = DEFAULT_VALUE;
1755 isHandleSequence_ = false;
1756 }
1757 }
1758 return true;
1759 }
1760 return false;
1761 }
1762
SendKeyEvent()1763 void KeyCommandHandler::SendKeyEvent()
1764 {
1765 CALL_DEBUG_ENTER;
1766 if (!isHandleSequence_) {
1767 MMI_HILOGD("Launch ability count:%{public}d count:%{public}d", launchAbilityCount_, count_);
1768 for (int32_t i = launchAbilityCount_; i < count_; i++) {
1769 int32_t keycode = repeatKey_.keyCode;
1770 if (IsSpecialType(keycode, SpecialType::KEY_DOWN_ACTION)) {
1771 HandleSpecialKeys(keycode, KeyEvent::KEY_ACTION_UP);
1772 }
1773 if (count_ == repeatKeyMaxTimes_[keycode] - 1 && keycode == KeyEvent::KEYCODE_POWER) {
1774 auto keyEventCancel = CreateKeyEvent(keycode, KeyEvent::KEY_ACTION_CANCEL, false);
1775 CHKPV(keyEventCancel);
1776 InputHandler->GetSubscriberHandler()->HandleKeyEvent(keyEventCancel);
1777 continue;
1778 }
1779 if (i != 0) {
1780 auto keyEventDown = CreateKeyEvent(keycode, KeyEvent::KEY_ACTION_DOWN, true);
1781 CHKPV(keyEventDown);
1782 InputHandler->GetSubscriberHandler()->HandleKeyEvent(keyEventDown);
1783 }
1784
1785 auto keyEventUp = CreateKeyEvent(keycode, KeyEvent::KEY_ACTION_UP, false);
1786 CHKPV(keyEventUp);
1787 InputHandler->GetSubscriberHandler()->HandleKeyEvent(keyEventUp);
1788 }
1789 }
1790 count_ = 0;
1791 repeatKeyCountMap_.clear();
1792 isDownStart_ = false;
1793 isHandleSequence_ = false;
1794 launchAbilityCount_ = 0;
1795 }
1796
HandleShortKeys(const std::shared_ptr<KeyEvent> keyEvent)1797 bool KeyCommandHandler::HandleShortKeys(const std::shared_ptr<KeyEvent> keyEvent)
1798 {
1799 CALL_DEBUG_ENTER;
1800 CHKPF(keyEvent);
1801 if (shortcutKeys_.empty()) {
1802 MMI_HILOGD("No shortkeys configuration data");
1803 return false;
1804 }
1805 if (IsKeyMatch(lastMatchedKey_, keyEvent)) {
1806 MMI_HILOGD("The same key is waiting timeout, skip");
1807 return true;
1808 }
1809 if (currentLaunchAbilityKey_.timerId >= 0 && IsKeyMatch(currentLaunchAbilityKey_, keyEvent)) {
1810 if (EventLogHelper::IsBetaVersion() && !keyEvent->HasFlag(InputEvent::EVENT_FLAG_PRIVACY_MODE)) {
1811 MMI_HILOGD("repeat, current key %d has launched ability", currentLaunchAbilityKey_.finalKey);
1812 } else {
1813 MMI_HILOGD("repeat, current key %d has launched ability", currentLaunchAbilityKey_.finalKey);
1814 }
1815 return true;
1816 }
1817 DfxHisysevent::GetComboStartTime();
1818 if (lastMatchedKey_.timerId >= 0) {
1819 MMI_HILOGD("Remove timer:%{public}d", lastMatchedKey_.timerId);
1820 TimerMgr->RemoveTimer(lastMatchedKey_.timerId);
1821 lastMatchedKey_.timerId = -1;
1822 }
1823 ResetLastMatchedKey();
1824 bool result = false;
1825 std::vector<ShortcutKey> upAbilities;
1826 for (auto &item : shortcutKeys_) {
1827 ShortcutKey &shortcutKey = item.second;
1828 if (!shortcutKey.statusConfigValue) {
1829 continue;
1830 }
1831 if (!IsKeyMatch(shortcutKey, keyEvent)) {
1832 MMI_HILOGD("Not key matched, next");
1833 continue;
1834 }
1835 int32_t delay = GetKeyDownDurationFromXml(shortcutKey.businessId);
1836 if (delay >= MIN_SHORT_KEY_DOWN_DURATION && delay <= MAX_SHORT_KEY_DOWN_DURATION) {
1837 MMI_HILOGD("User defined new short key down duration:%{public}d", delay);
1838 shortcutKey.keyDownDuration = delay;
1839 }
1840 shortcutKey.Print();
1841 if (shortcutKey.triggerType == KeyEvent::KEY_ACTION_DOWN) {
1842 result = HandleKeyDown(shortcutKey) || result;
1843 } else if (shortcutKey.triggerType == KeyEvent::KEY_ACTION_UP) {
1844 bool handleResult = HandleKeyUp(keyEvent, shortcutKey);
1845 result = handleResult || result;
1846 if (handleResult && shortcutKey.keyDownDuration > 0) {
1847 upAbilities.push_back(shortcutKey);
1848 }
1849 } else {
1850 result = HandleKeyCancel(shortcutKey) || result;
1851 }
1852 }
1853 if (!upAbilities.empty()) {
1854 std::sort(upAbilities.begin(), upAbilities.end(),
1855 [](const ShortcutKey &lShortcutKey, const ShortcutKey &rShortcutKey) -> bool {
1856 return lShortcutKey.keyDownDuration > rShortcutKey.keyDownDuration;
1857 });
1858 ShortcutKey tmpShorteKey = upAbilities.front();
1859 MMI_HILOGI("Start launch ability immediately");
1860 BytraceAdapter::StartLaunchAbility(KeyCommandType::TYPE_SHORTKEY, tmpShorteKey.ability.bundleName);
1861 LaunchAbility(tmpShorteKey);
1862 BytraceAdapter::StopLaunchAbility();
1863 }
1864 if (result) {
1865 if (currentLaunchAbilityKey_.finalKey == keyEvent->GetKeyCode()
1866 && keyEvent->GetKeyAction() == KeyEvent::KEY_ACTION_UP) {
1867 ResetCurrentLaunchAbilityKey();
1868 repeatKey_.keyCode = -1;
1869 repeatKey_.keyAction = -1;
1870 }
1871 return result;
1872 }
1873 return HandleConsumedKeyEvent(keyEvent);
1874 }
1875
HandleConsumedKeyEvent(const std::shared_ptr<KeyEvent> keyEvent)1876 bool KeyCommandHandler::HandleConsumedKeyEvent(const std::shared_ptr<KeyEvent> keyEvent)
1877 {
1878 CALL_DEBUG_ENTER;
1879 CHKPF(keyEvent);
1880 if (currentLaunchAbilityKey_.finalKey == keyEvent->GetKeyCode()
1881 && keyEvent->GetKeyAction() == KeyEvent::KEY_ACTION_UP) {
1882 MMI_HILOGI("Handle consumed key event, cancel opration");
1883 ResetCurrentLaunchAbilityKey();
1884 auto keyEventCancel = std::make_shared<KeyEvent>(*keyEvent);
1885 keyEventCancel->SetKeyAction(KeyEvent::KEY_ACTION_CANCEL);
1886 auto inputEventNormalizeHandler = InputHandler->GetEventNormalizeHandler();
1887 CHKPF(inputEventNormalizeHandler);
1888 inputEventNormalizeHandler->HandleKeyEvent(keyEventCancel);
1889 return true;
1890 }
1891 return false;
1892 }
1893
IsRepeatKeyEvent(const SequenceKey & sequenceKey)1894 bool KeyCommandHandler::IsRepeatKeyEvent(const SequenceKey &sequenceKey)
1895 {
1896 for (size_t i = keys_.size(); i > 0; --i) {
1897 if (keys_[i-1].keyCode == sequenceKey.keyCode) {
1898 if (keys_[i-1].keyAction == sequenceKey.keyAction) {
1899 MMI_HILOGI("Is repeat key, keyCode:%d", sequenceKey.keyCode);
1900 return true;
1901 }
1902 MMI_HILOGI("Is not repeat key");
1903 return false;
1904 }
1905 }
1906 return false;
1907 }
1908
IsActiveSequenceRepeating(std::shared_ptr<KeyEvent> keyEvent) const1909 bool KeyCommandHandler::IsActiveSequenceRepeating(std::shared_ptr<KeyEvent> keyEvent) const
1910 {
1911 return (sequenceOccurred_ && !keys_.empty() &&
1912 (keys_.back().keyCode == keyEvent->GetKeyCode()) &&
1913 (keys_.back().keyAction == KeyEvent::KEY_ACTION_DOWN) &&
1914 (keyEvent->GetKeyAction() == KeyEvent::KEY_ACTION_DOWN));
1915 }
1916
MarkActiveSequence(bool active)1917 void KeyCommandHandler::MarkActiveSequence(bool active)
1918 {
1919 sequenceOccurred_ = active;
1920 }
1921
HandleSequences(const std::shared_ptr<KeyEvent> keyEvent)1922 bool KeyCommandHandler::HandleSequences(const std::shared_ptr<KeyEvent> keyEvent)
1923 {
1924 CALL_DEBUG_ENTER;
1925 CHKPF(keyEvent);
1926 std::string screenStatus = DISPLAY_MONITOR->GetScreenStatus();
1927 if (screenStatus == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF) {
1928 if (keyEvent->GetKeyCode() == KeyEvent::KEYCODE_POWER) {
1929 MMI_HILOGI("The screen is currently off and the power button needs to respond");
1930 return false;
1931 }
1932 }
1933 if (IsActiveSequenceRepeating(keyEvent)) {
1934 MMI_HILOGD("Skip repeating key(%{public}d) in active sequence", keyEvent->GetKeyCode());
1935 return true;
1936 }
1937 MarkActiveSequence(false);
1938 if (matchedSequence_.timerId >= 0 && keyEvent->GetKeyAction() == KeyEvent::KEY_ACTION_UP) {
1939 MMI_HILOGD("Remove matchedSequence timer:%{public}d", matchedSequence_.timerId);
1940 TimerMgr->RemoveTimer(matchedSequence_.timerId);
1941 matchedSequence_.timerId = -1;
1942 }
1943 if (sequences_.empty()) {
1944 MMI_HILOGD("No sequences configuration data");
1945 return false;
1946 }
1947
1948 if (!AddSequenceKey(keyEvent)) {
1949 MMI_HILOGD("Add new sequence key failed");
1950 return false;
1951 }
1952
1953 if (filterSequences_.empty()) {
1954 filterSequences_ = sequences_;
1955 }
1956
1957 bool isLaunchAbility = false;
1958 for (auto iter = filterSequences_.begin(); iter != filterSequences_.end();) {
1959 if (!HandleSequence((*iter), isLaunchAbility)) {
1960 filterSequences_.erase(iter);
1961 continue;
1962 }
1963 ++iter;
1964 }
1965
1966 if (filterSequences_.empty()) {
1967 MMI_HILOGD("No sequences matched");
1968 keys_.clear();
1969 return false;
1970 }
1971
1972 if (isLaunchAbility) {
1973 MarkActiveSequence(true);
1974 for (const auto& item : keys_) {
1975 if (IsSpecialType(item.keyCode, SpecialType::KEY_DOWN_ACTION)) {
1976 HandleSpecialKeys(item.keyCode, item.keyAction);
1977 }
1978 InputHandler->GetSubscriberHandler()->RemoveSubscriberKeyUpTimer(item.keyCode);
1979 RemoveSubscribedTimer(item.keyCode);
1980 }
1981 }
1982 return isLaunchAbility;
1983 }
1984
AddSequenceKey(const std::shared_ptr<KeyEvent> keyEvent)1985 bool KeyCommandHandler::AddSequenceKey(const std::shared_ptr<KeyEvent> keyEvent)
1986 {
1987 CALL_DEBUG_ENTER;
1988 CHKPF(keyEvent);
1989 SequenceKey sequenceKey;
1990 sequenceKey.keyCode = keyEvent->GetKeyCode();
1991 sequenceKey.keyAction = keyEvent->GetKeyAction();
1992 sequenceKey.actionTime = keyEvent->GetActionTime();
1993 size_t size = keys_.size();
1994 if (size > 0) {
1995 if (keys_[size - 1].actionTime > sequenceKey.actionTime) {
1996 MMI_HILOGE("The current event time is greater than the last event time");
1997 ResetSequenceKeys();
1998 return false;
1999 }
2000 if ((sequenceKey.actionTime - keys_[size - 1].actionTime) > MAX_DELAY_TIME) {
2001 MMI_HILOGD("The delay time is greater than the maximum delay time");
2002 ResetSequenceKeys();
2003 } else {
2004 if (IsRepeatKeyEvent(sequenceKey)) {
2005 MMI_HILOGD("This is a repeat key event, don't add");
2006 return false;
2007 }
2008 keys_[size - 1].delay = sequenceKey.actionTime - keys_[size - 1].actionTime;
2009 InterruptTimers();
2010 }
2011 }
2012 if (size > MAX_SEQUENCEKEYS_NUM) {
2013 MMI_HILOGD("The save key size more than the max size");
2014 return false;
2015 }
2016 keys_.push_back(sequenceKey);
2017 return true;
2018 }
2019
HandleScreenLocked(Sequence & sequence,bool & isLaunchAbility)2020 bool KeyCommandHandler::HandleScreenLocked(Sequence& sequence, bool &isLaunchAbility)
2021 {
2022 sequence.timerId = TimerMgr->AddTimer(LONG_ABILITY_START_DELAY, 1, [this, &sequence] () {
2023 MMI_HILOGI("Timer callback");
2024 BytraceAdapter::StartLaunchAbility(KeyCommandType::TYPE_SEQUENCE, sequence.ability.bundleName);
2025 LaunchAbility(sequence);
2026 sequence.timerId = -1;
2027 BytraceAdapter::StopLaunchAbility();
2028 });
2029 if (sequence.timerId < 0) {
2030 MMI_HILOGE("Add Timer failed");
2031 return false;
2032 }
2033 MMI_HILOGI("Add timer success");
2034 matchedSequence_ = sequence;
2035 isLaunchAbility = true;
2036 return true;
2037 }
2038
HandleNormalSequence(Sequence & sequence,bool & isLaunchAbility)2039 bool KeyCommandHandler::HandleNormalSequence(Sequence& sequence, bool &isLaunchAbility)
2040 {
2041 if (sequence.abilityStartDelay == 0) {
2042 MMI_HILOGI("Start launch ability immediately");
2043 BytraceAdapter::StartLaunchAbility(KeyCommandType::TYPE_SEQUENCE, sequence.ability.bundleName);
2044 LaunchAbility(sequence);
2045 BytraceAdapter::StopLaunchAbility();
2046 isLaunchAbility = true;
2047 return true;
2048 }
2049 sequence.timerId = TimerMgr->AddTimer(sequence.abilityStartDelay, 1, [this, &sequence] () {
2050 MMI_HILOGI("Timer callback");
2051 BytraceAdapter::StartLaunchAbility(KeyCommandType::TYPE_SEQUENCE, sequence.ability.bundleName);
2052 LaunchAbility(sequence);
2053 sequence.timerId = -1;
2054 BytraceAdapter::StopLaunchAbility();
2055 });
2056 if (sequence.timerId < 0) {
2057 MMI_HILOGE("Add Timer failed");
2058 return false;
2059 }
2060 MMI_HILOGI("Add timer success");
2061 isLaunchAbility = true;
2062 return true;
2063 }
2064
HandleMatchedSequence(Sequence & sequence,bool & isLaunchAbility)2065 bool KeyCommandHandler::HandleMatchedSequence(Sequence& sequence, bool &isLaunchAbility)
2066 {
2067 std::string screenStatus = DISPLAY_MONITOR->GetScreenStatus();
2068 bool isScreenLocked = DISPLAY_MONITOR->GetScreenLocked();
2069 MMI_HILOGI("screenStatus: %{public}s, isScreenLocked: %{public}d", screenStatus.c_str(), isScreenLocked);
2070 std::string bundleName = sequence.ability.bundleName;
2071 std::string matchName = ".screenshot";
2072 if (bundleName.find(matchName) != std::string::npos) {
2073 bundleName = bundleName.substr(bundleName.size() - matchName.size());
2074 }
2075 if (screenStatus == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF) {
2076 if (bundleName == matchName) {
2077 MMI_HILOGI("screen off, screenshot invalid");
2078 return false;
2079 }
2080 } else {
2081 if (bundleName == matchName && isScreenLocked) {
2082 MMI_HILOGI("screen locked, screenshot delay 2000 milisecond");
2083 return HandleScreenLocked(sequence, isLaunchAbility);
2084 }
2085 }
2086 return HandleNormalSequence(sequence, isLaunchAbility);
2087 }
2088
HandleSequence(Sequence & sequence,bool & isLaunchAbility)2089 bool KeyCommandHandler::HandleSequence(Sequence &sequence, bool &isLaunchAbility)
2090 {
2091 CALL_DEBUG_ENTER;
2092 size_t keysSize = keys_.size();
2093 size_t sequenceKeysSize = sequence.sequenceKeys.size();
2094 if (!sequence.statusConfigValue) {
2095 return false;
2096 }
2097 if (keysSize > sequenceKeysSize) {
2098 MMI_HILOGI("The save sequence not matching ability sequence");
2099 return false;
2100 }
2101 for (size_t i = 0; i < keysSize; ++i) {
2102 if (keys_[i] != sequence.sequenceKeys[i]) {
2103 MMI_HILOGD("The keyCode or keyAction not matching");
2104 return false;
2105 }
2106 int64_t delay = sequence.sequenceKeys[i].delay;
2107 if (((i + 1) != keysSize) && (delay != 0) && (keys_[i].delay >= delay)) {
2108 MMI_HILOGD("Delay is not matching");
2109 return false;
2110 }
2111 }
2112 std::ostringstream oss;
2113 oss << sequence;
2114 MMI_HILOGI("SequenceKey matched: %{public}s", oss.str().c_str());
2115 if (keysSize == sequenceKeysSize) {
2116 return HandleMatchedSequence(sequence, isLaunchAbility);
2117 }
2118 return true;
2119 }
2120
HandleMulFingersTap(const std::shared_ptr<PointerEvent> pointerEvent)2121 bool KeyCommandHandler::HandleMulFingersTap(const std::shared_ptr<PointerEvent> pointerEvent)
2122 {
2123 CALL_DEBUG_ENTER;
2124 CHKPR(pointerEvent, ERROR_NULL_POINTER);
2125 if (pointerEvent->GetPointerAction() == PointerEvent::POINTER_ACTION_TRIPTAP) {
2126 MMI_HILOGI("The touchpad trip tap will launch ability");
2127 BytraceAdapter::StartLaunchAbility(KeyCommandType::TYPE_MULTI_FINGERS, threeFingersTap_.ability.bundleName);
2128 LaunchAbility(threeFingersTap_.ability, NO_DELAY);
2129 BytraceAdapter::StopLaunchAbility();
2130 return true;
2131 }
2132 return false;
2133 }
2134
IsKeyMatch(const ShortcutKey & shortcutKey,const std::shared_ptr<KeyEvent> & key)2135 bool KeyCommandHandler::IsKeyMatch(const ShortcutKey &shortcutKey, const std::shared_ptr<KeyEvent> &key)
2136 {
2137 CALL_DEBUG_ENTER;
2138 CHKPF(key);
2139 if ((key->GetKeyCode() != shortcutKey.finalKey) || (shortcutKey.triggerType != key->GetKeyAction())) {
2140 return false;
2141 }
2142 if ((shortcutKey.preKeys.size() + 1) != key->GetKeyItems().size()) {
2143 return false;
2144 }
2145 for (const auto &item : key->GetKeyItems()) {
2146 int32_t keyCode = item.GetKeyCode();
2147 if (SkipFinalKey(keyCode, key)) {
2148 continue;
2149 }
2150 if (shortcutKey.preKeys.find(keyCode) == shortcutKey.preKeys.end()) {
2151 return false;
2152 }
2153 }
2154 MMI_HILOGD("Leave, key matched");
2155 return true;
2156 }
2157
SkipFinalKey(const int32_t keyCode,const std::shared_ptr<KeyEvent> & key)2158 bool KeyCommandHandler::SkipFinalKey(const int32_t keyCode, const std::shared_ptr<KeyEvent> &key)
2159 {
2160 CHKPF(key);
2161 return keyCode == key->GetKeyCode();
2162 }
2163
HandleKeyDown(ShortcutKey & shortcutKey)2164 bool KeyCommandHandler::HandleKeyDown(ShortcutKey &shortcutKey)
2165 {
2166 CALL_DEBUG_ENTER;
2167 if (shortcutKey.keyDownDuration == 0) {
2168 MMI_HILOGI("Start launch ability immediately");
2169 BytraceAdapter::StartLaunchAbility(KeyCommandType::TYPE_SHORTKEY, shortcutKey.ability.bundleName);
2170 LaunchAbility(shortcutKey);
2171 BytraceAdapter::StopLaunchAbility();
2172 return true;
2173 }
2174 shortcutKey.timerId = TimerMgr->AddTimer(shortcutKey.keyDownDuration, 1, [this, &shortcutKey] () {
2175 MMI_HILOGI("Timer callback");
2176 currentLaunchAbilityKey_ = shortcutKey;
2177 shortcutKey.timerId = -1;
2178 BytraceAdapter::StartLaunchAbility(KeyCommandType::TYPE_SHORTKEY, shortcutKey.ability.bundleName);
2179 LaunchAbility(shortcutKey);
2180 BytraceAdapter::StopLaunchAbility();
2181 });
2182 if (shortcutKey.timerId < 0) {
2183 MMI_HILOGE("Add Timer failed");
2184 return false;
2185 }
2186 MMI_HILOGI("Add timer success");
2187 lastMatchedKey_ = shortcutKey;
2188 if (InputHandler->GetSubscriberHandler()->IsKeyEventSubscribed(shortcutKey.finalKey, shortcutKey.triggerType)) {
2189 MMI_HILOGI("current shortcutKey %d is subSubcribed", shortcutKey.finalKey);
2190 return false;
2191 }
2192 return true;
2193 }
2194
GetKeyDownDurationFromXml(const std::string & businessId)2195 int32_t KeyCommandHandler::GetKeyDownDurationFromXml(const std::string &businessId)
2196 {
2197 CALL_DEBUG_ENTER;
2198 return PREFERENCES_MGR->GetShortKeyDuration(businessId);
2199 }
2200
HandleKeyUp(const std::shared_ptr<KeyEvent> & keyEvent,const ShortcutKey & shortcutKey)2201 bool KeyCommandHandler::HandleKeyUp(const std::shared_ptr<KeyEvent> &keyEvent, const ShortcutKey &shortcutKey)
2202 {
2203 CALL_DEBUG_ENTER;
2204 CHKPF(keyEvent);
2205 if (shortcutKey.keyDownDuration == 0) {
2206 MMI_HILOGI("Start launch ability immediately");
2207 BytraceAdapter::StartLaunchAbility(KeyCommandType::TYPE_SHORTKEY, shortcutKey.ability.bundleName);
2208 LaunchAbility(shortcutKey);
2209 BytraceAdapter::StopLaunchAbility();
2210 return true;
2211 }
2212 std::optional<KeyEvent::KeyItem> keyItem = keyEvent->GetKeyItem();
2213 if (!keyItem) {
2214 MMI_HILOGE("The keyItem is nullopt");
2215 return false;
2216 }
2217 auto upTime = keyEvent->GetActionTime();
2218 auto downTime = keyItem->GetDownTime();
2219 MMI_HILOGI("upTime:%{public}" PRId64 ",downTime:%{public}" PRId64 ",keyDownDuration:%{public}d",
2220 upTime, downTime, shortcutKey.keyDownDuration);
2221 int64_t frequency = 1000;
2222 if (upTime - downTime <= static_cast<int64_t>(shortcutKey.keyDownDuration) * frequency) {
2223 MMI_HILOGI("Skip, upTime - downTime <= duration");
2224 return false;
2225 }
2226 return true;
2227 }
2228
HandleKeyCancel(ShortcutKey & shortcutKey)2229 bool KeyCommandHandler::HandleKeyCancel(ShortcutKey &shortcutKey)
2230 {
2231 CALL_DEBUG_ENTER;
2232 if (shortcutKey.timerId < 0) {
2233 MMI_HILOGE("Skip, timerid less than 0");
2234 }
2235 auto timerId = shortcutKey.timerId;
2236 shortcutKey.timerId = -1;
2237 TimerMgr->RemoveTimer(timerId);
2238 MMI_HILOGI("timerId:%{public}d", timerId);
2239 return false;
2240 }
2241
LaunchAbility(const Ability & ability,int64_t delay)2242 void KeyCommandHandler::LaunchAbility(const Ability &ability, int64_t delay)
2243 {
2244 CALL_DEBUG_ENTER;
2245 if (ability.bundleName.empty()) {
2246 MMI_HILOGW("BundleName is empty");
2247 return;
2248 }
2249 AAFwk::Want want;
2250 want.SetElementName(ability.deviceId, ability.bundleName, ability.abilityName);
2251 want.SetAction(ability.action);
2252 want.SetUri(ability.uri);
2253 want.SetType(ability.uri);
2254 for (const auto &entity : ability.entities) {
2255 want.AddEntity(entity);
2256 }
2257 for (const auto &item : ability.params) {
2258 want.SetParam(item.first, item.second);
2259 }
2260 DfxHisysevent::CalcComboStartTimes(delay);
2261 DfxHisysevent::ReportComboStartTimes();
2262 MMI_HILOGW("Start launch ability, bundleName:%{public}s", ability.bundleName.c_str());
2263 ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want);
2264 if (err != ERR_OK) {
2265 MMI_HILOGE("LaunchAbility failed, bundleName:%{public}s, err:%{public}d", ability.bundleName.c_str(), err);
2266 return;
2267 }
2268 int32_t state = NapProcess::GetInstance()->GetNapClientPid();
2269 if (state == REMOVE_OBSERVER) {
2270 MMI_HILOGW("nap client status:%{public}d", state);
2271 return;
2272 }
2273 OHOS::MMI::NapProcess::NapStatusData napData;
2274 napData.pid = -1;
2275 napData.uid = -1;
2276 napData.bundleName = ability.bundleName;
2277 int32_t syncState = ACTIVE_EVENT;
2278 NapProcess::GetInstance()->AddMmiSubscribedEventData(napData, syncState);
2279 NapProcess::GetInstance()->NotifyBundleName(napData, syncState);
2280 MMI_HILOGW("End launch ability, bundleName:%{public}s", ability.bundleName.c_str());
2281 return;
2282 }
2283
LaunchAbility(const Ability & ability)2284 void KeyCommandHandler::LaunchAbility(const Ability &ability)
2285 {
2286 CALL_DEBUG_ENTER;
2287 AAFwk::Want want;
2288 want.SetElementName(ability.deviceId, ability.bundleName, ability.abilityName);
2289 want.SetAction(ability.action);
2290 want.SetUri(ability.uri);
2291 want.SetType(ability.uri);
2292 for (const auto &entity : ability.entities) {
2293 want.AddEntity(entity);
2294 }
2295 for (const auto &item : ability.params) {
2296 want.SetParam(item.first, item.second);
2297 }
2298
2299 MMI_HILOGW("Start launch ability, bundleName:%{public}s", ability.bundleName.c_str());
2300 if (ability.abilityType == EXTENSION_ABILITY) {
2301 ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility(want, nullptr);
2302 if (err != ERR_OK) {
2303 MMI_HILOGE("LaunchAbility failed, bundleName:%{public}s, err:%{public}d", ability.bundleName.c_str(), err);
2304 }
2305 } else {
2306 ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want);
2307 if (err != ERR_OK) {
2308 MMI_HILOGE("LaunchAbility failed, bundleName:%{public}s, err:%{public}d", ability.bundleName.c_str(), err);
2309 }
2310 if (err == ERR_OK && ability.bundleName == SOS_BUNDLE_NAME) {
2311 if (isDownStart_) {
2312 isDownStart_ = false;
2313 }
2314 isFreezePowerKey_ = true;
2315 sosLaunchTime_ = OHOS::MMI::GetSysClockTime();
2316 count_ = 0;
2317 launchAbilityCount_ = 0;
2318 repeatKeyCountMap_.clear();
2319 repeatKey_.keyCode = -1;
2320 repeatKey_.keyAction = -1;
2321 sosDelayTimerId_ = TimerMgr->AddTimer(SOS_DELAY_TIMES / SECONDS_SYSTEM, 1, [this] () {
2322 isFreezePowerKey_ = false;
2323 sosDelayTimerId_ = -1;
2324 MMI_HILOGW("Timeout, restore the power button");
2325 });
2326 if (sosDelayTimerId_ < 0) {
2327 isFreezePowerKey_ = false;
2328 MMI_HILOGE("Add timer failed");
2329 }
2330 }
2331 }
2332 MMI_HILOGW("End launch ability, bundleName:%{public}s", ability.bundleName.c_str());
2333 }
2334
LaunchAbility(const ShortcutKey & key)2335 void KeyCommandHandler::LaunchAbility(const ShortcutKey &key)
2336 {
2337 CALL_INFO_TRACE;
2338 LaunchAbility(key.ability, lastMatchedKey_.keyDownDuration);
2339 ResetLastMatchedKey();
2340 }
2341
LaunchAbility(const Sequence & sequence)2342 void KeyCommandHandler::LaunchAbility(const Sequence &sequence)
2343 {
2344 CALL_INFO_TRACE;
2345 LaunchAbility(sequence.ability, sequence.abilityStartDelay);
2346 }
2347
Print() const2348 void ShortcutKey::Print() const
2349 {
2350 for (const auto &prekey: preKeys) {
2351 MMI_HILOGI("Eventkey matched, preKey:%d", prekey);
2352 }
2353 MMI_HILOGI("Eventkey matched, finalKey:%d, bundleName:%{public}s",
2354 finalKey, ability.bundleName.c_str());
2355 }
2356
RemoveSubscribedTimer(int32_t keyCode)2357 void KeyCommandHandler::RemoveSubscribedTimer(int32_t keyCode)
2358 {
2359 CALL_DEBUG_ENTER;
2360 auto iter = specialTimers_.find(keyCode);
2361 if (iter != specialTimers_.end()) {
2362 for (auto& item : iter->second) {
2363 TimerMgr->RemoveTimer(item);
2364 }
2365 specialTimers_.erase(keyCode);
2366 MMI_HILOGI("Remove timer success");
2367 }
2368 }
2369
HandleSpecialKeys(int32_t keyCode,int32_t keyAction)2370 void KeyCommandHandler::HandleSpecialKeys(int32_t keyCode, int32_t keyAction)
2371 {
2372 CALL_INFO_TRACE;
2373 auto iter = specialKeys_.find(keyCode);
2374 if (keyAction == KeyEvent::KEY_ACTION_UP) {
2375 if (iter != specialKeys_.end()) {
2376 specialKeys_.erase(iter);
2377 return;
2378 }
2379 }
2380
2381 if (keyAction == KeyEvent::KEY_ACTION_DOWN) {
2382 if (iter == specialKeys_.end()) {
2383 auto it = specialKeys_.emplace(keyCode, keyAction);
2384 if (!it.second) {
2385 MMI_HILOGD("KeyCode duplicated");
2386 return;
2387 }
2388 }
2389 }
2390 }
2391
InterruptTimers()2392 void KeyCommandHandler::InterruptTimers()
2393 {
2394 for (Sequence& item : filterSequences_) {
2395 if (item.timerId >= 0) {
2396 MMI_HILOGD("The key sequence change, close the timer");
2397 TimerMgr->RemoveTimer(item.timerId);
2398 item.timerId = -1;
2399 }
2400 }
2401 }
2402
HandlePointerVisibleKeys(const std::shared_ptr<KeyEvent> & keyEvent)2403 void KeyCommandHandler::HandlePointerVisibleKeys(const std::shared_ptr<KeyEvent> &keyEvent)
2404 {
2405 CALL_DEBUG_ENTER;
2406 CHKPV(keyEvent);
2407 if (keyEvent->GetKeyCode() == KeyEvent::KEYCODE_F9 && lastKeyEventCode_ == KeyEvent::KEYCODE_CTRL_LEFT) {
2408 MMI_HILOGI("force make pointer visible");
2409 #if defined(OHOS_BUILD_ENABLE_POINTER) && defined(OHOS_BUILD_ENABLE_POINTER_DRAWING)
2410 IPointerDrawingManager::GetInstance()->ForceClearPointerVisiableStatus();
2411 #endif // OHOS_BUILD_ENABLE_POINTER && OHOS_BUILD_ENABLE_POINTER_DRAWING
2412 }
2413 lastKeyEventCode_ = keyEvent->GetKeyCode();
2414 }
2415
2416
UpdateSettingsXml(const std::string & businessId,int32_t delay)2417 int32_t KeyCommandHandler::UpdateSettingsXml(const std::string &businessId, int32_t delay)
2418 {
2419 CALL_DEBUG_ENTER;
2420 if (businessId.empty() || businessIds_.empty()) {
2421 MMI_HILOGE("businessId or businessIds_ is empty");
2422 return PARAMETER_ERROR;
2423 }
2424 if (std::find(businessIds_.begin(), businessIds_.end(), businessId) == businessIds_.end()) {
2425 MMI_HILOGE("%{public}s not in the config file", businessId.c_str());
2426 return PARAMETER_ERROR;
2427 }
2428 if (delay < MIN_SHORT_KEY_DOWN_DURATION || delay > MAX_SHORT_KEY_DOWN_DURATION) {
2429 MMI_HILOGE("Delay is not in valid range");
2430 return PARAMETER_ERROR;
2431 }
2432 return PREFERENCES_MGR->SetShortKeyDuration(businessId, delay);
2433 }
2434
GetSingleKnuckleGesture() const2435 KnuckleGesture KeyCommandHandler::GetSingleKnuckleGesture() const
2436 {
2437 return singleKnuckleGesture_;
2438 }
2439
GetDoubleKnuckleGesture() const2440 KnuckleGesture KeyCommandHandler::GetDoubleKnuckleGesture() const
2441 {
2442 return doubleKnuckleGesture_;
2443 }
2444
SetKnuckleDoubleTapIntervalTime(int64_t interval)2445 void KeyCommandHandler::SetKnuckleDoubleTapIntervalTime(int64_t interval)
2446 {
2447 CALL_DEBUG_ENTER;
2448 if (interval < 0) {
2449 MMI_HILOGE("invalid interval time:%{public}" PRId64 "", interval);
2450 return;
2451 }
2452 downToPrevUpTimeConfig_ = interval;
2453 }
2454
SetKnuckleDoubleTapDistance(float distance)2455 void KeyCommandHandler::SetKnuckleDoubleTapDistance(float distance)
2456 {
2457 CALL_DEBUG_ENTER;
2458 if (distance <= std::numeric_limits<float>::epsilon()) {
2459 MMI_HILOGE("invalid distance:%{public}f", distance);
2460 return;
2461 }
2462 downToPrevDownDistanceConfig_ = distance;
2463 }
2464
CheckInputMethodArea(const std::shared_ptr<PointerEvent> touchEvent)2465 bool KeyCommandHandler::CheckInputMethodArea(const std::shared_ptr<PointerEvent> touchEvent)
2466 {
2467 CALL_DEBUG_ENTER;
2468 CHKPF(touchEvent);
2469 int32_t id = touchEvent->GetPointerId();
2470 PointerEvent::PointerItem item;
2471 touchEvent->GetPointerItem(id, item);
2472 int32_t targetWindowId = item.GetTargetWindowId();
2473 int32_t targetDisplayId = touchEvent->GetTargetDisplayId();
2474 auto window = WIN_MGR->GetWindowAndDisplayInfo(targetWindowId, targetDisplayId);
2475 if (!window || window->windowType != WINDOW_INPUT_METHOD_TYPE) {
2476 return false;
2477 }
2478 return true;
2479 }
2480
Dump(int32_t fd,const std::vector<std::string> & args)2481 void KeyCommandHandler::Dump(int32_t fd, const std::vector<std::string> &args)
2482 {
2483 static const std::unordered_map<int32_t, std::string> actionMap = { {0, "UNKNOWN"},
2484 {1, "CANCEL"}, {2, "DOWN"}, {3, "UP"} };
2485 CALL_DEBUG_ENTER;
2486 mprintf(fd, "----------------------------- ShortcutKey information ----------------------------\t");
2487 mprintf(fd, "ShortcutKey: count = %zu", shortcutKeys_.size());
2488 for (const auto &item : shortcutKeys_) {
2489 auto &shortcutKey = item.second;
2490 for (const auto &prekey : shortcutKey.preKeys) {
2491 mprintf(fd, "PreKey:%d", prekey);
2492 }
2493 mprintf(fd,
2494 "BusinessId: %s | StatusConfig: %s | StatusConfigValue: %s "
2495 "| FinalKey: %d | keyDownDuration: %d | TriggerType: %d | BundleName: %s | AbilityName: %s "
2496 "| Action: %s \t", shortcutKey.businessId.c_str(), shortcutKey.statusConfig.c_str(),
2497 shortcutKey.statusConfigValue ? "true" : "false", shortcutKey.finalKey, shortcutKey.keyDownDuration,
2498 shortcutKey.triggerType, shortcutKey.ability.bundleName.c_str(), shortcutKey.ability.abilityName.c_str(),
2499 shortcutKey.ability.action.c_str());
2500 }
2501 mprintf(fd, "-------------------------- Sequence information ----------------------------------\t");
2502 mprintf(fd, "Sequence: count = %zu", sequences_.size());
2503 for (const auto &item : sequences_) {
2504 for (const auto& sequenceKey : item.sequenceKeys) {
2505 mprintf(fd, "keyCode: %d | keyAction: %s",
2506 sequenceKey.keyCode, ConvertKeyActionToString(sequenceKey.keyAction).c_str());
2507 }
2508 mprintf(fd, "BundleName: %s | AbilityName: %s | Action: %s ",
2509 item.ability.bundleName.c_str(), item.ability.abilityName.c_str(), item.ability.action.c_str());
2510 }
2511 mprintf(fd, "-------------------------- ExcludeKey information --------------------------------\t");
2512 mprintf(fd, "ExcludeKey: count = %zu", excludeKeys_.size());
2513 for (const auto &item : excludeKeys_) {
2514 mprintf(fd, "keyCode: %d | keyAction: %s", item.keyCode, ConvertKeyActionToString(item.keyAction).c_str());
2515 }
2516 mprintf(fd, "-------------------------- RepeatKey information ---------------------------------\t");
2517 mprintf(fd, "RepeatKey: count = %zu", repeatKeys_.size());
2518 for (const auto &item : repeatKeys_) {
2519 mprintf(fd,
2520 "KeyCode: %d | KeyAction: %s | Times: %d"
2521 "| StatusConfig: %s | StatusConfigValue: %s | BundleName: %s | AbilityName: %s"
2522 "| Action:%s \t", item.keyCode, ConvertKeyActionToString(item.keyAction).c_str(), item.times,
2523 item.statusConfig.c_str(), item.statusConfigValue ? "true" : "false",
2524 item.ability.bundleName.c_str(), item.ability.abilityName.c_str(), item.ability.action.c_str());
2525 }
2526 PrintGestureInfo(fd);
2527 }
2528
PrintGestureInfo(int32_t fd)2529 void KeyCommandHandler::PrintGestureInfo(int32_t fd)
2530 {
2531 mprintf(fd, "-------------------------- TouchPad Two Fingers Gesture --------------------------\t");
2532 mprintf(fd,
2533 "GestureActive: %s | GestureBundleName: %s | GestureAbilityName: %s"
2534 "| GestureAction: %s \t", twoFingerGesture_.active ? "true" : "false",
2535 twoFingerGesture_.ability.bundleName.c_str(), twoFingerGesture_.ability.abilityName.c_str(),
2536 twoFingerGesture_.ability.action.c_str());
2537 mprintf(fd, "-------------------------- TouchPad Three Fingers Tap Gesture --------------------\t");
2538 mprintf(fd,
2539 "TapBundleName: %s | TapAbilityName: %s"
2540 "| TapAction: %s \t", threeFingersTap_.ability.bundleName.c_str(),
2541 threeFingersTap_.ability.abilityName.c_str(), threeFingersTap_.ability.action.c_str());
2542 mprintf(fd, "-------------------------- Knuckle Single Finger Gesture -------------------------\t");
2543 mprintf(fd,
2544 "GestureState: %s | GestureBundleName: %s | GestureAbilityName: %s"
2545 "| GestureAction: %s \t", singleKnuckleGesture_.state ? "true" : "false",
2546 singleKnuckleGesture_.ability.bundleName.c_str(), singleKnuckleGesture_.ability.abilityName.c_str(),
2547 singleKnuckleGesture_.ability.action.c_str());
2548 mprintf(fd, "-------------------------- Knuckle Two Fingers Gesture ---------------------------\t");
2549 mprintf(fd,
2550 "GestureState: %s | GestureBundleName: %s | GestureAbilityName: %s"
2551 "| GestureAction:%s \t", doubleKnuckleGesture_.state ? "true" : "false",
2552 doubleKnuckleGesture_.ability.bundleName.c_str(), doubleKnuckleGesture_.ability.abilityName.c_str(),
2553 doubleKnuckleGesture_.ability.action.c_str());
2554 }
ConvertKeyActionToString(int32_t keyAction)2555 std::string KeyCommandHandler::ConvertKeyActionToString(int32_t keyAction)
2556 {
2557 static const std::unordered_map<int32_t, std::string> actionMap = {
2558 {0, "UNKNOWN"},
2559 {1, "CANCEL"},
2560 {2, "DOWN"},
2561 {3, "UP"}
2562 };
2563 auto it = actionMap.find(keyAction);
2564 if (it != actionMap.end()) {
2565 return it->second;
2566 } else {
2567 return "UNKNOWN_ACTION";
2568 }
2569 }
operator <<(std::ostream & os,const Sequence & seq)2570 std::ostream& operator<<(std::ostream& os, const Sequence& seq)
2571 {
2572 os << "keys: [";
2573 for (const SequenceKey &singleKey: seq.sequenceKeys) {
2574 os << "(kc:" << singleKey.keyCode << ",ka:" << singleKey.keyAction << "d:" << singleKey.delay << "),";
2575 }
2576 os << "]: " << seq.ability.bundleName << ":" << seq.ability.abilityName;
2577 return os;
2578 }
2579
CheckAndUpdateTappingCountAtDown(std::shared_ptr<PointerEvent> touchEvent)2580 void KeyCommandHandler::CheckAndUpdateTappingCountAtDown(std::shared_ptr<PointerEvent> touchEvent)
2581 {
2582 CHKPV(touchEvent);
2583 int64_t currentDownTime = touchEvent->GetActionTime();
2584 int64_t downIntervalTime = currentDownTime - lastDownTime_;
2585 lastDownTime_ = currentDownTime;
2586 if (downIntervalTime <= 0 || downIntervalTime >= TAP_DOWN_INTERVAL_MILLIS) {
2587 tappingCount_ = 1;
2588 return;
2589 }
2590 tappingCount_++;
2591 int64_t timeDiffToPrevKnuckleUpTime = currentDownTime - previousUpTime_;
2592 if (timeDiffToPrevKnuckleUpTime <= downToPrevUpTimeConfig_) {
2593 if (tappingCount_ == MAX_TAP_COUNT) {
2594 DfxHisysevent::ReportFailIfOneSuccTwoFail(touchEvent);
2595 }
2596 if (tappingCount_ > MAX_TAP_COUNT) {
2597 DfxHisysevent::ReportFailIfKnockTooFast();
2598 }
2599 }
2600 }
2601 } // namespace MMI
2602 } // namespace OHOS
2603