blob: 10d2fe4ee62a16a697272c0c82d88c48967b7d2b [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:2843#if BUILDFLAG(ENABLE_BASE_TRACING)
44void ScopedInputEvent::WriteIntoTrace(
45 perfetto::TracedProto<perfetto::protos::pbzero::EventForwarder> forwarder)
46 const {
47 if (!a_input_event_) {
48 return;
49 }
50
51 const int history_size =
52 static_cast<const int>(AMotionEvent_getHistorySize(a_input_event_));
53 forwarder->set_history_size(history_size);
54
55 forwarder->set_latest_time_ns(AMotionEvent_getEventTime(a_input_event_));
56 if (history_size > 0) {
57 forwarder->set_oldest_time_ns(AMotionEvent_getHistoricalEventTime(
58 a_input_event_, /* history_index= */ 0));
59 }
60 forwarder->set_down_time_ns(AMotionEvent_getDownTime(a_input_event_));
61
62 forwarder->set_x_pixel(
63 AMotionEvent_getX(a_input_event_, /* pointer_index= */ 0));
64 forwarder->set_y_pixel(
65 AMotionEvent_getY(a_input_event_, /* pointer_index= */ 0));
66
67 const int action =
68 AMotionEvent_getAction(a_input_event_) & AMOTION_EVENT_ACTION_MASK;
69 forwarder->set_action(
70 static_cast<perfetto::protos::pbzero::EventForwarder::AMotionEventAction>(
71 action));
72}
73#endif // BUILDFLAG(ENABLE_BASE_TRACING)
74
Kartar Singh17e57592024-12-09 08:05:4075void ScopedInputEvent::DestroyIfNeeded() {
76 if (a_input_event_ == nullptr) {
77 return;
78 }
79 // If check to suppress the compiler warning.
80 if (__builtin_available(android SCOPED_INPUT_EVENT_MIN_API, *)) {
81 AInputEvent_release(a_input_event_);
82 a_input_event_ = nullptr;
83 return;
84 }
85 NOTREACHED();
86}
87
88} // namespace base::android