summaryrefslogtreecommitdiff
path: root/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchController.java
blob: f58fd4547d7a0dc8afe0d4b778e36abb6a9b553b (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
/*
 * Copyright (C) 2023 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.launcher3.taskbar;

import static com.android.quickstep.views.DesktopTaskView.isDesktopModeSupported;

import android.content.ComponentName;
import android.content.pm.ActivityInfo;

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

import com.android.launcher3.R;
import com.android.launcher3.statehandlers.DesktopVisibilityController;
import com.android.launcher3.taskbar.overlay.TaskbarOverlayContext;
import com.android.quickstep.LauncherActivityInterface;
import com.android.quickstep.RecentsModel;
import com.android.quickstep.util.DesktopTask;
import com.android.quickstep.util.GroupTask;
import com.android.systemui.shared.recents.model.Task;
import com.android.systemui.shared.recents.model.ThumbnailData;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * Handles initialization of the {@link KeyboardQuickSwitchViewController}.
 */
public final class KeyboardQuickSwitchController implements
        TaskbarControllers.LoggableTaskbarController {

    static final int MAX_TASKS = 6;

    @NonNull private final ControllerCallbacks mControllerCallbacks = new ControllerCallbacks();

    // Initialized on init
    @Nullable private RecentsModel mModel;

    // Used to keep track of the last requested task list id, so that we do not request to load the
    // tasks again if we have already requested it and the task list has not changed
    private int mTaskListChangeId = -1;
    // Only empty before the recent tasks list has been loaded the first time
    @NonNull private List<GroupTask> mTasks = new ArrayList<>();
    private int mNumHiddenTasks = 0;

    // Initialized in init
    private TaskbarControllers mControllers;

    @Nullable private KeyboardQuickSwitchViewController mQuickSwitchViewController;

    /** Initialize the controller. */
    public void init(@NonNull TaskbarControllers controllers) {
        mControllers = controllers;
        mModel = RecentsModel.INSTANCE.get(controllers.taskbarActivityContext);
    }

    void onConfigurationChanged(@ActivityInfo.Config int configChanges) {
        if (mQuickSwitchViewController == null) {
            return;
        }
        if ((configChanges & (ActivityInfo.CONFIG_KEYBOARD
                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN)) != 0) {
            mQuickSwitchViewController.closeQuickSwitchView(true);
            return;
        }
        int currentFocusedIndex = mQuickSwitchViewController.getCurrentFocusedIndex();
        onDestroy();
        if (currentFocusedIndex != -1) {
            mControllers.taskbarActivityContext.getMainThreadHandler().post(
                    () -> openQuickSwitchView(currentFocusedIndex));
        }
    }

    void openQuickSwitchView() {
        openQuickSwitchView(-1);
    }

    private void openQuickSwitchView(int currentFocusedIndex) {
        if (mQuickSwitchViewController != null) {
            return;
        }
        TaskbarOverlayContext overlayContext =
                mControllers.taskbarOverlayController.requestWindow();
        KeyboardQuickSwitchView keyboardQuickSwitchView =
                (KeyboardQuickSwitchView) overlayContext.getLayoutInflater()
                        .inflate(
                                R.layout.keyboard_quick_switch_view,
                                overlayContext.getDragLayer(),
                                /* attachToRoot= */ false);
        mQuickSwitchViewController = new KeyboardQuickSwitchViewController(
                mControllers, overlayContext, keyboardQuickSwitchView, mControllerCallbacks);

        DesktopVisibilityController desktopController =
                LauncherActivityInterface.INSTANCE.getDesktopVisibilityController();
        final boolean onDesktop =
                isDesktopModeSupported()
                        && desktopController != null
                        && desktopController.areFreeformTasksVisible();

        if (mModel.isTaskListValid(mTaskListChangeId)) {
            mQuickSwitchViewController.openQuickSwitchView(mTasks,
                    mNumHiddenTasks, /* updateTasks= */ false, currentFocusedIndex, onDesktop);
            return;
        }

        mTaskListChangeId = mModel.getTasks((tasks) -> {
            if (onDesktop) {
                processLoadedTasksOnDesktop(tasks);
            } else {
                processLoadedTasks(tasks);
            }
            mQuickSwitchViewController.openQuickSwitchView(mTasks,
                    mNumHiddenTasks, /* updateTasks= */ true, currentFocusedIndex, onDesktop);
        });
    }

    private void processLoadedTasks(ArrayList<GroupTask> tasks) {
        // Only store MAX_TASK tasks, from most to least recent
        Collections.reverse(tasks);

        // Hide all desktop tasks and show them on the hidden tile
        int hiddenDesktopTasks = 0;
        if (isDesktopModeSupported()) {
            DesktopTask desktopTask = findDesktopTask(tasks);
            if (desktopTask != null) {
                hiddenDesktopTasks = desktopTask.tasks.size();
                tasks = tasks.stream()
                        .filter(t -> !(t instanceof DesktopTask))
                        .collect(Collectors.toCollection(ArrayList<GroupTask>::new));
            }
        }
        mTasks = tasks.stream()
                .limit(MAX_TASKS)
                .collect(Collectors.toList());
        mNumHiddenTasks = Math.max(0, tasks.size() - MAX_TASKS) + hiddenDesktopTasks;
    }

    private void processLoadedTasksOnDesktop(ArrayList<GroupTask> tasks) {
        // Find the single desktop task that contains a grouping of desktop tasks
        DesktopTask desktopTask = findDesktopTask(tasks);

        if (desktopTask != null) {
            mTasks = desktopTask.tasks.stream().map(GroupTask::new).collect(Collectors.toList());
            // All other tasks, apart from the grouped desktop task, are hidden
            mNumHiddenTasks = Math.max(0, tasks.size() - 1);
        } else {
            // Desktop tasks were visible, but the recents entry is missing. Fall back to empty list
            mTasks = Collections.emptyList();
            mNumHiddenTasks = tasks.size();
        }
    }

    @Nullable
    private DesktopTask findDesktopTask(ArrayList<GroupTask> tasks) {
        return (DesktopTask) tasks.stream()
                .filter(t -> t instanceof DesktopTask)
                .findFirst()
                .orElse(null);
    }

    void closeQuickSwitchView() {
        if (mQuickSwitchViewController == null) {
            return;
        }
        mQuickSwitchViewController.closeQuickSwitchView(true);
    }

    /**
     * See {@link TaskbarUIController#launchFocusedTask()}
     */
    int launchFocusedTask() {
        // Return -1 so that the RecentsView is not incorrectly opened when the user closes the
        // quick switch view by tapping the screen or when there are no recent tasks.
        return mQuickSwitchViewController == null || mTasks.isEmpty()
                ? -1 : mQuickSwitchViewController.launchFocusedTask();
    }

    void onDestroy() {
        if (mQuickSwitchViewController != null) {
            mQuickSwitchViewController.onDestroy();
        }
    }

    @Override
    public void dumpLogs(String prefix, PrintWriter pw) {
        pw.println(prefix + "KeyboardQuickSwitchController:");

        pw.println(prefix + "\tisOpen=" + (mQuickSwitchViewController != null));
        pw.println(prefix + "\tmNumHiddenTasks=" + mNumHiddenTasks);
        pw.println(prefix + "\tmTaskListChangeId=" + mTaskListChangeId);
        pw.println(prefix + "\tmTasks=[");
        for (GroupTask task : mTasks) {
            Task task1 = task.task1;
            Task task2 = task.task2;
            ComponentName cn1 = task1.getTopComponent();
            ComponentName cn2 = task2 != null ? task2.getTopComponent() : null;
            pw.println(prefix + "\t\tt1: (id=" + task1.key.id
                    + "; package=" + (cn1 != null ? cn1.getPackageName() + ")" : "no package)")
                    + " t2: (id=" + (task2 != null ? task2.key.id : "-1")
                    + "; package=" + (cn2 != null ? cn2.getPackageName() + ")"
                    : "no package)"));
        }
        pw.println(prefix + "\t]");

        if (mQuickSwitchViewController != null) {
            mQuickSwitchViewController.dumpLogs(prefix + '\t', pw);
        }
    }

    class ControllerCallbacks {

        int getTaskCount() {
            return mTasks.size() + (mNumHiddenTasks == 0 ? 0 : 1);
        }

        @Nullable
        GroupTask getTaskAt(int index) {
            return index < 0 || index >= mTasks.size() ? null : mTasks.get(index);
        }

        void updateThumbnailInBackground(Task task, Consumer<ThumbnailData> callback) {
            mModel.getThumbnailCache().updateThumbnailInBackground(task, callback);
        }

        void updateIconInBackground(Task task, Consumer<Task> callback) {
            mModel.getIconCache().updateIconInBackground(task, callback);
        }

        void onCloseComplete() {
            mQuickSwitchViewController = null;
        }
    }
}