1 /*
2  * Copyright (c) 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 "inject_thread.h"
17 #include <sys/prctl.h>
18 #include <hdf_log.h>
19 
20 #define HDF_LOG_TAG inject_thread
21 
22 namespace OHOS {
23 namespace ExternalDeviceManager {
InjectThread(std::shared_ptr<VirtualDevice> virtualDevice)24 InjectThread::InjectThread(std::shared_ptr<VirtualDevice> virtualDevice)
25 {
26     virtualDevice_ = virtualDevice;
27     threadRun_ = true;
28 }
29 
~InjectThread()30 InjectThread::~InjectThread()
31 {
32     threadRun_ = false;
33     conditionVariable_.notify_all();
34     if (thread_.joinable()) {
35         thread_.join();
36     }
37 }
38 
Start()39 void InjectThread::Start()
40 {
41     thread_ = std::thread([this] {this->RunThread(this);});
42     pthread_setname_np(thread_.native_handle(), "emitEvent");
43 }
44 
RunThread(void * param)45 void InjectThread::RunThread(void *param)
46 {
47     InjectThread *thread = reinterpret_cast<InjectThread *>(param);
48     if (thread != nullptr) {
49         thread->InjectFunc();
50     } else {
51         HDF_LOGE("%{public}s: thread is nullptr", __func__);
52     }
53 }
54 
InjectFunc()55 void InjectThread::InjectFunc()
56 {
57     prctl(PR_SET_NAME, "ExternalDeviceManager-inject");
58     std::unique_lock<std::mutex> uniqueLock(mutex_);
59     while (threadRun_) {
60         conditionVariable_.wait(uniqueLock, [this] {
61             return (injectQueue_.size() > 0 || !threadRun_);
62         });
63         for (auto &event : injectQueue_) {
64             virtualDevice_->EmitEvent(event.type, event.code, event.value);
65         }
66         injectQueue_.clear();
67     }
68 }
69 
WaitFunc(const std::vector<Hid_EmitItem> & items)70 void InjectThread::WaitFunc(const std::vector<Hid_EmitItem> &items)
71 {
72     std::lock_guard<std::mutex> lockGuard(mutex_);
73     injectQueue_.insert(injectQueue_.begin(), items.begin(), items.end());
74     conditionVariable_.notify_one();
75 }
76 
Stop()77 void InjectThread::Stop()
78 {
79     {
80         std::lock_guard<std::mutex> lockGuard(mutex_);
81         threadRun_ = false;
82     }
83     conditionVariable_.notify_all();
84 }
85 } // namespace ExternalDeviceManager
86 } // namespace OHOS