1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "InputThread.h"
18
19 #include <android-base/logging.h>
20 #include <com_android_input_flags.h>
21 #include <processgroup/processgroup.h>
22
23 namespace android {
24
25 namespace input_flags = com::android::input::flags;
26
27 namespace {
28
applyInputEventProfile(const Thread & thread)29 bool applyInputEventProfile(const Thread& thread) {
30 #if defined(__ANDROID__)
31 return SetTaskProfiles(thread.getTid(), {"InputPolicy"});
32 #else
33 // Since thread information is not available and there's no benefit of
34 // applying the task profile on host, return directly.
35 return true;
36 #endif
37 }
38
39 // Implementation of Thread from libutils.
40 class InputThreadImpl : public Thread {
41 public:
InputThreadImpl(std::function<void ()> loop)42 explicit InputThreadImpl(std::function<void()> loop)
43 : Thread(/* canCallJava */ true), mThreadLoop(loop) {}
44
~InputThreadImpl()45 ~InputThreadImpl() {}
46
47 private:
48 std::function<void()> mThreadLoop;
49
threadLoop()50 bool threadLoop() override {
51 mThreadLoop();
52 return true;
53 }
54 };
55
56 } // namespace
57
InputThread(std::string name,std::function<void ()> loop,std::function<void ()> wake,bool isInCriticalPath)58 InputThread::InputThread(std::string name, std::function<void()> loop, std::function<void()> wake,
59 bool isInCriticalPath)
60 : mThreadWake(wake) {
61 mThread = sp<InputThreadImpl>::make(loop);
62 mThread->run(name.c_str(), ANDROID_PRIORITY_URGENT_DISPLAY);
63 if (input_flags::enable_input_policy_profile() && isInCriticalPath) {
64 if (!applyInputEventProfile(*mThread)) {
65 LOG(ERROR) << "Couldn't apply input policy profile for " << name;
66 }
67 }
68 }
69
~InputThread()70 InputThread::~InputThread() {
71 mThread->requestExit();
72 if (mThreadWake) {
73 mThreadWake();
74 }
75 mThread->requestExitAndWait();
76 }
77
isCallingThread()78 bool InputThread::isCallingThread() {
79 #if defined(__ANDROID__)
80 return gettid() == mThread->getTid();
81 #else
82 // Assume that the caller is doing everything correctly,
83 // since thread information is not available on host
84 return false;
85 #endif
86 }
87
88 } // namespace android
89