summaryrefslogtreecommitdiff
path: root/services/inputflinger/tests/FakeWindows.h
blob: 54dc25aaa07bcb02d6a37578de7bf90626bf976e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*
 * Copyright 2024 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include "../dispatcher/InputDispatcher.h"
#include "TestEventMatchers.h"

#include <android-base/logging.h>
#include <gtest/gtest.h>
#include <input/Input.h>
#include <input/InputConsumer.h>

namespace android {

/**
 * If we expect to receive the event, the timeout can be made very long. When the test are running
 * correctly, we will actually never wait until the end of the timeout because the wait will end
 * when the event comes in. Still, this value shouldn't be infinite. During development, a local
 * change may cause the test to fail. This timeout should be short enough to not annoy so that the
 * developer can see the failure quickly (on human scale).
 */
static constexpr std::chrono::duration CONSUME_TIMEOUT_EVENT_EXPECTED = 1000ms;

/**
 * When no event is expected, we can have a very short timeout. A large value here would slow down
 * the tests. In the unlikely event of system being too slow, the event may still be present but the
 * timeout would complete before it is consumed. This would result in test flakiness. If this
 * occurs, the flakiness rate would be high. Since the flakes are treated with high priority, this
 * would get noticed and addressed quickly.
 */
static constexpr std::chrono::duration CONSUME_TIMEOUT_NO_EVENT_EXPECTED = 10ms;

/**
 * The default pid and uid for windows created on the primary display by the test.
 */
static constexpr gui::Pid WINDOW_PID{999};
static constexpr gui::Uid WINDOW_UID{1001};

/**
 * Default input dispatching timeout if there is no focused application or paused window
 * from which to determine an appropriate dispatching timeout.
 */
static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
        android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
        android::base::HwTimeoutMultiplier());

// --- FakeInputReceiver ---

class FakeInputReceiver {
public:
    explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name);

    std::unique_ptr<InputEvent> consume(std::chrono::milliseconds timeout, bool handled = false);
    /**
     * Receive an event without acknowledging it.
     * Return the sequence number that could later be used to send finished signal.
     */
    std::pair<std::optional<uint32_t>, std::unique_ptr<InputEvent>> receiveEvent(
            std::chrono::milliseconds timeout);
    /**
     * To be used together with "receiveEvent" to complete the consumption of an event.
     */
    void finishEvent(uint32_t consumeSeq, bool handled = true);

    void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline);

    void consumeEvent(android::InputEventType expectedEventType, int32_t expectedAction,
                      std::optional<ui::LogicalDisplayId> expectedDisplayId,
                      std::optional<int32_t> expectedFlags);

    std::unique_ptr<MotionEvent> consumeMotion();
    void consumeMotionEvent(const ::testing::Matcher<MotionEvent>& matcher);

    void consumeFocusEvent(bool hasFocus, bool inTouchMode);
    void consumeCaptureEvent(bool hasCapture);
    void consumeDragEvent(bool isExiting, float x, float y);
    void consumeTouchModeEvent(bool inTouchMode);

    void assertNoEvents(std::chrono::milliseconds timeout);

    sp<IBinder> getToken();
    int getChannelFd();

private:
    InputConsumer mConsumer;
    DynamicInputEventFactory mEventFactory;
    std::string mName;
};

// --- FakeWindowHandle ---

class FakeWindowHandle : public gui::WindowInfoHandle {
public:
    static const int32_t WIDTH = 600;
    static const int32_t HEIGHT = 800;
    using InputConfig = gui::WindowInfo::InputConfig;

    // This is a callback that is fired when an event is received by the window.
    // It is static to avoid having to pass it individually into all of the FakeWindowHandles
    // created by tests.
    // TODO(b/210460522): Update the tests to use a factory pattern so that we can avoid
    //   the need to make this static.
    static std::function<void(const std::unique_ptr<InputEvent>&, const gui::WindowInfo&)>
            sOnEventReceivedCallback;

    FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
                     const std::unique_ptr<inputdispatcher::InputDispatcher>& dispatcher,
                     const std::string name, ui::LogicalDisplayId displayId,
                     bool createInputChannel = true);

    sp<FakeWindowHandle> clone(ui::LogicalDisplayId displayId);

    inline void setTouchable(bool touchable) {
        mInfo.setInputConfig(InputConfig::NOT_TOUCHABLE, !touchable);
    }

    inline void setFocusable(bool focusable) {
        mInfo.setInputConfig(InputConfig::NOT_FOCUSABLE, !focusable);
    }

    inline void setVisible(bool visible) {
        mInfo.setInputConfig(InputConfig::NOT_VISIBLE, !visible);
    }

    inline void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
        mInfo.dispatchingTimeout = timeout;
    }

    inline void setPaused(bool paused) {
        mInfo.setInputConfig(InputConfig::PAUSE_DISPATCHING, paused);
    }

    inline void setSlippery(bool slippery) {
        mInfo.setInputConfig(InputConfig::SLIPPERY, slippery);
    }

    inline void setWatchOutsideTouch(bool watchOutside) {
        mInfo.setInputConfig(InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
    }

    inline void setSpy(bool spy) { mInfo.setInputConfig(InputConfig::SPY, spy); }

    inline void setSecure(bool secure) {
        if (secure) {
            mInfo.layoutParamsFlags |= gui::WindowInfo::Flag::SECURE;
        } else {
            using namespace ftl::flag_operators;
            mInfo.layoutParamsFlags &= ~gui::WindowInfo::Flag::SECURE;
        }
        mInfo.setInputConfig(InputConfig::SENSITIVE_FOR_PRIVACY, secure);
    }

    inline void setInterceptsStylus(bool interceptsStylus) {
        mInfo.setInputConfig(InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
    }

    inline void setDropInput(bool dropInput) {
        mInfo.setInputConfig(InputConfig::DROP_INPUT, dropInput);
    }

    inline void setDropInputIfObscured(bool dropInputIfObscured) {
        mInfo.setInputConfig(InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
    }

    inline void setNoInputChannel(bool noInputChannel) {
        mInfo.setInputConfig(InputConfig::NO_INPUT_CHANNEL, noInputChannel);
    }

    inline void setDisableUserActivity(bool disableUserActivity) {
        mInfo.setInputConfig(InputConfig::DISABLE_USER_ACTIVITY, disableUserActivity);
    }

    inline void setGlobalStylusBlocksTouch(bool shouldGlobalStylusBlockTouch) {
        mInfo.setInputConfig(InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH, shouldGlobalStylusBlockTouch);
    }

    inline void setAlpha(float alpha) { mInfo.alpha = alpha; }

    inline void setTouchOcclusionMode(gui::TouchOcclusionMode mode) {
        mInfo.touchOcclusionMode = mode;
    }

    inline void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }

    inline void setFrame(const Rect& frame,
                         const ui::Transform& displayTransform = ui::Transform()) {
        mInfo.frame = frame;
        mInfo.touchableRegion.clear();
        mInfo.addTouchableRegion(frame);

        const Rect logicalDisplayFrame = displayTransform.transform(frame);
        ui::Transform translate;
        translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
        mInfo.transform = translate * displayTransform;
    }

    inline void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }

    inline void setIsWallpaper(bool isWallpaper) {
        mInfo.setInputConfig(InputConfig::IS_WALLPAPER, isWallpaper);
    }

    inline void setDupTouchToWallpaper(bool hasWallpaper) {
        mInfo.setInputConfig(InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
    }

    inline void setTrustedOverlay(bool trustedOverlay) {
        mInfo.setInputConfig(InputConfig::TRUSTED_OVERLAY, trustedOverlay);
    }

    inline void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
        mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
    }

    inline void setWindowScale(float xScale, float yScale) {
        setWindowTransform(xScale, 0, 0, yScale);
    }

    inline void setWindowOffset(float offsetX, float offsetY) {
        mInfo.transform.set(offsetX, offsetY);
    }

    std::unique_ptr<KeyEvent> consumeKey(bool handled = true);

    inline std::unique_ptr<KeyEvent> consumeKeyEvent(const ::testing::Matcher<KeyEvent>& matcher) {
        std::unique_ptr<KeyEvent> keyEvent = consumeKey();
        EXPECT_NE(nullptr, keyEvent);
        if (!keyEvent) {
            return nullptr;
        }
        EXPECT_THAT(*keyEvent, matcher);
        return keyEvent;
    }

    inline void consumeKeyDown(ui::LogicalDisplayId expectedDisplayId, int32_t expectedFlags = 0) {
        consumeKeyEvent(testing::AllOf(WithKeyAction(AKEY_EVENT_ACTION_DOWN),
                                       WithDisplayId(expectedDisplayId), WithFlags(expectedFlags)));
    }

    inline void consumeKeyUp(ui::LogicalDisplayId expectedDisplayId, int32_t expectedFlags = 0) {
        consumeKeyEvent(testing::AllOf(WithKeyAction(AKEY_EVENT_ACTION_UP),
                                       WithDisplayId(expectedDisplayId), WithFlags(expectedFlags)));
    }

    inline void consumeMotionCancel(
            ui::LogicalDisplayId expectedDisplayId = ui::LogicalDisplayId::DEFAULT,
            int32_t expectedFlags = 0) {
        consumeMotionEvent(testing::AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
                                          WithDisplayId(expectedDisplayId),
                                          WithFlags(expectedFlags | AMOTION_EVENT_FLAG_CANCELED)));
    }

    inline void consumeMotionMove(
            ui::LogicalDisplayId expectedDisplayId = ui::LogicalDisplayId::DEFAULT,
            int32_t expectedFlags = 0) {
        consumeMotionEvent(testing::AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
                                          WithDisplayId(expectedDisplayId),
                                          WithFlags(expectedFlags)));
    }

    inline void consumeMotionDown(
            ui::LogicalDisplayId expectedDisplayId = ui::LogicalDisplayId::DEFAULT,
            int32_t expectedFlags = 0) {
        consumeAnyMotionDown(expectedDisplayId, expectedFlags);
    }

    inline void consumeAnyMotionDown(
            std::optional<ui::LogicalDisplayId> expectedDisplayId = std::nullopt,
            std::optional<int32_t> expectedFlags = std::nullopt) {
        consumeMotionEvent(
                testing::AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
                               testing::Conditional(expectedDisplayId.has_value(),
                                                    WithDisplayId(*expectedDisplayId), testing::_),
                               testing::Conditional(expectedFlags.has_value(),
                                                    WithFlags(*expectedFlags), testing::_)));
    }

    inline void consumeMotionPointerDown(
            int32_t pointerIdx,
            ui::LogicalDisplayId expectedDisplayId = ui::LogicalDisplayId::DEFAULT,
            int32_t expectedFlags = 0) {
        const int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
                (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
        consumeMotionEvent(testing::AllOf(WithMotionAction(action),
                                          WithDisplayId(expectedDisplayId),
                                          WithFlags(expectedFlags)));
    }

    inline void consumeMotionPointerDown(int32_t pointerIdx,
                                         const ::testing::Matcher<MotionEvent>& matcher) {
        const int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
                (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
        consumeMotionEvent(testing::AllOf(WithMotionAction(action), matcher));
    }

    inline void consumeMotionPointerUp(int32_t pointerIdx,
                                       const ::testing::Matcher<MotionEvent>& matcher) {
        const int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
                (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
        consumeMotionEvent(testing::AllOf(WithMotionAction(action), matcher));
    }

    inline void consumeMotionUp(
            ui::LogicalDisplayId expectedDisplayId = ui::LogicalDisplayId::DEFAULT,
            int32_t expectedFlags = 0) {
        consumeMotionEvent(testing::AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
                                          WithDisplayId(expectedDisplayId),
                                          WithFlags(expectedFlags)));
    }

    inline void consumeMotionOutside(
            ui::LogicalDisplayId expectedDisplayId = ui::LogicalDisplayId::DEFAULT,
            int32_t expectedFlags = 0) {
        consumeMotionEvent(testing::AllOf(WithMotionAction(AMOTION_EVENT_ACTION_OUTSIDE),
                                          WithDisplayId(expectedDisplayId),
                                          WithFlags(expectedFlags)));
    }

    inline void consumeMotionOutsideWithZeroedCoords() {
        consumeMotionEvent(testing::AllOf(WithMotionAction(AMOTION_EVENT_ACTION_OUTSIDE),
                                          WithRawCoords(0, 0)));
    }

    inline void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
        ASSERT_NE(mInputReceiver, nullptr)
                << "Cannot consume events from a window with no receiver";
        mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
    }

    inline void consumeCaptureEvent(bool hasCapture) {
        ASSERT_NE(mInputReceiver, nullptr)
                << "Cannot consume events from a window with no receiver";
        mInputReceiver->consumeCaptureEvent(hasCapture);
    }

    std::unique_ptr<MotionEvent> consumeMotionEvent(
            const ::testing::Matcher<MotionEvent>& matcher = testing::_);

    inline void consumeDragEvent(bool isExiting, float x, float y) {
        mInputReceiver->consumeDragEvent(isExiting, x, y);
    }

    inline void consumeTouchModeEvent(bool inTouchMode) {
        ASSERT_NE(mInputReceiver, nullptr)
                << "Cannot consume events from a window with no receiver";
        mInputReceiver->consumeTouchModeEvent(inTouchMode);
    }

    inline std::pair<std::optional<uint32_t>, std::unique_ptr<InputEvent>> receiveEvent() {
        return receive();
    }

    inline void finishEvent(uint32_t sequenceNum) {
        ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
        mInputReceiver->finishEvent(sequenceNum);
    }

    inline void sendTimeline(int32_t inputEventId,
                             std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
        ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
        mInputReceiver->sendTimeline(inputEventId, timeline);
    }

    void assertNoEvents(std::optional<std::chrono::milliseconds> timeout = {});

    inline sp<IBinder> getToken() { return mInfo.token; }

    inline const std::string& getName() { return mName; }

    inline void setOwnerInfo(gui::Pid ownerPid, gui::Uid ownerUid) {
        mInfo.ownerPid = ownerPid;
        mInfo.ownerUid = ownerUid;
    }

    inline gui::Pid getPid() const { return mInfo.ownerPid; }

    inline void destroyReceiver() { mInputReceiver = nullptr; }

    inline int getChannelFd() { return mInputReceiver->getChannelFd(); }

    // FakeWindowHandle uses this consume method to ensure received events are added to the trace.
    std::unique_ptr<InputEvent> consume(std::chrono::milliseconds timeout, bool handled = true);

private:
    FakeWindowHandle(std::string name) : mName(name){};
    const std::string mName;
    std::shared_ptr<FakeInputReceiver> mInputReceiver;
    static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
    friend class sp<FakeWindowHandle>;

    // FakeWindowHandle uses this receive method to ensure received events are added to the trace.
    std::pair<std::optional<uint32_t /*seq*/>, std::unique_ptr<InputEvent>> receive();
};

} // namespace android