blob: 9b65a310ebf777979e27bd5e4d720db69ea68645 [file] [log] [blame]
Sebastian Francobd7919c2023-09-19 10:55:37 -07001package com.android.launcher3
2
Sebastian Franco0b461ef2023-12-08 12:20:07 -06003import android.annotation.TargetApi
4import android.os.Build
5import android.os.Trace
Sebastian Francobd7919c2023-09-19 10:55:37 -07006import androidx.annotation.UiThread
Sebastian Franco0b461ef2023-12-08 12:20:07 -06007import com.android.launcher3.LauncherConstants.TraceEvents
Sebastian Franco6dda7c72023-11-17 18:03:00 -06008import com.android.launcher3.WorkspaceLayoutManager.FIRST_SCREEN_ID
Sebastian Francoe4965122023-12-01 13:27:42 -06009import com.android.launcher3.allapps.AllAppsStore
Sebastian Franco6dda7c72023-11-17 18:03:00 -060010import com.android.launcher3.config.FeatureFlags
11import com.android.launcher3.config.FeatureFlags.shouldShowFirstPageWidget
Sebastian Francobd7919c2023-09-19 10:55:37 -070012import com.android.launcher3.model.BgDataModel
Sebastian Franco6dda7c72023-11-17 18:03:00 -060013import com.android.launcher3.model.StringCache
Sebastian Francobd7919c2023-09-19 10:55:37 -070014import com.android.launcher3.model.data.AppInfo
15import com.android.launcher3.model.data.ItemInfo
16import com.android.launcher3.model.data.LauncherAppWidgetInfo
17import com.android.launcher3.model.data.WorkspaceItemInfo
18import com.android.launcher3.popup.PopupContainerWithArrow
19import com.android.launcher3.util.ComponentKey
Sebastian Franco69fd7422023-10-06 16:48:58 -070020import com.android.launcher3.util.IntArray as LIntArray
21import com.android.launcher3.util.IntSet as LIntSet
Sebastian Francobd7919c2023-09-19 10:55:37 -070022import com.android.launcher3.util.PackageUserKey
23import com.android.launcher3.util.Preconditions
Sebastian Franco0b461ef2023-12-08 12:20:07 -060024import com.android.launcher3.util.RunnableList
Sebastian Francoe4965122023-12-01 13:27:42 -060025import com.android.launcher3.util.TraceHelper
26import com.android.launcher3.util.ViewOnDrawExecutor
Sebastian Franco50b74c32023-11-16 11:36:49 -060027import com.android.launcher3.widget.PendingAddWidgetInfo
Sebastian Francobd7919c2023-09-19 10:55:37 -070028import com.android.launcher3.widget.model.WidgetsListBaseEntry
29import java.util.function.Predicate
30
31class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
Sebastian Franco69fd7422023-10-06 16:48:58 -070032
33 var synchronouslyBoundPages = LIntSet()
34 var pagesToBindSynchronously = LIntSet()
35
Sebastian Francoe4965122023-12-01 13:27:42 -060036 private var isFirstPagePinnedItemEnabled =
Sebastian Franco6dda7c72023-11-17 18:03:00 -060037 (BuildConfig.QSB_ON_FIRST_SCREEN && !FeatureFlags.ENABLE_SMARTSPACE_REMOVAL.get())
38
39 var stringCache: StringCache? = null
40
Sebastian Francoe4965122023-12-01 13:27:42 -060041 var pendingExecutor: ViewOnDrawExecutor? = null
42
43 var workspaceLoading = true
44
45 /**
46 * Refreshes the shortcuts shown on the workspace.
47 *
48 * Implementation of the method from LauncherModel.Callbacks.
49 */
50 override fun startBinding() {
51 TraceHelper.INSTANCE.beginSection("startBinding")
52 // Floating panels (except the full widget sheet) are associated with individual icons. If
53 // we are starting a fresh bind, close all such panels as all the icons are about
54 // to go away.
55 AbstractFloatingView.closeOpenViews(
56 launcher,
57 true,
58 AbstractFloatingView.TYPE_ALL and AbstractFloatingView.TYPE_REBIND_SAFE.inv()
59 )
60 workspaceLoading = true
61
62 // Clear the workspace because it's going to be rebound
63 launcher.dragController.cancelDrag()
64 launcher.workspace.clearDropTargets()
65 launcher.workspace.removeAllWorkspaceScreens()
66 launcher.appWidgetHolder.clearViews()
67 launcher.hotseat?.resetLayout(launcher.deviceProfile.isVerticalBarLayout)
68 TraceHelper.INSTANCE.endSection()
69 }
70
Sebastian Franco0b461ef2023-12-08 12:20:07 -060071 @TargetApi(Build.VERSION_CODES.S)
72 override fun onInitialBindComplete(
73 boundPages: LIntSet,
74 pendingTasks: RunnableList,
Sunny Goyal72a74662024-02-14 12:32:59 -080075 onCompleteSignal: RunnableList,
Sebastian Franco0b461ef2023-12-08 12:20:07 -060076 workspaceItemCount: Int,
77 isBindSync: Boolean
78 ) {
Sunny Goyale337a802024-02-14 15:07:26 -080079 if (Utilities.ATLEAST_S) {
80 Trace.endAsyncSection(
81 TraceEvents.DISPLAY_WORKSPACE_TRACE_METHOD_NAME,
82 TraceEvents.DISPLAY_WORKSPACE_TRACE_COOKIE
83 )
84 }
Sebastian Franco0b461ef2023-12-08 12:20:07 -060085 synchronouslyBoundPages = boundPages
86 pagesToBindSynchronously = LIntSet()
87 clearPendingBinds()
Sebastian Franco0b461ef2023-12-08 12:20:07 -060088 if (!launcher.isInState(LauncherState.ALL_APPS)) {
89 launcher.appsView.appsStore.enableDeferUpdates(AllAppsStore.DEFER_UPDATES_NEXT_DRAW)
90 pendingTasks.add {
91 launcher.appsView.appsStore.disableDeferUpdates(
92 AllAppsStore.DEFER_UPDATES_NEXT_DRAW
93 )
94 }
95 }
Sunny Goyale337a802024-02-14 15:07:26 -080096 val executor =
97 ViewOnDrawExecutor(pendingTasks) {
98 if (pendingExecutor == it) {
99 pendingExecutor = null
Sebastian Franco0b461ef2023-12-08 12:20:07 -0600100 }
101 }
Sunny Goyale337a802024-02-14 15:07:26 -0800102 pendingExecutor = executor
Sunny Goyal72a74662024-02-14 12:32:59 -0800103
104 if (Flags.enableWorkspaceInflation()) {
105 // Finish the executor as soon as the pending inflation is completed
106 onCompleteSignal.add(executor::markCompleted)
107 } else {
108 // Pending executor is already completed, wait until first draw to run the tasks
109 executor.attachTo(launcher)
110 }
Sunny Goyale337a802024-02-14 15:07:26 -0800111 launcher.bindComplete(workspaceItemCount, isBindSync)
Sebastian Franco0b461ef2023-12-08 12:20:07 -0600112 }
113
Sebastian Francoe4965122023-12-01 13:27:42 -0600114 /**
Sebastian Franco6196b902023-12-06 11:39:52 -0600115 * Callback saying that there aren't any more items to bind.
116 *
117 * Implementation of the method from LauncherModel.Callbacks.
118 */
119 override fun finishBindingItems(pagesBoundFirst: LIntSet?) {
120 TraceHelper.INSTANCE.beginSection("finishBindingItems")
121 val deviceProfile = launcher.deviceProfile
122 launcher.workspace.restoreInstanceStateForRemainingPages()
123 workspaceLoading = false
124 launcher.processActivityResult()
125 val currentPage =
126 if (pagesBoundFirst != null && !pagesBoundFirst.isEmpty)
127 launcher.workspace.getPageIndexForScreenId(pagesBoundFirst.array[0])
128 else PagedView.INVALID_PAGE
129 // When undoing the removal of the last item on a page, return to that page.
130 // Since we are just resetting the current page without user interaction,
131 // override the previous page so we don't log the page switch.
132 launcher.workspace.setCurrentPage(currentPage, currentPage /* overridePrevPage */)
Sebastian Franco0b461ef2023-12-08 12:20:07 -0600133 pagesToBindSynchronously = LIntSet()
Sebastian Franco6196b902023-12-06 11:39:52 -0600134
135 // Cache one page worth of icons
136 launcher.viewCache.setCacheSize(
137 R.layout.folder_application,
Thales Lima1faa4ed2023-12-01 16:48:19 +0000138 deviceProfile.numFolderColumns * deviceProfile.numFolderRows
Sebastian Franco6196b902023-12-06 11:39:52 -0600139 )
140 launcher.viewCache.setCacheSize(R.layout.folder_page, 2)
141 TraceHelper.INSTANCE.endSection()
142 launcher.workspace.removeExtraEmptyScreen(/* stripEmptyScreens= */ true)
Shamali Pef4b1022024-02-19 18:05:27 +0000143 launcher.workspace.pageIndicator.setPauseScroll(/*pause=*/ false, deviceProfile.isTwoPanels)
Sebastian Franco6196b902023-12-06 11:39:52 -0600144 }
145
146 /**
Sebastian Francoe4965122023-12-01 13:27:42 -0600147 * Clear any pending bind callbacks. This is called when is loader is planning to perform a full
148 * rebind from scratch.
149 */
150 override fun clearPendingBinds() {
151 pendingExecutor?.cancel() ?: return
152 pendingExecutor = null
153
154 // We might have set this flag previously and forgot to clear it.
155 launcher.appsView.appsStore.disableDeferUpdatesSilently(
156 AllAppsStore.DEFER_UPDATES_NEXT_DRAW
157 )
158 }
159
Sebastian Francobd7919c2023-09-19 10:55:37 -0700160 override fun preAddApps() {
161 // If there's an undo snackbar, force it to complete to ensure empty screens are removed
162 // before trying to add new items.
163 launcher.modelWriter.commitDelete()
164 val snackbar =
165 AbstractFloatingView.getOpenView<AbstractFloatingView>(
166 launcher,
167 AbstractFloatingView.TYPE_SNACKBAR
168 )
169 snackbar?.post { snackbar.close(true) }
170 }
171
172 @UiThread
173 override fun bindAllApplications(
174 apps: Array<AppInfo?>?,
175 flags: Int,
176 packageUserKeytoUidMap: Map<PackageUserKey?, Int?>?
177 ) {
178 Preconditions.assertUIThread()
179 val hadWorkApps = launcher.appsView.shouldShowTabs()
180 launcher.appsView.appsStore.setApps(apps, flags, packageUserKeytoUidMap)
181 PopupContainerWithArrow.dismissInvalidPopup(launcher)
Alex Chau61d19382024-02-12 17:36:57 +0000182 if (
183 hadWorkApps != launcher.appsView.shouldShowTabs() &&
184 launcher.stateManager.state == LauncherState.ALL_APPS
185 ) {
Sebastian Francobd7919c2023-09-19 10:55:37 -0700186 launcher.stateManager.goToState(LauncherState.NORMAL)
187 }
188 }
189
190 /**
191 * Copies LauncherModel's map of activities to shortcut counts to Launcher's. This is necessary
192 * because LauncherModel's map is updated in the background, while Launcher runs on the UI.
193 */
194 override fun bindDeepShortcutMap(deepShortcutMapCopy: HashMap<ComponentKey?, Int?>?) {
195 launcher.popupDataProvider.setDeepShortcutMap(deepShortcutMapCopy)
196 }
197
198 override fun bindIncrementalDownloadProgressUpdated(app: AppInfo?) {
199 launcher.appsView.appsStore.updateProgressBar(app)
200 }
201
202 override fun bindWidgetsRestored(widgets: ArrayList<LauncherAppWidgetInfo?>?) {
203 launcher.workspace.widgetsRestored(widgets)
204 }
205
206 /**
207 * Some shortcuts were updated in the background. Implementation of the method from
208 * LauncherModel.Callbacks.
209 *
210 * @param updated list of shortcuts which have changed.
211 */
212 override fun bindWorkspaceItemsChanged(updated: List<WorkspaceItemInfo?>) {
213 if (updated.isNotEmpty()) {
214 launcher.workspace.updateWorkspaceItems(updated, launcher)
215 PopupContainerWithArrow.dismissInvalidPopup(launcher)
216 }
217 }
218
219 /**
220 * Update the state of a package, typically related to install state. Implementation of the
221 * method from LauncherModel.Callbacks.
222 */
223 override fun bindRestoreItemsChange(updates: HashSet<ItemInfo?>?) {
224 launcher.workspace.updateRestoreItems(updates, launcher)
225 }
226
227 /**
228 * A package was uninstalled/updated. We take both the super set of packageNames in addition to
229 * specific applications to remove, the reason being that this can be called when a package is
230 * updated as well. In that scenario, we only remove specific components from the workspace and
231 * hotseat, where as package-removal should clear all items by package name.
232 */
233 override fun bindWorkspaceComponentsRemoved(matcher: Predicate<ItemInfo?>?) {
234 launcher.workspace.removeItemsByMatcher(matcher)
235 launcher.dragController.onAppsRemoved(matcher)
236 PopupContainerWithArrow.dismissInvalidPopup(launcher)
237 }
238
239 override fun bindAllWidgets(allWidgets: List<WidgetsListBaseEntry?>?) {
240 launcher.popupDataProvider.allWidgets = allWidgets
241 }
Sebastian Franco69fd7422023-10-06 16:48:58 -0700242
243 /** Returns the ids of the workspaces to bind. */
244 override fun getPagesToBindSynchronously(orderedScreenIds: LIntArray): LIntSet {
245 // If workspace binding is still in progress, getCurrentPageScreenIds won't be
246 // accurate, and we should use mSynchronouslyBoundPages that's set during initial binding.
247 val visibleIds =
248 when {
249 !pagesToBindSynchronously.isEmpty -> pagesToBindSynchronously
Sebastian Francoe4965122023-12-01 13:27:42 -0600250 !workspaceLoading -> launcher.workspace.currentPageScreenIds
Sebastian Franco69fd7422023-10-06 16:48:58 -0700251 else -> synchronouslyBoundPages
252 }
253 // Launcher IntArray has the same name as Kotlin IntArray
254 val result = LIntSet()
255 if (visibleIds.isEmpty) {
256 return result
257 }
258 val actualIds = orderedScreenIds.clone()
259 val firstId = visibleIds.first()
260 val pairId = launcher.workspace.getScreenPair(firstId)
261 // Double check that actual screenIds contains the visibleId, as empty screens are hidden
262 // in single panel.
263 if (actualIds.contains(firstId)) {
264 result.add(firstId)
265 if (launcher.deviceProfile.isTwoPanels && actualIds.contains(pairId)) {
266 result.add(pairId)
267 }
268 } else if (
269 LauncherAppState.getIDP(launcher).supportedProfiles.any(DeviceProfile::isTwoPanels) &&
270 actualIds.contains(pairId)
271 ) {
272 // Add the right panel if left panel is hidden when switching display, due to empty
273 // pages being hidden in single panel.
274 result.add(pairId)
275 }
276 return result
277 }
Sebastian Franco50b74c32023-11-16 11:36:49 -0600278
279 override fun bindSmartspaceWidget() {
280 val cl: CellLayout? =
281 launcher.workspace.getScreenWithId(WorkspaceLayoutManager.FIRST_SCREEN_ID)
282 val spanX = InvariantDeviceProfile.INSTANCE.get(launcher).numSearchContainerColumns
283
284 if (cl?.isRegionVacant(0, 0, spanX, 1) != true) {
285 return
286 }
287
288 val widgetsListBaseEntry: WidgetsListBaseEntry =
289 launcher.popupDataProvider.allWidgets.firstOrNull { item: WidgetsListBaseEntry ->
290 item.mPkgItem.packageName == BuildConfig.APPLICATION_ID
291 }
292 ?: return
293
294 val info =
295 PendingAddWidgetInfo(
296 widgetsListBaseEntry.mWidgets[0].widgetInfo,
297 LauncherSettings.Favorites.CONTAINER_DESKTOP
298 )
299 launcher.addPendingItem(
300 info,
301 info.container,
302 WorkspaceLayoutManager.FIRST_SCREEN_ID,
303 intArrayOf(0, 0),
304 info.spanX,
305 info.spanY
306 )
307 }
Sebastian Franco6dda7c72023-11-17 18:03:00 -0600308
Sebastian Franco6196b902023-12-06 11:39:52 -0600309 override fun bindScreens(orderedScreenIds: LIntArray) {
Shamali Pef4b1022024-02-19 18:05:27 +0000310 launcher.workspace.pageIndicator.setPauseScroll(
311 /*pause=*/ true,
Sebastian Franco6dda7c72023-11-17 18:03:00 -0600312 launcher.deviceProfile.isTwoPanels
313 )
314 val firstScreenPosition = 0
315 if (
316 (FeatureFlags.QSB_ON_FIRST_SCREEN &&
317 isFirstPagePinnedItemEnabled &&
318 !shouldShowFirstPageWidget()) &&
319 orderedScreenIds.indexOf(FIRST_SCREEN_ID) != firstScreenPosition
320 ) {
321 orderedScreenIds.removeValue(FIRST_SCREEN_ID)
322 orderedScreenIds.add(firstScreenPosition, FIRST_SCREEN_ID)
323 } else if (
324 (!FeatureFlags.QSB_ON_FIRST_SCREEN && !isFirstPagePinnedItemEnabled ||
325 shouldShowFirstPageWidget()) && orderedScreenIds.isEmpty
326 ) {
327 // If there are no screens, we need to have an empty screen
328 launcher.workspace.addExtraEmptyScreens()
329 }
330 bindAddScreens(orderedScreenIds)
331
332 // After we have added all the screens, if the wallpaper was locked to the default state,
333 // then notify to indicate that it can be released and a proper wallpaper offset can be
334 // computed before the next layout
335 launcher.workspace.unlockWallpaperFromDefaultPageOnNextLayout()
336 }
337
338 override fun bindAppsAdded(
Sebastian Franco6196b902023-12-06 11:39:52 -0600339 newScreens: LIntArray?,
Sebastian Franco6dda7c72023-11-17 18:03:00 -0600340 addNotAnimated: java.util.ArrayList<ItemInfo?>?,
341 addAnimated: java.util.ArrayList<ItemInfo?>?
342 ) {
343 // Add the new screens
344 if (newScreens != null) {
345 // newScreens can contain an empty right panel that is already bound, but not known
346 // by BgDataModel.
347 newScreens.removeAllValues(launcher.workspace.mScreenOrder)
348 bindAddScreens(newScreens)
349 }
350
351 // We add the items without animation on non-visible pages, and with
352 // animations on the new page (which we will try and snap to).
353 if (!addNotAnimated.isNullOrEmpty()) {
354 launcher.bindItems(addNotAnimated, false)
355 }
356 if (!addAnimated.isNullOrEmpty()) {
357 launcher.bindItems(addAnimated, true)
358 }
359
360 // Remove the extra empty screen
361 launcher.workspace.removeExtraEmptyScreen(false)
362 }
363
Sebastian Franco6196b902023-12-06 11:39:52 -0600364 private fun bindAddScreens(orderedScreenIdsArg: LIntArray) {
Sebastian Franco6dda7c72023-11-17 18:03:00 -0600365 var orderedScreenIds = orderedScreenIdsArg
366 if (launcher.deviceProfile.isTwoPanels) {
367 if (FeatureFlags.FOLDABLE_SINGLE_PAGE.get()) {
368 orderedScreenIds = filterTwoPanelScreenIds(orderedScreenIds)
369 } else {
370 // Some empty pages might have been removed while the phone was in a single panel
371 // mode, so we want to add those empty pages back.
Sebastian Franco0b461ef2023-12-08 12:20:07 -0600372 val screenIds = LIntSet.wrap(orderedScreenIds)
Sebastian Franco6dda7c72023-11-17 18:03:00 -0600373 orderedScreenIds.forEach { screenId: Int ->
374 screenIds.add(launcher.workspace.getScreenPair(screenId))
375 }
376 orderedScreenIds = screenIds.array
377 }
378 }
379 orderedScreenIds
380 .filterNot { screenId ->
381 FeatureFlags.QSB_ON_FIRST_SCREEN &&
382 isFirstPagePinnedItemEnabled &&
383 !FeatureFlags.shouldShowFirstPageWidget() &&
384 screenId == WorkspaceLayoutManager.FIRST_SCREEN_ID
385 }
386 .forEach { screenId ->
387 launcher.workspace.insertNewWorkspaceScreenBeforeEmptyScreen(screenId)
388 }
389 }
390
391 /**
392 * Remove odd number because they are already included when isTwoPanels and add the pair screen
393 * if not present.
394 */
Sebastian Franco6196b902023-12-06 11:39:52 -0600395 private fun filterTwoPanelScreenIds(orderedScreenIds: LIntArray): LIntArray {
Sebastian Franco0b461ef2023-12-08 12:20:07 -0600396 val screenIds = LIntSet.wrap(orderedScreenIds)
Sebastian Franco6dda7c72023-11-17 18:03:00 -0600397 orderedScreenIds
398 .filter { screenId -> screenId % 2 == 1 }
399 .forEach { screenId ->
400 screenIds.remove(screenId)
401 // In case the pair is not added, add it
402 if (!launcher.workspace.containsScreenId(screenId - 1)) {
403 screenIds.add(screenId - 1)
404 }
405 }
406 return screenIds.array
407 }
408
409 override fun setIsFirstPagePinnedItemEnabled(isFirstPagePinnedItemEnabled: Boolean) {
410 this.isFirstPagePinnedItemEnabled = isFirstPagePinnedItemEnabled
411 launcher.workspace.bindAndInitFirstWorkspaceScreen()
412 }
413
414 override fun bindStringCache(cache: StringCache) {
415 stringCache = cache
416 launcher.appsView.updateWorkUI()
417 }
418
419 fun getIsFirstPagePinnedItemEnabled(): Boolean = isFirstPagePinnedItemEnabled
Sunny Goyal72a74662024-02-14 12:32:59 -0800420
421 override fun getItemInflater() = launcher.itemInflater
Sebastian Francobd7919c2023-09-19 10:55:37 -0700422}