summaryrefslogtreecommitdiff
path: root/quickstep/src/com/android/quickstep/RecentsActivity.java
blob: 72439dec268a6a86ff9637df37d0e56834d33e97 (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
/*
 * 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.os.Trace.TRACE_TAG_APP;
import static android.view.RemoteAnimationTarget.MODE_CLOSING;
import static android.view.RemoteAnimationTarget.MODE_OPENING;

import static com.android.launcher3.QuickstepTransitionManager.RECENTS_LAUNCH_DURATION;
import static com.android.launcher3.QuickstepTransitionManager.STATUS_BAR_TRANSITION_DURATION;
import static com.android.launcher3.QuickstepTransitionManager.STATUS_BAR_TRANSITION_PRE_DELAY;
import static com.android.launcher3.testing.shared.TestProtocol.OVERVIEW_STATE_ORDINAL;
import static com.android.quickstep.OverviewComponentObserver.startHomeIntentSafely;
import static com.android.quickstep.TaskUtils.taskIsATargetWithMode;
import static com.android.quickstep.TaskViewUtils.createRecentsWindowAnimator;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.app.ActivityOptions;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Trace;
import android.util.Log;
import android.view.Display;
import android.view.RemoteAnimationAdapter;
import android.view.RemoteAnimationTarget;
import android.view.SurfaceControl.Transaction;
import android.view.View;
import android.window.RemoteTransition;
import android.window.SplashScreen;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.app.animation.Interpolators;
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherAnimationRunner;
import com.android.launcher3.LauncherAnimationRunner.AnimationResult;
import com.android.launcher3.LauncherAnimationRunner.RemoteAnimationFactory;
import com.android.launcher3.R;
import com.android.launcher3.anim.AnimatorPlaybackController;
import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.compat.AccessibilityManagerCompat;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.statemanager.StateManager;
import com.android.launcher3.statemanager.StateManager.AtomicAnimationFactory;
import com.android.launcher3.statemanager.StateManager.StateHandler;
import com.android.launcher3.statemanager.StatefulActivity;
import com.android.launcher3.taskbar.FallbackTaskbarUIController;
import com.android.launcher3.taskbar.TaskbarManager;
import com.android.launcher3.testing.shared.TestProtocol;
import com.android.launcher3.util.ActivityOptionsWrapper;
import com.android.launcher3.util.ActivityTracker;
import com.android.launcher3.util.RunnableList;
import com.android.launcher3.util.SystemUiController;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.BaseDragLayer;
import com.android.launcher3.views.ScrimView;
import com.android.quickstep.fallback.FallbackRecentsStateController;
import com.android.quickstep.fallback.FallbackRecentsView;
import com.android.quickstep.fallback.RecentsDragLayer;
import com.android.quickstep.fallback.RecentsState;
import com.android.quickstep.util.RecentsAtomicAnimationFactory;
import com.android.quickstep.util.SplitSelectStateController;
import com.android.quickstep.util.TISBindHelper;
import com.android.quickstep.views.OverviewActionsView;
import com.android.quickstep.views.RecentsView;
import com.android.quickstep.views.TaskView;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.List;

/**
 * A recents activity that shows the recently launched tasks as swipable task cards.
 * See {@link com.android.quickstep.views.RecentsView}.
 */
public final class RecentsActivity extends StatefulActivity<RecentsState> {

    public static final ActivityTracker<RecentsActivity> ACTIVITY_TRACKER =
            new ActivityTracker<>();

    private Handler mUiHandler = new Handler(Looper.getMainLooper());

    private static final long HOME_APPEAR_DURATION = 250;
    private static final long RECENTS_ANIMATION_TIMEOUT = 1000;

    private RecentsDragLayer mDragLayer;
    private ScrimView mScrimView;
    private FallbackRecentsView mFallbackRecentsView;
    private OverviewActionsView mActionsView;
    private TISBindHelper mTISBindHelper;
    private @Nullable FallbackTaskbarUIController mTaskbarUIController;

    private StateManager<RecentsState> mStateManager;

    // Strong refs to runners which are cleared when the activity is destroyed
    private RemoteAnimationFactory mActivityLaunchAnimationRunner;

    // For handling degenerate cases where starting an activity doesn't actually trigger the remote
    // animation callback
    private final Handler mHandler = new Handler();
    private final Runnable mAnimationStartTimeoutRunnable = this::onAnimationStartTimeout;
    private SplitSelectStateController mSplitSelectStateController;

    /**
     * Init drag layer and overview panel views.
     */
    protected void setupViews() {
        inflateRootView(R.layout.fallback_recents_activity);
        setContentView(getRootView());
        mDragLayer = findViewById(R.id.drag_layer);
        mScrimView = findViewById(R.id.scrim_view);
        mFallbackRecentsView = findViewById(R.id.overview_panel);
        mActionsView = findViewById(R.id.overview_actions_view);
        getRootView().getSysUiScrim().getSysUIProgress().updateValue(0);
        mSplitSelectStateController =
                new SplitSelectStateController(this, mHandler, getStateManager(),
                        null /* depthController */, getStatsLogManager(),
                        SystemUiProxy.INSTANCE.get(this), RecentsModel.INSTANCE.get(this));
        mDragLayer.recreateControllers();
        mFallbackRecentsView.init(mActionsView, mSplitSelectStateController);

        mTISBindHelper = new TISBindHelper(this, this::onTISConnected);
    }

    private void onTISConnected(TouchInteractionService.TISBinder binder) {
        TaskbarManager taskbarManager = binder.getTaskbarManager();
        if (taskbarManager != null) {
            taskbarManager.setActivity(this);
        }
    }

    @Override
    public void runOnBindToTouchInteractionService(Runnable r) {
        mTISBindHelper.runOnBindToTouchInteractionService(r);
    }

    public void setTaskbarUIController(FallbackTaskbarUIController taskbarUIController) {
        mTaskbarUIController = taskbarUIController;
    }

    public FallbackTaskbarUIController getTaskbarUIController() {
        return mTaskbarUIController;
    }

    @Override
    public void onMultiWindowModeChanged(boolean isInMultiWindowMode, Configuration newConfig) {
        onHandleConfigurationChanged();
        super.onMultiWindowModeChanged(isInMultiWindowMode, newConfig);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        ACTIVITY_TRACKER.handleNewIntent(this);
    }

    @Override
    protected void onHandleConfigurationChanged() {
        initDeviceProfile();

        AbstractFloatingView.closeOpenViews(this, true,
                AbstractFloatingView.TYPE_ALL & ~AbstractFloatingView.TYPE_REBIND_SAFE);
        dispatchDeviceProfileChanged();

        reapplyUi();
        mDragLayer.recreateControllers();
    }

    /**
     * Generate the device profile to use in this activity.
     * @return device profile
     */
    protected DeviceProfile createDeviceProfile() {
        DeviceProfile dp = InvariantDeviceProfile.INSTANCE.get(this).getDeviceProfile(this);

        // In case we are reusing IDP, create a copy so that we don't conflict with Launcher
        // activity.
        return (mDragLayer != null) && isInMultiWindowMode()
                ? dp.getMultiWindowProfile(this, getMultiWindowDisplaySize())
                : dp.copy(this);
    }

    @Override
    public BaseDragLayer getDragLayer() {
        return mDragLayer;
    }

    public ScrimView getScrimView() {
        return mScrimView;
    }

    @Override
    public <T extends View> T getOverviewPanel() {
        return (T) mFallbackRecentsView;
    }

    public OverviewActionsView getActionsView() {
        return mActionsView;
    }

    @Override
    public void returnToHomescreen() {
        super.returnToHomescreen();
        // TODO(b/137318995) This should go home, but doing so removes freeform windows
    }

    /**
     * Called if the remote animation callback from #getActivityLaunchOptions() hasn't called back
     * in a reasonable time due to a conflict with the recents animation.
     */
    private void onAnimationStartTimeout() {
        if (mActivityLaunchAnimationRunner != null) {
            mActivityLaunchAnimationRunner.onAnimationCancelled();
        }
    }

    @Override
    public ActivityOptionsWrapper getActivityLaunchOptions(final View v, @Nullable ItemInfo item) {
        if (!(v instanceof TaskView)) {
            return super.getActivityLaunchOptions(v, item);
        }

        final TaskView taskView = (TaskView) v;
        final RecentsView recentsView = taskView.getRecentsView();
        if (recentsView == null) {
            return super.getActivityLaunchOptions(v, item);
        }

        RunnableList onEndCallback = new RunnableList();

        mActivityLaunchAnimationRunner = new RemoteAnimationFactory() {
            @Override
            public void onAnimationStart(int transit, RemoteAnimationTarget[] appTargets,
                    RemoteAnimationTarget[] wallpaperTargets,
                    RemoteAnimationTarget[] nonAppTargets, AnimationResult result) {
                mHandler.removeCallbacks(mAnimationStartTimeoutRunnable);
                AnimatorSet anim = composeRecentsLaunchAnimator(recentsView, taskView, appTargets,
                        wallpaperTargets, nonAppTargets);
                anim.addListener(resetStateListener());
                result.setAnimation(anim, RecentsActivity.this, onEndCallback::executeAllAndDestroy,
                        true /* skipFirstFrame */);
            }

            @Override
            public void onAnimationCancelled() {
                mHandler.removeCallbacks(mAnimationStartTimeoutRunnable);
                onEndCallback.executeAllAndDestroy();
            }
        };

        final LauncherAnimationRunner wrapper = new LauncherAnimationRunner(
                mUiHandler, mActivityLaunchAnimationRunner, true /* startAtFrontOfQueue */);
        final ActivityOptions options = ActivityOptions.makeRemoteAnimation(
                new RemoteAnimationAdapter(wrapper, RECENTS_LAUNCH_DURATION,
                        RECENTS_LAUNCH_DURATION - STATUS_BAR_TRANSITION_DURATION
                                - STATUS_BAR_TRANSITION_PRE_DELAY),
                new RemoteTransition(wrapper.toRemoteTransition(), getIApplicationThread(),
                        "LaunchFromRecents"));
        final ActivityOptionsWrapper activityOptions = new ActivityOptionsWrapper(options,
                onEndCallback);
        activityOptions.options.setSplashScreenStyle(SplashScreen.SPLASH_SCREEN_STYLE_ICON);
        activityOptions.options.setLaunchDisplayId(
                (v != null && v.getDisplay() != null) ? v.getDisplay().getDisplayId()
                        : Display.DEFAULT_DISPLAY);
        activityOptions.options.setPendingIntentBackgroundActivityStartMode(
                ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
        mHandler.postDelayed(mAnimationStartTimeoutRunnable, RECENTS_ANIMATION_TIMEOUT);
        return activityOptions;
    }

    /**
     * Composes the animations for a launch from the recents list if possible.
     */
    private AnimatorSet  composeRecentsLaunchAnimator(
            @NonNull RecentsView recentsView,
            @NonNull TaskView taskView,
            RemoteAnimationTarget[] appTargets,
            RemoteAnimationTarget[] wallpaperTargets,
            RemoteAnimationTarget[] nonAppTargets) {
        AnimatorSet target = new AnimatorSet();
        boolean activityClosing = taskIsATargetWithMode(appTargets, getTaskId(), MODE_CLOSING);
        PendingAnimation pa = new PendingAnimation(RECENTS_LAUNCH_DURATION);
        createRecentsWindowAnimator(recentsView, taskView, !activityClosing, appTargets,
                wallpaperTargets, nonAppTargets, null /* depthController */, pa);
        target.play(pa.buildAnim());

        // Found a visible recents task that matches the opening app, lets launch the app from there
        if (activityClosing) {
            Animator adjacentAnimation = mFallbackRecentsView
                    .createAdjacentPageAnimForTaskLaunch(taskView);
            adjacentAnimation.setInterpolator(Interpolators.TOUCH_RESPONSE);
            adjacentAnimation.setDuration(RECENTS_LAUNCH_DURATION);
            adjacentAnimation.addListener(resetStateListener());
            target.play(adjacentAnimation);
        }
        return target;
    }

    @Override
    protected void onStart() {
        // Set the alpha to 1 before calling super, as it may get set back to 0 due to
        // onActivityStart callback.
        mFallbackRecentsView.setContentAlpha(1);
        super.onStart();
        mFallbackRecentsView.updateLocusId();
    }

    @Override
    protected void onStop() {
        super.onStop();

        // Workaround for b/78520668, explicitly trim memory once UI is hidden
        onTrimMemory(TRIM_MEMORY_UI_HIDDEN);
        mFallbackRecentsView.updateLocusId();
    }

    @Override
    protected void onResume() {
        super.onResume();
        AccessibilityManagerCompat.sendStateEventToTest(getBaseContext(), OVERVIEW_STATE_ORDINAL);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mStateManager = new StateManager<>(this, RecentsState.BG_LAUNCHER);

        initDeviceProfile();
        setupViews();

        getSystemUiController().updateUiState(SystemUiController.UI_STATE_BASE_WINDOW,
                Themes.getAttrBoolean(this, R.attr.isWorkspaceDarkText));
        ACTIVITY_TRACKER.handleCreate(this);
    }

    @Override
    public void onStateSetEnd(RecentsState state) {
        super.onStateSetEnd(state);

        if (state == RecentsState.DEFAULT) {
            AccessibilityManagerCompat.sendStateEventToTest(getBaseContext(),
                    OVERVIEW_STATE_ORDINAL);
        }
    }

    /**
     * Initialize/update the device profile.
     */
    private void initDeviceProfile() {
        mDeviceProfile = createDeviceProfile();
        onDeviceProfileInitiated();
    }

    @Override
    public void onEnterAnimationComplete() {
        super.onEnterAnimationComplete();
        // After the transition to home, enable the high-res thumbnail loader if it wasn't enabled
        // as a part of quickstep, so that high-res thumbnails can load the next time we enter
        // overview
        RecentsModel.INSTANCE.get(this).getThumbnailCache()
                .getHighResLoadingState().setVisible(true);
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        RecentsModel.INSTANCE.get(this).onTrimMemory(level);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ACTIVITY_TRACKER.onActivityDestroyed(this);
        mActivityLaunchAnimationRunner = null;
        mSplitSelectStateController.onDestroy();
        mTISBindHelper.onDestroy();
    }

    @Override
    public void onBackPressed() {
        // TODO: Launch the task we came from
        startHome();
    }

    public void startHome() {
        Log.d(TestProtocol.INCORRECT_HOME_STATE, "start home from recents activity");
        RecentsView recentsView = getOverviewPanel();
        recentsView.switchToScreenshot(() -> recentsView.finishRecentsAnimation(true,
                this::startHomeInternal));
    }

    private void startHomeInternal() {
        LauncherAnimationRunner runner = new LauncherAnimationRunner(
                getMainThreadHandler(), mAnimationToHomeFactory, true);
        ActivityOptions options = ActivityOptions.makeRemoteAnimation(
                new RemoteAnimationAdapter(runner, HOME_APPEAR_DURATION, 0),
                new RemoteTransition(runner.toRemoteTransition(), getIApplicationThread(),
                        "StartHomeFromRecents"));
        startHomeIntentSafely(this, options.toBundle());
    }

    private final RemoteAnimationFactory mAnimationToHomeFactory =
            (transit, appTargets, wallpaperTargets, nonAppTargets, result) -> {
                AnimatorPlaybackController controller =
                        getStateManager().createAnimationToNewWorkspace(
                                RecentsState.BG_LAUNCHER, HOME_APPEAR_DURATION);
                controller.dispatchOnStart();

                RemoteAnimationTargets targets = new RemoteAnimationTargets(
                        appTargets, wallpaperTargets, nonAppTargets, MODE_OPENING);
                for (RemoteAnimationTarget app : targets.apps) {
                    new Transaction().setAlpha(app.leash, 1).apply();
                }
                AnimatorSet anim = new AnimatorSet();
                anim.play(controller.getAnimationPlayer());
                anim.setDuration(HOME_APPEAR_DURATION);
                result.setAnimation(anim, RecentsActivity.this,
                        () -> getStateManager().goToState(RecentsState.HOME, false),
                        true /* skipFirstFrame */);
            };

    @Override
    protected void collectStateHandlers(List<StateHandler> out) {
        out.add(new FallbackRecentsStateController(this));
    }

    @Override
    public StateManager<RecentsState> getStateManager() {
        return mStateManager;
    }

    @Override
    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
        super.dump(prefix, fd, writer, args);
        writer.println(prefix + "Misc:");
        dumpMisc(prefix + "\t", writer);
    }

    @Override
    public AtomicAnimationFactory<RecentsState> createAtomicAnimationFactory() {
        return new RecentsAtomicAnimationFactory<>(this);
    }

    @Override
    public void dispatchDeviceProfileChanged() {
        super.dispatchDeviceProfileChanged();
        Trace.instantForTrack(TRACE_TAG_APP, "RecentsActivity#DeviceProfileChanged",
                getDeviceProfile().toSmallString());
    }

    private AnimatorListenerAdapter resetStateListener() {
        return new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mFallbackRecentsView.resetTaskVisuals();
                mStateManager.reapplyState();
            }
        };
    }

    public boolean canStartHomeSafely() {
        OverviewCommandHelper overviewCommandHelper = mTISBindHelper.getOverviewCommandHelper();
        return overviewCommandHelper == null || overviewCommandHelper.canStartHomeSafely();
    }
}