1 /*
2 * Copyright (c) 2021-2022 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 "keyboard_inject.h"
17
18 #include "mmi_log.h"
19
20 #undef MMI_LOG_TAG
21 #define MMI_LOG_TAG "keyBoardInject"
22
23 using namespace OHOS::HiviewDFX;
24 namespace OHOS {
25 namespace MMI {
26 namespace {
27 std::shared_ptr<KeyboardInject> g_instance = nullptr;
28 constexpr int32_t INPUT_KEY_BACK { 2 };
29 constexpr int32_t LINUX_KEY_BACK { 158 };
30 } // namespace
31 std::mutex KeyboardInject::mutex_;
32 std::unique_ptr<VirtualKeyboard> g_pKeyboard = nullptr;
33 std::unique_ptr<InjectThread> KeyboardInject::injectThread_ = nullptr;
34
KeyboardInject()35 KeyboardInject::KeyboardInject()
36 {
37 std::lock_guard<std::mutex> keyboardLock(mutex_);
38 auto it = keyCodeMap_.find(INPUT_KEY_BACK);
39 if (it == keyCodeMap_.end()) {
40 auto ret = keyCodeMap_.insert(std::make_pair(INPUT_KEY_BACK, LINUX_KEY_BACK));
41 MMI_HILOGD("ret.second:%{public}d", ret.second);
42 }
43 injectThread_ = std::make_unique<InjectThread>();
44 g_pKeyboard = std::make_unique<VirtualKeyboard>();
45 g_pKeyboard->SetUp();
46 }
47
~KeyboardInject()48 KeyboardInject::~KeyboardInject() {}
49
InjectKeyEvent(uint16_t code,uint32_t value) const50 void KeyboardInject::InjectKeyEvent(uint16_t code, uint32_t value) const
51 {
52 std::lock_guard<std::mutex> keyboardLock(mutex_);
53 auto it = keyCodeMap_.find(code);
54 if (it == keyCodeMap_.end()) {
55 return;
56 }
57 InjectInputEvent injectInputEvent = { injectThread_->KEYBOARD_DEVICE_ID, EV_KEY, it->second, value };
58 injectThread_->WaitFunc(injectInputEvent);
59 InjectInputEvent injectInputSync = { injectThread_->KEYBOARD_DEVICE_ID, EV_SYN, SYN_REPORT, 0 };
60 injectThread_->WaitFunc(injectInputSync);
61 }
62 } // namespace MMI
63 } // namespace OHOS
64