blob: 74d7a144aacb301e10f40f2f4bd965e8f4a3cb15 [file] [log] [blame]
Kartar Singh17e57592024-12-09 08:05:401// Copyright 2024 The Chromium Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/android/scoped_input_event.h"
6
7#include "base/android/build_info.h"
8#include "base/check.h"
9#include "base/notreached.h"
10
11namespace base::android {
12
13// The class calls AInputEvent_release which was added only in Android S(31).
14#ifndef SCOPED_INPUT_EVENT_MIN_API
15#define SCOPED_INPUT_EVENT_MIN_API 31
16#endif
17
18ScopedInputEvent::ScopedInputEvent(const AInputEvent* event) {
19 CHECK(base::android::BuildInfo::GetInstance()->sdk_int() >=
20 SCOPED_INPUT_EVENT_MIN_API);
21 CHECK(event);
22 a_input_event_ = event;
23}
24
25ScopedInputEvent::~ScopedInputEvent() {
26 DestroyIfNeeded();
27}
28
29ScopedInputEvent::ScopedInputEvent(ScopedInputEvent&& other)
30 : a_input_event_(other.a_input_event_) {
31 other.a_input_event_ = nullptr;
32}
33
34ScopedInputEvent& ScopedInputEvent::operator=(ScopedInputEvent&& other) {
35 if (this != &other) {
36 DestroyIfNeeded();
37 a_input_event_ = other.a_input_event_;
38 other.a_input_event_ = nullptr;
39 }
40 return *this;
41}
42
Kartar Singhd7f0b3142025-03-28 21:18:2843void ScopedInputEvent::WriteIntoTrace(
44 perfetto::TracedProto<perfetto::protos::pbzero::EventForwarder> forwarder)
45 const {
46 if (!a_input_event_) {
47 return;
48 }
49
50 const int history_size =
51 static_cast<const int>(AMotionEvent_getHistorySize(a_input_event_));
52 forwarder->set_history_size(history_size);
53
54 forwarder->set_latest_time_ns(AMotionEvent_getEventTime(a_input_event_));
55 if (history_size > 0) {
56 forwarder->set_oldest_time_ns(AMotionEvent_getHistoricalEventTime(
57 a_input_event_, /* history_index= */ 0));
58 }
59 forwarder->set_down_time_ns(AMotionEvent_getDownTime(a_input_event_));
60
61 forwarder->set_x_pixel(
62 AMotionEvent_getX(a_input_event_, /* pointer_index= */ 0));
63 forwarder->set_y_pixel(
64 AMotionEvent_getY(a_input_event_, /* pointer_index= */ 0));
65
66 const int action =
67 AMotionEvent_getAction(a_input_event_) & AMOTION_EVENT_ACTION_MASK;
68 forwarder->set_action(
69 static_cast<perfetto::protos::pbzero::EventForwarder::AMotionEventAction>(
70 action));
71}
Kartar Singhd7f0b3142025-03-28 21:18:2872
Kartar Singh17e57592024-12-09 08:05:4073void ScopedInputEvent::DestroyIfNeeded() {
74 if (a_input_event_ == nullptr) {
75 return;
76 }
77 // If check to suppress the compiler warning.
78 if (__builtin_available(android SCOPED_INPUT_EVENT_MIN_API, *)) {
79 AInputEvent_release(a_input_event_);
80 a_input_event_ = nullptr;
81 return;
82 }
83 NOTREACHED();
84}
85
86} // namespace base::android