summaryrefslogtreecommitdiff
path: root/quickstep/src/com/android/quickstep/GestureState.java
blob: c2d8c6214eb31a0d4f5e890efdb95c263439bef2 (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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/*
 * Copyright (C) 2019 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.
 */
package com.android.quickstep;

import static android.app.ActivityTaskManager.INVALID_TASK_ID;

import static com.android.launcher3.MotionEventsUtils.isTrackpadFourFingerSwipe;
import static com.android.launcher3.MotionEventsUtils.isTrackpadThreeFingerSwipe;
import static com.android.launcher3.logging.StatsLogManager.LAUNCHER_STATE_ALLAPPS;
import static com.android.launcher3.logging.StatsLogManager.LAUNCHER_STATE_BACKGROUND;
import static com.android.launcher3.logging.StatsLogManager.LAUNCHER_STATE_HOME;
import static com.android.launcher3.logging.StatsLogManager.LAUNCHER_STATE_OVERVIEW;
import static com.android.quickstep.MultiStateCallback.DEBUG_STATES;
import static com.android.quickstep.util.ActiveGestureErrorDetector.GestureEvent.SET_END_TARGET;
import static com.android.quickstep.util.ActiveGestureErrorDetector.GestureEvent.SET_END_TARGET_ALL_APPS;
import static com.android.quickstep.util.ActiveGestureErrorDetector.GestureEvent.SET_END_TARGET_HOME;
import static com.android.quickstep.util.ActiveGestureErrorDetector.GestureEvent.SET_END_TARGET_NEW_TASK;

import android.annotation.Nullable;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.view.MotionEvent;
import android.view.RemoteAnimationTarget;

import com.android.launcher3.statemanager.BaseState;
import com.android.launcher3.statemanager.StatefulActivity;
import com.android.quickstep.TopTaskTracker.CachedTaskInfo;
import com.android.quickstep.util.ActiveGestureErrorDetector;
import com.android.quickstep.util.ActiveGestureLog;
import com.android.systemui.shared.recents.model.ThumbnailData;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;

/**
 * Manages the state for an active system gesture, listens for events from the system and Launcher,
 * and fires events when the states change.
 */
@TargetApi(Build.VERSION_CODES.R)
public class GestureState implements RecentsAnimationCallbacks.RecentsAnimationListener {

    final Predicate<RemoteAnimationTarget> mLastStartedTaskIdPredicate = new Predicate<>() {
        @Override
        public boolean test(RemoteAnimationTarget targetCompat) {
            for (int taskId : mLastStartedTaskId) {
                if (targetCompat.taskId == taskId) {
                    return true;
                }
            }
            return false;
        }
    };

    /**
     * Defines the end targets of a gesture and the associated state.
     */
    public enum GestureEndTarget {
        HOME(true, LAUNCHER_STATE_HOME, false),

        RECENTS(true, LAUNCHER_STATE_OVERVIEW, true),

        NEW_TASK(false, LAUNCHER_STATE_BACKGROUND, true),

        LAST_TASK(false, LAUNCHER_STATE_BACKGROUND, true),

        ALL_APPS(true, LAUNCHER_STATE_ALLAPPS, false);

        GestureEndTarget(boolean isLauncher, int containerType,
                boolean recentsAttachedToAppWindow) {
            this.isLauncher = isLauncher;
            this.containerType = containerType;
            this.recentsAttachedToAppWindow = recentsAttachedToAppWindow;
        }

        /** Whether the target is in the launcher activity. Implicitly, if the end target is going
         to Launcher, then we can not interrupt the animation to start another gesture. */
        public final boolean isLauncher;
        /** Used to log where the user ended up after the gesture ends */
        public final int containerType;
        /** Whether RecentsView should be attached to the window as we animate to this target */
        public final boolean recentsAttachedToAppWindow;
    }

    private static final String TAG = "GestureState";

    private static final List<String> STATE_NAMES = new ArrayList<>();
    public static final GestureState DEFAULT_STATE = new GestureState();

    private static int FLAG_COUNT = 0;
    private static int getNextStateFlag(String name) {
        if (DEBUG_STATES) {
            STATE_NAMES.add(name);
        }
        int index = 1 << FLAG_COUNT;
        FLAG_COUNT++;
        return index;
    }

    // Called when the end target as been set
    public static final int STATE_END_TARGET_SET =
            getNextStateFlag("STATE_END_TARGET_SET");

    // Called when the end target animation has finished
    public static final int STATE_END_TARGET_ANIMATION_FINISHED =
            getNextStateFlag("STATE_END_TARGET_ANIMATION_FINISHED");

    // Called when the recents animation has been requested to start
    public static final int STATE_RECENTS_ANIMATION_INITIALIZED =
            getNextStateFlag("STATE_RECENTS_ANIMATION_INITIALIZED");

    // Called when the recents animation is started and the TaskAnimationManager has been updated
    // with the controller and targets
    public static final int STATE_RECENTS_ANIMATION_STARTED =
            getNextStateFlag("STATE_RECENTS_ANIMATION_STARTED");

    // Called when the recents animation is canceled
    public static final int STATE_RECENTS_ANIMATION_CANCELED =
            getNextStateFlag("STATE_RECENTS_ANIMATION_CANCELED");

    // Called when the recents animation finishes
    public static final int STATE_RECENTS_ANIMATION_FINISHED =
            getNextStateFlag("STATE_RECENTS_ANIMATION_FINISHED");

    // Always called when the recents animation ends (regardless of cancel or finish)
    public static final int STATE_RECENTS_ANIMATION_ENDED =
            getNextStateFlag("STATE_RECENTS_ANIMATION_ENDED");

    // Called when RecentsView stops scrolling and settles on a TaskView.
    public static final int STATE_RECENTS_SCROLLING_FINISHED =
            getNextStateFlag("STATE_RECENTS_SCROLLING_FINISHED");

    // Needed to interact with the current activity
    private final Intent mHomeIntent;
    private final Intent mOverviewIntent;
    private final BaseActivityInterface mActivityInterface;
    private final MultiStateCallback mStateCallback;
    private final int mGestureId;

    public enum TrackpadGestureType {
        NONE,
        THREE_FINGER,
        FOUR_FINGER;

        public static TrackpadGestureType getTrackpadGestureType(MotionEvent event) {
            if (isTrackpadThreeFingerSwipe(event)) {
                return TrackpadGestureType.THREE_FINGER;
            }
            if (isTrackpadFourFingerSwipe(event)) {
                return TrackpadGestureType.FOUR_FINGER;
            }

            return TrackpadGestureType.NONE;
        }
    }

    private TrackpadGestureType mTrackpadGestureType = TrackpadGestureType.NONE;
    private CachedTaskInfo mRunningTask;
    private GestureEndTarget mEndTarget;
    private RemoteAnimationTarget[] mLastAppearedTaskTargets;
    private Set<Integer> mPreviouslyAppearedTaskIds = new HashSet<>();
    private int[] mLastStartedTaskId = new int[]{INVALID_TASK_ID, INVALID_TASK_ID};
    private RecentsAnimationController mRecentsAnimationController;
    private HashMap<Integer, ThumbnailData> mRecentsAnimationCanceledSnapshots;

    /** The time when the swipe up gesture is triggered. */
    private long mSwipeUpStartTimeMs;

    private boolean mHandlingAtomicEvent;

    public GestureState(OverviewComponentObserver componentObserver, int gestureId) {
        mHomeIntent = componentObserver.getHomeIntent();
        mOverviewIntent = componentObserver.getOverviewIntent();
        mActivityInterface = componentObserver.getActivityInterface();
        mStateCallback = new MultiStateCallback(
                STATE_NAMES.toArray(new String[0]), GestureState::getTrackedEventForState);
        mGestureId = gestureId;
    }

    public GestureState(GestureState other) {
        mHomeIntent = other.mHomeIntent;
        mOverviewIntent = other.mOverviewIntent;
        mActivityInterface = other.mActivityInterface;
        mStateCallback = other.mStateCallback;
        mGestureId = other.mGestureId;
        mRunningTask = other.mRunningTask;
        mEndTarget = other.mEndTarget;
        mLastAppearedTaskTargets = other.mLastAppearedTaskTargets;
        mPreviouslyAppearedTaskIds = other.mPreviouslyAppearedTaskIds;
        mLastStartedTaskId = other.mLastStartedTaskId;
    }

    public GestureState() {
        // Do nothing, only used for initializing the gesture state prior to user unlock
        mHomeIntent = new Intent();
        mOverviewIntent = new Intent();
        mActivityInterface = null;
        mStateCallback = new MultiStateCallback(
                STATE_NAMES.toArray(new String[0]), GestureState::getTrackedEventForState);
        mGestureId = -1;
    }

    @Nullable
    private static ActiveGestureErrorDetector.GestureEvent getTrackedEventForState(int stateFlag) {
        if (stateFlag == STATE_END_TARGET_ANIMATION_FINISHED) {
            return ActiveGestureErrorDetector.GestureEvent.STATE_END_TARGET_ANIMATION_FINISHED;
        } else if (stateFlag == STATE_RECENTS_SCROLLING_FINISHED) {
            return ActiveGestureErrorDetector.GestureEvent.STATE_RECENTS_SCROLLING_FINISHED;
        } else if (stateFlag == STATE_RECENTS_ANIMATION_CANCELED) {
            return ActiveGestureErrorDetector.GestureEvent.STATE_RECENTS_ANIMATION_CANCELED;
        }
        return null;
    }

    /**
     * @return whether the gesture state has the provided {@param stateMask} flags set.
     */
    public boolean hasState(int stateMask) {
        return mStateCallback.hasStates(stateMask);
    }

    /**
     * Sets the given {@param stateFlag}s.
     */
    public void setState(int stateFlag) {
        mStateCallback.setState(stateFlag);
    }

    /**
     * Adds a callback for when the states matching the given {@param stateMask} is set.
     */
    public void runOnceAtState(int stateMask, Runnable callback) {
        mStateCallback.runOnceAtState(stateMask, callback);
    }

    /**
     * @return the intent for the Home component.
     */
    public Intent getHomeIntent() {
        return mHomeIntent;
    }

    /**
     * @return the intent for the Overview component.
     */
    public Intent getOverviewIntent() {
        return mOverviewIntent;
    }

    /**
     * @return the interface to the activity handing the UI updates for this gesture.
     */
    public <S extends BaseState<S>,
            T extends StatefulActivity<S>> BaseActivityInterface<S, T> getActivityInterface() {
        return mActivityInterface;
    }

    /**
     * @return the id for this particular gesture.
     */
    public int getGestureId() {
        return mGestureId;
    }

    /**
     * Sets if the gesture is is from the trackpad, if so, whether 3-finger, or 4-finger
     */
    public void setTrackpadGestureType(TrackpadGestureType trackpadGestureType) {
        mTrackpadGestureType = trackpadGestureType;
    }

    public boolean isTrackpadGesture() {
        return mTrackpadGestureType != TrackpadGestureType.NONE;
    }

    public boolean isThreeFingerTrackpadGesture() {
        return mTrackpadGestureType == TrackpadGestureType.THREE_FINGER;
    }

    public boolean isFourFingerTrackpadGesture() {
        return mTrackpadGestureType == TrackpadGestureType.FOUR_FINGER;
    }

    /**
     * @return the running task for this gesture.
     */
    public CachedTaskInfo getRunningTask() {
        return mRunningTask;
    }

    /**
     * @param getMultipleTasks Whether multiple tasks or not are to be returned (for split)
     * @return the running task ids for this gesture.
     */
    public int[] getRunningTaskIds(boolean getMultipleTasks) {
        if (mRunningTask == null) {
            return new int[]{INVALID_TASK_ID, INVALID_TASK_ID};
        } else {
            int cachedTasksSize = mRunningTask.mAllCachedTasks.size();
            int count = Math.min(cachedTasksSize, getMultipleTasks ? 2 : 1);
            int[] runningTaskIds = new int[count];
            for (int i = 0; i < count; i++) {
                runningTaskIds[i] = mRunningTask.mAllCachedTasks.get(i).taskId;
            }
            return runningTaskIds;
        }
    }

    /**
     * @see #getRunningTaskIds(boolean)
     * @return the single top-most running taskId for this gesture
     */
    public int getTopRunningTaskId() {
        return getRunningTaskIds(false /*getMultipleTasks*/)[0];
    }

    /**
     * Updates the running task for the gesture to be the given {@param runningTask}.
     */
    public void updateRunningTask(CachedTaskInfo runningTask) {
        mRunningTask = runningTask;
    }

    /**
     * Updates the last task that appeared during this gesture.
     */
    public void updateLastAppearedTaskTargets(RemoteAnimationTarget[] lastAppearedTaskTargets) {
        mLastAppearedTaskTargets = lastAppearedTaskTargets;
        for (RemoteAnimationTarget target : lastAppearedTaskTargets) {
            if (target == null) {
                continue;
            }
            mPreviouslyAppearedTaskIds.add(target.taskId);
        }
    }

    /**
     * @return The id of the task that appeared during this gesture.
     */
    public int[] getLastAppearedTaskIds() {
        if (mLastAppearedTaskTargets == null) {
            return new int[]{INVALID_TASK_ID, INVALID_TASK_ID};
        } else {
            return Arrays.stream(mLastAppearedTaskTargets)
                    .mapToInt(target -> target != null ? target.taskId : INVALID_TASK_ID).toArray();
        }
    }

    public void updatePreviouslyAppearedTaskIds(Set<Integer> previouslyAppearedTaskIds) {
        mPreviouslyAppearedTaskIds = previouslyAppearedTaskIds;
    }

    public Set<Integer> getPreviouslyAppearedTaskIds() {
        return mPreviouslyAppearedTaskIds;
    }

    /**
     * Updates the last task that we started via startActivityFromRecents() during this gesture.
     */
    public void updateLastStartedTaskIds(int[] lastStartedTaskId) {
        mLastStartedTaskId = lastStartedTaskId;
    }

    /**
     * @return The id of the task that was most recently started during this gesture, or -1 if
     * no task has been started yet (i.e. we haven't settled on a new task).
     */
    public int[] getLastStartedTaskIds() {
        return mLastStartedTaskId;
    }

    /**
     * @return the end target for this gesture (if known).
     */
    public GestureEndTarget getEndTarget() {
        return mEndTarget;
    }

    /**
     * Sets the end target of this gesture and immediately notifies the state changes.
     */
    public void setEndTarget(GestureEndTarget target) {
        setEndTarget(target, true /* isAtomic */);
    }

    /**
     * Sets the end target of this gesture, but if {@param isAtomic} is {@code false}, then the
     * caller must explicitly set {@link #STATE_END_TARGET_ANIMATION_FINISHED} themselves.
     */
    public void setEndTarget(GestureEndTarget target, boolean isAtomic) {
        mEndTarget = target;
        mStateCallback.setState(STATE_END_TARGET_SET);
        ActiveGestureLog.INSTANCE.addLog(
                /* event= */ "setEndTarget " + mEndTarget,
                /* gestureEvent= */ SET_END_TARGET);
        switch (mEndTarget) {
            case HOME:
                ActiveGestureLog.INSTANCE.trackEvent(SET_END_TARGET_HOME);
                break;
            case NEW_TASK:
                ActiveGestureLog.INSTANCE.trackEvent(SET_END_TARGET_NEW_TASK);
                break;
            case ALL_APPS:
                ActiveGestureLog.INSTANCE.trackEvent(SET_END_TARGET_ALL_APPS);
                break;
            case LAST_TASK:
            case RECENTS:
            default:
                // No-Op
        }
        if (isAtomic) {
            mStateCallback.setState(STATE_END_TARGET_ANIMATION_FINISHED);
        }
    }

    /**
     * Indicates if the gesture is handling an atomic event like a click and not a
     * user controlled gesture.
     */
    public void setHandlingAtomicEvent(boolean handlingAtomicEvent) {
        mHandlingAtomicEvent = handlingAtomicEvent;
    }

    /**
     * Returns true if the gesture is handling an atomic event like a click and not a
     * user controlled gesture.
     */
    public boolean isHandlingAtomicEvent() {
        return mHandlingAtomicEvent;
    }

    /**
     * @return whether the current gesture is still running a recents animation to a state in the
     *         Launcher or Recents activity.
     */
    public boolean isRunningAnimationToLauncher() {
        return isRecentsAnimationRunning() && mEndTarget != null && mEndTarget.isLauncher;
    }

    /**
     * @return whether the recents animation is started but not yet ended
     */
    public boolean isRecentsAnimationRunning() {
        return mStateCallback.hasStates(STATE_RECENTS_ANIMATION_STARTED)
                && !mStateCallback.hasStates(STATE_RECENTS_ANIMATION_ENDED);
    }

    @Override
    public void onRecentsAnimationStart(RecentsAnimationController controller,
            RecentsAnimationTargets targets) {
        mRecentsAnimationController = controller;
        mStateCallback.setState(STATE_RECENTS_ANIMATION_STARTED);
    }

    @Override
    public void onRecentsAnimationCanceled(HashMap<Integer, ThumbnailData> thumbnailDatas) {
        mRecentsAnimationCanceledSnapshots = thumbnailDatas;
        mStateCallback.setState(STATE_RECENTS_ANIMATION_CANCELED);
        mStateCallback.setState(STATE_RECENTS_ANIMATION_ENDED);
        if (mRecentsAnimationCanceledSnapshots != null) {
            // Clean up the screenshot to finalize the recents animation cancel
            if (mRecentsAnimationController != null) {
                mRecentsAnimationController.cleanupScreenshot();
            }
            mRecentsAnimationCanceledSnapshots = null;
        }
    }

    @Override
    public void onRecentsAnimationFinished(RecentsAnimationController controller) {
        mStateCallback.setState(STATE_RECENTS_ANIMATION_FINISHED);
        mStateCallback.setState(STATE_RECENTS_ANIMATION_ENDED);
    }

    /**
     * Returns and clears the canceled animation thumbnail data. This call only returns a value
     * while STATE_RECENTS_ANIMATION_CANCELED state is being set, and the caller is responsible for
     * calling {@link RecentsAnimationController#cleanupScreenshot()}.
     */
    @Nullable
    HashMap<Integer, ThumbnailData> consumeRecentsAnimationCanceledSnapshot() {
        if (mRecentsAnimationCanceledSnapshots != null) {
            HashMap<Integer, ThumbnailData> data =
                    new HashMap<Integer, ThumbnailData>(mRecentsAnimationCanceledSnapshots);
            mRecentsAnimationCanceledSnapshots = null;
            return data;
        }
        return null;
    }

    void setSwipeUpStartTimeMs(long uptimeMs) {
        mSwipeUpStartTimeMs = uptimeMs;
    }

    long getSwipeUpStartTimeMs() {
        return mSwipeUpStartTimeMs;
    }

    public void dump(PrintWriter pw) {
        pw.println("GestureState:");
        pw.println("  gestureID=" + mGestureId);
        pw.println("  runningTask=" + mRunningTask);
        pw.println("  endTarget=" + mEndTarget);
        pw.println("  lastAppearedTaskTargetId=" + Arrays.toString(mLastAppearedTaskTargets));
        pw.println("  lastStartedTaskId=" + Arrays.toString(mLastStartedTaskId));
        pw.println("  isRecentsAnimationRunning=" + isRecentsAnimationRunning());
    }
}