summaryrefslogtreecommitdiffstats
path: root/quickstep/src/com/android/quickstep/RecentsModel.java
blob: fa4e016db4d822b5535f79742bc93bc447600bbe (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
/*
 * Copyright (C) 2018 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 com.android.quickstep.TaskUtils.checkCurrentOrManagedUserId;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.ComponentCallbacks2;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.UserHandle;
import android.support.annotation.WorkerThread;
import android.util.Log;
import android.util.LruCache;
import android.util.SparseArray;
import android.view.accessibility.AccessibilityManager;

import com.android.launcher3.MainThreadExecutor;
import com.android.launcher3.R;
import com.android.launcher3.util.MainThreadInitializedObject;
import com.android.launcher3.util.Preconditions;
import com.android.systemui.shared.recents.ISystemUiProxy;
import com.android.systemui.shared.recents.model.IconLoader;
import com.android.systemui.shared.recents.model.RecentsTaskLoadPlan;
import com.android.systemui.shared.recents.model.RecentsTaskLoadPlan.PreloadOptions;
import com.android.systemui.shared.recents.model.RecentsTaskLoader;
import com.android.systemui.shared.recents.model.TaskKeyLruCache;
import com.android.systemui.shared.system.ActivityManagerWrapper;
import com.android.systemui.shared.system.BackgroundExecutor;
import com.android.systemui.shared.system.TaskStackChangeListener;

import java.util.ArrayList;
import java.util.function.Consumer;

/**
 * Singleton class to load and manage recents model.
 */
@TargetApi(Build.VERSION_CODES.O)
public class RecentsModel extends TaskStackChangeListener {
    // We do not need any synchronization for this variable as its only written on UI thread.
    public static final MainThreadInitializedObject<RecentsModel> INSTANCE =
            new MainThreadInitializedObject<>(c -> new RecentsModel(c));

    private final SparseArray<Bundle> mCachedAssistData = new SparseArray<>(1);
    private final ArrayList<AssistDataListener> mAssistDataListeners = new ArrayList<>();

    private final Context mContext;
    private final RecentsTaskLoader mRecentsTaskLoader;
    private final MainThreadExecutor mMainThreadExecutor;

    private RecentsTaskLoadPlan mLastLoadPlan;
    private int mLastLoadPlanId;
    private int mTaskChangeId;
    private ISystemUiProxy mSystemUiProxy;
    private boolean mClearAssistCacheOnStackChange = true;
    private final boolean mIsLowRamDevice;
    private boolean mPreloadTasksInBackground;
    private final AccessibilityManager mAccessibilityManager;

    private RecentsModel(Context context) {
        mContext = context;

        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        mIsLowRamDevice = activityManager.isLowRamDevice();
        mMainThreadExecutor = new MainThreadExecutor();

        Resources res = context.getResources();
        mRecentsTaskLoader = new RecentsTaskLoader(mContext,
                res.getInteger(R.integer.config_recentsMaxThumbnailCacheSize),
                res.getInteger(R.integer.config_recentsMaxIconCacheSize), 0) {

            @Override
            protected IconLoader createNewIconLoader(Context context,
                    TaskKeyLruCache<Drawable> iconCache,
                    LruCache<ComponentName, ActivityInfo> activityInfoCache) {
                return new NormalizedIconLoader(context, iconCache, activityInfoCache);
            }
        };
        mRecentsTaskLoader.startLoader(mContext);
        ActivityManagerWrapper.getInstance().registerTaskStackListener(this);

        mTaskChangeId = 1;
        loadTasks(-1, null);
        mAccessibilityManager = context.getSystemService(AccessibilityManager.class);
    }

    public RecentsTaskLoader getRecentsTaskLoader() {
        return mRecentsTaskLoader;
    }

    /**
     * Preloads the task plan
     * @param taskId The running task id or -1
     * @param callback The callback to receive the task plan once its complete or null. This is
     *                always called on the UI thread.
     * @return the request id associated with this call.
     */
    public int loadTasks(int taskId, Consumer<RecentsTaskLoadPlan> callback) {
        final int requestId = mTaskChangeId;

        // Fail fast if nothing has changed.
        if (mLastLoadPlanId == mTaskChangeId) {
            if (callback != null) {
                final RecentsTaskLoadPlan plan = mLastLoadPlan;
                mMainThreadExecutor.execute(() -> callback.accept(plan));
            }
            return requestId;
        }

        BackgroundExecutor.get().submit(() -> {
            // Preload the plan
            RecentsTaskLoadPlan loadPlan = new RecentsTaskLoadPlan(mContext);
            PreloadOptions opts = new PreloadOptions();
            opts.loadTitles = mAccessibilityManager.isEnabled();
            loadPlan.preloadPlan(opts, mRecentsTaskLoader, taskId, UserHandle.myUserId());
            // Set the load plan on UI thread
            mMainThreadExecutor.execute(() -> {
                mLastLoadPlan = loadPlan;
                mLastLoadPlanId = requestId;

                if (callback != null) {
                    callback.accept(loadPlan);
                }
            });
        });
        return requestId;
    }

    public void setPreloadTasksInBackground(boolean preloadTasksInBackground) {
        mPreloadTasksInBackground = preloadTasksInBackground && !mIsLowRamDevice;
    }

    @Override
    public void onActivityPinned(String packageName, int userId, int taskId, int stackId) {
        mTaskChangeId++;
    }

    @Override
    public void onActivityUnpinned() {
        mTaskChangeId++;
    }

    @Override
    public void onTaskStackChanged() {
        mTaskChangeId++;

        Preconditions.assertUIThread();
        if (mClearAssistCacheOnStackChange) {
            mCachedAssistData.clear();
        } else {
            mClearAssistCacheOnStackChange = true;
        }
    }

    @Override
    public void onTaskStackChangedBackground() {
        int userId = UserHandle.myUserId();
        if (!mPreloadTasksInBackground || !checkCurrentOrManagedUserId(userId, mContext)) {
            // TODO: Only register this for the current user
            return;
        }

        // Preload a fixed number of task icons/thumbnails in the background
        ActivityManager.RunningTaskInfo runningTaskInfo =
                ActivityManagerWrapper.getInstance().getRunningTask();
        RecentsTaskLoadPlan plan = new RecentsTaskLoadPlan(mContext);
        RecentsTaskLoadPlan.Options launchOpts = new RecentsTaskLoadPlan.Options();
        launchOpts.runningTaskId = runningTaskInfo != null ? runningTaskInfo.id : -1;
        launchOpts.numVisibleTasks = 2;
        launchOpts.numVisibleTaskThumbnails = 2;
        launchOpts.onlyLoadForCache = true;
        launchOpts.onlyLoadPausedActivities = true;
        launchOpts.loadThumbnails = true;
        PreloadOptions preloadOpts = new PreloadOptions();
        preloadOpts.loadTitles = mAccessibilityManager.isEnabled();
        plan.preloadPlan(preloadOpts, mRecentsTaskLoader, -1, userId);
        mRecentsTaskLoader.loadTasks(plan, launchOpts);
    }

    public boolean isLoadPlanValid(int resultId) {
        return mTaskChangeId == resultId;
    }

    public RecentsTaskLoadPlan getLastLoadPlan() {
        return mLastLoadPlan;
    }

    public void setSystemUiProxy(ISystemUiProxy systemUiProxy) {
        mSystemUiProxy = systemUiProxy;
    }

    public ISystemUiProxy getSystemUiProxy() {
        return mSystemUiProxy;
    }

    public void onStart() {
        mRecentsTaskLoader.startLoader(mContext);
    }

    public void onTrimMemory(int level) {
        if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
            // We already stop the loader in UI_HIDDEN, so stop the high res loader as well
            mRecentsTaskLoader.getHighResThumbnailLoader().setVisible(false);
        }
        mRecentsTaskLoader.onTrimMemory(level);
    }

    public void onOverviewShown(boolean fromHome, String tag) {
        if (mSystemUiProxy == null) {
            return;
        }
        try {
            mSystemUiProxy.onOverviewShown(fromHome);
        } catch (RemoteException e) {
            Log.w(tag,
                    "Failed to notify SysUI of overview shown from " + (fromHome ? "home" : "app")
                            + ": ", e);
        }
    }

    public void resetAssistCache() {
        mCachedAssistData.clear();
    }

    @WorkerThread
    public void preloadAssistData(int taskId, Bundle data) {
        mMainThreadExecutor.execute(() -> {
            mCachedAssistData.put(taskId, data);
            // We expect a stack change callback after the assist data is set. So ignore the
            // very next stack change callback.
            mClearAssistCacheOnStackChange = false;

            int count = mAssistDataListeners.size();
            for (int i = 0; i < count; i++) {
                mAssistDataListeners.get(i).onAssistDataReceived(taskId);
            }
        });
    }

    public Bundle getAssistData(int taskId) {
        Preconditions.assertUIThread();
        return mCachedAssistData.get(taskId);
    }

    public void addAssistDataListener(AssistDataListener listener) {
        mAssistDataListeners.add(listener);
    }

    public void removeAssistDataListener(AssistDataListener listener) {
        mAssistDataListeners.remove(listener);
    }

    /**
     * Callback for receiving assist data
     */
    public interface AssistDataListener {

        void onAssistDataReceived(int taskId);
    }
}