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