blob: c42f896ce0b9981e5bdfb416497e1f1be44edc95 [file] [log] [blame]
Prabir Pradhanbb7a0202024-02-10 02:09:01 +00001/*
2 * Copyright 2024 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#pragma once
18
19#include "InputTracingPerfettoBackend.h"
20
21#include <android-base/thread_annotations.h>
22#include <mutex>
23#include <thread>
24#include <variant>
25#include <vector>
26
27namespace android::inputdispatcher::trace::impl {
28
29/**
30 * A wrapper around an InputTracingBackend implementation that writes to the inner tracing backend
31 * from a single new thread that it creates. The new tracing thread is started when the
32 * ThreadedBackend is created, and is stopped when it is destroyed. The ThreadedBackend is
33 * thread-safe.
34 */
35template <typename Backend>
36class ThreadedBackend : public InputTracingBackendInterface {
37public:
38 ThreadedBackend(Backend&& innerBackend);
39 ~ThreadedBackend() override;
40
41 void traceKeyEvent(const TracedKeyEvent&) override;
42 void traceMotionEvent(const TracedMotionEvent&) override;
43 void traceWindowDispatch(const WindowDispatchArgs&) override;
44
45private:
46 std::mutex mLock;
47 std::thread mTracerThread;
48 bool mThreadExit GUARDED_BY(mLock){false};
49 std::condition_variable mThreadWakeCondition;
50 Backend mBackend;
51 std::vector<std::variant<TracedKeyEvent, TracedMotionEvent, WindowDispatchArgs>> mQueue
52 GUARDED_BY(mLock);
53
54 using WindowDispatchArgs = InputTracingBackendInterface::WindowDispatchArgs;
55
56 void threadLoop();
57};
58
59} // namespace android::inputdispatcher::trace::impl