1 /*
2 * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "key_command_handler.h"
17
18 #include "ability_manager_client.h"
19 #include "nap_process.h"
20 #include "bytrace_adapter.h"
21 #include "cJSON.h"
22 #include "config_policy_utils.h"
23 #include "define_multimodal.h"
24 #include "dfx_hisysevent.h"
25 #include "error_multimodal.h"
26 #include "file_ex.h"
27 #include "input_event_data_transformation.h"
28 #include "input_event_handler.h"
29 #include "mmi_log.h"
30 #include "net_packet.h"
31 #include "proto.h"
32 #include "setting_datashare.h"
33 #include "system_ability_definition.h"
34 #include "timer_manager.h"
35 #include "util_ex.h"
36 #include "nap_process.h"
37 #include "multimodal_input_preferences_manager.h"
38
39 namespace OHOS {
40 namespace MMI {
41 namespace {
42 constexpr int32_t MAX_PREKEYS_NUM = 4;
43 constexpr int32_t MAX_SEQUENCEKEYS_NUM = 10;
44 constexpr int64_t MAX_DELAY_TIME = 1000000;
45 constexpr int64_t SECONDS_SYSTEM = 1000;
46 constexpr int32_t SPECIAL_KEY_DOWN_DELAY = 150;
47 constexpr int32_t MAX_SHORT_KEY_DOWN_DURATION = 4000;
48 constexpr int32_t MIN_SHORT_KEY_DOWN_DURATION = 0;
49 constexpr int32_t TOUCH_MAX_THRESHOLD = 15;
50 constexpr int32_t COMMON_PARAMETER_ERROR = 401;
51 constexpr size_t SINGLE_KNUCKLE_SIZE = 1;
52 constexpr size_t DOUBLE_KNUCKLE_SIZE = 2;
53 constexpr int32_t MAX_TIME_FOR_ADJUST_CONFIG = 5;
54 constexpr int32_t POW_SQUARE = 2;
55 constexpr int64_t DOUBLE_CLICK_INTERVAL_TIME_DEFAULT = 250000;
56 constexpr int64_t DOUBLE_CLICK_INTERVAL_TIME_SLOW = 450000;
57 constexpr float DOUBLE_CLICK_DISTANCE_DEFAULT_CONFIG = 64.0f;
58 constexpr float DOUBLE_CLICK_DISTANCE_LONG_CONFIG = 96.0f;
59 constexpr float VPR_CONFIG = 3.25f;
60 constexpr int32_t REMOVE_OBSERVER = -2;
61 constexpr int32_t ACTIVE_EVENT = 2;
62 const std::string EXTENSION_ABILITY = "extensionAbility";
63
64 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, MMI_LOG_DOMAIN, "KeyCommandHandler" };
65 const std::string SINGLE_KNUCKLE_ABILITY = "SingleKnuckleDoubleClickGesture";
66 const std::string DOUBLE_KNUCKLE_ABILITY = "DoubleKnuckleDoubleClickGesture";
67 const std::string TOUCHPAD_TRIP_TAP_ABILITY = "ThreeFingersTap";
68 enum SpecialType {
69 SPECIAL_ALL = 0,
70 SUBSCRIBER_BEFORE_DELAY = 1,
71 KEY_DOWN_ACTION = 2
72 };
73 const std::map<int32_t, SpecialType> SPECIAL_KEYS = {
74 { KeyEvent::KEYCODE_POWER, SpecialType::KEY_DOWN_ACTION },
75 { KeyEvent::KEYCODE_VOLUME_DOWN, SpecialType::SPECIAL_ALL },
76 { KeyEvent::KEYCODE_VOLUME_UP, SpecialType::SPECIAL_ALL }
77 };
78 struct JsonParser {
79 JsonParser() = default;
~JsonParserOHOS::MMI::__anonecc789280111::JsonParser80 ~JsonParser()
81 {
82 if (json_ != nullptr) {
83 cJSON_Delete(json_);
84 }
85 }
operator cJSON*OHOS::MMI::__anonecc789280111::JsonParser86 operator cJSON *()
87 {
88 return json_;
89 }
90 cJSON *json_ { nullptr };
91 };
92
IsSpecialType(int32_t keyCode,SpecialType type)93 bool IsSpecialType(int32_t keyCode, SpecialType type)
94 {
95 auto it = SPECIAL_KEYS.find(keyCode);
96 if (it == SPECIAL_KEYS.end()) {
97 return false;
98 }
99 return (it->second == SpecialType::SPECIAL_ALL || it->second == type);
100 }
101
GetBusinessId(const cJSON * jsonData,std::string & businessIdValue,std::vector<std::string> & businessIds)102 bool GetBusinessId(const cJSON* jsonData, std::string &businessIdValue, std::vector<std::string> &businessIds)
103 {
104 if (!cJSON_IsObject(jsonData)) {
105 MMI_HILOGE("jsonData is not object");
106 return false;
107 }
108 cJSON *businessId = cJSON_GetObjectItemCaseSensitive(jsonData, "businessId");
109 if (!cJSON_IsString(businessId)) {
110 MMI_HILOGE("businessId is not string");
111 return false;
112 }
113 businessIdValue = businessId->valuestring;
114 businessIds.push_back(businessIdValue);
115 return true;
116 }
117
GetPreKeys(const cJSON * jsonData,ShortcutKey & shortcutKey)118 bool GetPreKeys(const cJSON* jsonData, ShortcutKey &shortcutKey)
119 {
120 if (!cJSON_IsObject(jsonData)) {
121 MMI_HILOGE("jsonData is not object");
122 return false;
123 }
124 cJSON* preKey = cJSON_GetObjectItemCaseSensitive(jsonData, "preKey");
125 if (!cJSON_IsArray(preKey)) {
126 MMI_HILOGE("preKey number must be array");
127 return false;
128 }
129 int32_t preKeySize = cJSON_GetArraySize(preKey);
130 if (preKeySize > MAX_PREKEYS_NUM) {
131 MMI_HILOGE("preKeySize number must less and equal four");
132 return false;
133 }
134 for (int32_t i = 0; i < preKeySize; ++i) {
135 cJSON *preKeyJson = cJSON_GetArrayItem(preKey, i);
136 if (!cJSON_IsNumber(preKeyJson)) {
137 MMI_HILOGE("preKeyJson is not number");
138 return false;
139 }
140 if (preKeyJson->valueint < 0) {
141 MMI_HILOGE("preKeyJson must be number and bigger or equal than 0");
142 return false;
143 }
144 if (!shortcutKey.preKeys.emplace(preKeyJson->valueint).second) {
145 MMI_HILOGE("preKeyJson must be unduplicated");
146 return false;
147 }
148 }
149 return true;
150 }
151
GetTrigger(const cJSON * jsonData,int32_t & triggerType)152 bool GetTrigger(const cJSON* jsonData, int32_t &triggerType)
153 {
154 if (!cJSON_IsObject(jsonData)) {
155 MMI_HILOGE("jsonData is not object");
156 return false;
157 }
158 cJSON *trigger = cJSON_GetObjectItemCaseSensitive(jsonData, "trigger");
159 if (!cJSON_IsString(trigger)) {
160 MMI_HILOGE("trigger is not string");
161 return false;
162 }
163 if (((std::strcmp(trigger->valuestring, "key_up") != 0)
164 && (std::strcmp(trigger->valuestring, "key_down") != 0))) {
165 MMI_HILOGE("trigger must be one of [key_up, key_down]");
166 return false;
167 }
168 if (std::strcmp(trigger->valuestring, "key_up") == 0) {
169 triggerType = KeyEvent::KEY_ACTION_UP;
170 } else {
171 triggerType = KeyEvent::KEY_ACTION_DOWN;
172 }
173 return true;
174 }
175
GetKeyDownDuration(const cJSON * jsonData,int32_t & keyDownDurationInt)176 bool GetKeyDownDuration(const cJSON* jsonData, int32_t &keyDownDurationInt)
177 {
178 if (!cJSON_IsObject(jsonData)) {
179 MMI_HILOGE("jsonData is not object");
180 return false;
181 }
182 cJSON *keyDownDuration = cJSON_GetObjectItemCaseSensitive(jsonData, "keyDownDuration");
183 if (!cJSON_IsNumber(keyDownDuration)) {
184 MMI_HILOGE("keyDownDuration is not number");
185 return false;
186 }
187 if (keyDownDuration->valueint < 0) {
188 MMI_HILOGE("keyDownDuration must be number and bigger and equal zero");
189 return false;
190 }
191 keyDownDurationInt = keyDownDuration->valueint;
192 return true;
193 }
194
GetKeyFinalKey(const cJSON * jsonData,int32_t & finalKeyInt)195 bool GetKeyFinalKey(const cJSON* jsonData, int32_t &finalKeyInt)
196 {
197 if (!cJSON_IsObject(jsonData)) {
198 MMI_HILOGE("jsonData is not object");
199 return false;
200 }
201 cJSON *finalKey = cJSON_GetObjectItemCaseSensitive(jsonData, "finalKey");
202 if (!cJSON_IsNumber(finalKey)) {
203 MMI_HILOGE("finalKey must be number");
204 return false;
205 }
206 finalKeyInt = finalKey->valueint;
207 return true;
208 }
209
GetKeyVal(const cJSON * json,const std::string & key,std::string & value)210 void GetKeyVal(const cJSON* json, const std::string &key, std::string &value)
211 {
212 if (!cJSON_IsObject(json)) {
213 MMI_HILOGE("json is not object");
214 return;
215 }
216 cJSON *valueJson = cJSON_GetObjectItemCaseSensitive(json, key.c_str());
217 if (cJSON_IsString(valueJson)) {
218 value = valueJson->valuestring;
219 }
220 return;
221 }
222
GetEntities(const cJSON * jsonAbility,Ability & ability)223 bool GetEntities(const cJSON* jsonAbility, Ability &ability)
224 {
225 if (!cJSON_IsObject(jsonAbility)) {
226 MMI_HILOGE("jsonAbility is not object");
227 return false;
228 }
229 cJSON *entities = cJSON_GetObjectItemCaseSensitive(jsonAbility, "entities");
230 if (entities == nullptr) {
231 return true;
232 }
233 if (!cJSON_IsArray(entities)) {
234 MMI_HILOGE("entities must be array");
235 return false;
236 }
237 int32_t entitySize = cJSON_GetArraySize(entities);
238 for (int32_t i = 0; i < entitySize; i++) {
239 cJSON* entity = cJSON_GetArrayItem(entities, i);
240 if (!cJSON_IsString(entity)) {
241 MMI_HILOGE("entity is not string");
242 return false;
243 }
244 ability.entities.push_back(entity->valuestring);
245 }
246 return true;
247 }
248
GetParams(const cJSON * jsonAbility,Ability & ability)249 bool GetParams(const cJSON* jsonAbility, Ability &ability)
250 {
251 if (!cJSON_IsObject(jsonAbility)) {
252 MMI_HILOGE("jsonAbility is not object");
253 return false;
254 }
255 cJSON *params = cJSON_GetObjectItemCaseSensitive(jsonAbility, "params");
256 if (params == nullptr) {
257 return true;
258 }
259 if (!cJSON_IsArray(params)) {
260 MMI_HILOGE("params must be array");
261 return false;
262 }
263 int32_t paramsSize = cJSON_GetArraySize(params);
264 for (int32_t i = 0; i < paramsSize; ++i) {
265 cJSON* param = cJSON_GetArrayItem(params, i);
266 if (!cJSON_IsObject(param)) {
267 MMI_HILOGE("param must be object");
268 return false;
269 }
270 cJSON* key = cJSON_GetObjectItemCaseSensitive(param, "key");
271 if (!cJSON_IsString(key)) {
272 MMI_HILOGE("key is not string");
273 return false;
274 }
275 cJSON* value = cJSON_GetObjectItemCaseSensitive(param, "value");
276 if (!cJSON_IsString(value)) {
277 MMI_HILOGE("value is not string");
278 return false;
279 }
280 auto ret = ability.params.emplace(key->valuestring, value->valuestring);
281 if (!ret.second) {
282 MMI_HILOGW("Emplace to failed");
283 }
284 }
285 return true;
286 }
287
PackageAbility(const cJSON * jsonAbility,Ability & ability)288 bool PackageAbility(const cJSON* jsonAbility, Ability &ability)
289 {
290 if (!cJSON_IsObject(jsonAbility)) {
291 MMI_HILOGE("JsonAbility is not object");
292 return false;
293 }
294 GetKeyVal(jsonAbility, "bundleName", ability.bundleName);
295 GetKeyVal(jsonAbility, "abilityName", ability.abilityName);
296 GetKeyVal(jsonAbility, "action", ability.action);
297 GetKeyVal(jsonAbility, "type", ability.type);
298 GetKeyVal(jsonAbility, "deviceId", ability.deviceId);
299 GetKeyVal(jsonAbility, "uri", ability.uri);
300 GetKeyVal(jsonAbility, "abilityType", ability.abilityType);
301 if (!GetEntities(jsonAbility, ability)) {
302 MMI_HILOGE("Get centities failed");
303 return false;
304 }
305 if (!GetParams(jsonAbility, ability)) {
306 MMI_HILOGE("Get params failed");
307 return false;
308 }
309 return true;
310 }
311
ConvertToShortcutKey(const cJSON * jsonData,ShortcutKey & shortcutKey,std::vector<std::string> & businessIds)312 bool ConvertToShortcutKey(const cJSON* jsonData, ShortcutKey &shortcutKey, std::vector<std::string> &businessIds)
313 {
314 if (!cJSON_IsObject(jsonData)) {
315 MMI_HILOGE("jsonData is not object");
316 return false;
317 }
318 if (!GetBusinessId(jsonData, shortcutKey.businessId, businessIds)) {
319 MMI_HILOGW("Get abilityKey failed");
320 }
321 if (!GetPreKeys(jsonData, shortcutKey)) {
322 MMI_HILOGE("Get preKeys failed");
323 return false;
324 }
325 if (!GetKeyFinalKey(jsonData, shortcutKey.finalKey)) {
326 MMI_HILOGE("Get finalKey failed");
327 return false;
328 }
329 if (!GetTrigger(jsonData, shortcutKey.triggerType)) {
330 MMI_HILOGE("Get trigger failed");
331 return false;
332 }
333 if (!GetKeyDownDuration(jsonData, shortcutKey.keyDownDuration)) {
334 MMI_HILOGE("Get downDuration failed");
335 return false;
336 }
337
338 GetKeyVal(jsonData, "statusConfig", shortcutKey.statusConfig);
339
340 cJSON *ability = cJSON_GetObjectItemCaseSensitive(jsonData, "ability");
341 if (!cJSON_IsObject(ability)) {
342 MMI_HILOGE("ability is not object");
343 return false;
344 }
345 if (!PackageAbility(ability, shortcutKey.ability)) {
346 MMI_HILOGE("Package ability failed");
347 return false;
348 }
349 return true;
350 }
351
GetKeyCode(const cJSON * jsonData,int32_t & keyCodeInt)352 bool GetKeyCode(const cJSON* jsonData, int32_t &keyCodeInt)
353 {
354 if (!cJSON_IsObject(jsonData)) {
355 MMI_HILOGE("jsonData is not object");
356 return false;
357 }
358 cJSON *keyCode = cJSON_GetObjectItemCaseSensitive(jsonData, "keyCode");
359 if (!cJSON_IsNumber(keyCode)) {
360 MMI_HILOGE("keyCode is not number");
361 return false;
362 }
363 if (keyCode->valueint < 0) {
364 MMI_HILOGE("keyCode must be number and bigger and equal zero");
365 return false;
366 }
367 keyCodeInt = keyCode->valueint;
368 return true;
369 }
370
GetKeyAction(const cJSON * jsonData,int32_t & keyActionInt)371 bool GetKeyAction(const cJSON* jsonData, int32_t &keyActionInt)
372 {
373 if (!cJSON_IsObject(jsonData)) {
374 MMI_HILOGE("jsonData is not object");
375 return false;
376 }
377 cJSON *keyAction = cJSON_GetObjectItemCaseSensitive(jsonData, "keyAction");
378 if (!cJSON_IsNumber(keyAction)) {
379 MMI_HILOGE("keyAction is not number");
380 return false;
381 }
382 if ((keyAction->valueint != KeyEvent::KEY_ACTION_DOWN) && (keyAction->valueint != KeyEvent::KEY_ACTION_UP)) {
383 MMI_HILOGE("keyAction must be down or up");
384 return false;
385 }
386 keyActionInt = keyAction->valueint;
387 return true;
388 }
389
GetDelay(const cJSON * jsonData,int64_t & delayInt)390 bool GetDelay(const cJSON* jsonData, int64_t &delayInt)
391 {
392 if (!cJSON_IsObject(jsonData)) {
393 MMI_HILOGE("jsonData is not object");
394 return false;
395 }
396 cJSON *delay = cJSON_GetObjectItemCaseSensitive(jsonData, "delay");
397 if (!cJSON_IsNumber(delay)) {
398 MMI_HILOGE("delay is not number");
399 return false;
400 }
401 if ((delay->valueint < 0) || (delay->valueint > MAX_DELAY_TIME)) {
402 MMI_HILOGE("delay must be number and bigger and equal zero and less than max delay");
403 return false;
404 }
405 delayInt = delay->valueint * SECONDS_SYSTEM;
406 return true;
407 }
408
GetRepeatTimes(const cJSON * jsonData,int32_t & repeatTimesInt)409 bool GetRepeatTimes(const cJSON* jsonData, int32_t &repeatTimesInt)
410 {
411 if (!cJSON_IsObject(jsonData)) {
412 MMI_HILOGE("GetRepeatTimes jsonData is not object");
413 return false;
414 }
415 cJSON *repeatTimes = cJSON_GetObjectItemCaseSensitive(jsonData, "times");
416 if (!cJSON_IsNumber(repeatTimes)) {
417 MMI_HILOGE("repeatTimes is not number");
418 return false;
419 }
420 if (repeatTimes->valueint < 0) {
421 MMI_HILOGE("repeatTimes must be number and bigger and equal zero");
422 return false;
423 }
424 repeatTimesInt = repeatTimes->valueint;
425 return true;
426 }
427
GetAbilityStartDelay(const cJSON * jsonData,int64_t & abilityStartDelayInt)428 bool GetAbilityStartDelay(const cJSON* jsonData, int64_t &abilityStartDelayInt)
429 {
430 if (!cJSON_IsObject(jsonData)) {
431 MMI_HILOGE("jsonData is not object");
432 return false;
433 }
434 cJSON *abilityStartDelay = cJSON_GetObjectItemCaseSensitive(jsonData, "abilityStartDelay");
435 if (!cJSON_IsNumber(abilityStartDelay)) {
436 MMI_HILOGE("abilityStartDelay is not number");
437 return false;
438 }
439 if ((abilityStartDelay->valueint < 0) || (abilityStartDelay->valueint > MAX_DELAY_TIME)) {
440 MMI_HILOGE("abilityStartDelay must be number and bigger and equal zero and less than max delay time");
441 return false;
442 }
443 abilityStartDelayInt = abilityStartDelay->valueint;
444 return true;
445 }
446
PackageSequenceKey(const cJSON * sequenceKeysJson,SequenceKey & sequenceKey)447 bool PackageSequenceKey(const cJSON* sequenceKeysJson, SequenceKey &sequenceKey)
448 {
449 if (!cJSON_IsObject(sequenceKeysJson)) {
450 MMI_HILOGE("sequenceKeysJson is not object");
451 return false;
452 }
453 if (!GetKeyCode(sequenceKeysJson, sequenceKey.keyCode)) {
454 MMI_HILOGE("Get keyCode failed");
455 return false;
456 }
457 if (!GetKeyAction(sequenceKeysJson, sequenceKey.keyAction)) {
458 MMI_HILOGE("Get keyAction failed");
459 return false;
460 }
461 if (!GetDelay(sequenceKeysJson, sequenceKey.delay)) {
462 MMI_HILOGE("Get delay failed");
463 return false;
464 }
465 return true;
466 }
467
GetSequenceKeys(const cJSON * jsonData,Sequence & sequence)468 bool GetSequenceKeys(const cJSON* jsonData, Sequence &sequence)
469 {
470 if (!cJSON_IsObject(jsonData)) {
471 MMI_HILOGE("jsonData is not object");
472 return false;
473 }
474 cJSON* sequenceKeys = cJSON_GetObjectItemCaseSensitive(jsonData, "sequenceKeys");
475 if (!cJSON_IsArray(sequenceKeys)) {
476 MMI_HILOGE("sequenceKeys number must be array");
477 return false;
478 }
479 int32_t sequenceKeysSize = cJSON_GetArraySize(sequenceKeys);
480 if (sequenceKeysSize > MAX_SEQUENCEKEYS_NUM) {
481 MMI_HILOGE("sequenceKeysSize number must less and equal %{public}d", MAX_SEQUENCEKEYS_NUM);
482 return false;
483 }
484 for (int32_t i = 0; i < sequenceKeysSize; ++i) {
485 cJSON *sequenceKeysJson = cJSON_GetArrayItem(sequenceKeys, i);
486 if (!cJSON_IsObject(sequenceKeysJson)) {
487 MMI_HILOGE("sequenceKeysJson is not object");
488 return false;
489 }
490 SequenceKey sequenceKey;
491 if (!PackageSequenceKey(sequenceKeysJson, sequenceKey)) {
492 MMI_HILOGE("Packege sequenceKey failed");
493 return false;
494 }
495 sequence.sequenceKeys.push_back(sequenceKey);
496 }
497 return true;
498 }
499
IsSequenceKeysValid(const Sequence & sequence)500 bool IsSequenceKeysValid(const Sequence &sequence)
501 {
502 if (sequence.sequenceKeys.empty()) {
503 MMI_HILOGE("sequenceKeys can not be empty");
504 return false;
505 }
506
507 if (sequence.sequenceKeys.size() > MAX_SEQUENCEKEYS_NUM) {
508 MMI_HILOGE("sequenceKeys size must less or equal to %{public}d", MAX_SEQUENCEKEYS_NUM);
509 return false;
510 }
511
512 std::map<int32_t, SequenceKey> sequenceKeys;
513 for (const SequenceKey& item : sequence.sequenceKeys) {
514 if (sequenceKeys.find(item.keyCode) == sequenceKeys.end()) {
515 auto it = sequenceKeys.emplace(item.keyCode, item);
516 if (!it.second) {
517 MMI_HILOGE("Emplace duplicated");
518 return false;
519 }
520 } else {
521 if (sequenceKeys[item.keyCode].keyAction == item.keyAction) {
522 MMI_HILOGE("sequenceKeys illegal");
523 return false;
524 }
525 sequenceKeys[item.keyCode].keyAction = item.keyAction;
526 sequenceKeys[item.keyCode].delay = item.delay;
527 }
528 }
529 return true;
530 }
531
ConvertToKeySequence(const cJSON * jsonData,Sequence & sequence)532 bool ConvertToKeySequence(const cJSON* jsonData, Sequence &sequence)
533 {
534 if (!cJSON_IsObject(jsonData)) {
535 MMI_HILOGE("jsonData is not object");
536 return false;
537 }
538 if (!GetSequenceKeys(jsonData, sequence)) {
539 MMI_HILOGE("Get sequenceKeys failed");
540 return false;
541 }
542 if (!IsSequenceKeysValid(sequence)) {
543 MMI_HILOGE("Sequence invalid");
544 return false;
545 }
546 if (!GetAbilityStartDelay(jsonData, sequence.abilityStartDelay)) {
547 MMI_HILOGE("Get abilityStartDelay failed");
548 return false;
549 }
550
551 GetKeyVal(jsonData, "statusConfig", sequence.statusConfig);
552
553 cJSON *ability = cJSON_GetObjectItemCaseSensitive(jsonData, "ability");
554 if (!cJSON_IsObject(ability)) {
555 MMI_HILOGE("ability is not object");
556 return false;
557 }
558 if (!PackageAbility(ability, sequence.ability)) {
559 MMI_HILOGE("Package ability failed");
560 return false;
561 }
562 return true;
563 }
564
ConvertToKeyRepeat(const cJSON * jsonData,RepeatKey & repeatKey)565 bool ConvertToKeyRepeat(const cJSON* jsonData, RepeatKey &repeatKey)
566 {
567 if (!cJSON_IsObject(jsonData)) {
568 MMI_HILOGE("jsonData is not object");
569 return false;
570 }
571
572 if (!GetKeyCode(jsonData, repeatKey.keyCode)) {
573 MMI_HILOGE("Get keyCode failed");
574 return false;
575 }
576
577 if (!GetRepeatTimes(jsonData, repeatKey.times)) {
578 MMI_HILOGE("Get repeatTimes failed");
579 return false;
580 }
581
582 if (!GetDelay(jsonData, repeatKey.delay)) {
583 MMI_HILOGE("Get delay failed");
584 return false;
585 }
586
587 GetKeyVal(jsonData, "statusConfig", repeatKey.statusConfig);
588
589 cJSON *ability = cJSON_GetObjectItemCaseSensitive(jsonData, "ability");
590 if (!cJSON_IsObject(ability)) {
591 MMI_HILOGE("ability is not object");
592 return false;
593 }
594 if (!PackageAbility(ability, repeatKey.ability)) {
595 MMI_HILOGE("Package ability failed");
596 return false;
597 }
598 return true;
599 }
600
GenerateKey(const ShortcutKey & key)601 std::string GenerateKey(const ShortcutKey& key)
602 {
603 std::set<int32_t> preKeys = key.preKeys;
604 std::stringstream ss;
605 for (const auto& preKey : preKeys) {
606 ss << preKey << ",";
607 }
608 ss << key.finalKey << ",";
609 ss << key.triggerType;
610 return std::string(ss.str());
611 }
612
ParseShortcutKeys(const JsonParser & parser,std::map<std::string,ShortcutKey> & shortcutKeyMap,std::vector<std::string> & businessIds)613 bool ParseShortcutKeys(const JsonParser& parser, std::map<std::string, ShortcutKey>& shortcutKeyMap,
614 std::vector<std::string>& businessIds)
615 {
616 cJSON* shortkeys = cJSON_GetObjectItemCaseSensitive(parser.json_, "Shortkeys");
617 if (!cJSON_IsArray(shortkeys)) {
618 MMI_HILOGE("shortkeys is not array");
619 return false;
620 }
621 int32_t shortkeysSize = cJSON_GetArraySize(shortkeys);
622 for (int32_t i = 0; i < shortkeysSize; ++i) {
623 ShortcutKey shortcutKey;
624 cJSON *shortkey = cJSON_GetArrayItem(shortkeys, i);
625 if (!cJSON_IsObject(shortkey)) {
626 continue;
627 }
628 if (!ConvertToShortcutKey(shortkey, shortcutKey, businessIds)) {
629 continue;
630 }
631 std::string key = GenerateKey(shortcutKey);
632 if (shortcutKeyMap.find(key) == shortcutKeyMap.end()) {
633 if (!shortcutKeyMap.emplace(key, shortcutKey).second) {
634 MMI_HILOGW("Duplicate shortcutKey:%{public}s", key.c_str());
635 }
636 }
637 }
638 return true;
639 }
640
ParseSequences(const JsonParser & parser,std::vector<Sequence> & sequenceVec)641 bool ParseSequences(const JsonParser& parser, std::vector<Sequence>& sequenceVec)
642 {
643 cJSON* sequences = cJSON_GetObjectItemCaseSensitive(parser.json_, "Sequences");
644 if (!cJSON_IsArray(sequences)) {
645 MMI_HILOGE("sequences is not array");
646 return false;
647 }
648 int32_t sequencesSize = cJSON_GetArraySize(sequences);
649 for (int32_t i = 0; i < sequencesSize; ++i) {
650 Sequence seq;
651 cJSON *sequence = cJSON_GetArrayItem(sequences, i);
652 if (!cJSON_IsObject(sequence)) {
653 continue;
654 }
655 if (!ConvertToKeySequence(sequence, seq)) {
656 continue;
657 }
658 sequenceVec.push_back(seq);
659 }
660 return true;
661 }
662
ParseRepeatKeys(const JsonParser & parser,std::vector<RepeatKey> & repeatKeyVec)663 bool ParseRepeatKeys(const JsonParser& parser, std::vector<RepeatKey>& repeatKeyVec)
664 {
665 cJSON* repeatKeys = cJSON_GetObjectItemCaseSensitive(parser.json_, "RepeatKeys");
666 if (!cJSON_IsArray(repeatKeys)) {
667 MMI_HILOGE("repeatKeys is not array");
668 return false;
669 }
670 int32_t repeatKeysSize = cJSON_GetArraySize(repeatKeys);
671 for (int32_t i = 0; i < repeatKeysSize; i++) {
672 RepeatKey rep;
673 cJSON *repeatKey = cJSON_GetArrayItem(repeatKeys, i);
674 if (!cJSON_IsObject(repeatKey)) {
675 continue;
676 }
677 if (!ConvertToKeyRepeat(repeatKey, rep)) {
678 continue;
679 }
680 repeatKeyVec.push_back(rep);
681 }
682
683 return true;
684 }
685
ParseTwoFingerGesture(const JsonParser & parser,TwoFingerGesture & gesture)686 bool ParseTwoFingerGesture(const JsonParser& parser, TwoFingerGesture& gesture)
687 {
688 cJSON *jsonData = cJSON_GetObjectItemCaseSensitive(parser.json_, "TwoFingerGesture");
689 if (!cJSON_IsObject(jsonData)) {
690 MMI_HILOGE("TwoFingerGesture is not object");
691 return false;
692 }
693 if (!GetAbilityStartDelay(jsonData, gesture.abilityStartDelay)) {
694 MMI_HILOGE("Get abilityStartDelay failed");
695 return false;
696 }
697 cJSON *ability = cJSON_GetObjectItemCaseSensitive(jsonData, "ability");
698 if (!cJSON_IsObject(ability)) {
699 MMI_HILOGE("ability is not object");
700 return false;
701 }
702 if (!PackageAbility(ability, gesture.ability)) {
703 MMI_HILOGE("Package ability failed");
704 return false;
705 }
706 gesture.active = true;
707 return true;
708 }
709
IsPackageKnuckleGesture(const cJSON * jsonData,const std::string knuckleGesture,Ability & launchAbility)710 bool IsPackageKnuckleGesture(const cJSON* jsonData, const std::string knuckleGesture, Ability &launchAbility)
711 {
712 cJSON *knuckleGestureData = cJSON_GetObjectItemCaseSensitive(jsonData, knuckleGesture.c_str());
713 if (!cJSON_IsObject(knuckleGestureData)) {
714 MMI_HILOGE("KnuckleGestureData is not object");
715 return false;
716 }
717 cJSON *ability = cJSON_GetObjectItemCaseSensitive(knuckleGestureData, "ability");
718 if (!cJSON_IsObject(ability)) {
719 MMI_HILOGE("Ability is not object");
720 return false;
721 }
722 if (!PackageAbility(ability, launchAbility)) {
723 MMI_HILOGE("Package ability failed");
724 return false;
725 }
726 return true;
727 }
728
IsParseKnuckleGesture(const JsonParser & parser,const std::string ability,KnuckleGesture & knuckleGesture)729 bool IsParseKnuckleGesture(const JsonParser &parser, const std::string ability, KnuckleGesture &knuckleGesture)
730 {
731 cJSON *jsonData = cJSON_GetObjectItemCaseSensitive(parser.json_, "KnuckleGesture");
732 if (!cJSON_IsObject(jsonData)) {
733 MMI_HILOGE("KnuckleGesture is not object");
734 return false;
735 }
736 if (!IsPackageKnuckleGesture(jsonData, ability, knuckleGesture.ability)) {
737 MMI_HILOGE("Package knuckle gesture failed");
738 return false;
739 }
740 return true;
741 }
742
AbsDiff(KnuckleGesture knuckleGesture,const std::shared_ptr<PointerEvent> pointerEvent)743 float AbsDiff(KnuckleGesture knuckleGesture, const std::shared_ptr<PointerEvent> pointerEvent)
744 {
745 CHKPR(pointerEvent, -1);
746 auto id = pointerEvent->GetPointerId();
747 PointerEvent::PointerItem item;
748 pointerEvent->GetPointerItem(id, item);
749 return (float) sqrt(pow(knuckleGesture.lastDownPointer.x - item.GetDisplayX(), POW_SQUARE) +
750 pow(knuckleGesture.lastDownPointer.y - item.GetDisplayY(), POW_SQUARE));
751 }
752
IsEqual(float f1,float f2)753 bool IsEqual(float f1, float f2)
754 {
755 return (std::fabs(f1 - f2) <= std::numeric_limits<double>::epsilon());
756 }
757
ParseMultiFingersTap(const JsonParser & parser,const std::string ability,MultiFingersTap & mulFingersTap)758 bool ParseMultiFingersTap(const JsonParser &parser, const std::string ability, MultiFingersTap &mulFingersTap)
759 {
760 cJSON *jsonData = cJSON_GetObjectItemCaseSensitive(parser.json_, "TouchPadMultiFingersTap");
761 if (!cJSON_IsObject(jsonData)) {
762 MMI_HILOGE("MultiFingersTap is not object");
763 return false;
764 }
765 if (!IsPackageKnuckleGesture(jsonData, ability, mulFingersTap.ability)) {
766 MMI_HILOGE("Package mulFingersTap gesture failed");
767 return false;
768 }
769 return true;
770 }
771 } // namespace
772
773 #ifdef OHOS_BUILD_ENABLE_KEYBOARD
HandleKeyEvent(const std::shared_ptr<KeyEvent> keyEvent)774 void KeyCommandHandler::HandleKeyEvent(const std::shared_ptr<KeyEvent> keyEvent)
775 {
776 CHKPV(keyEvent);
777 if (OnHandleEvent(keyEvent)) {
778 MMI_HILOGD("The keyEvent start launch an ability, keyCode:%{public}d", keyEvent->GetKeyCode());
779 BytraceAdapter::StartBytrace(keyEvent, BytraceAdapter::KEY_LAUNCH_EVENT);
780 return;
781 }
782 CHKPV(nextHandler_);
783 nextHandler_->HandleKeyEvent(keyEvent);
784 }
785 #endif // OHOS_BUILD_ENABLE_KEYBOARD
786
787 #ifdef OHOS_BUILD_ENABLE_POINTER
HandlePointerEvent(const std::shared_ptr<PointerEvent> pointerEvent)788 void KeyCommandHandler::HandlePointerEvent(const std::shared_ptr<PointerEvent> pointerEvent)
789 {
790 CHKPV(pointerEvent);
791 if (OnHandleEvent(pointerEvent)) {
792 MMI_HILOGD("The pointerEvent start launch an ability, pointAction:%{public}s",
793 pointerEvent->DumpPointerAction());
794 }
795 CHKPV(nextHandler_);
796 nextHandler_->HandlePointerEvent(pointerEvent);
797 }
798 #endif // OHOS_BUILD_ENABLE_POINTER
799
800 #ifdef OHOS_BUILD_ENABLE_TOUCH
HandleTouchEvent(const std::shared_ptr<PointerEvent> pointerEvent)801 void KeyCommandHandler::HandleTouchEvent(const std::shared_ptr<PointerEvent> pointerEvent)
802 {
803 CHKPV(pointerEvent);
804 CHKPV(nextHandler_);
805 OnHandleTouchEvent(pointerEvent);
806 if (isKnuckleState_) {
807 MMI_HILOGD("current pointer event is knuckle");
808 return;
809 }
810 nextHandler_->HandleTouchEvent(pointerEvent);
811 }
812
OnHandleTouchEvent(const std::shared_ptr<PointerEvent> touchEvent)813 void KeyCommandHandler::OnHandleTouchEvent(const std::shared_ptr<PointerEvent> touchEvent)
814 {
815 CALL_DEBUG_ENTER;
816 CHKPV(touchEvent);
817 if (!isParseConfig_) {
818 if (!ParseConfig()) {
819 MMI_HILOGE("Parse configFile failed");
820 return;
821 }
822 isParseConfig_ = true;
823 }
824 if (!isTimeConfig_) {
825 SetKnuckleDoubleTapIntervalTime(DOUBLE_CLICK_INTERVAL_TIME_DEFAULT);
826 isTimeConfig_ = true;
827 }
828 if (!isDistanceConfig_) {
829 distanceDefaultConfig_ = DOUBLE_CLICK_DISTANCE_DEFAULT_CONFIG * VPR_CONFIG;
830 distanceLongConfig_ = DOUBLE_CLICK_DISTANCE_LONG_CONFIG * VPR_CONFIG;
831 SetKnuckleDoubleTapDistance(distanceDefaultConfig_);
832 isDistanceConfig_ = true;
833 }
834
835 switch (touchEvent->GetPointerAction()) {
836 case PointerEvent::POINTER_ACTION_CANCEL:
837 case PointerEvent::POINTER_ACTION_UP: {
838 HandlePointerActionUpEvent(touchEvent);
839 break;
840 }
841 case PointerEvent::POINTER_ACTION_MOVE: {
842 HandlePointerActionMoveEvent(touchEvent);
843 break;
844 }
845 case PointerEvent::POINTER_ACTION_DOWN: {
846 HandlePointerActionDownEvent(touchEvent);
847 break;
848 }
849 default:
850 // Don't care about other actions
851 MMI_HILOGW("other action not match.");
852 break;
853 }
854 }
855
HandlePointerActionDownEvent(const std::shared_ptr<PointerEvent> touchEvent)856 void KeyCommandHandler::HandlePointerActionDownEvent(const std::shared_ptr<PointerEvent> touchEvent)
857 {
858 CALL_DEBUG_ENTER;
859 CHKPV(touchEvent);
860 auto id = touchEvent->GetPointerId();
861 PointerEvent::PointerItem item;
862 touchEvent->GetPointerItem(id, item);
863 int32_t toolType = item.GetToolType();
864 MMI_HILOGD("Pointer tool type:%{public}d", toolType);
865 singleKnuckleGesture_.state = false;
866 doubleKnuckleGesture_.state = false;
867 switch (toolType) {
868 case PointerEvent::TOOL_TYPE_FINGER: {
869 isKnuckleState_ = false;
870 HandleFingerGestureDownEvent(touchEvent);
871 break;
872 }
873 case PointerEvent::TOOL_TYPE_KNUCKLE: {
874 DfxHisysevent::ReportKnuckleClickEvent();
875 HandleKnuckleGestureDownEvent(touchEvent);
876 break;
877 }
878 default: {
879 // other tool type are not processed
880 isKnuckleState_ = false;
881 MMI_HILOGD("Current touch event tool type:%{public}d", toolType);
882 break;
883 }
884 }
885 }
886
HandlePointerActionMoveEvent(const std::shared_ptr<PointerEvent> touchEvent)887 void KeyCommandHandler::HandlePointerActionMoveEvent(const std::shared_ptr<PointerEvent> touchEvent)
888 {
889 CALL_DEBUG_ENTER;
890 if (!twoFingerGesture_.active) {
891 return;
892 }
893 if (twoFingerGesture_.timerId == -1) {
894 MMI_HILOGD("Two finger gesture timer id is -1.");
895 return;
896 }
897 auto id = touchEvent->GetPointerId();
898 auto pos = std::find_if(std::begin(twoFingerGesture_.touches), std::end(twoFingerGesture_.touches),
899 [id](const auto& item) { return item.id == id; });
900 if (pos == std::end(twoFingerGesture_.touches)) {
901 return;
902 }
903 PointerEvent::PointerItem item;
904 touchEvent->GetPointerItem(id, item);
905 auto dx = std::abs(pos->x - item.GetDisplayX());
906 auto dy = std::abs(pos->y - item.GetDisplayY());
907 if (dx > TOUCH_MAX_THRESHOLD || dy > TOUCH_MAX_THRESHOLD) {
908 StopTwoFingerGesture();
909 }
910 }
911
HandlePointerActionUpEvent(const std::shared_ptr<PointerEvent> touchEvent)912 void KeyCommandHandler::HandlePointerActionUpEvent(const std::shared_ptr<PointerEvent> touchEvent)
913 {
914 CALL_DEBUG_ENTER;
915 CHKPV(touchEvent);
916 auto id = touchEvent->GetPointerId();
917 PointerEvent::PointerItem item;
918 touchEvent->GetPointerItem(id, item);
919 int32_t toolType = item.GetToolType();
920 switch (toolType) {
921 case PointerEvent::TOOL_TYPE_FINGER: {
922 HandleFingerGestureUpEvent(touchEvent);
923 break;
924 }
925 case PointerEvent::TOOL_TYPE_KNUCKLE: {
926 HandleKnuckleGestureUpEvent(touchEvent);
927 break;
928 }
929 default: {
930 // other tool type are not processed
931 MMI_HILOGW("Current touch event tool type:%{public}d", toolType);
932 break;
933 }
934 }
935 }
936
HandleFingerGestureDownEvent(const std::shared_ptr<PointerEvent> touchEvent)937 void KeyCommandHandler::HandleFingerGestureDownEvent(const std::shared_ptr<PointerEvent> touchEvent)
938 {
939 CALL_DEBUG_ENTER;
940 if (!twoFingerGesture_.active) {
941 MMI_HILOGD("Two finger gesture is not active");
942 return;
943 }
944 auto num = touchEvent->GetPointerIds().size();
945 if (num == TwoFingerGesture::MAX_TOUCH_NUM) {
946 StartTwoFingerGesture();
947 } else {
948 StopTwoFingerGesture();
949 }
950 if (num > 0 && num <= TwoFingerGesture::MAX_TOUCH_NUM) {
951 auto id = touchEvent->GetPointerId();
952 PointerEvent::PointerItem item;
953 touchEvent->GetPointerItem(id, item);
954 twoFingerGesture_.touches[num - 1].id = id;
955 twoFingerGesture_.touches[num - 1].x = item.GetDisplayX();
956 twoFingerGesture_.touches[num - 1].y = item.GetDisplayY();
957 }
958 }
959
HandleFingerGestureUpEvent(const std::shared_ptr<PointerEvent> touchEvent)960 void KeyCommandHandler::HandleFingerGestureUpEvent(const std::shared_ptr<PointerEvent> touchEvent)
961 {
962 CALL_DEBUG_ENTER;
963 CHKPV(touchEvent);
964 if (!twoFingerGesture_.active) {
965 MMI_HILOGD("Two finger gesture is not active");
966 return;
967 }
968 StopTwoFingerGesture();
969 }
970
HandleKnuckleGestureDownEvent(const std::shared_ptr<PointerEvent> touchEvent)971 void KeyCommandHandler::HandleKnuckleGestureDownEvent(const std::shared_ptr<PointerEvent> touchEvent)
972 {
973 CALL_DEBUG_ENTER;
974 CHKPV(touchEvent);
975
976 auto id = touchEvent->GetPointerId();
977 PointerEvent::PointerItem item;
978 touchEvent->GetPointerItem(id, item);
979 if (item.GetToolType() != PointerEvent::TOOL_TYPE_KNUCKLE) {
980 MMI_HILOGW("Touch event tool type:%{public}d not knuckle", item.GetToolType());
981 return;
982 }
983 size_t size = touchEvent->GetPointerIds().size();
984 if (size == SINGLE_KNUCKLE_SIZE) {
985 SingleKnuckleGestureProcesser(touchEvent);
986 isDoubleClick_ = false;
987 } else if (size == DOUBLE_KNUCKLE_SIZE) {
988 DoubleKnuckleGestureProcesser(touchEvent);
989 isDoubleClick_ = true;
990 } else {
991 MMI_HILOGW("Other kunckle size not process, size:%{public}zu", size);
992 }
993 }
994
HandleKnuckleGestureUpEvent(const std::shared_ptr<PointerEvent> touchEvent)995 void KeyCommandHandler::HandleKnuckleGestureUpEvent(const std::shared_ptr<PointerEvent> touchEvent)
996 {
997 CALL_DEBUG_ENTER;
998 CHKPV(touchEvent);
999 size_t size = touchEvent->GetPointerIds().size();
1000 if ((size == SINGLE_KNUCKLE_SIZE) && (!isDoubleClick_)) {
1001 singleKnuckleGesture_.lastPointerUpTime = touchEvent->GetActionTime();
1002 } else if (size == DOUBLE_KNUCKLE_SIZE) {
1003 doubleKnuckleGesture_.lastPointerUpTime = touchEvent->GetActionTime();
1004 } else {
1005 MMI_HILOGW("Other kunckle size not process, size:%{public}zu", size);
1006 }
1007 }
1008
SingleKnuckleGestureProcesser(const std::shared_ptr<PointerEvent> touchEvent)1009 void KeyCommandHandler::SingleKnuckleGestureProcesser(const std::shared_ptr<PointerEvent> touchEvent)
1010 {
1011 CALL_DEBUG_ENTER;
1012 CHKPV(touchEvent);
1013 singleKnuckleGesture_.state = false;
1014 KnuckleGestureProcessor(touchEvent, singleKnuckleGesture_);
1015 }
1016
DoubleKnuckleGestureProcesser(const std::shared_ptr<PointerEvent> touchEvent)1017 void KeyCommandHandler::DoubleKnuckleGestureProcesser(const std::shared_ptr<PointerEvent> touchEvent)
1018 {
1019 CALL_DEBUG_ENTER;
1020 CHKPV(touchEvent);
1021 doubleKnuckleGesture_.state = false;
1022 KnuckleGestureProcessor(touchEvent, doubleKnuckleGesture_);
1023 }
1024
KnuckleGestureProcessor(const std::shared_ptr<PointerEvent> touchEvent,KnuckleGesture & knuckleGesture)1025 void KeyCommandHandler::KnuckleGestureProcessor(const std::shared_ptr<PointerEvent> touchEvent,
1026 KnuckleGesture &knuckleGesture)
1027 {
1028 CALL_DEBUG_ENTER;
1029 CHKPV(touchEvent);
1030 isKnuckleState_ = true;
1031 if (knuckleGesture.lastPointerDownEvent == nullptr) {
1032 MMI_HILOGI("knuckle gesture first down Event");
1033 knuckleGesture.lastPointerDownEvent = touchEvent;
1034 UpdateKnuckleGestureInfo(touchEvent, knuckleGesture);
1035 return;
1036 }
1037 int64_t intervalTime = touchEvent->GetActionTime() - knuckleGesture.lastPointerUpTime;
1038 bool isTimeIntervalReady = intervalTime > 0 && intervalTime <= downToPrevUpTimeConfig_;
1039 float downToPrevDownDistance = AbsDiff(knuckleGesture, touchEvent);
1040 bool isDistanceReady = downToPrevDownDistance < downToPrevDownDistanceConfig_;
1041 knuckleGesture.downToPrevUpTime = intervalTime;
1042 knuckleGesture.doubleClickDistance = downToPrevDownDistance;
1043 UpdateKnuckleGestureInfo(touchEvent, knuckleGesture);
1044 if (isTimeIntervalReady && isDistanceReady) {
1045 MMI_HILOGI("knuckle gesture start launch ability");
1046 DfxHisysevent::ReportSingleKnuckleDoubleClickEvent(intervalTime);
1047 LaunchAbility(knuckleGesture.ability, 0);
1048 knuckleGesture.state = true;
1049 ReportKnuckleScreenCapture(touchEvent);
1050 } else {
1051 MMI_HILOGW("time ready:%{public}d, distance ready:%{public}d", isTimeIntervalReady, isDistanceReady);
1052 if (!isTimeIntervalReady) {
1053 DfxHisysevent::ReportFailIfInvalidTime(touchEvent, intervalTime);
1054 }
1055 if (!isDistanceReady) {
1056 DfxHisysevent::ReportFailIfInvalidDistance(touchEvent, downToPrevDownDistance);
1057 }
1058 }
1059 AdjustTimeIntervalConfigIfNeed(intervalTime);
1060 AdjustDistanceConfigIfNeed(downToPrevDownDistance);
1061 }
1062
UpdateKnuckleGestureInfo(const std::shared_ptr<PointerEvent> touchEvent,KnuckleGesture & knuckleGesture)1063 void KeyCommandHandler::UpdateKnuckleGestureInfo(const std::shared_ptr<PointerEvent> touchEvent,
1064 KnuckleGesture &knuckleGesture)
1065 {
1066 auto id = touchEvent->GetPointerId();
1067 PointerEvent::PointerItem item;
1068 touchEvent->GetPointerItem(id, item);
1069 knuckleGesture.lastDownPointer.x = item.GetDisplayX();
1070 knuckleGesture.lastDownPointer.y = item.GetDisplayY();
1071 knuckleGesture.lastDownPointer.id = touchEvent->GetId();
1072 }
1073
AdjustTimeIntervalConfigIfNeed(int64_t intervalTime)1074 void KeyCommandHandler::AdjustTimeIntervalConfigIfNeed(int64_t intervalTime)
1075 {
1076 CALL_DEBUG_ENTER;
1077 int64_t newTimeConfig;
1078 MMI_HILOGI("down to prev up interval time:%{public}" PRId64 ",config time:%{public}" PRId64"",
1079 intervalTime, downToPrevUpTimeConfig_);
1080 if (downToPrevUpTimeConfig_ == DOUBLE_CLICK_INTERVAL_TIME_DEFAULT) {
1081 if (intervalTime < DOUBLE_CLICK_INTERVAL_TIME_DEFAULT || intervalTime > DOUBLE_CLICK_INTERVAL_TIME_SLOW) {
1082 return;
1083 }
1084 newTimeConfig = DOUBLE_CLICK_INTERVAL_TIME_SLOW;
1085 } else if (downToPrevUpTimeConfig_ == DOUBLE_CLICK_INTERVAL_TIME_SLOW) {
1086 if (intervalTime > DOUBLE_CLICK_INTERVAL_TIME_DEFAULT) {
1087 return;
1088 }
1089 newTimeConfig = DOUBLE_CLICK_INTERVAL_TIME_DEFAULT;
1090 } else {
1091 return;
1092 }
1093 checkAdjustIntervalTimeCount_++;
1094 if (checkAdjustIntervalTimeCount_ < MAX_TIME_FOR_ADJUST_CONFIG) {
1095 return;
1096 }
1097 MMI_HILOGI("adjust new double click interval time:%{public}" PRId64 "", newTimeConfig);
1098 downToPrevUpTimeConfig_ = newTimeConfig;
1099 checkAdjustIntervalTimeCount_ = 0;
1100 }
1101
AdjustDistanceConfigIfNeed(float distance)1102 void KeyCommandHandler::AdjustDistanceConfigIfNeed(float distance)
1103 {
1104 CALL_DEBUG_ENTER;
1105 float newDistanceConfig;
1106 MMI_HILOGI("down to prev down distance:%{public}f, config distance:%{public}f",
1107 distance, downToPrevDownDistanceConfig_);
1108 if (IsEqual(downToPrevDownDistanceConfig_, distanceDefaultConfig_)) {
1109 if (distance < distanceDefaultConfig_ || distance > distanceLongConfig_) {
1110 return;
1111 }
1112 newDistanceConfig = distanceLongConfig_;
1113 } else if (IsEqual(downToPrevDownDistanceConfig_, distanceLongConfig_)) {
1114 if (distance > distanceDefaultConfig_) {
1115 return;
1116 }
1117 newDistanceConfig = distanceDefaultConfig_;
1118 } else {
1119 return;
1120 }
1121 checkAdjustDistanceCount_++;
1122 if (checkAdjustDistanceCount_ < MAX_TIME_FOR_ADJUST_CONFIG) {
1123 return;
1124 }
1125 MMI_HILOGI("adjust new double click distance:%{public}f", newDistanceConfig);
1126 downToPrevDownDistanceConfig_ = newDistanceConfig;
1127 checkAdjustDistanceCount_ = 0;
1128 }
1129
ReportKnuckleDoubleClickEvent(const std::shared_ptr<PointerEvent> touchEvent,KnuckleGesture & knuckleGesture)1130 void KeyCommandHandler::ReportKnuckleDoubleClickEvent(const std::shared_ptr<PointerEvent> touchEvent,
1131 KnuckleGesture &knuckleGesture)
1132 {
1133 CHKPV(touchEvent);
1134 size_t size = touchEvent->GetPointerIds().size();
1135 if (size == SINGLE_KNUCKLE_SIZE) {
1136 DfxHisysevent::ReportSingleKnuckleDoubleClickEvent(knuckleGesture.downToPrevUpTime);
1137 return;
1138 }
1139 MMI_HILOGW("current touch event size:%{public}zu", size);
1140 }
1141
ReportKnuckleScreenCapture(const std::shared_ptr<PointerEvent> touchEvent)1142 void KeyCommandHandler::ReportKnuckleScreenCapture(const std::shared_ptr<PointerEvent> touchEvent)
1143 {
1144 CHKPV(touchEvent);
1145 size_t size = touchEvent->GetPointerIds().size();
1146 if (size == SINGLE_KNUCKLE_SIZE) {
1147 DfxHisysevent::ReportScreenCaptureGesture();
1148 return;
1149 }
1150 MMI_HILOGW("current touch event size:%{public}zu", size);
1151 }
1152
StartTwoFingerGesture()1153 void KeyCommandHandler::StartTwoFingerGesture()
1154 {
1155 CALL_DEBUG_ENTER;
1156 twoFingerGesture_.timerId = TimerMgr->AddTimer(twoFingerGesture_.abilityStartDelay, 1, [this]() {
1157 LaunchAbility(twoFingerGesture_.ability, twoFingerGesture_.abilityStartDelay);
1158 twoFingerGesture_.timerId = -1;
1159 });
1160 }
1161
StopTwoFingerGesture()1162 void KeyCommandHandler::StopTwoFingerGesture()
1163 {
1164 CALL_DEBUG_ENTER;
1165 if (twoFingerGesture_.timerId != -1) {
1166 TimerMgr->RemoveTimer(twoFingerGesture_.timerId);
1167 twoFingerGesture_.timerId = -1;
1168 }
1169 }
1170 #endif // OHOS_BUILD_ENABLE_TOUCH
1171
ParseConfig()1172 bool KeyCommandHandler::ParseConfig()
1173 {
1174 #ifndef UNIT_TEST
1175 const char *testPathSuffix = "/etc/multimodalinput/ability_launch_config.json";
1176 #else
1177 const char *testPathSuffix = "/data/test/test.json";
1178 #endif
1179 char buf[MAX_PATH_LEN] = { 0 };
1180 char *filePath = GetOneCfgFile(testPathSuffix, buf, MAX_PATH_LEN);
1181 #ifndef UNIT_TEST
1182 std::string defaultConfig = "/system/etc/multimodalinput/ability_launch_config.json";
1183 #else
1184 std::string defaultConfig = "/data/test/test.json";
1185 #endif
1186 if (filePath == nullptr || filePath[0] == '\0' || strlen(filePath) > MAX_PATH_LEN) {
1187 MMI_HILOGD("Can not get customization config file");
1188 return ParseJson(defaultConfig);
1189 }
1190 std::string customConfig = filePath;
1191 MMI_HILOGD("The configuration file path is :%{public}s", customConfig.c_str());
1192 return ParseJson(customConfig) || ParseJson(defaultConfig);
1193 }
1194
ParseRepeatKeyMaxCount()1195 void KeyCommandHandler::ParseRepeatKeyMaxCount()
1196 {
1197 if (repeatKeys_.empty()) {
1198 maxCount_ = 0;
1199 }
1200 int32_t tempCount = 0;
1201 for (RepeatKey& item : repeatKeys_) {
1202 if (item.times > tempCount) {
1203 tempCount = item.times;
1204 }
1205 }
1206 maxCount_ = tempCount;
1207 }
1208
ParseJson(const std::string & configFile)1209 bool KeyCommandHandler::ParseJson(const std::string &configFile)
1210 {
1211 CALL_DEBUG_ENTER;
1212 std::string jsonStr = ReadJsonFile(configFile);
1213 if (jsonStr.empty()) {
1214 MMI_HILOGE("Read configFile failed");
1215 return false;
1216 }
1217 JsonParser parser;
1218 parser.json_ = cJSON_Parse(jsonStr.c_str());
1219 if (!cJSON_IsObject(parser.json_)) {
1220 MMI_HILOGE("Parser.json_ is not object");
1221 return false;
1222 }
1223
1224 bool isParseShortKeys = ParseShortcutKeys(parser, shortcutKeys_, businessIds_);
1225 bool isParseSequences = ParseSequences(parser, sequences_);
1226 bool isParseTwoFingerGesture = ParseTwoFingerGesture(parser, twoFingerGesture_);
1227 bool isParseSingleKnuckleGesture = IsParseKnuckleGesture(parser, SINGLE_KNUCKLE_ABILITY, singleKnuckleGesture_);
1228 bool isParseDoubleKnuckleGesture = IsParseKnuckleGesture(parser, DOUBLE_KNUCKLE_ABILITY, doubleKnuckleGesture_);
1229 bool isParseMultiFingersTap = ParseMultiFingersTap(parser, TOUCHPAD_TRIP_TAP_ABILITY, threeFingersTap_);
1230 bool isParseRepeatKeys = ParseRepeatKeys(parser, repeatKeys_);
1231 if (!isParseShortKeys && !isParseSequences && !isParseTwoFingerGesture && !isParseSingleKnuckleGesture &&
1232 !isParseDoubleKnuckleGesture && !isParseMultiFingersTap && !isParseRepeatKeys) {
1233 MMI_HILOGE("Parse configFile failed");
1234 return false;
1235 }
1236
1237 Print();
1238 PrintSeq();
1239 return true;
1240 }
1241
Print()1242 void KeyCommandHandler::Print()
1243 {
1244 MMI_HILOGD("shortcutKey count:%{public}zu", shortcutKeys_.size());
1245 int32_t row = 0;
1246 for (const auto &item : shortcutKeys_) {
1247 MMI_HILOGD("row:%{public}d", row++);
1248 auto &shortcutKey = item.second;
1249 for (const auto &prekey : shortcutKey.preKeys) {
1250 MMI_HILOGD("preKey:%{public}d", prekey);
1251 }
1252 MMI_HILOGD("finalKey:%{public}d, keyDownDuration:%{public}d, triggerType:%{public}d,"
1253 " bundleName:%{public}s, abilityName:%{public}s", shortcutKey.finalKey,
1254 shortcutKey.keyDownDuration, shortcutKey.triggerType,
1255 shortcutKey.ability.bundleName.c_str(), shortcutKey.ability.abilityName.c_str());
1256 }
1257 }
1258
PrintSeq()1259 void KeyCommandHandler::PrintSeq()
1260 {
1261 MMI_HILOGD("sequences count:%{public}zu", sequences_.size());
1262 int32_t row = 0;
1263 for (const auto &item : sequences_) {
1264 MMI_HILOGD("row:%{public}d", row++);
1265 for (const auto& sequenceKey : item.sequenceKeys) {
1266 MMI_HILOGD("keyCode:%{public}d, keyAction:%{public}d, delay:%{public}" PRId64,
1267 sequenceKey.keyCode, sequenceKey.keyAction, sequenceKey.delay);
1268 }
1269 MMI_HILOGD("bundleName:%{public}s, abilityName:%{public}s",
1270 item.ability.bundleName.c_str(), item.ability.abilityName.c_str());
1271 }
1272 }
1273
IsEnableCombineKey(const std::shared_ptr<KeyEvent> key)1274 bool KeyCommandHandler::IsEnableCombineKey(const std::shared_ptr<KeyEvent> key)
1275 {
1276 CHKPF(key);
1277 if (enableCombineKey_) {
1278 return true;
1279 }
1280 if (key->GetKeyCode() == KeyEvent::KEYCODE_POWER && key->GetKeyAction() == KeyEvent::KEY_ACTION_UP) {
1281 auto items = key->GetKeyItems();
1282 if (items.size() != 1) {
1283 return enableCombineKey_;
1284 }
1285 return true;
1286 }
1287 if (key->GetKeyCode() == KeyEvent::KEYCODE_L) {
1288 for (const auto &item : key->GetKeyItems()) {
1289 int32_t keyCode = item.GetKeyCode();
1290 if (keyCode != KeyEvent::KEYCODE_L && keyCode != KeyEvent::KEYCODE_META_LEFT &&
1291 keyCode != KeyEvent::KEYCODE_META_RIGHT) {
1292 return enableCombineKey_;
1293 }
1294 }
1295 return true;
1296 }
1297 return enableCombineKey_;
1298 }
1299
EnableCombineKey(bool enable)1300 int32_t KeyCommandHandler::EnableCombineKey(bool enable)
1301 {
1302 enableCombineKey_ = enable;
1303 MMI_HILOGI("Enable combineKey is successful in keyCommand handler, enable:%{public}d", enable);
1304 return RET_OK;
1305 }
1306
ParseStatusConfigObserver()1307 void KeyCommandHandler::ParseStatusConfigObserver()
1308 {
1309 CALL_DEBUG_ENTER;
1310 for (Sequence& item : sequences_) {
1311 if (item.statusConfig.empty()) {
1312 continue;
1313 }
1314 CreateStatusConfigObserver<Sequence>(item);
1315 }
1316
1317 for (auto& item : shortcutKeys_) {
1318 ShortcutKey &shortcutKey = item.second;
1319 if (shortcutKey.statusConfig.empty()) {
1320 continue;
1321 }
1322 CreateStatusConfigObserver<ShortcutKey>(shortcutKey);
1323 }
1324 }
1325
1326 template <class T>
CreateStatusConfigObserver(T & item)1327 void KeyCommandHandler::CreateStatusConfigObserver(T& item)
1328 {
1329 CALL_DEBUG_ENTER;
1330 SettingObserver::UpdateFunc updateFunc = [&item](const std::string& key) {
1331 bool statusValue = true;
1332 auto ret = SettingDataShare::GetInstance(MULTIMODAL_INPUT_SERVICE_ID)
1333 .GetBoolValue(key, statusValue);
1334 if (ret != RET_OK) {
1335 MMI_HILOGE("Get value from setting date fail");
1336 return;
1337 }
1338 item.statusConfigValue = statusValue;
1339 };
1340 sptr<SettingObserver> statusObserver = SettingDataShare::GetInstance(MULTIMODAL_INPUT_SERVICE_ID)
1341 .CreateObserver(item.statusConfig, updateFunc);
1342 ErrCode ret = SettingDataShare::GetInstance(MULTIMODAL_INPUT_SERVICE_ID).RegisterObserver(statusObserver);
1343 if (ret != ERR_OK) {
1344 MMI_HILOGE("register setting observer failed, ret=%{public}d", ret);
1345 statusObserver = nullptr;
1346 }
1347 }
1348
CreateKeyEvent(int32_t keyCode,int32_t keyAction,bool isPressed)1349 std::shared_ptr<KeyEvent> KeyCommandHandler::CreateKeyEvent(int32_t keyCode, int32_t keyAction, bool isPressed)
1350 {
1351 CALL_DEBUG_ENTER;
1352 std::shared_ptr<KeyEvent> keyEvent = KeyEvent::Create();
1353 CHKPP(keyEvent);
1354 KeyEvent::KeyItem item;
1355 item.SetKeyCode(keyCode);
1356 item.SetPressed(isPressed);
1357 keyEvent->SetKeyCode(keyCode);
1358 keyEvent->SetKeyAction(keyAction);
1359 keyEvent->AddPressedKeyItems(item);
1360 return keyEvent;
1361 }
1362
HandleEvent(const std::shared_ptr<KeyEvent> key)1363 bool KeyCommandHandler::HandleEvent(const std::shared_ptr<KeyEvent> key)
1364 {
1365 CALL_DEBUG_ENTER;
1366 CHKPF(key);
1367 if (!IsEnableCombineKey(key)) {
1368 MMI_HILOGI("Combine key is taken over in key command");
1369 return false;
1370 }
1371 if (!isParseConfig_) {
1372 if (!ParseConfig()) {
1373 MMI_HILOGE("Parse configFile failed");
1374 return false;
1375 }
1376 isParseConfig_ = true;
1377 }
1378
1379 if (!isParseMaxCount_) {
1380 ParseRepeatKeyMaxCount();
1381 isParseMaxCount_ = true;
1382 if (repeatKeys_.size() > 0) {
1383 intervalTime_ = repeatKeys_[0].delay;
1384 }
1385 }
1386
1387 if (!isParseStatusConfig_) {
1388 ParseStatusConfigObserver();
1389 isParseStatusConfig_ = true;
1390 }
1391
1392 bool isHandled = HandleShortKeys(key);
1393 isHandled = HandleSequences(key) || isHandled;
1394 if (isHandled) {
1395 if (isKeyCancel_) {
1396 isHandleSequence_ = false;
1397 isKeyCancel_ = false;
1398 } else {
1399 isHandleSequence_ = true;
1400 }
1401 return true;
1402 }
1403
1404 if (!isDownStart_) {
1405 HandleRepeatKeys(key);
1406 return false;
1407 } else {
1408 bool isRepeatKeyHandle = HandleRepeatKeys(key);
1409 if (isRepeatKeyHandle) {
1410 return true;
1411 }
1412 }
1413
1414 count_ = 0;
1415 isDownStart_ = false;
1416 return false;
1417 }
1418
OnHandleEvent(const std::shared_ptr<KeyEvent> key)1419 bool KeyCommandHandler::OnHandleEvent(const std::shared_ptr<KeyEvent> key)
1420 {
1421 CALL_DEBUG_ENTER;
1422 CHKPF(key);
1423
1424 bool handleEventStatus = HandleEvent(key);
1425 if (handleEventStatus) {
1426 return true;
1427 }
1428
1429 if (!specialKeys_.empty() && specialKeys_.find(key->GetKeyCode()) != specialKeys_.end()) {
1430 HandleSpecialKeys(key->GetKeyCode(), key->GetAction());
1431 return true;
1432 }
1433
1434 if (IsSpecialType(key->GetKeyCode(), SpecialType::SUBSCRIBER_BEFORE_DELAY)) {
1435 auto tmpKey = KeyEvent::Clone(key);
1436 int32_t timerId = TimerMgr->AddTimer(SPECIAL_KEY_DOWN_DELAY, 1, [this, tmpKey] () {
1437 MMI_HILOGD("Timer callback");
1438 auto it = specialTimers_.find(tmpKey->GetKeyCode());
1439 if (it != specialTimers_.end() && !it->second.empty()) {
1440 it->second.pop_front();
1441 }
1442 InputHandler->GetSubscriberHandler()->HandleKeyEvent(tmpKey);
1443 });
1444 if (timerId < 0) {
1445 MMI_HILOGE("Add timer failed");
1446 return false;
1447 }
1448
1449 auto it = specialTimers_.find(key->GetKeyCode());
1450 if (it == specialTimers_.end()) {
1451 std::list<int32_t> timerIds;
1452 timerIds.push_back(timerId);
1453 auto it = specialTimers_.emplace(key->GetKeyCode(), timerIds);
1454 if (!it.second) {
1455 MMI_HILOGE("Keycode duplicated");
1456 return false;
1457 }
1458 } else {
1459 it->second.push_back(timerId);
1460 }
1461 MMI_HILOGD("Add timer success");
1462 return true;
1463 }
1464 return false;
1465 }
1466
OnHandleEvent(const std::shared_ptr<PointerEvent> pointer)1467 bool KeyCommandHandler::OnHandleEvent(const std::shared_ptr<PointerEvent> pointer)
1468 {
1469 CALL_DEBUG_ENTER;
1470 CHKPF(pointer);
1471 if (!isParseConfig_) {
1472 if (!ParseConfig()) {
1473 MMI_HILOGE("Parse configFile failed");
1474 return false;
1475 }
1476 isParseConfig_ = true;
1477 }
1478 bool isHandled = HandleMulFingersTap(pointer);
1479 if (isHandled) {
1480 return true;
1481 }
1482 return false;
1483 }
1484
HandleRepeatKeys(const std::shared_ptr<KeyEvent> keyEvent)1485 bool KeyCommandHandler::HandleRepeatKeys(const std::shared_ptr<KeyEvent> keyEvent)
1486 {
1487 CALL_DEBUG_ENTER;
1488 CHKPF(keyEvent);
1489 if (repeatKeys_.empty()) {
1490 MMI_HILOGD("No sequences configuration data");
1491 return false;
1492 }
1493
1494 if (count_ > maxCount_) {
1495 return false;
1496 }
1497
1498 bool isLaunched = false;
1499 bool waitRepeatKey = false;
1500
1501 for (RepeatKey& item : repeatKeys_) {
1502 if (HandleKeyUpCancel(item, keyEvent)) {
1503 return false;
1504 }
1505 if (HandleRepeatKeyCount(item, keyEvent)) {
1506 break;
1507 }
1508 }
1509
1510 for (RepeatKey& item : repeatKeys_) {
1511 bool isRepeatKey = HandleRepeatKey(item, isLaunched, keyEvent);
1512 if (isRepeatKey) {
1513 waitRepeatKey = true;
1514 }
1515 }
1516
1517 return isLaunched || waitRepeatKey;
1518 }
1519
HandleRepeatKey(const RepeatKey & item,bool & isLaunched,const std::shared_ptr<KeyEvent> keyEvent)1520 bool KeyCommandHandler::HandleRepeatKey(const RepeatKey &item, bool &isLaunched,
1521 const std::shared_ptr<KeyEvent> keyEvent)
1522 {
1523 CALL_DEBUG_ENTER;
1524 CHKPF(keyEvent);
1525
1526 if (keyEvent->GetKeyCode() != item.keyCode) {
1527 return false;
1528 }
1529 if (count_ == item.times) {
1530 bool statusValue = true;
1531 auto ret = SettingDataShare::GetInstance(MULTIMODAL_INPUT_SERVICE_ID)
1532 .GetBoolValue(item.statusConfig, statusValue);
1533 if (ret != RET_OK) {
1534 MMI_HILOGE("Get value from setting date fail");
1535 return false;
1536 }
1537 if (!statusValue) {
1538 return false;
1539 }
1540 LaunchAbility(item.ability);
1541 launchAbilityCount_ = count_;
1542 isLaunched = true;
1543 isDownStart_ = false;
1544 auto keyEventCancel = std::make_shared<KeyEvent>(*keyEvent);
1545 keyEventCancel->SetKeyAction(KeyEvent::KEY_ACTION_CANCEL);
1546 InputHandler->GetSubscriberHandler()->HandleKeyEvent(keyEventCancel);
1547 }
1548 return true;
1549 }
1550
HandleKeyUpCancel(const RepeatKey & item,const std::shared_ptr<KeyEvent> keyEvent)1551 bool KeyCommandHandler::HandleKeyUpCancel(const RepeatKey &item, const std::shared_ptr<KeyEvent> keyEvent)
1552 {
1553 CALL_DEBUG_ENTER;
1554 CHKPF(keyEvent);
1555 if (keyEvent->GetKeyCode() == item.keyCode && keyEvent->GetKeyAction() == KeyEvent::KEY_ACTION_CANCEL) {
1556 isKeyCancel_ = true;
1557 isDownStart_ = false;
1558 return true;
1559 }
1560 return false;
1561 }
1562
HandleRepeatKeyCount(const RepeatKey & item,const std::shared_ptr<KeyEvent> keyEvent)1563 bool KeyCommandHandler::HandleRepeatKeyCount(const RepeatKey &item, const std::shared_ptr<KeyEvent> keyEvent)
1564 {
1565 CALL_DEBUG_ENTER;
1566 CHKPF(keyEvent);
1567
1568 if (keyEvent->GetKeyCode() == item.keyCode && keyEvent->GetKeyAction() == KeyEvent::KEY_ACTION_UP) {
1569 if (repeatKey_.keyCode != item.keyCode) {
1570 std::vector<int32_t> pressedKeys = keyEvent->GetPressedKeys();
1571
1572 if (pressedKeys.size() == 0) {
1573 count_ = 1;
1574 } else {
1575 count_ = 0;
1576 }
1577 repeatKey_.keyCode = item.keyCode;
1578 } else {
1579 count_++;
1580 }
1581
1582 upActionTime_ = keyEvent->GetActionTime();
1583 repeatTimerId_ = TimerMgr->AddTimer(intervalTime_ / SECONDS_SYSTEM, 1, [this] () {
1584 SendKeyEvent();
1585 });
1586 if (repeatTimerId_ < 0) {
1587 return false;
1588 }
1589 repeatKey_.keyCode = item.keyCode;
1590 return true;
1591 }
1592
1593 if (keyEvent->GetKeyCode() == item.keyCode && keyEvent->GetKeyAction() == KeyEvent::KEY_ACTION_DOWN) {
1594 repeatKey_.keyCode = item.keyCode;
1595 isDownStart_ = true;
1596
1597 downActionTime_ = keyEvent->GetActionTime();
1598 if ((downActionTime_ - upActionTime_) < intervalTime_) {
1599 if (repeatTimerId_ >= 0) {
1600 TimerMgr->RemoveTimer(repeatTimerId_);
1601 }
1602 }
1603 return true;
1604 }
1605 return false;
1606 }
1607
SendKeyEvent()1608 void KeyCommandHandler::SendKeyEvent()
1609 {
1610 CALL_DEBUG_ENTER;
1611 if (!isHandleSequence_) {
1612 for (int32_t i = launchAbilityCount_; i < count_; i++) {
1613 int32_t keycode = repeatKey_.keyCode;
1614 if (IsSpecialType(keycode, SpecialType::KEY_DOWN_ACTION)) {
1615 HandleSpecialKeys(keycode, KeyEvent::KEY_ACTION_UP);
1616 }
1617 if (i != 0) {
1618 auto keyEventDown = CreateKeyEvent(keycode, KeyEvent::KEY_ACTION_DOWN, true);
1619 CHKPV(keyEventDown);
1620 InputHandler->GetSubscriberHandler()->HandleKeyEvent(keyEventDown);
1621 }
1622
1623 auto keyEventUp = CreateKeyEvent(keycode, KeyEvent::KEY_ACTION_UP, false);
1624 CHKPV(keyEventUp);
1625 InputHandler->GetSubscriberHandler()->HandleKeyEvent(keyEventUp);
1626 }
1627 }
1628 count_ = 0;
1629 isDownStart_ = false;
1630 isHandleSequence_ = false;
1631 launchAbilityCount_ = 0;
1632 }
1633
HandleShortKeys(const std::shared_ptr<KeyEvent> keyEvent)1634 bool KeyCommandHandler::HandleShortKeys(const std::shared_ptr<KeyEvent> keyEvent)
1635 {
1636 CALL_DEBUG_ENTER;
1637 CHKPF(keyEvent);
1638 if (shortcutKeys_.empty()) {
1639 MMI_HILOGD("No shortkeys configuration data");
1640 return false;
1641 }
1642 if (IsKeyMatch(lastMatchedKey_, keyEvent)) {
1643 MMI_HILOGD("The same key is waiting timeout, skip");
1644 return true;
1645 }
1646 if (currentLaunchAbilityKey_.timerId >= 0 && IsKeyMatch(currentLaunchAbilityKey_, keyEvent)) {
1647 MMI_HILOGD("repeat, current key %{public}d has launched ability", currentLaunchAbilityKey_.finalKey);
1648 return true;
1649 }
1650 DfxHisysevent::GetComboStartTime();
1651 if (lastMatchedKey_.timerId >= 0) {
1652 MMI_HILOGD("Remove timer:%{public}d", lastMatchedKey_.timerId);
1653 TimerMgr->RemoveTimer(lastMatchedKey_.timerId);
1654 }
1655 ResetLastMatchedKey();
1656 for (auto &item : shortcutKeys_) {
1657 ShortcutKey &shortcutKey = item.second;
1658 if (!shortcutKey.statusConfigValue) {
1659 continue;
1660 }
1661 if (!IsKeyMatch(shortcutKey, keyEvent)) {
1662 MMI_HILOGD("Not key matched, next");
1663 continue;
1664 }
1665 int32_t delay = GetKeyDownDurationFromXml(shortcutKey.businessId);
1666 if (delay >= MIN_SHORT_KEY_DOWN_DURATION && delay <= MAX_SHORT_KEY_DOWN_DURATION) {
1667 MMI_HILOGD("User defined new short key down duration:%{public}d", delay);
1668 shortcutKey.keyDownDuration = delay;
1669 }
1670 shortcutKey.Print();
1671 if (shortcutKey.triggerType == KeyEvent::KEY_ACTION_DOWN) {
1672 return HandleKeyDown(shortcutKey);
1673 } else if (shortcutKey.triggerType == KeyEvent::KEY_ACTION_UP) {
1674 return HandleKeyUp(keyEvent, shortcutKey);
1675 } else {
1676 return HandleKeyCancel(shortcutKey);
1677 }
1678 }
1679 return HandleConsumedKeyEvent(keyEvent);
1680 }
1681
HandleConsumedKeyEvent(const std::shared_ptr<KeyEvent> keyEvent)1682 bool KeyCommandHandler::HandleConsumedKeyEvent(const std::shared_ptr<KeyEvent> keyEvent)
1683 {
1684 CALL_DEBUG_ENTER;
1685 CHKPF(keyEvent);
1686 if (currentLaunchAbilityKey_.finalKey == keyEvent->GetKeyCode()
1687 && keyEvent->GetKeyAction() == KeyEvent::KEY_ACTION_UP) {
1688 MMI_HILOGD("Handle consumed key event, cancel opration");
1689 ResetCurrentLaunchAbilityKey();
1690 auto keyEventCancel = std::make_shared<KeyEvent>(*keyEvent);
1691 keyEventCancel->SetKeyAction(KeyEvent::KEY_ACTION_CANCEL);
1692 auto inputEventNormalizeHandler = InputHandler->GetEventNormalizeHandler();
1693 CHKPF(inputEventNormalizeHandler);
1694 inputEventNormalizeHandler->HandleKeyEvent(keyEventCancel);
1695 return true;
1696 }
1697 return false;
1698 }
1699
IsRepeatKeyEvent(const SequenceKey & sequenceKey)1700 bool KeyCommandHandler::IsRepeatKeyEvent(const SequenceKey &sequenceKey)
1701 {
1702 for (size_t i = keys_.size(); i > 0; --i) {
1703 if (keys_[i-1].keyCode == sequenceKey.keyCode) {
1704 if (keys_[i-1].keyAction == sequenceKey.keyAction) {
1705 MMI_HILOGD("Is repeat key, keyCode:%{public}d", sequenceKey.keyCode);
1706 return true;
1707 }
1708 MMI_HILOGD("Is not repeat key");
1709 return false;
1710 }
1711 }
1712 return false;
1713 }
1714
HandleSequences(const std::shared_ptr<KeyEvent> keyEvent)1715 bool KeyCommandHandler::HandleSequences(const std::shared_ptr<KeyEvent> keyEvent)
1716 {
1717 CALL_DEBUG_ENTER;
1718 CHKPF(keyEvent);
1719 if (sequences_.empty()) {
1720 MMI_HILOGD("No sequences configuration data");
1721 return false;
1722 }
1723
1724 if (!AddSequenceKey(keyEvent)) {
1725 MMI_HILOGD("Add new sequence key failed");
1726 return false;
1727 }
1728
1729 if (filterSequences_.empty()) {
1730 filterSequences_ = sequences_;
1731 }
1732
1733 bool isLaunchAbility = false;
1734 for (auto iter = filterSequences_.begin(); iter != filterSequences_.end();) {
1735 if (!HandleSequence((*iter), isLaunchAbility)) {
1736 filterSequences_.erase(iter);
1737 continue;
1738 }
1739 ++iter;
1740 }
1741
1742 if (filterSequences_.empty()) {
1743 MMI_HILOGW("no sequences matched");
1744 keys_.clear();
1745 return false;
1746 }
1747
1748 if (isLaunchAbility) {
1749 for (const auto& item : keys_) {
1750 if (IsSpecialType(item.keyCode, SpecialType::KEY_DOWN_ACTION)) {
1751 HandleSpecialKeys(item.keyCode, item.keyAction);
1752 }
1753 InputHandler->GetSubscriberHandler()->RemoveSubscriberKeyUpTimer(item.keyCode);
1754 RemoveSubscribedTimer(item.keyCode);
1755 }
1756 }
1757 return isLaunchAbility;
1758 }
1759
AddSequenceKey(const std::shared_ptr<KeyEvent> keyEvent)1760 bool KeyCommandHandler::AddSequenceKey(const std::shared_ptr<KeyEvent> keyEvent)
1761 {
1762 CALL_DEBUG_ENTER;
1763 CHKPF(keyEvent);
1764 SequenceKey sequenceKey;
1765 sequenceKey.keyCode = keyEvent->GetKeyCode();
1766 sequenceKey.keyAction = keyEvent->GetKeyAction();
1767 sequenceKey.actionTime = keyEvent->GetActionTime();
1768 size_t size = keys_.size();
1769 if (size > 0) {
1770 if (keys_[size - 1].actionTime > sequenceKey.actionTime) {
1771 MMI_HILOGE("The current event time is greater than the last event time");
1772 ResetSequenceKeys();
1773 return false;
1774 }
1775 if ((sequenceKey.actionTime - keys_[size - 1].actionTime) > MAX_DELAY_TIME) {
1776 MMI_HILOGD("The delay time is greater than the maximum delay time");
1777 ResetSequenceKeys();
1778 } else {
1779 if (IsRepeatKeyEvent(sequenceKey)) {
1780 MMI_HILOGD("This is a repeat key event, don't add");
1781 return false;
1782 }
1783 keys_[size - 1].delay = sequenceKey.actionTime - keys_[size - 1].actionTime;
1784 InterruptTimers();
1785 }
1786 }
1787 if (size > MAX_SEQUENCEKEYS_NUM) {
1788 MMI_HILOGD("The save key size more than the max size");
1789 return false;
1790 }
1791 keys_.push_back(sequenceKey);
1792 return true;
1793 }
1794
HandleSequence(Sequence & sequence,bool & isLaunchAbility)1795 bool KeyCommandHandler::HandleSequence(Sequence &sequence, bool &isLaunchAbility)
1796 {
1797 CALL_DEBUG_ENTER;
1798 size_t keysSize = keys_.size();
1799 size_t sequenceKeysSize = sequence.sequenceKeys.size();
1800
1801 if (!sequence.statusConfigValue) {
1802 return false;
1803 }
1804
1805 if (keysSize > sequenceKeysSize) {
1806 MMI_HILOGD("The save sequence not matching ability sequence");
1807 return false;
1808 }
1809
1810 for (size_t i = 0; i < keysSize; ++i) {
1811 if (keys_[i] != sequence.sequenceKeys[i]) {
1812 MMI_HILOGD("The keyCode or keyAction not matching");
1813 return false;
1814 }
1815 int64_t delay = sequence.sequenceKeys[i].delay;
1816 if (((i + 1) != keysSize) && (delay != 0) && (keys_[i].delay >= delay)) {
1817 MMI_HILOGD("Delay is not matching");
1818 return false;
1819 }
1820 }
1821
1822 if (keysSize == sequenceKeysSize) {
1823 if (sequence.abilityStartDelay == 0) {
1824 MMI_HILOGD("Start launch ability immediately");
1825 LaunchAbility(sequence);
1826 isLaunchAbility = true;
1827 return true;
1828 }
1829 sequence.timerId = TimerMgr->AddTimer(sequence.abilityStartDelay, 1, [this, sequence] () {
1830 MMI_HILOGD("Timer callback");
1831 LaunchAbility(sequence);
1832 });
1833 if (sequence.timerId < 0) {
1834 MMI_HILOGE("Add Timer failed");
1835 return false;
1836 }
1837 MMI_HILOGD("Add timer success");
1838 isLaunchAbility = true;
1839 }
1840 return true;
1841 }
1842
HandleMulFingersTap(const std::shared_ptr<PointerEvent> pointerEvent)1843 bool KeyCommandHandler::HandleMulFingersTap(const std::shared_ptr<PointerEvent> pointerEvent)
1844 {
1845 CALL_DEBUG_ENTER;
1846 if (pointerEvent->GetPointerAction() == PointerEvent::POINTER_ACTION_TRIPTAP) {
1847 MMI_HILOGI("The touchpad trip tap will launch ability");
1848 LaunchAbility(threeFingersTap_.ability, 0);
1849 return true;
1850 }
1851 return false;
1852 }
1853
IsKeyMatch(const ShortcutKey & shortcutKey,const std::shared_ptr<KeyEvent> & key)1854 bool KeyCommandHandler::IsKeyMatch(const ShortcutKey &shortcutKey, const std::shared_ptr<KeyEvent> &key)
1855 {
1856 CALL_DEBUG_ENTER;
1857 CHKPF(key);
1858 if ((key->GetKeyCode() != shortcutKey.finalKey) || (shortcutKey.triggerType != key->GetKeyAction())) {
1859 return false;
1860 }
1861 if ((shortcutKey.preKeys.size() + 1) != key->GetKeyItems().size()) {
1862 return false;
1863 }
1864 for (const auto &item : key->GetKeyItems()) {
1865 int32_t keyCode = item.GetKeyCode();
1866 if (SkipFinalKey(keyCode, key)) {
1867 continue;
1868 }
1869 if (shortcutKey.preKeys.find(keyCode) == shortcutKey.preKeys.end()) {
1870 return false;
1871 }
1872 }
1873 MMI_HILOGD("Leave, key matched");
1874 return true;
1875 }
1876
SkipFinalKey(const int32_t keyCode,const std::shared_ptr<KeyEvent> & key)1877 bool KeyCommandHandler::SkipFinalKey(const int32_t keyCode, const std::shared_ptr<KeyEvent> &key)
1878 {
1879 CHKPF(key);
1880 return keyCode == key->GetKeyCode();
1881 }
1882
HandleKeyDown(ShortcutKey & shortcutKey)1883 bool KeyCommandHandler::HandleKeyDown(ShortcutKey &shortcutKey)
1884 {
1885 CALL_DEBUG_ENTER;
1886 if (shortcutKey.keyDownDuration == 0) {
1887 MMI_HILOGD("Start launch ability immediately");
1888 LaunchAbility(shortcutKey);
1889 return true;
1890 }
1891 shortcutKey.timerId = TimerMgr->AddTimer(shortcutKey.keyDownDuration, 1, [this, shortcutKey] () {
1892 MMI_HILOGD("Timer callback");
1893 currentLaunchAbilityKey_ = shortcutKey;
1894 LaunchAbility(shortcutKey);
1895 });
1896 if (shortcutKey.timerId < 0) {
1897 MMI_HILOGE("Add Timer failed");
1898 return false;
1899 }
1900 MMI_HILOGD("Add timer success");
1901 lastMatchedKey_ = shortcutKey;
1902 if (InputHandler->GetSubscriberHandler()->IsKeyEventSubscribed(shortcutKey.finalKey, shortcutKey.triggerType)) {
1903 MMI_HILOGD("current shortcutKey %{public}d is subSubcribed", shortcutKey.finalKey);
1904 return false;
1905 }
1906 return true;
1907 }
1908
GetKeyDownDurationFromXml(const std::string & businessId)1909 int32_t KeyCommandHandler::GetKeyDownDurationFromXml(const std::string &businessId)
1910 {
1911 CALL_DEBUG_ENTER;
1912 return PreferencesMgr->GetShortKeyDuration(businessId);
1913 }
1914
HandleKeyUp(const std::shared_ptr<KeyEvent> & keyEvent,const ShortcutKey & shortcutKey)1915 bool KeyCommandHandler::HandleKeyUp(const std::shared_ptr<KeyEvent> &keyEvent, const ShortcutKey &shortcutKey)
1916 {
1917 CALL_DEBUG_ENTER;
1918 CHKPF(keyEvent);
1919 if (shortcutKey.keyDownDuration == 0) {
1920 MMI_HILOGD("Start launch ability immediately");
1921 LaunchAbility(shortcutKey);
1922 return true;
1923 }
1924 std::optional<KeyEvent::KeyItem> keyItem = keyEvent->GetKeyItem();
1925 if (!keyItem) {
1926 MMI_HILOGE("The keyItem is nullopt");
1927 return false;
1928 }
1929 auto upTime = keyEvent->GetActionTime();
1930 auto downTime = keyItem->GetDownTime();
1931 MMI_HILOGD("upTime:%{public}" PRId64 ",downTime:%{public}" PRId64 ",keyDownDuration:%{public}d",
1932 upTime, downTime, shortcutKey.keyDownDuration);
1933 if (upTime - downTime >= static_cast<int64_t>(shortcutKey.keyDownDuration) * 1000) {
1934 MMI_HILOGD("Skip, upTime - downTime >= duration");
1935 return false;
1936 }
1937 MMI_HILOGD("Start launch ability immediately");
1938 LaunchAbility(shortcutKey);
1939 return true;
1940 }
1941
HandleKeyCancel(ShortcutKey & shortcutKey)1942 bool KeyCommandHandler::HandleKeyCancel(ShortcutKey &shortcutKey)
1943 {
1944 CALL_DEBUG_ENTER;
1945 if (shortcutKey.timerId < 0) {
1946 MMI_HILOGE("Skip, timerid less than 0");
1947 }
1948 auto timerId = shortcutKey.timerId;
1949 shortcutKey.timerId = -1;
1950 TimerMgr->RemoveTimer(timerId);
1951 MMI_HILOGD("timerId:%{public}d", timerId);
1952 return false;
1953 }
1954
LaunchAbility(const Ability & ability,int64_t delay)1955 void KeyCommandHandler::LaunchAbility(const Ability &ability, int64_t delay)
1956 {
1957 CALL_DEBUG_ENTER;
1958 if (ability.bundleName.empty()) {
1959 MMI_HILOGW("BundleName is empty");
1960 return;
1961 }
1962 AAFwk::Want want;
1963 want.SetElementName(ability.deviceId, ability.bundleName, ability.abilityName);
1964 want.SetAction(ability.action);
1965 want.SetUri(ability.uri);
1966 want.SetType(ability.type);
1967 for (const auto &entity : ability.entities) {
1968 want.AddEntity(entity);
1969 }
1970 for (const auto &item : ability.params) {
1971 want.SetParam(item.first, item.second);
1972 }
1973 DfxHisysevent::CalcComboStartTimes(delay);
1974 DfxHisysevent::ReportComboStartTimes();
1975 MMI_HILOGD("Start launch ability, bundleName:%{public}s", ability.bundleName.c_str());
1976 ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want);
1977 if (err != ERR_OK) {
1978 MMI_HILOGE("LaunchAbility failed, bundleName:%{public}s, err:%{public}d", ability.bundleName.c_str(), err);
1979 }
1980 int32_t state = NapProcess::GetInstance()->GetNapClientPid();
1981 if (state == REMOVE_OBSERVER) {
1982 MMI_HILOGW("nap client status:%{public}d", state);
1983 return;
1984 }
1985 OHOS::MMI::NapProcess::NapStatusData napData;
1986 napData.pid = -1;
1987 napData.uid = -1;
1988 napData.bundleName = ability.bundleName;
1989 int32_t syncState = ACTIVE_EVENT;
1990 NapProcess::GetInstance()->AddMmiSubscribedEventData(napData, syncState);
1991 NapProcess::GetInstance()->NotifyBundleName(napData, syncState);
1992 MMI_HILOGD("End launch ability, bundleName:%{public}s", ability.bundleName.c_str());
1993 }
1994
LaunchAbility(const Ability & ability)1995 void KeyCommandHandler::LaunchAbility(const Ability &ability)
1996 {
1997 CALL_DEBUG_ENTER;
1998 AAFwk::Want want;
1999 want.SetElementName(ability.deviceId, ability.bundleName, ability.abilityName);
2000 want.SetAction(ability.action);
2001 want.SetUri(ability.uri);
2002 want.SetType(ability.uri);
2003 for (const auto &entity : ability.entities) {
2004 want.AddEntity(entity);
2005 }
2006 for (const auto &item : ability.params) {
2007 want.SetParam(item.first, item.second);
2008 }
2009
2010 MMI_HILOGD("Start launch ability, bundleName:%{public}s", ability.bundleName.c_str());
2011 if (ability.abilityType == EXTENSION_ABILITY) {
2012 ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility(want, nullptr);
2013 if (err != ERR_OK) {
2014 MMI_HILOGE("LaunchAbility failed, bundleName:%{public}s, err:%{public}d", ability.bundleName.c_str(), err);
2015 }
2016 } else {
2017 ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want);
2018 if (err != ERR_OK) {
2019 MMI_HILOGE("LaunchAbility failed, bundleName:%{public}s, err:%{public}d", ability.bundleName.c_str(), err);
2020 }
2021 }
2022
2023 MMI_HILOGD("End launch ability, bundleName:%{public}s", ability.bundleName.c_str());
2024 }
2025
LaunchAbility(const ShortcutKey & key)2026 void KeyCommandHandler::LaunchAbility(const ShortcutKey &key)
2027 {
2028 CALL_INFO_TRACE;
2029 LaunchAbility(key.ability, lastMatchedKey_.keyDownDuration);
2030 ResetLastMatchedKey();
2031 }
2032
LaunchAbility(const Sequence & sequence)2033 void KeyCommandHandler::LaunchAbility(const Sequence &sequence)
2034 {
2035 CALL_INFO_TRACE;
2036 LaunchAbility(sequence.ability, sequence.abilityStartDelay);
2037 }
2038
Print() const2039 void ShortcutKey::Print() const
2040 {
2041 for (const auto &prekey: preKeys) {
2042 MMI_HILOGI("Eventkey matched, preKey:%{public}d", prekey);
2043 }
2044 MMI_HILOGD("Eventkey matched, finalKey:%{public}d, bundleName:%{public}s",
2045 finalKey, ability.bundleName.c_str());
2046 }
2047
RemoveSubscribedTimer(int32_t keyCode)2048 void KeyCommandHandler::RemoveSubscribedTimer(int32_t keyCode)
2049 {
2050 CALL_DEBUG_ENTER;
2051 auto iter = specialTimers_.find(keyCode);
2052 if (iter != specialTimers_.end()) {
2053 for (auto& item : iter->second) {
2054 TimerMgr->RemoveTimer(item);
2055 }
2056 specialTimers_.erase(keyCode);
2057 MMI_HILOGD("Remove timer success");
2058 }
2059 }
2060
HandleSpecialKeys(int32_t keyCode,int32_t keyAction)2061 void KeyCommandHandler::HandleSpecialKeys(int32_t keyCode, int32_t keyAction)
2062 {
2063 CALL_DEBUG_ENTER;
2064 auto iter = specialKeys_.find(keyCode);
2065 if (keyAction == KeyEvent::KEY_ACTION_UP) {
2066 if (iter != specialKeys_.end()) {
2067 specialKeys_.erase(iter);
2068 return;
2069 }
2070 }
2071
2072 if (keyAction == KeyEvent::KEY_ACTION_DOWN) {
2073 if (iter == specialKeys_.end()) {
2074 auto it = specialKeys_.emplace(keyCode, keyAction);
2075 if (!it.second) {
2076 MMI_HILOGD("KeyCode duplicated");
2077 return;
2078 }
2079 }
2080 }
2081 }
2082
InterruptTimers()2083 void KeyCommandHandler::InterruptTimers()
2084 {
2085 for (Sequence& item : filterSequences_) {
2086 if (item.timerId >= 0) {
2087 MMI_HILOGD("The key sequence change, close the timer");
2088 TimerMgr->RemoveTimer(item.timerId);
2089 item.timerId = -1;
2090 }
2091 }
2092 }
2093
UpdateSettingsXml(const std::string & businessId,int32_t delay)2094 int32_t KeyCommandHandler::UpdateSettingsXml(const std::string &businessId, int32_t delay)
2095 {
2096 CALL_DEBUG_ENTER;
2097 if (businessId.empty() || businessIds_.empty()) {
2098 MMI_HILOGE("businessId or businessIds_ is empty");
2099 return COMMON_PARAMETER_ERROR;
2100 }
2101 if (std::find(businessIds_.begin(), businessIds_.end(), businessId) == businessIds_.end()) {
2102 MMI_HILOGE("%{public}s not in the config file", businessId.c_str());
2103 return COMMON_PARAMETER_ERROR;
2104 }
2105 if (delay < MIN_SHORT_KEY_DOWN_DURATION || delay > MAX_SHORT_KEY_DOWN_DURATION) {
2106 MMI_HILOGE("delay is not in valid range.");
2107 return COMMON_PARAMETER_ERROR;
2108 }
2109 return PreferencesMgr->SetShortKeyDuration(businessId, delay);
2110 }
2111
GetSingleKnuckleGesture()2112 KnuckleGesture KeyCommandHandler::GetSingleKnuckleGesture()
2113 {
2114 return singleKnuckleGesture_;
2115 }
GetDoubleKnuckleGesture()2116 KnuckleGesture KeyCommandHandler::GetDoubleKnuckleGesture()
2117 {
2118 return doubleKnuckleGesture_;
2119 }
SetKnuckleDoubleTapIntervalTime(int64_t interval)2120 void KeyCommandHandler::SetKnuckleDoubleTapIntervalTime(int64_t interval)
2121 {
2122 CALL_DEBUG_ENTER;
2123 if (interval < 0) {
2124 MMI_HILOGE("invalid interval time:%{public}" PRId64 "", interval);
2125 return;
2126 }
2127 downToPrevUpTimeConfig_ = interval;
2128 }
SetKnuckleDoubleTapDistance(float distance)2129 void KeyCommandHandler::SetKnuckleDoubleTapDistance(float distance)
2130 {
2131 CALL_DEBUG_ENTER;
2132 if (distance <= std::numeric_limits<float>::epsilon()) {
2133 MMI_HILOGE("invalid distance:%{public}f", distance);
2134 return;
2135 }
2136 downToPrevDownDistanceConfig_ = distance;
2137 }
2138 } // namespace MMI
2139 } // namespace OHOS