LauncherModel.java revision 6c56c68555dcb3d99b05d5faecd582a1f683cc92
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.launcher3; 18 19import android.app.SearchManager; 20import android.appwidget.AppWidgetProviderInfo; 21import android.content.BroadcastReceiver; 22import android.content.ComponentName; 23import android.content.ContentProviderOperation; 24import android.content.ContentResolver; 25import android.content.ContentValues; 26import android.content.Context; 27import android.content.Intent; 28import android.content.Intent.ShortcutIconResource; 29import android.content.IntentFilter; 30import android.content.pm.PackageManager; 31import android.content.pm.ProviderInfo; 32import android.content.pm.ResolveInfo; 33import android.database.Cursor; 34import android.graphics.Bitmap; 35import android.net.Uri; 36import android.os.Build; 37import android.os.Environment; 38import android.os.Handler; 39import android.os.HandlerThread; 40import android.os.Looper; 41import android.os.Parcelable; 42import android.os.Process; 43import android.os.SystemClock; 44import android.os.TransactionTooLargeException; 45import android.provider.BaseColumns; 46import android.text.TextUtils; 47import android.util.Log; 48import android.util.LongSparseArray; 49import android.util.Pair; 50 51import com.android.launcher3.compat.AppWidgetManagerCompat; 52import com.android.launcher3.compat.LauncherActivityInfoCompat; 53import com.android.launcher3.compat.LauncherAppsCompat; 54import com.android.launcher3.compat.PackageInstallerCompat; 55import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo; 56import com.android.launcher3.compat.UserHandleCompat; 57import com.android.launcher3.compat.UserManagerCompat; 58import com.android.launcher3.config.ProviderConfig; 59import com.android.launcher3.model.WidgetsModel; 60import com.android.launcher3.util.ComponentKey; 61import com.android.launcher3.util.CursorIconInfo; 62import com.android.launcher3.util.LongArrayMap; 63import com.android.launcher3.util.ManagedProfileHeuristic; 64import com.android.launcher3.util.Thunk; 65 66import java.lang.ref.WeakReference; 67import java.net.URISyntaxException; 68import java.security.InvalidParameterException; 69import java.util.ArrayList; 70import java.util.Arrays; 71import java.util.Collection; 72import java.util.Collections; 73import java.util.Comparator; 74import java.util.HashMap; 75import java.util.HashSet; 76import java.util.Iterator; 77import java.util.List; 78import java.util.Map.Entry; 79import java.util.Set; 80 81/** 82 * Maintains in-memory state of the Launcher. It is expected that there should be only one 83 * LauncherModel object held in a static. Also provide APIs for updating the database state 84 * for the Launcher. 85 */ 86public class LauncherModel extends BroadcastReceiver 87 implements LauncherAppsCompat.OnAppsChangedCallbackCompat { 88 static final boolean DEBUG_LOADERS = false; 89 private static final boolean DEBUG_RECEIVER = false; 90 private static final boolean REMOVE_UNRESTORED_ICONS = true; 91 92 static final String TAG = "Launcher.Model"; 93 94 public static final int LOADER_FLAG_NONE = 0; 95 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0; 96 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1; 97 98 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons 99 private static final long INVALID_SCREEN_ID = -1L; 100 101 @Thunk final boolean mAppsCanBeOnRemoveableStorage; 102 private final boolean mOldContentProviderExists; 103 104 @Thunk final LauncherAppState mApp; 105 @Thunk final Object mLock = new Object(); 106 @Thunk DeferredHandler mHandler = new DeferredHandler(); 107 @Thunk LoaderTask mLoaderTask; 108 @Thunk boolean mIsLoaderTaskRunning; 109 @Thunk boolean mHasLoaderCompletedOnce; 110 111 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings"; 112 113 @Thunk static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader"); 114 static { 115 sWorkerThread.start(); 116 } 117 @Thunk static final Handler sWorker = new Handler(sWorkerThread.getLooper()); 118 119 // We start off with everything not loaded. After that, we assume that 120 // our monitoring of the package manager provides all updates and we never 121 // need to do a requery. These are only ever touched from the loader thread. 122 @Thunk boolean mWorkspaceLoaded; 123 @Thunk boolean mAllAppsLoaded; 124 125 // When we are loading pages synchronously, we can't just post the binding of items on the side 126 // pages as this delays the rotation process. Instead, we wait for a callback from the first 127 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start 128 // a normal load, we also clear this set of Runnables. 129 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>(); 130 131 /** 132 * Set of runnables to be called on the background thread after the workspace binding 133 * is complete. 134 */ 135 static final ArrayList<Runnable> mBindCompleteRunnables = new ArrayList<Runnable>(); 136 137 @Thunk WeakReference<Callbacks> mCallbacks; 138 139 // < only access in worker thread > 140 AllAppsList mBgAllAppsList; 141 // Entire list of widgets. 142 WidgetsModel mBgWidgetsModel; 143 144 // The lock that must be acquired before referencing any static bg data structures. Unlike 145 // other locks, this one can generally be held long-term because we never expect any of these 146 // static data structures to be referenced outside of the worker thread except on the first 147 // load after configuration change. 148 static final Object sBgLock = new Object(); 149 150 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by 151 // LauncherModel to their ids 152 static final LongArrayMap<ItemInfo> sBgItemsIdMap = new LongArrayMap<>(); 153 154 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts 155 // created by LauncherModel that are directly on the home screen (however, no widgets or 156 // shortcuts within folders). 157 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>(); 158 159 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget() 160 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets = 161 new ArrayList<LauncherAppWidgetInfo>(); 162 163 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders() 164 static final LongArrayMap<FolderInfo> sBgFolders = new LongArrayMap<>(); 165 166 // sBgWorkspaceScreens is the ordered set of workspace screens. 167 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>(); 168 169 // sBgWidgetProviders is the set of widget providers including custom internal widgets 170 public static HashMap<ComponentKey, LauncherAppWidgetProviderInfo> sBgWidgetProviders; 171 172 // sPendingPackages is a set of packages which could be on sdcard and are not available yet 173 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages = 174 new HashMap<UserHandleCompat, HashSet<String>>(); 175 176 // </ only access in worker thread > 177 178 @Thunk IconCache mIconCache; 179 180 @Thunk final LauncherAppsCompat mLauncherApps; 181 @Thunk final UserManagerCompat mUserManager; 182 183 public interface Callbacks { 184 public boolean setLoadOnResume(); 185 public int getCurrentWorkspaceScreen(); 186 public void startBinding(); 187 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end, 188 boolean forceAnimateIcons); 189 public void bindScreens(ArrayList<Long> orderedScreenIds); 190 public void bindAddScreens(ArrayList<Long> orderedScreenIds); 191 public void bindFolders(LongArrayMap<FolderInfo> folders); 192 public void finishBindingItems(); 193 public void bindAppWidget(LauncherAppWidgetInfo info); 194 public void bindAllApplications(ArrayList<AppInfo> apps); 195 public void bindAppsAdded(ArrayList<Long> newScreens, 196 ArrayList<ItemInfo> addNotAnimated, 197 ArrayList<ItemInfo> addAnimated, 198 ArrayList<AppInfo> addedApps); 199 public void bindAppsUpdated(ArrayList<AppInfo> apps); 200 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated, 201 ArrayList<ShortcutInfo> removed, UserHandleCompat user); 202 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets); 203 public void bindRestoreItemsChange(HashSet<ItemInfo> updates); 204 public void bindComponentsRemoved(ArrayList<String> packageNames, 205 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason); 206 public void bindAllPackages(WidgetsModel model); 207 public void bindSearchablesChanged(); 208 public boolean isAllAppsButtonRank(int rank); 209 public void onPageBoundSynchronously(int page); 210 public void dumpLogsToLocalData(); 211 } 212 213 public interface ItemInfoFilter { 214 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn); 215 } 216 217 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) { 218 Context context = app.getContext(); 219 220 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable(); 221 String oldProvider = context.getString(R.string.old_launcher_provider_uri); 222 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different 223 // resource string. 224 String redirectAuthority = Uri.parse(oldProvider).getAuthority(); 225 ProviderInfo providerInfo = 226 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0); 227 ProviderInfo redirectProvider = 228 context.getPackageManager().resolveContentProvider(redirectAuthority, 0); 229 230 Log.d(TAG, "Old launcher provider: " + oldProvider); 231 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null); 232 233 if (mOldContentProviderExists) { 234 Log.d(TAG, "Old launcher provider exists."); 235 } else { 236 Log.d(TAG, "Old launcher provider does not exist."); 237 } 238 239 mApp = app; 240 mBgAllAppsList = new AllAppsList(iconCache, appFilter); 241 mBgWidgetsModel = new WidgetsModel(context, iconCache, appFilter); 242 mIconCache = iconCache; 243 244 mLauncherApps = LauncherAppsCompat.getInstance(context); 245 mUserManager = UserManagerCompat.getInstance(context); 246 } 247 248 /** Runs the specified runnable immediately if called from the main thread, otherwise it is 249 * posted on the main thread handler. */ 250 @Thunk void runOnMainThread(Runnable r) { 251 if (sWorkerThread.getThreadId() == Process.myTid()) { 252 // If we are on the worker thread, post onto the main handler 253 mHandler.post(r); 254 } else { 255 r.run(); 256 } 257 } 258 259 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is 260 * posted on the worker thread handler. */ 261 private static void runOnWorkerThread(Runnable r) { 262 if (sWorkerThread.getThreadId() == Process.myTid()) { 263 r.run(); 264 } else { 265 // If we are not on the worker thread, then post to the worker handler 266 sWorker.post(r); 267 } 268 } 269 270 /** 271 * Runs the specified runnable after the loader is complete 272 */ 273 @Thunk void runAfterBindCompletes(Runnable r) { 274 if (isLoadingWorkspace() || !mHasLoaderCompletedOnce) { 275 synchronized (mBindCompleteRunnables) { 276 mBindCompleteRunnables.add(r); 277 } 278 } else { 279 runOnWorkerThread(r); 280 } 281 } 282 283 boolean canMigrateFromOldLauncherDb(Launcher launcher) { 284 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ; 285 } 286 287 public void setPackageState(final PackageInstallInfo installInfo) { 288 Runnable updateRunnable = new Runnable() { 289 290 @Override 291 public void run() { 292 synchronized (sBgLock) { 293 final HashSet<ItemInfo> updates = new HashSet<>(); 294 295 if (installInfo.state == PackageInstallerCompat.STATUS_INSTALLED) { 296 // Ignore install success events as they are handled by Package add events. 297 return; 298 } 299 300 for (ItemInfo info : sBgItemsIdMap) { 301 if (info instanceof ShortcutInfo) { 302 ShortcutInfo si = (ShortcutInfo) info; 303 ComponentName cn = si.getTargetComponent(); 304 if (si.isPromise() && (cn != null) 305 && installInfo.packageName.equals(cn.getPackageName())) { 306 si.setInstallProgress(installInfo.progress); 307 308 if (installInfo.state == PackageInstallerCompat.STATUS_FAILED) { 309 // Mark this info as broken. 310 si.status &= ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE; 311 } 312 updates.add(si); 313 } 314 } 315 } 316 317 for (LauncherAppWidgetInfo widget : sBgAppWidgets) { 318 if (widget.providerName.getPackageName().equals(installInfo.packageName)) { 319 widget.installProgress = installInfo.progress; 320 updates.add(widget); 321 } 322 } 323 324 if (!updates.isEmpty()) { 325 // Push changes to the callback. 326 Runnable r = new Runnable() { 327 public void run() { 328 Callbacks callbacks = getCallback(); 329 if (callbacks != null) { 330 callbacks.bindRestoreItemsChange(updates); 331 } 332 } 333 }; 334 mHandler.post(r); 335 } 336 } 337 } 338 }; 339 runOnWorkerThread(updateRunnable); 340 } 341 342 /** 343 * Updates the icons and label of all pending icons for the provided package name. 344 */ 345 public void updateSessionDisplayInfo(final String packageName) { 346 Runnable updateRunnable = new Runnable() { 347 348 @Override 349 public void run() { 350 synchronized (sBgLock) { 351 final ArrayList<ShortcutInfo> updates = new ArrayList<>(); 352 final UserHandleCompat user = UserHandleCompat.myUserHandle(); 353 354 for (ItemInfo info : sBgItemsIdMap) { 355 if (info instanceof ShortcutInfo) { 356 ShortcutInfo si = (ShortcutInfo) info; 357 ComponentName cn = si.getTargetComponent(); 358 if (si.isPromise() && (cn != null) 359 && packageName.equals(cn.getPackageName())) { 360 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) { 361 // For auto install apps update the icon as well as label. 362 mIconCache.getTitleAndIcon(si, 363 si.promisedIntent, user, 364 si.shouldUseLowResIcon()); 365 } else { 366 // Only update the icon for restored apps. 367 si.updateIcon(mIconCache); 368 } 369 updates.add(si); 370 } 371 } 372 } 373 374 if (!updates.isEmpty()) { 375 // Push changes to the callback. 376 Runnable r = new Runnable() { 377 public void run() { 378 Callbacks callbacks = getCallback(); 379 if (callbacks != null) { 380 callbacks.bindShortcutsChanged(updates, 381 new ArrayList<ShortcutInfo>(), user); 382 } 383 } 384 }; 385 mHandler.post(r); 386 } 387 } 388 } 389 }; 390 runOnWorkerThread(updateRunnable); 391 } 392 393 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) { 394 final Callbacks callbacks = getCallback(); 395 396 if (allAppsApps == null) { 397 throw new RuntimeException("allAppsApps must not be null"); 398 } 399 if (allAppsApps.isEmpty()) { 400 return; 401 } 402 403 // Process the newly added applications and add them to the database first 404 Runnable r = new Runnable() { 405 public void run() { 406 runOnMainThread(new Runnable() { 407 public void run() { 408 Callbacks cb = getCallback(); 409 if (callbacks == cb && cb != null) { 410 callbacks.bindAppsAdded(null, null, null, allAppsApps); 411 } 412 } 413 }); 414 } 415 }; 416 runOnWorkerThread(r); 417 } 418 419 private static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> occupiedPos, 420 int[] xy, int spanX, int spanY) { 421 LauncherAppState app = LauncherAppState.getInstance(); 422 InvariantDeviceProfile profile = app.getInvariantDeviceProfile(); 423 final int xCount = (int) profile.numColumns; 424 final int yCount = (int) profile.numRows; 425 boolean[][] occupied = new boolean[xCount][yCount]; 426 if (occupiedPos != null) { 427 for (ItemInfo r : occupiedPos) { 428 int right = r.cellX + r.spanX; 429 int bottom = r.cellY + r.spanY; 430 for (int x = r.cellX; 0 <= x && x < right && x < xCount; x++) { 431 for (int y = r.cellY; 0 <= y && y < bottom && y < yCount; y++) { 432 occupied[x][y] = true; 433 } 434 } 435 } 436 } 437 return Utilities.findVacantCell(xy, spanX, spanY, xCount, yCount, occupied); 438 } 439 440 /** 441 * Find a position on the screen for the given size or adds a new screen. 442 * @return screenId and the coordinates for the item. 443 */ 444 @Thunk Pair<Long, int[]> findSpaceForItem( 445 Context context, 446 ArrayList<Long> workspaceScreens, 447 ArrayList<Long> addedWorkspaceScreensFinal, 448 int spanX, int spanY) { 449 LongSparseArray<ArrayList<ItemInfo>> screenItems = new LongSparseArray<>(); 450 451 // Use sBgItemsIdMap as all the items are already loaded. 452 assertWorkspaceLoaded(); 453 synchronized (sBgLock) { 454 for (ItemInfo info : sBgItemsIdMap) { 455 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { 456 ArrayList<ItemInfo> items = screenItems.get(info.screenId); 457 if (items == null) { 458 items = new ArrayList<>(); 459 screenItems.put(info.screenId, items); 460 } 461 items.add(info); 462 } 463 } 464 } 465 466 // Find appropriate space for the item. 467 long screenId = 0; 468 int[] cordinates = new int[2]; 469 boolean found = false; 470 471 int screenCount = workspaceScreens.size(); 472 // First check the preferred screen. 473 int preferredScreenIndex = workspaceScreens.isEmpty() ? 0 : 1; 474 if (preferredScreenIndex < screenCount) { 475 screenId = workspaceScreens.get(preferredScreenIndex); 476 found = findNextAvailableIconSpaceInScreen( 477 screenItems.get(screenId), cordinates, spanX, spanY); 478 } 479 480 if (!found) { 481 // Search on any of the screens starting from the first screen. 482 for (int screen = 1; screen < screenCount; screen++) { 483 screenId = workspaceScreens.get(screen); 484 if (findNextAvailableIconSpaceInScreen( 485 screenItems.get(screenId), cordinates, spanX, spanY)) { 486 // We found a space for it 487 found = true; 488 break; 489 } 490 } 491 } 492 493 if (!found) { 494 // Still no position found. Add a new screen to the end. 495 screenId = LauncherAppState.getLauncherProvider().generateNewScreenId(); 496 497 // Save the screen id for binding in the workspace 498 workspaceScreens.add(screenId); 499 addedWorkspaceScreensFinal.add(screenId); 500 501 // If we still can't find an empty space, then God help us all!!! 502 if (!findNextAvailableIconSpaceInScreen( 503 screenItems.get(screenId), cordinates, spanX, spanY)) { 504 throw new RuntimeException("Can't find space to add the item"); 505 } 506 } 507 return Pair.create(screenId, cordinates); 508 } 509 510 /** 511 * Adds the provided items to the workspace. 512 */ 513 public void addAndBindAddedWorkspaceItems(final Context context, 514 final ArrayList<? extends ItemInfo> workspaceApps) { 515 final Callbacks callbacks = getCallback(); 516 if (workspaceApps.isEmpty()) { 517 return; 518 } 519 // Process the newly added applications and add them to the database first 520 Runnable r = new Runnable() { 521 public void run() { 522 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>(); 523 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>(); 524 525 // Get the list of workspace screens. We need to append to this list and 526 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been 527 // called. 528 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context); 529 synchronized(sBgLock) { 530 for (ItemInfo item : workspaceApps) { 531 if (item instanceof ShortcutInfo) { 532 // Short-circuit this logic if the icon exists somewhere on the workspace 533 if (shortcutExists(context, item.getIntent(), item.user)) { 534 continue; 535 } 536 } 537 538 // Find appropriate space for the item. 539 Pair<Long, int[]> coords = findSpaceForItem(context, 540 workspaceScreens, addedWorkspaceScreensFinal, 541 1, 1); 542 long screenId = coords.first; 543 int[] cordinates = coords.second; 544 545 ItemInfo itemInfo; 546 if (item instanceof ShortcutInfo || item instanceof FolderInfo) { 547 itemInfo = item; 548 } else if (item instanceof AppInfo) { 549 itemInfo = ((AppInfo) item).makeShortcut(); 550 } else { 551 throw new RuntimeException("Unexpected info type"); 552 } 553 554 // Add the shortcut to the db 555 addItemToDatabase(context, itemInfo, 556 LauncherSettings.Favorites.CONTAINER_DESKTOP, 557 screenId, cordinates[0], cordinates[1]); 558 // Save the ShortcutInfo for binding in the workspace 559 addedShortcutsFinal.add(itemInfo); 560 } 561 } 562 563 // Update the workspace screens 564 updateWorkspaceScreenOrder(context, workspaceScreens); 565 566 if (!addedShortcutsFinal.isEmpty()) { 567 runOnMainThread(new Runnable() { 568 public void run() { 569 Callbacks cb = getCallback(); 570 if (callbacks == cb && cb != null) { 571 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>(); 572 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>(); 573 if (!addedShortcutsFinal.isEmpty()) { 574 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1); 575 long lastScreenId = info.screenId; 576 for (ItemInfo i : addedShortcutsFinal) { 577 if (i.screenId == lastScreenId) { 578 addAnimated.add(i); 579 } else { 580 addNotAnimated.add(i); 581 } 582 } 583 } 584 callbacks.bindAppsAdded(addedWorkspaceScreensFinal, 585 addNotAnimated, addAnimated, null); 586 } 587 } 588 }); 589 } 590 } 591 }; 592 runOnWorkerThread(r); 593 } 594 595 private void unbindItemInfosAndClearQueuedBindRunnables() { 596 if (sWorkerThread.getThreadId() == Process.myTid()) { 597 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " + 598 "main thread"); 599 } 600 601 // Clear any deferred bind runnables 602 synchronized (mDeferredBindRunnables) { 603 mDeferredBindRunnables.clear(); 604 } 605 606 // Remove any queued UI runnables 607 mHandler.cancelAll(); 608 // Unbind all the workspace items 609 unbindWorkspaceItemsOnMainThread(); 610 } 611 612 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */ 613 void unbindWorkspaceItemsOnMainThread() { 614 // Ensure that we don't use the same workspace items data structure on the main thread 615 // by making a copy of workspace items first. 616 final ArrayList<ItemInfo> tmpItems = new ArrayList<ItemInfo>(); 617 synchronized (sBgLock) { 618 tmpItems.addAll(sBgWorkspaceItems); 619 tmpItems.addAll(sBgAppWidgets); 620 } 621 Runnable r = new Runnable() { 622 @Override 623 public void run() { 624 for (ItemInfo item : tmpItems) { 625 item.unbind(); 626 } 627 } 628 }; 629 runOnMainThread(r); 630 } 631 632 /** 633 * Adds an item to the DB if it was not created previously, or move it to a new 634 * <container, screen, cellX, cellY> 635 */ 636 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container, 637 long screenId, int cellX, int cellY) { 638 if (item.container == ItemInfo.NO_ID) { 639 // From all apps 640 addItemToDatabase(context, item, container, screenId, cellX, cellY); 641 } else { 642 // From somewhere else 643 moveItemInDatabase(context, item, container, screenId, cellX, cellY); 644 } 645 } 646 647 static void checkItemInfoLocked( 648 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) { 649 ItemInfo modelItem = sBgItemsIdMap.get(itemId); 650 if (modelItem != null && item != modelItem) { 651 // check all the data is consistent 652 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) { 653 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem; 654 ShortcutInfo shortcut = (ShortcutInfo) item; 655 if (modelShortcut.title.toString().equals(shortcut.title.toString()) && 656 modelShortcut.intent.filterEquals(shortcut.intent) && 657 modelShortcut.id == shortcut.id && 658 modelShortcut.itemType == shortcut.itemType && 659 modelShortcut.container == shortcut.container && 660 modelShortcut.screenId == shortcut.screenId && 661 modelShortcut.cellX == shortcut.cellX && 662 modelShortcut.cellY == shortcut.cellY && 663 modelShortcut.spanX == shortcut.spanX && 664 modelShortcut.spanY == shortcut.spanY) { 665 // For all intents and purposes, this is the same object 666 return; 667 } 668 } 669 670 // the modelItem needs to match up perfectly with item if our model is 671 // to be consistent with the database-- for now, just require 672 // modelItem == item or the equality check above 673 String msg = "item: " + ((item != null) ? item.toString() : "null") + 674 "modelItem: " + 675 ((modelItem != null) ? modelItem.toString() : "null") + 676 "Error: ItemInfo passed to checkItemInfo doesn't match original"; 677 RuntimeException e = new RuntimeException(msg); 678 if (stackTrace != null) { 679 e.setStackTrace(stackTrace); 680 } 681 throw e; 682 } 683 } 684 685 static void checkItemInfo(final ItemInfo item) { 686 final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); 687 final long itemId = item.id; 688 Runnable r = new Runnable() { 689 public void run() { 690 synchronized (sBgLock) { 691 checkItemInfoLocked(itemId, item, stackTrace); 692 } 693 } 694 }; 695 runOnWorkerThread(r); 696 } 697 698 static void updateItemInDatabaseHelper(Context context, final ContentValues values, 699 final ItemInfo item, final String callingFunction) { 700 final long itemId = item.id; 701 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId); 702 final ContentResolver cr = context.getContentResolver(); 703 704 final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); 705 Runnable r = new Runnable() { 706 public void run() { 707 cr.update(uri, values, null, null); 708 updateItemArrays(item, itemId, stackTrace); 709 } 710 }; 711 runOnWorkerThread(r); 712 } 713 714 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList, 715 final ArrayList<ItemInfo> items, final String callingFunction) { 716 final ContentResolver cr = context.getContentResolver(); 717 718 final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); 719 Runnable r = new Runnable() { 720 public void run() { 721 ArrayList<ContentProviderOperation> ops = 722 new ArrayList<ContentProviderOperation>(); 723 int count = items.size(); 724 for (int i = 0; i < count; i++) { 725 ItemInfo item = items.get(i); 726 final long itemId = item.id; 727 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId); 728 ContentValues values = valuesList.get(i); 729 730 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); 731 updateItemArrays(item, itemId, stackTrace); 732 733 } 734 try { 735 cr.applyBatch(LauncherProvider.AUTHORITY, ops); 736 } catch (Exception e) { 737 e.printStackTrace(); 738 } 739 } 740 }; 741 runOnWorkerThread(r); 742 } 743 744 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) { 745 // Lock on mBgLock *after* the db operation 746 synchronized (sBgLock) { 747 checkItemInfoLocked(itemId, item, stackTrace); 748 749 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP && 750 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 751 // Item is in a folder, make sure this folder exists 752 if (!sBgFolders.containsKey(item.container)) { 753 // An items container is being set to a that of an item which is not in 754 // the list of Folders. 755 String msg = "item: " + item + " container being set to: " + 756 item.container + ", not in the list of folders"; 757 Log.e(TAG, msg); 758 } 759 } 760 761 // Items are added/removed from the corresponding FolderInfo elsewhere, such 762 // as in Workspace.onDrop. Here, we just add/remove them from the list of items 763 // that are on the desktop, as appropriate 764 ItemInfo modelItem = sBgItemsIdMap.get(itemId); 765 if (modelItem != null && 766 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || 767 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { 768 switch (modelItem.itemType) { 769 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 770 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 771 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 772 if (!sBgWorkspaceItems.contains(modelItem)) { 773 sBgWorkspaceItems.add(modelItem); 774 } 775 break; 776 default: 777 break; 778 } 779 } else { 780 sBgWorkspaceItems.remove(modelItem); 781 } 782 } 783 } 784 785 /** 786 * Move an item in the DB to a new <container, screen, cellX, cellY> 787 */ 788 public static void moveItemInDatabase(Context context, final ItemInfo item, final long container, 789 final long screenId, final int cellX, final int cellY) { 790 item.container = container; 791 item.cellX = cellX; 792 item.cellY = cellY; 793 794 // We store hotseat items in canonical form which is this orientation invariant position 795 // in the hotseat 796 if (context instanceof Launcher && screenId < 0 && 797 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 798 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); 799 } else { 800 item.screenId = screenId; 801 } 802 803 final ContentValues values = new ContentValues(); 804 values.put(LauncherSettings.Favorites.CONTAINER, item.container); 805 values.put(LauncherSettings.Favorites.CELLX, item.cellX); 806 values.put(LauncherSettings.Favorites.CELLY, item.cellY); 807 values.put(LauncherSettings.Favorites.RANK, item.rank); 808 values.put(LauncherSettings.Favorites.SCREEN, item.screenId); 809 810 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase"); 811 } 812 813 /** 814 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the 815 * cellX, cellY have already been updated on the ItemInfos. 816 */ 817 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items, 818 final long container, final int screen) { 819 820 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>(); 821 int count = items.size(); 822 823 for (int i = 0; i < count; i++) { 824 ItemInfo item = items.get(i); 825 item.container = container; 826 827 // We store hotseat items in canonical form which is this orientation invariant position 828 // in the hotseat 829 if (context instanceof Launcher && screen < 0 && 830 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 831 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX, 832 item.cellY); 833 } else { 834 item.screenId = screen; 835 } 836 837 final ContentValues values = new ContentValues(); 838 values.put(LauncherSettings.Favorites.CONTAINER, item.container); 839 values.put(LauncherSettings.Favorites.CELLX, item.cellX); 840 values.put(LauncherSettings.Favorites.CELLY, item.cellY); 841 values.put(LauncherSettings.Favorites.RANK, item.rank); 842 values.put(LauncherSettings.Favorites.SCREEN, item.screenId); 843 844 contentValues.add(values); 845 } 846 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase"); 847 } 848 849 /** 850 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY> 851 */ 852 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container, 853 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) { 854 item.container = container; 855 item.cellX = cellX; 856 item.cellY = cellY; 857 item.spanX = spanX; 858 item.spanY = spanY; 859 860 // We store hotseat items in canonical form which is this orientation invariant position 861 // in the hotseat 862 if (context instanceof Launcher && screenId < 0 && 863 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 864 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); 865 } else { 866 item.screenId = screenId; 867 } 868 869 final ContentValues values = new ContentValues(); 870 values.put(LauncherSettings.Favorites.CONTAINER, item.container); 871 values.put(LauncherSettings.Favorites.CELLX, item.cellX); 872 values.put(LauncherSettings.Favorites.CELLY, item.cellY); 873 values.put(LauncherSettings.Favorites.RANK, item.rank); 874 values.put(LauncherSettings.Favorites.SPANX, item.spanX); 875 values.put(LauncherSettings.Favorites.SPANY, item.spanY); 876 values.put(LauncherSettings.Favorites.SCREEN, item.screenId); 877 878 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase"); 879 } 880 881 /** 882 * Update an item to the database in a specified container. 883 */ 884 public static void updateItemInDatabase(Context context, final ItemInfo item) { 885 final ContentValues values = new ContentValues(); 886 item.onAddToDatabase(context, values); 887 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase"); 888 } 889 890 private void assertWorkspaceLoaded() { 891 if (ProviderConfig.IS_DOGFOOD_BUILD && (isLoadingWorkspace() || !mHasLoaderCompletedOnce)) { 892 throw new RuntimeException("Trying to add shortcut while loader is running"); 893 } 894 } 895 896 /** 897 * Returns true if the shortcuts already exists on the workspace. This must be called after 898 * the workspace has been loaded. We identify a shortcut by its intent. 899 */ 900 @Thunk boolean shortcutExists(Context context, Intent intent, UserHandleCompat user) { 901 assertWorkspaceLoaded(); 902 final String intentWithPkg, intentWithoutPkg; 903 if (intent.getComponent() != null) { 904 // If component is not null, an intent with null package will produce 905 // the same result and should also be a match. 906 String packageName = intent.getComponent().getPackageName(); 907 if (intent.getPackage() != null) { 908 intentWithPkg = intent.toUri(0); 909 intentWithoutPkg = new Intent(intent).setPackage(null).toUri(0); 910 } else { 911 intentWithPkg = new Intent(intent).setPackage(packageName).toUri(0); 912 intentWithoutPkg = intent.toUri(0); 913 } 914 } else { 915 intentWithPkg = intent.toUri(0); 916 intentWithoutPkg = intent.toUri(0); 917 } 918 919 synchronized (sBgLock) { 920 for (ItemInfo item : sBgItemsIdMap) { 921 if (item instanceof ShortcutInfo) { 922 ShortcutInfo info = (ShortcutInfo) item; 923 Intent targetIntent = info.promisedIntent == null 924 ? info.intent : info.promisedIntent; 925 if (targetIntent != null && info.user.equals(user)) { 926 String s = targetIntent.toUri(0); 927 if (intentWithPkg.equals(s) || intentWithoutPkg.equals(s)) { 928 return true; 929 } 930 } 931 } 932 } 933 } 934 return false; 935 } 936 937 /** 938 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. 939 */ 940 FolderInfo getFolderById(Context context, LongArrayMap<FolderInfo> folderList, long id) { 941 final ContentResolver cr = context.getContentResolver(); 942 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, 943 "_id=? and (itemType=? or itemType=?)", 944 new String[] { String.valueOf(id), 945 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); 946 947 try { 948 if (c.moveToFirst()) { 949 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); 950 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); 951 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); 952 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); 953 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); 954 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); 955 final int optionsIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.OPTIONS); 956 957 FolderInfo folderInfo = null; 958 switch (c.getInt(itemTypeIndex)) { 959 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 960 folderInfo = findOrMakeFolder(folderList, id); 961 break; 962 } 963 964 // Do not trim the folder label, as is was set by the user. 965 folderInfo.title = c.getString(titleIndex); 966 folderInfo.id = id; 967 folderInfo.container = c.getInt(containerIndex); 968 folderInfo.screenId = c.getInt(screenIndex); 969 folderInfo.cellX = c.getInt(cellXIndex); 970 folderInfo.cellY = c.getInt(cellYIndex); 971 folderInfo.options = c.getInt(optionsIndex); 972 973 return folderInfo; 974 } 975 } finally { 976 c.close(); 977 } 978 979 return null; 980 } 981 982 /** 983 * Add an item to the database in a specified container. Sets the container, screen, cellX and 984 * cellY fields of the item. Also assigns an ID to the item. 985 */ 986 public static void addItemToDatabase(Context context, final ItemInfo item, final long container, 987 final long screenId, final int cellX, final int cellY) { 988 item.container = container; 989 item.cellX = cellX; 990 item.cellY = cellY; 991 // We store hotseat items in canonical form which is this orientation invariant position 992 // in the hotseat 993 if (context instanceof Launcher && screenId < 0 && 994 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 995 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); 996 } else { 997 item.screenId = screenId; 998 } 999 1000 final ContentValues values = new ContentValues(); 1001 final ContentResolver cr = context.getContentResolver(); 1002 item.onAddToDatabase(context, values); 1003 1004 item.id = LauncherAppState.getLauncherProvider().generateNewItemId(); 1005 values.put(LauncherSettings.Favorites._ID, item.id); 1006 1007 final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); 1008 Runnable r = new Runnable() { 1009 public void run() { 1010 cr.insert(LauncherSettings.Favorites.CONTENT_URI, values); 1011 1012 // Lock on mBgLock *after* the db operation 1013 synchronized (sBgLock) { 1014 checkItemInfoLocked(item.id, item, stackTrace); 1015 sBgItemsIdMap.put(item.id, item); 1016 switch (item.itemType) { 1017 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 1018 sBgFolders.put(item.id, (FolderInfo) item); 1019 // Fall through 1020 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 1021 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 1022 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || 1023 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 1024 sBgWorkspaceItems.add(item); 1025 } else { 1026 if (!sBgFolders.containsKey(item.container)) { 1027 // Adding an item to a folder that doesn't exist. 1028 String msg = "adding item: " + item + " to a folder that " + 1029 " doesn't exist"; 1030 Log.e(TAG, msg); 1031 } 1032 } 1033 break; 1034 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 1035 sBgAppWidgets.add((LauncherAppWidgetInfo) item); 1036 break; 1037 } 1038 } 1039 } 1040 }; 1041 runOnWorkerThread(r); 1042 } 1043 1044 /** 1045 * Creates a new unique child id, for a given cell span across all layouts. 1046 */ 1047 static int getCellLayoutChildId( 1048 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { 1049 return (((int) container & 0xFF) << 24) 1050 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); 1051 } 1052 1053 private static ArrayList<ItemInfo> getItemsByPackageName( 1054 final String pn, final UserHandleCompat user) { 1055 ItemInfoFilter filter = new ItemInfoFilter() { 1056 @Override 1057 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { 1058 return cn.getPackageName().equals(pn) && info.user.equals(user); 1059 } 1060 }; 1061 return filterItemInfos(sBgItemsIdMap, filter); 1062 } 1063 1064 /** 1065 * Removes all the items from the database corresponding to the specified package. 1066 */ 1067 static void deletePackageFromDatabase(Context context, final String pn, 1068 final UserHandleCompat user) { 1069 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user)); 1070 } 1071 1072 /** 1073 * Removes the specified item from the database 1074 * @param context 1075 * @param item 1076 */ 1077 public static void deleteItemFromDatabase(Context context, final ItemInfo item) { 1078 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); 1079 items.add(item); 1080 deleteItemsFromDatabase(context, items); 1081 } 1082 1083 /** 1084 * Removes the specified items from the database 1085 * @param context 1086 * @param item 1087 */ 1088 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) { 1089 final ContentResolver cr = context.getContentResolver(); 1090 Runnable r = new Runnable() { 1091 public void run() { 1092 for (ItemInfo item : items) { 1093 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id); 1094 cr.delete(uri, null, null); 1095 1096 // Lock on mBgLock *after* the db operation 1097 synchronized (sBgLock) { 1098 switch (item.itemType) { 1099 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 1100 sBgFolders.remove(item.id); 1101 for (ItemInfo info: sBgItemsIdMap) { 1102 if (info.container == item.id) { 1103 // We are deleting a folder which still contains items that 1104 // think they are contained by that folder. 1105 String msg = "deleting a folder (" + item + ") which still " + 1106 "contains items (" + info + ")"; 1107 Log.e(TAG, msg); 1108 } 1109 } 1110 sBgWorkspaceItems.remove(item); 1111 break; 1112 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 1113 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 1114 sBgWorkspaceItems.remove(item); 1115 break; 1116 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 1117 sBgAppWidgets.remove((LauncherAppWidgetInfo) item); 1118 break; 1119 } 1120 sBgItemsIdMap.remove(item.id); 1121 } 1122 } 1123 } 1124 }; 1125 runOnWorkerThread(r); 1126 } 1127 1128 /** 1129 * Update the order of the workspace screens in the database. The array list contains 1130 * a list of screen ids in the order that they should appear. 1131 */ 1132 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { 1133 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens); 1134 final ContentResolver cr = context.getContentResolver(); 1135 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; 1136 1137 // Remove any negative screen ids -- these aren't persisted 1138 Iterator<Long> iter = screensCopy.iterator(); 1139 while (iter.hasNext()) { 1140 long id = iter.next(); 1141 if (id < 0) { 1142 iter.remove(); 1143 } 1144 } 1145 1146 Runnable r = new Runnable() { 1147 @Override 1148 public void run() { 1149 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); 1150 // Clear the table 1151 ops.add(ContentProviderOperation.newDelete(uri).build()); 1152 int count = screensCopy.size(); 1153 for (int i = 0; i < count; i++) { 1154 ContentValues v = new ContentValues(); 1155 long screenId = screensCopy.get(i); 1156 v.put(LauncherSettings.WorkspaceScreens._ID, screenId); 1157 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); 1158 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build()); 1159 } 1160 1161 try { 1162 cr.applyBatch(LauncherProvider.AUTHORITY, ops); 1163 } catch (Exception ex) { 1164 throw new RuntimeException(ex); 1165 } 1166 1167 synchronized (sBgLock) { 1168 sBgWorkspaceScreens.clear(); 1169 sBgWorkspaceScreens.addAll(screensCopy); 1170 } 1171 } 1172 }; 1173 runOnWorkerThread(r); 1174 } 1175 1176 /** 1177 * Remove the contents of the specified folder from the database 1178 */ 1179 public static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { 1180 final ContentResolver cr = context.getContentResolver(); 1181 1182 Runnable r = new Runnable() { 1183 public void run() { 1184 cr.delete(LauncherSettings.Favorites.getContentUri(info.id), null, null); 1185 // Lock on mBgLock *after* the db operation 1186 synchronized (sBgLock) { 1187 sBgItemsIdMap.remove(info.id); 1188 sBgFolders.remove(info.id); 1189 sBgWorkspaceItems.remove(info); 1190 } 1191 1192 cr.delete(LauncherSettings.Favorites.CONTENT_URI, 1193 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); 1194 // Lock on mBgLock *after* the db operation 1195 synchronized (sBgLock) { 1196 for (ItemInfo childInfo : info.contents) { 1197 sBgItemsIdMap.remove(childInfo.id); 1198 } 1199 } 1200 } 1201 }; 1202 runOnWorkerThread(r); 1203 } 1204 1205 /** 1206 * Set this as the current Launcher activity object for the loader. 1207 */ 1208 public void initialize(Callbacks callbacks) { 1209 synchronized (mLock) { 1210 // Disconnect any of the callbacks and drawables associated with ItemInfos on the 1211 // workspace to prevent leaking Launcher activities on orientation change. 1212 unbindItemInfosAndClearQueuedBindRunnables(); 1213 mCallbacks = new WeakReference<Callbacks>(callbacks); 1214 } 1215 } 1216 1217 @Override 1218 public void onPackageChanged(String packageName, UserHandleCompat user) { 1219 int op = PackageUpdatedTask.OP_UPDATE; 1220 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }, 1221 user)); 1222 } 1223 1224 @Override 1225 public void onPackageRemoved(String packageName, UserHandleCompat user) { 1226 int op = PackageUpdatedTask.OP_REMOVE; 1227 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }, 1228 user)); 1229 } 1230 1231 @Override 1232 public void onPackageAdded(String packageName, UserHandleCompat user) { 1233 int op = PackageUpdatedTask.OP_ADD; 1234 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }, 1235 user)); 1236 } 1237 1238 @Override 1239 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user, 1240 boolean replacing) { 1241 if (!replacing) { 1242 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames, 1243 user)); 1244 if (mAppsCanBeOnRemoveableStorage) { 1245 // Only rebind if we support removable storage. It catches the 1246 // case where 1247 // apps on the external sd card need to be reloaded 1248 startLoaderFromBackground(); 1249 } 1250 } else { 1251 // If we are replacing then just update the packages in the list 1252 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE, 1253 packageNames, user)); 1254 } 1255 } 1256 1257 @Override 1258 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user, 1259 boolean replacing) { 1260 if (!replacing) { 1261 enqueuePackageUpdated(new PackageUpdatedTask( 1262 PackageUpdatedTask.OP_UNAVAILABLE, packageNames, 1263 user)); 1264 } 1265 } 1266 1267 /** 1268 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and 1269 * ACTION_PACKAGE_CHANGED. 1270 */ 1271 @Override 1272 public void onReceive(Context context, Intent intent) { 1273 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent); 1274 1275 final String action = intent.getAction(); 1276 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { 1277 // If we have changed locale we need to clear out the labels in all apps/workspace. 1278 forceReload(); 1279 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || 1280 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { 1281 Callbacks callbacks = getCallback(); 1282 if (callbacks != null) { 1283 callbacks.bindSearchablesChanged(); 1284 } 1285 } else if (LauncherAppsCompat.ACTION_MANAGED_PROFILE_ADDED.equals(action) 1286 || LauncherAppsCompat.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) { 1287 forceReload(); 1288 } 1289 } 1290 1291 void forceReload() { 1292 resetLoadedState(true, true); 1293 1294 // Do this here because if the launcher activity is running it will be restarted. 1295 // If it's not running startLoaderFromBackground will merely tell it that it needs 1296 // to reload. 1297 startLoaderFromBackground(); 1298 } 1299 1300 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { 1301 synchronized (mLock) { 1302 // Stop any existing loaders first, so they don't set mAllAppsLoaded or 1303 // mWorkspaceLoaded to true later 1304 stopLoaderLocked(); 1305 if (resetAllAppsLoaded) mAllAppsLoaded = false; 1306 if (resetWorkspaceLoaded) mWorkspaceLoaded = false; 1307 } 1308 } 1309 1310 /** 1311 * When the launcher is in the background, it's possible for it to miss paired 1312 * configuration changes. So whenever we trigger the loader from the background 1313 * tell the launcher that it needs to re-run the loader when it comes back instead 1314 * of doing it now. 1315 */ 1316 public void startLoaderFromBackground() { 1317 boolean runLoader = false; 1318 Callbacks callbacks = getCallback(); 1319 if (callbacks != null) { 1320 // Only actually run the loader if they're not paused. 1321 if (!callbacks.setLoadOnResume()) { 1322 runLoader = true; 1323 } 1324 } 1325 if (runLoader) { 1326 startLoader(PagedView.INVALID_RESTORE_PAGE); 1327 } 1328 } 1329 1330 /** 1331 * If there is already a loader task running, tell it to stop. 1332 */ 1333 private void stopLoaderLocked() { 1334 LoaderTask oldTask = mLoaderTask; 1335 if (oldTask != null) { 1336 oldTask.stopLocked(); 1337 } 1338 } 1339 1340 public boolean isCurrentCallbacks(Callbacks callbacks) { 1341 return (mCallbacks != null && mCallbacks.get() == callbacks); 1342 } 1343 1344 public void startLoader(int synchronousBindPage) { 1345 startLoader(synchronousBindPage, LOADER_FLAG_NONE); 1346 } 1347 1348 public void startLoader(int synchronousBindPage, int loadFlags) { 1349 // Enable queue before starting loader. It will get disabled in Launcher#finishBindingItems 1350 InstallShortcutReceiver.enableInstallQueue(); 1351 synchronized (mLock) { 1352 // Clear any deferred bind-runnables from the synchronized load process 1353 // We must do this before any loading/binding is scheduled below. 1354 synchronized (mDeferredBindRunnables) { 1355 mDeferredBindRunnables.clear(); 1356 } 1357 1358 // Don't bother to start the thread if we know it's not going to do anything 1359 if (mCallbacks != null && mCallbacks.get() != null) { 1360 // If there is already one running, tell it to stop. 1361 stopLoaderLocked(); 1362 mLoaderTask = new LoaderTask(mApp.getContext(), loadFlags); 1363 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE 1364 && mAllAppsLoaded && mWorkspaceLoaded && !mIsLoaderTaskRunning) { 1365 mLoaderTask.runBindSynchronousPage(synchronousBindPage); 1366 } else { 1367 sWorkerThread.setPriority(Thread.NORM_PRIORITY); 1368 sWorker.post(mLoaderTask); 1369 } 1370 } 1371 } 1372 } 1373 1374 void bindRemainingSynchronousPages() { 1375 // Post the remaining side pages to be loaded 1376 if (!mDeferredBindRunnables.isEmpty()) { 1377 Runnable[] deferredBindRunnables = null; 1378 synchronized (mDeferredBindRunnables) { 1379 deferredBindRunnables = mDeferredBindRunnables.toArray( 1380 new Runnable[mDeferredBindRunnables.size()]); 1381 mDeferredBindRunnables.clear(); 1382 } 1383 for (final Runnable r : deferredBindRunnables) { 1384 mHandler.post(r); 1385 } 1386 } 1387 1388 // Run all the bind complete runnables after workspace is bound. 1389 if (!mBindCompleteRunnables.isEmpty()) { 1390 synchronized (mBindCompleteRunnables) { 1391 for (final Runnable r : mBindCompleteRunnables) { 1392 runOnWorkerThread(r); 1393 } 1394 mBindCompleteRunnables.clear(); 1395 } 1396 } 1397 } 1398 1399 public void stopLoader() { 1400 synchronized (mLock) { 1401 if (mLoaderTask != null) { 1402 mLoaderTask.stopLocked(); 1403 } 1404 } 1405 } 1406 1407 /** 1408 * Loads the workspace screen ids in an ordered list. 1409 */ 1410 @Thunk static ArrayList<Long> loadWorkspaceScreensDb(Context context) { 1411 final ContentResolver contentResolver = context.getContentResolver(); 1412 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; 1413 1414 // Get screens ordered by rank. 1415 final Cursor sc = contentResolver.query(screensUri, null, null, null, 1416 LauncherSettings.WorkspaceScreens.SCREEN_RANK); 1417 ArrayList<Long> screenIds = new ArrayList<Long>(); 1418 try { 1419 final int idIndex = sc.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens._ID); 1420 while (sc.moveToNext()) { 1421 try { 1422 screenIds.add(sc.getLong(idIndex)); 1423 } catch (Exception e) { 1424 Launcher.addDumpLog(TAG, "Desktop items loading interrupted" 1425 + " - invalid screens: " + e, true); 1426 } 1427 } 1428 } finally { 1429 sc.close(); 1430 } 1431 return screenIds; 1432 } 1433 1434 public boolean isAllAppsLoaded() { 1435 return mAllAppsLoaded; 1436 } 1437 1438 boolean isLoadingWorkspace() { 1439 synchronized (mLock) { 1440 if (mLoaderTask != null) { 1441 return mLoaderTask.isLoadingWorkspace(); 1442 } 1443 } 1444 return false; 1445 } 1446 1447 /** 1448 * Runnable for the thread that loads the contents of the launcher: 1449 * - workspace icons 1450 * - widgets 1451 * - all apps icons 1452 */ 1453 private class LoaderTask implements Runnable { 1454 private Context mContext; 1455 @Thunk boolean mIsLoadingAndBindingWorkspace; 1456 private boolean mStopped; 1457 @Thunk boolean mLoadAndBindStepFinished; 1458 private int mFlags; 1459 1460 LoaderTask(Context context, int flags) { 1461 mContext = context; 1462 mFlags = flags; 1463 } 1464 1465 boolean isLoadingWorkspace() { 1466 return mIsLoadingAndBindingWorkspace; 1467 } 1468 1469 private void loadAndBindWorkspace() { 1470 mIsLoadingAndBindingWorkspace = true; 1471 1472 // Load the workspace 1473 if (DEBUG_LOADERS) { 1474 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); 1475 } 1476 1477 if (!mWorkspaceLoaded) { 1478 loadWorkspace(); 1479 synchronized (LoaderTask.this) { 1480 if (mStopped) { 1481 return; 1482 } 1483 mWorkspaceLoaded = true; 1484 } 1485 } 1486 1487 // Bind the workspace 1488 bindWorkspace(-1); 1489 } 1490 1491 private void waitForIdle() { 1492 // Wait until the either we're stopped or the other threads are done. 1493 // This way we don't start loading all apps until the workspace has settled 1494 // down. 1495 synchronized (LoaderTask.this) { 1496 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; 1497 1498 mHandler.postIdle(new Runnable() { 1499 public void run() { 1500 synchronized (LoaderTask.this) { 1501 mLoadAndBindStepFinished = true; 1502 if (DEBUG_LOADERS) { 1503 Log.d(TAG, "done with previous binding step"); 1504 } 1505 LoaderTask.this.notify(); 1506 } 1507 } 1508 }); 1509 1510 while (!mStopped && !mLoadAndBindStepFinished) { 1511 try { 1512 // Just in case mFlushingWorkerThread changes but we aren't woken up, 1513 // wait no longer than 1sec at a time 1514 this.wait(1000); 1515 } catch (InterruptedException ex) { 1516 // Ignore 1517 } 1518 } 1519 if (DEBUG_LOADERS) { 1520 Log.d(TAG, "waited " 1521 + (SystemClock.uptimeMillis()-workspaceWaitTime) 1522 + "ms for previous step to finish binding"); 1523 } 1524 } 1525 } 1526 1527 void runBindSynchronousPage(int synchronousBindPage) { 1528 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) { 1529 // Ensure that we have a valid page index to load synchronously 1530 throw new RuntimeException("Should not call runBindSynchronousPage() without " + 1531 "valid page index"); 1532 } 1533 if (!mAllAppsLoaded || !mWorkspaceLoaded) { 1534 // Ensure that we don't try and bind a specified page when the pages have not been 1535 // loaded already (we should load everything asynchronously in that case) 1536 throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); 1537 } 1538 synchronized (mLock) { 1539 if (mIsLoaderTaskRunning) { 1540 // Ensure that we are never running the background loading at this point since 1541 // we also touch the background collections 1542 throw new RuntimeException("Error! Background loading is already running"); 1543 } 1544 } 1545 1546 // XXX: Throw an exception if we are already loading (since we touch the worker thread 1547 // data structures, we can't allow any other thread to touch that data, but because 1548 // this call is synchronous, we can get away with not locking). 1549 1550 // The LauncherModel is static in the LauncherAppState and mHandler may have queued 1551 // operations from the previous activity. We need to ensure that all queued operations 1552 // are executed before any synchronous binding work is done. 1553 mHandler.flush(); 1554 1555 // Divide the set of loaded items into those that we are binding synchronously, and 1556 // everything else that is to be bound normally (asynchronously). 1557 bindWorkspace(synchronousBindPage); 1558 // XXX: For now, continue posting the binding of AllApps as there are other issues that 1559 // arise from that. 1560 onlyBindAllApps(); 1561 } 1562 1563 public void run() { 1564 synchronized (mLock) { 1565 if (mStopped) { 1566 return; 1567 } 1568 mIsLoaderTaskRunning = true; 1569 } 1570 // Optimize for end-user experience: if the Launcher is up and // running with the 1571 // All Apps interface in the foreground, load All Apps first. Otherwise, load the 1572 // workspace first (default). 1573 keep_running: { 1574 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); 1575 loadAndBindWorkspace(); 1576 1577 if (mStopped) { 1578 break keep_running; 1579 } 1580 1581 waitForIdle(); 1582 1583 // second step 1584 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); 1585 loadAndBindAllApps(); 1586 } 1587 1588 // Clear out this reference, otherwise we end up holding it until all of the 1589 // callback runnables are done. 1590 mContext = null; 1591 1592 synchronized (mLock) { 1593 // If we are still the last one to be scheduled, remove ourselves. 1594 if (mLoaderTask == this) { 1595 mLoaderTask = null; 1596 } 1597 mIsLoaderTaskRunning = false; 1598 mHasLoaderCompletedOnce = true; 1599 } 1600 } 1601 1602 public void stopLocked() { 1603 synchronized (LoaderTask.this) { 1604 mStopped = true; 1605 this.notify(); 1606 } 1607 } 1608 1609 /** 1610 * Gets the callbacks object. If we've been stopped, or if the launcher object 1611 * has somehow been garbage collected, return null instead. Pass in the Callbacks 1612 * object that was around when the deferred message was scheduled, and if there's 1613 * a new Callbacks object around then also return null. This will save us from 1614 * calling onto it with data that will be ignored. 1615 */ 1616 Callbacks tryGetCallbacks(Callbacks oldCallbacks) { 1617 synchronized (mLock) { 1618 if (mStopped) { 1619 return null; 1620 } 1621 1622 if (mCallbacks == null) { 1623 return null; 1624 } 1625 1626 final Callbacks callbacks = mCallbacks.get(); 1627 if (callbacks != oldCallbacks) { 1628 return null; 1629 } 1630 if (callbacks == null) { 1631 Log.w(TAG, "no mCallbacks"); 1632 return null; 1633 } 1634 1635 return callbacks; 1636 } 1637 } 1638 1639 // check & update map of what's occupied; used to discard overlapping/invalid items 1640 private boolean checkItemPlacement(LongArrayMap<ItemInfo[][]> occupied, ItemInfo item) { 1641 LauncherAppState app = LauncherAppState.getInstance(); 1642 InvariantDeviceProfile profile = app.getInvariantDeviceProfile(); 1643 final int countX = (int) profile.numColumns; 1644 final int countY = (int) profile.numRows; 1645 1646 long containerIndex = item.screenId; 1647 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 1648 // Return early if we detect that an item is under the hotseat button 1649 if (mCallbacks == null || 1650 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) { 1651 Log.e(TAG, "Error loading shortcut into hotseat " + item 1652 + " into position (" + item.screenId + ":" + item.cellX + "," 1653 + item.cellY + ") occupied by all apps"); 1654 return false; 1655 } 1656 1657 final ItemInfo[][] hotseatItems = 1658 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT); 1659 1660 if (item.screenId >= profile.numHotseatIcons) { 1661 Log.e(TAG, "Error loading shortcut " + item 1662 + " into hotseat position " + item.screenId 1663 + ", position out of bounds: (0 to " + (profile.numHotseatIcons - 1) 1664 + ")"); 1665 return false; 1666 } 1667 1668 if (hotseatItems != null) { 1669 if (hotseatItems[(int) item.screenId][0] != null) { 1670 Log.e(TAG, "Error loading shortcut into hotseat " + item 1671 + " into position (" + item.screenId + ":" + item.cellX + "," 1672 + item.cellY + ") occupied by " 1673 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) 1674 [(int) item.screenId][0]); 1675 return false; 1676 } else { 1677 hotseatItems[(int) item.screenId][0] = item; 1678 return true; 1679 } 1680 } else { 1681 final ItemInfo[][] items = new ItemInfo[(int) profile.numHotseatIcons][1]; 1682 items[(int) item.screenId][0] = item; 1683 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); 1684 return true; 1685 } 1686 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { 1687 // Skip further checking if it is not the hotseat or workspace container 1688 return true; 1689 } 1690 1691 if (!occupied.containsKey(item.screenId)) { 1692 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1]; 1693 occupied.put(item.screenId, items); 1694 } 1695 1696 final ItemInfo[][] screens = occupied.get(item.screenId); 1697 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && 1698 item.cellX < 0 || item.cellY < 0 || 1699 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) { 1700 Log.e(TAG, "Error loading shortcut " + item 1701 + " into cell (" + containerIndex + "-" + item.screenId + ":" 1702 + item.cellX + "," + item.cellY 1703 + ") out of screen bounds ( " + countX + "x" + countY + ")"); 1704 return false; 1705 } 1706 1707 // Check if any workspace icons overlap with each other 1708 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { 1709 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { 1710 if (screens[x][y] != null) { 1711 Log.e(TAG, "Error loading shortcut " + item 1712 + " into cell (" + containerIndex + "-" + item.screenId + ":" 1713 + x + "," + y 1714 + ") occupied by " 1715 + screens[x][y]); 1716 return false; 1717 } 1718 } 1719 } 1720 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { 1721 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { 1722 screens[x][y] = item; 1723 } 1724 } 1725 1726 return true; 1727 } 1728 1729 /** Clears all the sBg data structures */ 1730 private void clearSBgDataStructures() { 1731 synchronized (sBgLock) { 1732 sBgWorkspaceItems.clear(); 1733 sBgAppWidgets.clear(); 1734 sBgFolders.clear(); 1735 sBgItemsIdMap.clear(); 1736 sBgWorkspaceScreens.clear(); 1737 } 1738 } 1739 1740 private void loadWorkspace() { 1741 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; 1742 1743 final Context context = mContext; 1744 final ContentResolver contentResolver = context.getContentResolver(); 1745 final PackageManager manager = context.getPackageManager(); 1746 final boolean isSafeMode = manager.isSafeMode(); 1747 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context); 1748 final boolean isSdCardReady = context.registerReceiver(null, 1749 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null; 1750 1751 LauncherAppState app = LauncherAppState.getInstance(); 1752 InvariantDeviceProfile profile = app.getInvariantDeviceProfile(); 1753 int countX = (int) profile.numColumns; 1754 int countY = (int) profile.numRows; 1755 1756 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) { 1757 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true); 1758 LauncherAppState.getLauncherProvider().deleteDatabase(); 1759 } 1760 1761 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) { 1762 // append the user's Launcher2 shortcuts 1763 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true); 1764 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts(); 1765 } else { 1766 // Make sure the default workspace is loaded 1767 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false); 1768 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(); 1769 } 1770 1771 synchronized (sBgLock) { 1772 clearSBgDataStructures(); 1773 final HashMap<String, Integer> installingPkgs = PackageInstallerCompat 1774 .getInstance(mContext).updateAndGetActiveSessionCache(); 1775 1776 final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); 1777 final ArrayList<Long> restoredRows = new ArrayList<Long>(); 1778 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI; 1779 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri); 1780 final Cursor c = contentResolver.query(contentUri, null, null, null, null); 1781 1782 // +1 for the hotseat (it can be larger than the workspace) 1783 // Load workspace in reverse order to ensure that latest items are loaded first (and 1784 // before any earlier duplicates) 1785 final LongArrayMap<ItemInfo[][]> occupied = new LongArrayMap<>(); 1786 1787 try { 1788 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); 1789 final int intentIndex = c.getColumnIndexOrThrow 1790 (LauncherSettings.Favorites.INTENT); 1791 final int titleIndex = c.getColumnIndexOrThrow 1792 (LauncherSettings.Favorites.TITLE); 1793 final int containerIndex = c.getColumnIndexOrThrow( 1794 LauncherSettings.Favorites.CONTAINER); 1795 final int itemTypeIndex = c.getColumnIndexOrThrow( 1796 LauncherSettings.Favorites.ITEM_TYPE); 1797 final int appWidgetIdIndex = c.getColumnIndexOrThrow( 1798 LauncherSettings.Favorites.APPWIDGET_ID); 1799 final int appWidgetProviderIndex = c.getColumnIndexOrThrow( 1800 LauncherSettings.Favorites.APPWIDGET_PROVIDER); 1801 final int screenIndex = c.getColumnIndexOrThrow( 1802 LauncherSettings.Favorites.SCREEN); 1803 final int cellXIndex = c.getColumnIndexOrThrow 1804 (LauncherSettings.Favorites.CELLX); 1805 final int cellYIndex = c.getColumnIndexOrThrow 1806 (LauncherSettings.Favorites.CELLY); 1807 final int spanXIndex = c.getColumnIndexOrThrow 1808 (LauncherSettings.Favorites.SPANX); 1809 final int spanYIndex = c.getColumnIndexOrThrow( 1810 LauncherSettings.Favorites.SPANY); 1811 final int rankIndex = c.getColumnIndexOrThrow( 1812 LauncherSettings.Favorites.RANK); 1813 final int restoredIndex = c.getColumnIndexOrThrow( 1814 LauncherSettings.Favorites.RESTORED); 1815 final int profileIdIndex = c.getColumnIndexOrThrow( 1816 LauncherSettings.Favorites.PROFILE_ID); 1817 final int optionsIndex = c.getColumnIndexOrThrow( 1818 LauncherSettings.Favorites.OPTIONS); 1819 final CursorIconInfo cursorIconInfo = new CursorIconInfo(c); 1820 1821 final LongSparseArray<UserHandleCompat> allUsers = new LongSparseArray<>(); 1822 for (UserHandleCompat user : mUserManager.getUserProfiles()) { 1823 allUsers.put(mUserManager.getSerialNumberForUser(user), user); 1824 } 1825 1826 ShortcutInfo info; 1827 String intentDescription; 1828 LauncherAppWidgetInfo appWidgetInfo; 1829 int container; 1830 long id; 1831 long serialNumber; 1832 Intent intent; 1833 UserHandleCompat user; 1834 1835 while (!mStopped && c.moveToNext()) { 1836 try { 1837 int itemType = c.getInt(itemTypeIndex); 1838 boolean restored = 0 != c.getInt(restoredIndex); 1839 boolean allowMissingTarget = false; 1840 container = c.getInt(containerIndex); 1841 1842 switch (itemType) { 1843 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 1844 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 1845 id = c.getLong(idIndex); 1846 intentDescription = c.getString(intentIndex); 1847 serialNumber = c.getInt(profileIdIndex); 1848 user = allUsers.get(serialNumber); 1849 int promiseType = c.getInt(restoredIndex); 1850 int disabledState = 0; 1851 boolean itemReplaced = false; 1852 if (user == null) { 1853 // User has been deleted remove the item. 1854 itemsToRemove.add(id); 1855 continue; 1856 } 1857 try { 1858 intent = Intent.parseUri(intentDescription, 0); 1859 ComponentName cn = intent.getComponent(); 1860 if (cn != null && cn.getPackageName() != null) { 1861 boolean validPkg = launcherApps.isPackageEnabledForProfile( 1862 cn.getPackageName(), user); 1863 boolean validComponent = validPkg && 1864 launcherApps.isActivityEnabledForProfile(cn, user); 1865 1866 if (validComponent) { 1867 if (restored) { 1868 // no special handling necessary for this item 1869 restoredRows.add(id); 1870 restored = false; 1871 } 1872 } else if (validPkg) { 1873 intent = null; 1874 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) { 1875 // We allow auto install apps to have their intent 1876 // updated after an install. 1877 intent = manager.getLaunchIntentForPackage( 1878 cn.getPackageName()); 1879 if (intent != null) { 1880 ContentValues values = new ContentValues(); 1881 values.put(LauncherSettings.Favorites.INTENT, 1882 intent.toUri(0)); 1883 updateItem(id, values); 1884 } 1885 } 1886 1887 if (intent == null) { 1888 // The app is installed but the component is no 1889 // longer available. 1890 Launcher.addDumpLog(TAG, 1891 "Invalid component removed: " + cn, true); 1892 itemsToRemove.add(id); 1893 continue; 1894 } else { 1895 // no special handling necessary for this item 1896 restoredRows.add(id); 1897 restored = false; 1898 } 1899 } else if (restored) { 1900 // Package is not yet available but might be 1901 // installed later. 1902 Launcher.addDumpLog(TAG, 1903 "package not yet restored: " + cn, true); 1904 1905 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) { 1906 // Restore has started once. 1907 } else if (installingPkgs.containsKey(cn.getPackageName())) { 1908 // App restore has started. Update the flag 1909 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED; 1910 ContentValues values = new ContentValues(); 1911 values.put(LauncherSettings.Favorites.RESTORED, 1912 promiseType); 1913 updateItem(id, values); 1914 } else if ((promiseType & ShortcutInfo.FLAG_RESTORED_APP_TYPE) != 0) { 1915 // This is a common app. Try to replace this. 1916 int appType = CommonAppTypeParser.decodeItemTypeFromFlag(promiseType); 1917 CommonAppTypeParser parser = new CommonAppTypeParser(id, appType, context); 1918 if (parser.findDefaultApp()) { 1919 // Default app found. Replace it. 1920 intent = parser.parsedIntent; 1921 cn = intent.getComponent(); 1922 ContentValues values = parser.parsedValues; 1923 values.put(LauncherSettings.Favorites.RESTORED, 0); 1924 updateItem(id, values); 1925 restored = false; 1926 itemReplaced = true; 1927 1928 } else if (REMOVE_UNRESTORED_ICONS) { 1929 Launcher.addDumpLog(TAG, 1930 "Unrestored package removed: " + cn, true); 1931 itemsToRemove.add(id); 1932 continue; 1933 } 1934 } else if (REMOVE_UNRESTORED_ICONS) { 1935 Launcher.addDumpLog(TAG, 1936 "Unrestored package removed: " + cn, true); 1937 itemsToRemove.add(id); 1938 continue; 1939 } 1940 } else if (launcherApps.isAppEnabled( 1941 manager, cn.getPackageName(), 1942 PackageManager.GET_UNINSTALLED_PACKAGES)) { 1943 // Package is present but not available. 1944 allowMissingTarget = true; 1945 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE; 1946 } else if (!isSdCardReady) { 1947 // SdCard is not ready yet. Package might get available, 1948 // once it is ready. 1949 Launcher.addDumpLog(TAG, "Invalid package: " + cn 1950 + " (check again later)", true); 1951 HashSet<String> pkgs = sPendingPackages.get(user); 1952 if (pkgs == null) { 1953 pkgs = new HashSet<String>(); 1954 sPendingPackages.put(user, pkgs); 1955 } 1956 pkgs.add(cn.getPackageName()); 1957 allowMissingTarget = true; 1958 // Add the icon on the workspace anyway. 1959 1960 } else { 1961 // Do not wait for external media load anymore. 1962 // Log the invalid package, and remove it 1963 Launcher.addDumpLog(TAG, 1964 "Invalid package removed: " + cn, true); 1965 itemsToRemove.add(id); 1966 continue; 1967 } 1968 } else if (cn == null) { 1969 // For shortcuts with no component, keep them as they are 1970 restoredRows.add(id); 1971 restored = false; 1972 } 1973 } catch (URISyntaxException e) { 1974 Launcher.addDumpLog(TAG, 1975 "Invalid uri: " + intentDescription, true); 1976 continue; 1977 } 1978 1979 boolean useLowResIcon = container >= 0 && 1980 c.getInt(rankIndex) >= FolderIcon.NUM_ITEMS_IN_PREVIEW; 1981 1982 if (itemReplaced) { 1983 if (user.equals(UserHandleCompat.myUserHandle())) { 1984 info = getAppShortcutInfo(manager, intent, user, context, null, 1985 cursorIconInfo.iconIndex, titleIndex, 1986 false, useLowResIcon); 1987 } else { 1988 // Don't replace items for other profiles. 1989 itemsToRemove.add(id); 1990 continue; 1991 } 1992 } else if (restored) { 1993 if (user.equals(UserHandleCompat.myUserHandle())) { 1994 Launcher.addDumpLog(TAG, 1995 "constructing info for partially restored package", 1996 true); 1997 info = getRestoredItemInfo(c, titleIndex, intent, 1998 promiseType, itemType, cursorIconInfo, context); 1999 intent = getRestoredItemIntent(c, context, intent); 2000 } else { 2001 // Don't restore items for other profiles. 2002 itemsToRemove.add(id); 2003 continue; 2004 } 2005 } else if (itemType == 2006 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { 2007 info = getAppShortcutInfo(manager, intent, user, context, c, 2008 cursorIconInfo.iconIndex, titleIndex, 2009 allowMissingTarget, useLowResIcon); 2010 } else { 2011 info = getShortcutInfo(c, context, titleIndex, cursorIconInfo); 2012 2013 // App shortcuts that used to be automatically added to Launcher 2014 // didn't always have the correct intent flags set, so do that 2015 // here 2016 if (intent.getAction() != null && 2017 intent.getCategories() != null && 2018 intent.getAction().equals(Intent.ACTION_MAIN) && 2019 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { 2020 intent.addFlags( 2021 Intent.FLAG_ACTIVITY_NEW_TASK | 2022 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 2023 } 2024 } 2025 2026 if (info != null) { 2027 info.id = id; 2028 info.intent = intent; 2029 info.container = container; 2030 info.screenId = c.getInt(screenIndex); 2031 info.cellX = c.getInt(cellXIndex); 2032 info.cellY = c.getInt(cellYIndex); 2033 info.rank = c.getInt(rankIndex); 2034 info.spanX = 1; 2035 info.spanY = 1; 2036 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber); 2037 if (info.promisedIntent != null) { 2038 info.promisedIntent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber); 2039 } 2040 info.isDisabled = disabledState; 2041 if (isSafeMode && !Utilities.isSystemApp(context, intent)) { 2042 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE; 2043 } 2044 2045 // check & update map of what's occupied 2046 if (!checkItemPlacement(occupied, info)) { 2047 itemsToRemove.add(id); 2048 break; 2049 } 2050 2051 if (restored) { 2052 ComponentName cn = info.getTargetComponent(); 2053 if (cn != null) { 2054 Integer progress = installingPkgs.get(cn.getPackageName()); 2055 if (progress != null) { 2056 info.setInstallProgress(progress); 2057 } else { 2058 info.status &= ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE; 2059 } 2060 } 2061 } 2062 2063 switch (container) { 2064 case LauncherSettings.Favorites.CONTAINER_DESKTOP: 2065 case LauncherSettings.Favorites.CONTAINER_HOTSEAT: 2066 sBgWorkspaceItems.add(info); 2067 break; 2068 default: 2069 // Item is in a user folder 2070 FolderInfo folderInfo = 2071 findOrMakeFolder(sBgFolders, container); 2072 folderInfo.add(info); 2073 break; 2074 } 2075 sBgItemsIdMap.put(info.id, info); 2076 } else { 2077 throw new RuntimeException("Unexpected null ShortcutInfo"); 2078 } 2079 break; 2080 2081 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 2082 id = c.getLong(idIndex); 2083 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); 2084 2085 // Do not trim the folder label, as is was set by the user. 2086 folderInfo.title = c.getString(titleIndex); 2087 folderInfo.id = id; 2088 folderInfo.container = container; 2089 folderInfo.screenId = c.getInt(screenIndex); 2090 folderInfo.cellX = c.getInt(cellXIndex); 2091 folderInfo.cellY = c.getInt(cellYIndex); 2092 folderInfo.spanX = 1; 2093 folderInfo.spanY = 1; 2094 folderInfo.options = c.getInt(optionsIndex); 2095 2096 // check & update map of what's occupied 2097 if (!checkItemPlacement(occupied, folderInfo)) { 2098 itemsToRemove.add(id); 2099 break; 2100 } 2101 2102 switch (container) { 2103 case LauncherSettings.Favorites.CONTAINER_DESKTOP: 2104 case LauncherSettings.Favorites.CONTAINER_HOTSEAT: 2105 sBgWorkspaceItems.add(folderInfo); 2106 break; 2107 } 2108 2109 if (restored) { 2110 // no special handling required for restored folders 2111 restoredRows.add(id); 2112 } 2113 2114 sBgItemsIdMap.put(folderInfo.id, folderInfo); 2115 sBgFolders.put(folderInfo.id, folderInfo); 2116 break; 2117 2118 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 2119 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET: 2120 // Read all Launcher-specific widget details 2121 boolean customWidget = itemType == 2122 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET; 2123 2124 int appWidgetId = c.getInt(appWidgetIdIndex); 2125 serialNumber = c.getLong(profileIdIndex); 2126 String savedProvider = c.getString(appWidgetProviderIndex); 2127 id = c.getLong(idIndex); 2128 user = allUsers.get(serialNumber); 2129 if (user == null) { 2130 itemsToRemove.add(id); 2131 continue; 2132 } 2133 2134 final ComponentName component = 2135 ComponentName.unflattenFromString(savedProvider); 2136 2137 final int restoreStatus = c.getInt(restoredIndex); 2138 final boolean isIdValid = (restoreStatus & 2139 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0; 2140 final boolean wasProviderReady = (restoreStatus & 2141 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0; 2142 2143 final LauncherAppWidgetProviderInfo provider = 2144 LauncherModel.getProviderInfo(context, 2145 ComponentName.unflattenFromString(savedProvider), 2146 user); 2147 2148 final boolean isProviderReady = isValidProvider(provider); 2149 if (!isSafeMode && !customWidget && 2150 wasProviderReady && !isProviderReady) { 2151 String log = "Deleting widget that isn't installed anymore: " 2152 + "id=" + id + " appWidgetId=" + appWidgetId; 2153 2154 Log.e(TAG, log); 2155 Launcher.addDumpLog(TAG, log, false); 2156 itemsToRemove.add(id); 2157 } else { 2158 if (isProviderReady) { 2159 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, 2160 provider.provider); 2161 2162 int status = restoreStatus; 2163 if (!wasProviderReady) { 2164 // If provider was not previously ready, update the 2165 // status and UI flag. 2166 2167 // Id would be valid only if the widget restore broadcast was received. 2168 if (isIdValid) { 2169 status = LauncherAppWidgetInfo.RESTORE_COMPLETED; 2170 } else { 2171 status &= ~LauncherAppWidgetInfo 2172 .FLAG_PROVIDER_NOT_READY; 2173 } 2174 } 2175 appWidgetInfo.restoreStatus = status; 2176 } else { 2177 Log.v(TAG, "Widget restore pending id=" + id 2178 + " appWidgetId=" + appWidgetId 2179 + " status =" + restoreStatus); 2180 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, 2181 component); 2182 appWidgetInfo.restoreStatus = restoreStatus; 2183 Integer installProgress = installingPkgs.get(component.getPackageName()); 2184 2185 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) { 2186 // Restore has started once. 2187 } else if (installProgress != null) { 2188 // App restore has started. Update the flag 2189 appWidgetInfo.restoreStatus |= 2190 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED; 2191 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) { 2192 Launcher.addDumpLog(TAG, 2193 "Unrestored widget removed: " + component, true); 2194 itemsToRemove.add(id); 2195 continue; 2196 } 2197 2198 appWidgetInfo.installProgress = 2199 installProgress == null ? 0 : installProgress; 2200 } 2201 2202 appWidgetInfo.id = id; 2203 appWidgetInfo.screenId = c.getInt(screenIndex); 2204 appWidgetInfo.cellX = c.getInt(cellXIndex); 2205 appWidgetInfo.cellY = c.getInt(cellYIndex); 2206 appWidgetInfo.spanX = c.getInt(spanXIndex); 2207 appWidgetInfo.spanY = c.getInt(spanYIndex); 2208 appWidgetInfo.user = user; 2209 2210 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && 2211 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 2212 Log.e(TAG, "Widget found where container != " + 2213 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); 2214 continue; 2215 } 2216 2217 appWidgetInfo.container = container; 2218 // check & update map of what's occupied 2219 if (!checkItemPlacement(occupied, appWidgetInfo)) { 2220 itemsToRemove.add(id); 2221 break; 2222 } 2223 2224 if (!customWidget) { 2225 String providerName = 2226 appWidgetInfo.providerName.flattenToString(); 2227 if (!providerName.equals(savedProvider) || 2228 (appWidgetInfo.restoreStatus != restoreStatus)) { 2229 ContentValues values = new ContentValues(); 2230 values.put( 2231 LauncherSettings.Favorites.APPWIDGET_PROVIDER, 2232 providerName); 2233 values.put(LauncherSettings.Favorites.RESTORED, 2234 appWidgetInfo.restoreStatus); 2235 updateItem(id, values); 2236 } 2237 } 2238 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); 2239 sBgAppWidgets.add(appWidgetInfo); 2240 } 2241 break; 2242 } 2243 } catch (Exception e) { 2244 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true); 2245 } 2246 } 2247 } finally { 2248 if (c != null) { 2249 c.close(); 2250 } 2251 } 2252 2253 // Break early if we've stopped loading 2254 if (mStopped) { 2255 clearSBgDataStructures(); 2256 return; 2257 } 2258 2259 if (itemsToRemove.size() > 0) { 2260 // Remove dead items 2261 contentResolver.delete(LauncherSettings.Favorites.CONTENT_URI, 2262 Utilities.createDbSelectionQuery( 2263 LauncherSettings.Favorites._ID, itemsToRemove), null); 2264 if (DEBUG_LOADERS) { 2265 Log.d(TAG, "Removed = " + Utilities.createDbSelectionQuery( 2266 LauncherSettings.Favorites._ID, itemsToRemove)); 2267 } 2268 2269 // Remove any empty folder 2270 for (long folderId : LauncherAppState.getLauncherProvider() 2271 .deleteEmptyFolders()) { 2272 sBgWorkspaceItems.remove(sBgFolders.get(folderId)); 2273 sBgFolders.remove(folderId); 2274 sBgItemsIdMap.remove(folderId); 2275 } 2276 } 2277 2278 if (restoredRows.size() > 0) { 2279 // Update restored items that no longer require special handling 2280 ContentValues values = new ContentValues(); 2281 values.put(LauncherSettings.Favorites.RESTORED, 0); 2282 contentResolver.update(LauncherSettings.Favorites.CONTENT_URI, values, 2283 Utilities.createDbSelectionQuery( 2284 LauncherSettings.Favorites._ID, restoredRows), null); 2285 } 2286 2287 if (!isSdCardReady && !sPendingPackages.isEmpty()) { 2288 context.registerReceiver(new AppsAvailabilityCheck(), 2289 new IntentFilter(StartupReceiver.SYSTEM_READY), 2290 null, sWorker); 2291 } 2292 2293 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext)); 2294 2295 // Remove any empty screens 2296 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens); 2297 for (ItemInfo item: sBgItemsIdMap) { 2298 long screenId = item.screenId; 2299 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && 2300 unusedScreens.contains(screenId)) { 2301 unusedScreens.remove(screenId); 2302 } 2303 } 2304 2305 // If there are any empty screens remove them, and update. 2306 if (unusedScreens.size() != 0) { 2307 sBgWorkspaceScreens.removeAll(unusedScreens); 2308 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); 2309 } 2310 2311 if (DEBUG_LOADERS) { 2312 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); 2313 Log.d(TAG, "workspace layout: "); 2314 int nScreens = occupied.size(); 2315 for (int y = 0; y < countY; y++) { 2316 String line = ""; 2317 2318 for (int i = 0; i < nScreens; i++) { 2319 long screenId = occupied.keyAt(i); 2320 if (screenId > 0) { 2321 line += " | "; 2322 } 2323 ItemInfo[][] screen = occupied.valueAt(i); 2324 for (int x = 0; x < countX; x++) { 2325 if (x < screen.length && y < screen[x].length) { 2326 line += (screen[x][y] != null) ? "#" : "."; 2327 } else { 2328 line += "!"; 2329 } 2330 } 2331 } 2332 Log.d(TAG, "[ " + line + " ]"); 2333 } 2334 } 2335 } 2336 } 2337 2338 /** 2339 * Partially updates the item without any notification. Must be called on the worker thread. 2340 */ 2341 private void updateItem(long itemId, ContentValues update) { 2342 mContext.getContentResolver().update( 2343 LauncherSettings.Favorites.CONTENT_URI, 2344 update, 2345 BaseColumns._ID + "= ?", 2346 new String[]{Long.toString(itemId)}); 2347 } 2348 2349 /** Filters the set of items who are directly or indirectly (via another container) on the 2350 * specified screen. */ 2351 private void filterCurrentWorkspaceItems(long currentScreenId, 2352 ArrayList<ItemInfo> allWorkspaceItems, 2353 ArrayList<ItemInfo> currentScreenItems, 2354 ArrayList<ItemInfo> otherScreenItems) { 2355 // Purge any null ItemInfos 2356 Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); 2357 while (iter.hasNext()) { 2358 ItemInfo i = iter.next(); 2359 if (i == null) { 2360 iter.remove(); 2361 } 2362 } 2363 2364 // Order the set of items by their containers first, this allows use to walk through the 2365 // list sequentially, build up a list of containers that are in the specified screen, 2366 // as well as all items in those containers. 2367 Set<Long> itemsOnScreen = new HashSet<Long>(); 2368 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { 2369 @Override 2370 public int compare(ItemInfo lhs, ItemInfo rhs) { 2371 return (int) (lhs.container - rhs.container); 2372 } 2373 }); 2374 for (ItemInfo info : allWorkspaceItems) { 2375 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { 2376 if (info.screenId == currentScreenId) { 2377 currentScreenItems.add(info); 2378 itemsOnScreen.add(info.id); 2379 } else { 2380 otherScreenItems.add(info); 2381 } 2382 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 2383 currentScreenItems.add(info); 2384 itemsOnScreen.add(info.id); 2385 } else { 2386 if (itemsOnScreen.contains(info.container)) { 2387 currentScreenItems.add(info); 2388 itemsOnScreen.add(info.id); 2389 } else { 2390 otherScreenItems.add(info); 2391 } 2392 } 2393 } 2394 } 2395 2396 /** Filters the set of widgets which are on the specified screen. */ 2397 private void filterCurrentAppWidgets(long currentScreenId, 2398 ArrayList<LauncherAppWidgetInfo> appWidgets, 2399 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, 2400 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { 2401 2402 for (LauncherAppWidgetInfo widget : appWidgets) { 2403 if (widget == null) continue; 2404 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && 2405 widget.screenId == currentScreenId) { 2406 currentScreenWidgets.add(widget); 2407 } else { 2408 otherScreenWidgets.add(widget); 2409 } 2410 } 2411 } 2412 2413 /** Filters the set of folders which are on the specified screen. */ 2414 private void filterCurrentFolders(long currentScreenId, 2415 LongArrayMap<ItemInfo> itemsIdMap, 2416 LongArrayMap<FolderInfo> folders, 2417 LongArrayMap<FolderInfo> currentScreenFolders, 2418 LongArrayMap<FolderInfo> otherScreenFolders) { 2419 2420 int total = folders.size(); 2421 for (int i = 0; i < total; i++) { 2422 long id = folders.keyAt(i); 2423 FolderInfo folder = folders.valueAt(i); 2424 2425 ItemInfo info = itemsIdMap.get(id); 2426 if (info == null || folder == null) continue; 2427 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && 2428 info.screenId == currentScreenId) { 2429 currentScreenFolders.put(id, folder); 2430 } else { 2431 otherScreenFolders.put(id, folder); 2432 } 2433 } 2434 } 2435 2436 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to 2437 * right) */ 2438 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { 2439 final LauncherAppState app = LauncherAppState.getInstance(); 2440 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile(); 2441 final int screenCols = profile.numColumns; 2442 final int screenCellCount = profile.numColumns * profile.numRows; 2443 Collections.sort(workspaceItems, new Comparator<ItemInfo>() { 2444 @Override 2445 public int compare(ItemInfo lhs, ItemInfo rhs) { 2446 if (lhs.container == rhs.container) { 2447 // Within containers, order by their spatial position in that container 2448 switch ((int) lhs.container) { 2449 case LauncherSettings.Favorites.CONTAINER_DESKTOP: { 2450 long lr = (lhs.screenId * screenCellCount + 2451 lhs.cellY * screenCols + lhs.cellX); 2452 long rr = (rhs.screenId * screenCellCount + 2453 rhs.cellY * screenCols + rhs.cellX); 2454 return (int) (lr - rr); 2455 } 2456 case LauncherSettings.Favorites.CONTAINER_HOTSEAT: { 2457 // We currently use the screen id as the rank 2458 return (int) (lhs.screenId - rhs.screenId); 2459 } 2460 default: 2461 if (ProviderConfig.IS_DOGFOOD_BUILD) { 2462 throw new RuntimeException("Unexpected container type when " + 2463 "sorting workspace items."); 2464 } 2465 return 0; 2466 } 2467 } else { 2468 // Between containers, order by hotseat, desktop 2469 return (int) (lhs.container - rhs.container); 2470 } 2471 } 2472 }); 2473 } 2474 2475 private void bindWorkspaceScreens(final Callbacks oldCallbacks, 2476 final ArrayList<Long> orderedScreens) { 2477 final Runnable r = new Runnable() { 2478 @Override 2479 public void run() { 2480 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2481 if (callbacks != null) { 2482 callbacks.bindScreens(orderedScreens); 2483 } 2484 } 2485 }; 2486 runOnMainThread(r); 2487 } 2488 2489 private void bindWorkspaceItems(final Callbacks oldCallbacks, 2490 final ArrayList<ItemInfo> workspaceItems, 2491 final ArrayList<LauncherAppWidgetInfo> appWidgets, 2492 final LongArrayMap<FolderInfo> folders, 2493 ArrayList<Runnable> deferredBindRunnables) { 2494 2495 final boolean postOnMainThread = (deferredBindRunnables != null); 2496 2497 // Bind the workspace items 2498 int N = workspaceItems.size(); 2499 for (int i = 0; i < N; i += ITEMS_CHUNK) { 2500 final int start = i; 2501 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); 2502 final Runnable r = new Runnable() { 2503 @Override 2504 public void run() { 2505 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2506 if (callbacks != null) { 2507 callbacks.bindItems(workspaceItems, start, start+chunkSize, 2508 false); 2509 } 2510 } 2511 }; 2512 if (postOnMainThread) { 2513 synchronized (deferredBindRunnables) { 2514 deferredBindRunnables.add(r); 2515 } 2516 } else { 2517 runOnMainThread(r); 2518 } 2519 } 2520 2521 // Bind the folders 2522 if (!folders.isEmpty()) { 2523 final Runnable r = new Runnable() { 2524 public void run() { 2525 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2526 if (callbacks != null) { 2527 callbacks.bindFolders(folders); 2528 } 2529 } 2530 }; 2531 if (postOnMainThread) { 2532 synchronized (deferredBindRunnables) { 2533 deferredBindRunnables.add(r); 2534 } 2535 } else { 2536 runOnMainThread(r); 2537 } 2538 } 2539 2540 // Bind the widgets, one at a time 2541 N = appWidgets.size(); 2542 for (int i = 0; i < N; i++) { 2543 final LauncherAppWidgetInfo widget = appWidgets.get(i); 2544 final Runnable r = new Runnable() { 2545 public void run() { 2546 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2547 if (callbacks != null) { 2548 callbacks.bindAppWidget(widget); 2549 } 2550 } 2551 }; 2552 if (postOnMainThread) { 2553 deferredBindRunnables.add(r); 2554 } else { 2555 runOnMainThread(r); 2556 } 2557 } 2558 } 2559 2560 /** 2561 * Binds all loaded data to actual views on the main thread. 2562 */ 2563 private void bindWorkspace(int synchronizeBindPage) { 2564 final long t = SystemClock.uptimeMillis(); 2565 Runnable r; 2566 2567 // Don't use these two variables in any of the callback runnables. 2568 // Otherwise we hold a reference to them. 2569 final Callbacks oldCallbacks = mCallbacks.get(); 2570 if (oldCallbacks == null) { 2571 // This launcher has exited and nobody bothered to tell us. Just bail. 2572 Log.w(TAG, "LoaderTask running with no launcher"); 2573 return; 2574 } 2575 2576 // Save a copy of all the bg-thread collections 2577 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); 2578 ArrayList<LauncherAppWidgetInfo> appWidgets = 2579 new ArrayList<LauncherAppWidgetInfo>(); 2580 ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); 2581 2582 final LongArrayMap<FolderInfo> folders; 2583 final LongArrayMap<ItemInfo> itemsIdMap; 2584 2585 synchronized (sBgLock) { 2586 workspaceItems.addAll(sBgWorkspaceItems); 2587 appWidgets.addAll(sBgAppWidgets); 2588 orderedScreenIds.addAll(sBgWorkspaceScreens); 2589 2590 folders = sBgFolders.clone(); 2591 itemsIdMap = sBgItemsIdMap.clone(); 2592 } 2593 2594 final boolean isLoadingSynchronously = 2595 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE; 2596 int currScreen = isLoadingSynchronously ? synchronizeBindPage : 2597 oldCallbacks.getCurrentWorkspaceScreen(); 2598 if (currScreen >= orderedScreenIds.size()) { 2599 // There may be no workspace screens (just hotseat items and an empty page). 2600 currScreen = PagedView.INVALID_RESTORE_PAGE; 2601 } 2602 final int currentScreen = currScreen; 2603 final long currentScreenId = currentScreen < 0 2604 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen); 2605 2606 // Load all the items that are on the current page first (and in the process, unbind 2607 // all the existing workspace items before we call startBinding() below. 2608 unbindWorkspaceItemsOnMainThread(); 2609 2610 // Separate the items that are on the current screen, and all the other remaining items 2611 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); 2612 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); 2613 ArrayList<LauncherAppWidgetInfo> currentAppWidgets = 2614 new ArrayList<LauncherAppWidgetInfo>(); 2615 ArrayList<LauncherAppWidgetInfo> otherAppWidgets = 2616 new ArrayList<LauncherAppWidgetInfo>(); 2617 LongArrayMap<FolderInfo> currentFolders = new LongArrayMap<>(); 2618 LongArrayMap<FolderInfo> otherFolders = new LongArrayMap<>(); 2619 2620 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems, 2621 otherWorkspaceItems); 2622 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets, 2623 otherAppWidgets); 2624 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders, 2625 otherFolders); 2626 sortWorkspaceItemsSpatially(currentWorkspaceItems); 2627 sortWorkspaceItemsSpatially(otherWorkspaceItems); 2628 2629 // Tell the workspace that we're about to start binding items 2630 r = new Runnable() { 2631 public void run() { 2632 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2633 if (callbacks != null) { 2634 callbacks.startBinding(); 2635 } 2636 } 2637 }; 2638 runOnMainThread(r); 2639 2640 bindWorkspaceScreens(oldCallbacks, orderedScreenIds); 2641 2642 // Load items on the current page 2643 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, 2644 currentFolders, null); 2645 if (isLoadingSynchronously) { 2646 r = new Runnable() { 2647 public void run() { 2648 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2649 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) { 2650 callbacks.onPageBoundSynchronously(currentScreen); 2651 } 2652 } 2653 }; 2654 runOnMainThread(r); 2655 } 2656 2657 // Load all the remaining pages (if we are loading synchronously, we want to defer this 2658 // work until after the first render) 2659 synchronized (mDeferredBindRunnables) { 2660 mDeferredBindRunnables.clear(); 2661 } 2662 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, 2663 (isLoadingSynchronously ? mDeferredBindRunnables : null)); 2664 2665 // Tell the workspace that we're done binding items 2666 r = new Runnable() { 2667 public void run() { 2668 Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2669 if (callbacks != null) { 2670 callbacks.finishBindingItems(); 2671 } 2672 2673 // If we're profiling, ensure this is the last thing in the queue. 2674 if (DEBUG_LOADERS) { 2675 Log.d(TAG, "bound workspace in " 2676 + (SystemClock.uptimeMillis()-t) + "ms"); 2677 } 2678 2679 mIsLoadingAndBindingWorkspace = false; 2680 } 2681 }; 2682 if (isLoadingSynchronously) { 2683 synchronized (mDeferredBindRunnables) { 2684 mDeferredBindRunnables.add(r); 2685 } 2686 } else { 2687 runOnMainThread(r); 2688 } 2689 } 2690 2691 private void loadAndBindAllApps() { 2692 if (DEBUG_LOADERS) { 2693 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); 2694 } 2695 if (!mAllAppsLoaded) { 2696 loadAllApps(); 2697 synchronized (LoaderTask.this) { 2698 if (mStopped) { 2699 return; 2700 } 2701 } 2702 updateIconCache(); 2703 synchronized (LoaderTask.this) { 2704 if (mStopped) { 2705 return; 2706 } 2707 mAllAppsLoaded = true; 2708 } 2709 } else { 2710 onlyBindAllApps(); 2711 } 2712 } 2713 2714 private void updateIconCache() { 2715 // Ignore packages which have a promise icon. 2716 HashSet<String> packagesToIgnore = new HashSet<>(); 2717 synchronized (sBgLock) { 2718 for (ItemInfo info : sBgItemsIdMap) { 2719 if (info instanceof ShortcutInfo) { 2720 ShortcutInfo si = (ShortcutInfo) info; 2721 if (si.isPromise() && si.getTargetComponent() != null) { 2722 packagesToIgnore.add(si.getTargetComponent().getPackageName()); 2723 } 2724 } else if (info instanceof LauncherAppWidgetInfo) { 2725 LauncherAppWidgetInfo lawi = (LauncherAppWidgetInfo) info; 2726 if (lawi.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)) { 2727 packagesToIgnore.add(lawi.providerName.getPackageName()); 2728 } 2729 } 2730 } 2731 } 2732 mIconCache.updateDbIcons(packagesToIgnore); 2733 } 2734 2735 private void onlyBindAllApps() { 2736 final Callbacks oldCallbacks = mCallbacks.get(); 2737 if (oldCallbacks == null) { 2738 // This launcher has exited and nobody bothered to tell us. Just bail. 2739 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); 2740 return; 2741 } 2742 2743 // shallow copy 2744 @SuppressWarnings("unchecked") 2745 final ArrayList<AppInfo> list 2746 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone(); 2747 final WidgetsModel widgetList = mBgWidgetsModel.clone(); 2748 Runnable r = new Runnable() { 2749 public void run() { 2750 final long t = SystemClock.uptimeMillis(); 2751 final Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2752 if (callbacks != null) { 2753 callbacks.bindAllApplications(list); 2754 callbacks.bindAllPackages(widgetList); 2755 } 2756 if (DEBUG_LOADERS) { 2757 Log.d(TAG, "bound all " + list.size() + " apps from cache in " 2758 + (SystemClock.uptimeMillis()-t) + "ms"); 2759 } 2760 } 2761 }; 2762 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); 2763 if (isRunningOnMainThread) { 2764 r.run(); 2765 } else { 2766 mHandler.post(r); 2767 } 2768 } 2769 2770 private void loadAllApps() { 2771 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; 2772 2773 final Callbacks oldCallbacks = mCallbacks.get(); 2774 if (oldCallbacks == null) { 2775 // This launcher has exited and nobody bothered to tell us. Just bail. 2776 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)"); 2777 return; 2778 } 2779 2780 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles(); 2781 2782 // Clear the list of apps 2783 mBgAllAppsList.clear(); 2784 for (UserHandleCompat user : profiles) { 2785 // Query for the set of apps 2786 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; 2787 final List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user); 2788 if (DEBUG_LOADERS) { 2789 Log.d(TAG, "getActivityList took " 2790 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user); 2791 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user); 2792 } 2793 // Fail if we don't have any apps 2794 // TODO: Fix this. Only fail for the current user. 2795 if (apps == null || apps.isEmpty()) { 2796 return; 2797 } 2798 2799 // Create the ApplicationInfos 2800 for (int i = 0; i < apps.size(); i++) { 2801 LauncherActivityInfoCompat app = apps.get(i); 2802 // This builds the icon bitmaps. 2803 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache)); 2804 } 2805 2806 final ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(mContext, user); 2807 if (heuristic != null) { 2808 runAfterBindCompletes(new Runnable() { 2809 2810 @Override 2811 public void run() { 2812 heuristic.processUserApps(apps); 2813 } 2814 }); 2815 } 2816 } 2817 // Huh? Shouldn't this be inside the Runnable below? 2818 final ArrayList<AppInfo> added = mBgAllAppsList.added; 2819 mBgAllAppsList.added = new ArrayList<AppInfo>(); 2820 2821 // Post callback on main thread 2822 mHandler.post(new Runnable() { 2823 public void run() { 2824 2825 final long bindTime = SystemClock.uptimeMillis(); 2826 final Callbacks callbacks = tryGetCallbacks(oldCallbacks); 2827 if (callbacks != null) { 2828 callbacks.bindAllApplications(added); 2829 if (DEBUG_LOADERS) { 2830 Log.d(TAG, "bound " + added.size() + " apps in " 2831 + (SystemClock.uptimeMillis() - bindTime) + "ms"); 2832 } 2833 } else { 2834 Log.i(TAG, "not binding apps: no Launcher activity"); 2835 } 2836 } 2837 }); 2838 // Cleanup any data stored for a deleted user. 2839 ManagedProfileHeuristic.processAllUsers(profiles, mContext); 2840 2841 loadAndBindWidgetsAndShortcuts(mApp.getContext(), tryGetCallbacks(oldCallbacks), 2842 true /* refresh */); 2843 if (DEBUG_LOADERS) { 2844 Log.d(TAG, "Icons processed in " 2845 + (SystemClock.uptimeMillis() - loadTime) + "ms"); 2846 } 2847 } 2848 2849 public void dumpState() { 2850 synchronized (sBgLock) { 2851 Log.d(TAG, "mLoaderTask.mContext=" + mContext); 2852 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); 2853 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); 2854 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); 2855 } 2856 } 2857 } 2858 2859 /** 2860 * Called when the icons for packages have been updated in the icon cache. 2861 */ 2862 public void onPackageIconsUpdated(HashSet<String> updatedPackages, UserHandleCompat user) { 2863 final Callbacks callbacks = getCallback(); 2864 final ArrayList<AppInfo> updatedApps = new ArrayList<>(); 2865 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<>(); 2866 2867 // If any package icon has changed (app was updated while launcher was dead), 2868 // update the corresponding shortcuts. 2869 synchronized (sBgLock) { 2870 for (ItemInfo info : sBgItemsIdMap) { 2871 if (info instanceof ShortcutInfo && user.equals(info.user) 2872 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { 2873 ShortcutInfo si = (ShortcutInfo) info; 2874 ComponentName cn = si.getTargetComponent(); 2875 if (cn != null && updatedPackages.contains(cn.getPackageName())) { 2876 si.updateIcon(mIconCache); 2877 updatedShortcuts.add(si); 2878 } 2879 } 2880 } 2881 mBgAllAppsList.updateIconsAndLabels(updatedPackages, user, updatedApps); 2882 } 2883 2884 if (!updatedShortcuts.isEmpty()) { 2885 final UserHandleCompat userFinal = user; 2886 mHandler.post(new Runnable() { 2887 2888 public void run() { 2889 Callbacks cb = getCallback(); 2890 if (cb != null && callbacks == cb) { 2891 cb.bindShortcutsChanged(updatedShortcuts, 2892 new ArrayList<ShortcutInfo>(), userFinal); 2893 } 2894 } 2895 }); 2896 } 2897 2898 if (!updatedApps.isEmpty()) { 2899 mHandler.post(new Runnable() { 2900 2901 public void run() { 2902 Callbacks cb = getCallback(); 2903 if (cb != null && callbacks == cb) { 2904 cb.bindAppsUpdated(updatedApps); 2905 } 2906 } 2907 }); 2908 } 2909 2910 // Reload widget list. No need to refresh, as we only want to update the icons and labels. 2911 loadAndBindWidgetsAndShortcuts(mApp.getContext(), callbacks, false); 2912 } 2913 2914 void enqueuePackageUpdated(PackageUpdatedTask task) { 2915 sWorker.post(task); 2916 } 2917 2918 @Thunk class AppsAvailabilityCheck extends BroadcastReceiver { 2919 2920 @Override 2921 public void onReceive(Context context, Intent intent) { 2922 synchronized (sBgLock) { 2923 final LauncherAppsCompat launcherApps = LauncherAppsCompat 2924 .getInstance(mApp.getContext()); 2925 final PackageManager manager = context.getPackageManager(); 2926 final ArrayList<String> packagesRemoved = new ArrayList<String>(); 2927 final ArrayList<String> packagesUnavailable = new ArrayList<String>(); 2928 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) { 2929 UserHandleCompat user = entry.getKey(); 2930 packagesRemoved.clear(); 2931 packagesUnavailable.clear(); 2932 for (String pkg : entry.getValue()) { 2933 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) { 2934 boolean packageOnSdcard = launcherApps.isAppEnabled( 2935 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES); 2936 if (packageOnSdcard) { 2937 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true); 2938 packagesUnavailable.add(pkg); 2939 } else { 2940 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true); 2941 packagesRemoved.add(pkg); 2942 } 2943 } 2944 } 2945 if (!packagesRemoved.isEmpty()) { 2946 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE, 2947 packagesRemoved.toArray(new String[packagesRemoved.size()]), user)); 2948 } 2949 if (!packagesUnavailable.isEmpty()) { 2950 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE, 2951 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user)); 2952 } 2953 } 2954 sPendingPackages.clear(); 2955 } 2956 } 2957 } 2958 2959 private class PackageUpdatedTask implements Runnable { 2960 int mOp; 2961 String[] mPackages; 2962 UserHandleCompat mUser; 2963 2964 public static final int OP_NONE = 0; 2965 public static final int OP_ADD = 1; 2966 public static final int OP_UPDATE = 2; 2967 public static final int OP_REMOVE = 3; // uninstlled 2968 public static final int OP_UNAVAILABLE = 4; // external media unmounted 2969 2970 2971 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) { 2972 mOp = op; 2973 mPackages = packages; 2974 mUser = user; 2975 } 2976 2977 public void run() { 2978 if (!mHasLoaderCompletedOnce) { 2979 // Loader has not yet run. 2980 return; 2981 } 2982 final Context context = mApp.getContext(); 2983 2984 final String[] packages = mPackages; 2985 final int N = packages.length; 2986 switch (mOp) { 2987 case OP_ADD: { 2988 for (int i=0; i<N; i++) { 2989 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); 2990 mIconCache.updateIconsForPkg(packages[i], mUser); 2991 mBgAllAppsList.addPackage(context, packages[i], mUser); 2992 } 2993 2994 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(context, mUser); 2995 if (heuristic != null) { 2996 heuristic.processPackageAdd(mPackages); 2997 } 2998 break; 2999 } 3000 case OP_UPDATE: 3001 for (int i=0; i<N; i++) { 3002 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); 3003 mIconCache.updateIconsForPkg(packages[i], mUser); 3004 mBgAllAppsList.updatePackage(context, packages[i], mUser); 3005 mApp.getWidgetCache().removePackage(packages[i], mUser); 3006 } 3007 break; 3008 case OP_REMOVE: { 3009 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(context, mUser); 3010 if (heuristic != null) { 3011 heuristic.processPackageRemoved(mPackages); 3012 } 3013 for (int i=0; i<N; i++) { 3014 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); 3015 mIconCache.removeIconsForPkg(packages[i], mUser); 3016 } 3017 // Fall through 3018 } 3019 case OP_UNAVAILABLE: 3020 for (int i=0; i<N; i++) { 3021 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); 3022 mBgAllAppsList.removePackage(packages[i], mUser); 3023 mApp.getWidgetCache().removePackage(packages[i], mUser); 3024 } 3025 break; 3026 } 3027 3028 ArrayList<AppInfo> added = null; 3029 ArrayList<AppInfo> modified = null; 3030 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>(); 3031 3032 if (mBgAllAppsList.added.size() > 0) { 3033 added = new ArrayList<AppInfo>(mBgAllAppsList.added); 3034 mBgAllAppsList.added.clear(); 3035 } 3036 if (mBgAllAppsList.modified.size() > 0) { 3037 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified); 3038 mBgAllAppsList.modified.clear(); 3039 } 3040 if (mBgAllAppsList.removed.size() > 0) { 3041 removedApps.addAll(mBgAllAppsList.removed); 3042 mBgAllAppsList.removed.clear(); 3043 } 3044 3045 final Callbacks callbacks = getCallback(); 3046 if (callbacks == null) { 3047 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); 3048 return; 3049 } 3050 3051 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps = 3052 new HashMap<ComponentName, AppInfo>(); 3053 3054 if (added != null) { 3055 addAppsToAllApps(context, added); 3056 for (AppInfo ai : added) { 3057 addedOrUpdatedApps.put(ai.componentName, ai); 3058 } 3059 } 3060 3061 if (modified != null) { 3062 final ArrayList<AppInfo> modifiedFinal = modified; 3063 for (AppInfo ai : modified) { 3064 addedOrUpdatedApps.put(ai.componentName, ai); 3065 } 3066 3067 mHandler.post(new Runnable() { 3068 public void run() { 3069 Callbacks cb = getCallback(); 3070 if (callbacks == cb && cb != null) { 3071 callbacks.bindAppsUpdated(modifiedFinal); 3072 } 3073 } 3074 }); 3075 } 3076 3077 // Update shortcut infos 3078 if (mOp == OP_ADD || mOp == OP_UPDATE) { 3079 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>(); 3080 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>(); 3081 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>(); 3082 3083 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages)); 3084 synchronized (sBgLock) { 3085 for (ItemInfo info : sBgItemsIdMap) { 3086 if (info instanceof ShortcutInfo && mUser.equals(info.user)) { 3087 ShortcutInfo si = (ShortcutInfo) info; 3088 boolean infoUpdated = false; 3089 boolean shortcutUpdated = false; 3090 3091 // Update shortcuts which use iconResource. 3092 if ((si.iconResource != null) 3093 && packageSet.contains(si.iconResource.packageName)) { 3094 Bitmap icon = Utilities.createIconBitmap( 3095 si.iconResource.packageName, 3096 si.iconResource.resourceName, context); 3097 if (icon != null) { 3098 si.setIcon(icon); 3099 si.usingFallbackIcon = false; 3100 infoUpdated = true; 3101 } 3102 } 3103 3104 ComponentName cn = si.getTargetComponent(); 3105 if (cn != null && packageSet.contains(cn.getPackageName())) { 3106 AppInfo appInfo = addedOrUpdatedApps.get(cn); 3107 3108 if (si.isPromise()) { 3109 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) { 3110 // Auto install icon 3111 PackageManager pm = context.getPackageManager(); 3112 ResolveInfo matched = pm.resolveActivity( 3113 new Intent(Intent.ACTION_MAIN) 3114 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER), 3115 PackageManager.MATCH_DEFAULT_ONLY); 3116 if (matched == null) { 3117 // Try to find the best match activity. 3118 Intent intent = pm.getLaunchIntentForPackage( 3119 cn.getPackageName()); 3120 if (intent != null) { 3121 cn = intent.getComponent(); 3122 appInfo = addedOrUpdatedApps.get(cn); 3123 } 3124 3125 if ((intent == null) || (appInfo == null)) { 3126 removedShortcuts.add(si); 3127 continue; 3128 } 3129 si.promisedIntent = intent; 3130 } 3131 } 3132 3133 // Restore the shortcut. 3134 if (appInfo != null) { 3135 si.flags = appInfo.flags; 3136 } 3137 3138 si.intent = si.promisedIntent; 3139 si.promisedIntent = null; 3140 si.status = ShortcutInfo.DEFAULT; 3141 infoUpdated = true; 3142 si.updateIcon(mIconCache); 3143 } 3144 3145 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction()) 3146 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { 3147 si.updateIcon(mIconCache); 3148 si.title = Utilities.trim(appInfo.title); 3149 si.contentDescription = appInfo.contentDescription; 3150 infoUpdated = true; 3151 } 3152 3153 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) { 3154 // Since package was just updated, the target must be available now. 3155 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE; 3156 shortcutUpdated = true; 3157 } 3158 } 3159 3160 if (infoUpdated || shortcutUpdated) { 3161 updatedShortcuts.add(si); 3162 } 3163 if (infoUpdated) { 3164 updateItemInDatabase(context, si); 3165 } 3166 } else if (info instanceof LauncherAppWidgetInfo) { 3167 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info; 3168 if (mUser.equals(widgetInfo.user) 3169 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) 3170 && packageSet.contains(widgetInfo.providerName.getPackageName())) { 3171 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY; 3172 widgets.add(widgetInfo); 3173 updateItemInDatabase(context, widgetInfo); 3174 } 3175 } 3176 } 3177 } 3178 3179 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) { 3180 mHandler.post(new Runnable() { 3181 3182 public void run() { 3183 Callbacks cb = getCallback(); 3184 if (callbacks == cb && cb != null) { 3185 callbacks.bindShortcutsChanged( 3186 updatedShortcuts, removedShortcuts, mUser); 3187 } 3188 } 3189 }); 3190 if (!removedShortcuts.isEmpty()) { 3191 deleteItemsFromDatabase(context, removedShortcuts); 3192 } 3193 } 3194 if (!widgets.isEmpty()) { 3195 mHandler.post(new Runnable() { 3196 public void run() { 3197 Callbacks cb = getCallback(); 3198 if (callbacks == cb && cb != null) { 3199 callbacks.bindWidgetsRestored(widgets); 3200 } 3201 } 3202 }); 3203 } 3204 } 3205 3206 final ArrayList<String> removedPackageNames = 3207 new ArrayList<String>(); 3208 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) { 3209 // Mark all packages in the broadcast to be removed 3210 removedPackageNames.addAll(Arrays.asList(packages)); 3211 } else if (mOp == OP_UPDATE) { 3212 // Mark disabled packages in the broadcast to be removed 3213 for (int i=0; i<N; i++) { 3214 if (isPackageDisabled(context, packages[i], mUser)) { 3215 removedPackageNames.add(packages[i]); 3216 } 3217 } 3218 } 3219 3220 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) { 3221 final int removeReason; 3222 if (mOp == OP_UNAVAILABLE) { 3223 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE; 3224 } else { 3225 // Remove all the components associated with this package 3226 for (String pn : removedPackageNames) { 3227 deletePackageFromDatabase(context, pn, mUser); 3228 } 3229 // Remove all the specific components 3230 for (AppInfo a : removedApps) { 3231 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser); 3232 deleteItemsFromDatabase(context, infos); 3233 } 3234 removeReason = 0; 3235 } 3236 3237 // Remove any queued items from the install queue 3238 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser); 3239 // Call the components-removed callback 3240 mHandler.post(new Runnable() { 3241 public void run() { 3242 Callbacks cb = getCallback(); 3243 if (callbacks == cb && cb != null) { 3244 callbacks.bindComponentsRemoved( 3245 removedPackageNames, removedApps, mUser, removeReason); 3246 } 3247 } 3248 }); 3249 } 3250 3251 // onProvidersChanged method (API >= 17) already refreshed the widget list 3252 loadAndBindWidgetsAndShortcuts(context, callbacks, Build.VERSION.SDK_INT < 17); 3253 3254 // Write all the logs to disk 3255 mHandler.post(new Runnable() { 3256 public void run() { 3257 Callbacks cb = getCallback(); 3258 if (callbacks == cb && cb != null) { 3259 callbacks.dumpLogsToLocalData(); 3260 } 3261 } 3262 }); 3263 } 3264 } 3265 3266 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context, 3267 boolean refresh) { 3268 ArrayList<LauncherAppWidgetProviderInfo> results = 3269 new ArrayList<LauncherAppWidgetProviderInfo>(); 3270 try { 3271 synchronized (sBgLock) { 3272 if (sBgWidgetProviders == null || refresh) { 3273 HashMap<ComponentKey, LauncherAppWidgetProviderInfo> tmpWidgetProviders 3274 = new HashMap<>(); 3275 AppWidgetManagerCompat wm = AppWidgetManagerCompat.getInstance(context); 3276 LauncherAppWidgetProviderInfo info; 3277 3278 List<AppWidgetProviderInfo> widgets = wm.getAllProviders(); 3279 for (AppWidgetProviderInfo pInfo : widgets) { 3280 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo); 3281 UserHandleCompat user = wm.getUser(info); 3282 tmpWidgetProviders.put(new ComponentKey(info.provider, user), info); 3283 } 3284 3285 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values(); 3286 for (CustomAppWidget widget : customWidgets) { 3287 info = new LauncherAppWidgetProviderInfo(context, widget); 3288 UserHandleCompat user = wm.getUser(info); 3289 tmpWidgetProviders.put(new ComponentKey(info.provider, user), info); 3290 } 3291 // Replace the global list at the very end, so that if there is an exception, 3292 // previously loaded provider list is used. 3293 sBgWidgetProviders = tmpWidgetProviders; 3294 } 3295 results.addAll(sBgWidgetProviders.values()); 3296 return results; 3297 } 3298 } catch (Exception e) { 3299 if (e.getCause() instanceof TransactionTooLargeException) { 3300 // the returned value may be incomplete and will not be refreshed until the next 3301 // time Launcher starts. 3302 // TODO: after figuring out a repro step, introduce a dirty bit to check when 3303 // onResume is called to refresh the widget provider list. 3304 synchronized (sBgLock) { 3305 if (sBgWidgetProviders != null) { 3306 results.addAll(sBgWidgetProviders.values()); 3307 } 3308 return results; 3309 } 3310 } else { 3311 throw e; 3312 } 3313 } 3314 } 3315 3316 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name, 3317 UserHandleCompat user) { 3318 synchronized (sBgLock) { 3319 if (sBgWidgetProviders == null) { 3320 getWidgetProviders(ctx, false /* refresh */); 3321 } 3322 return sBgWidgetProviders.get(new ComponentKey(name, user)); 3323 } 3324 } 3325 3326 public void loadAndBindWidgetsAndShortcuts(final Context context, final Callbacks callbacks, 3327 final boolean refresh) { 3328 3329 runOnWorkerThread(new Runnable() { 3330 @Override 3331 public void run() { 3332 updateWidgetsModel(context, refresh); 3333 final WidgetsModel model = mBgWidgetsModel.clone(); 3334 3335 mHandler.post(new Runnable() { 3336 @Override 3337 public void run() { 3338 Callbacks cb = getCallback(); 3339 if (callbacks == cb && cb != null) { 3340 callbacks.bindAllPackages(model); 3341 } 3342 } 3343 }); 3344 // update the Widget entries inside DB on the worker thread. 3345 LauncherAppState.getInstance().getWidgetCache().removeObsoletePreviews( 3346 model.getRawList()); 3347 } 3348 }); 3349 } 3350 3351 /** 3352 * Returns a list of ResolveInfos/AppWidgetInfos. 3353 * 3354 * @see #loadAndBindWidgetsAndShortcuts 3355 */ 3356 @Thunk void updateWidgetsModel(Context context, boolean refresh) { 3357 PackageManager packageManager = context.getPackageManager(); 3358 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); 3359 widgetsAndShortcuts.addAll(getWidgetProviders(context, refresh)); 3360 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); 3361 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); 3362 mBgWidgetsModel.setWidgetsAndShortcuts(widgetsAndShortcuts); 3363 } 3364 3365 @Thunk static boolean isPackageDisabled(Context context, String packageName, 3366 UserHandleCompat user) { 3367 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context); 3368 return !launcherApps.isPackageEnabledForProfile(packageName, user); 3369 } 3370 3371 public static boolean isValidPackageActivity(Context context, ComponentName cn, 3372 UserHandleCompat user) { 3373 if (cn == null) { 3374 return false; 3375 } 3376 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context); 3377 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) { 3378 return false; 3379 } 3380 return launcherApps.isActivityEnabledForProfile(cn, user); 3381 } 3382 3383 public static boolean isValidPackage(Context context, String packageName, 3384 UserHandleCompat user) { 3385 if (packageName == null) { 3386 return false; 3387 } 3388 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context); 3389 return launcherApps.isPackageEnabledForProfile(packageName, user); 3390 } 3391 3392 /** 3393 * Make an ShortcutInfo object for a restored application or shortcut item that points 3394 * to a package that is not yet installed on the system. 3395 */ 3396 public ShortcutInfo getRestoredItemInfo(Cursor c, int titleIndex, Intent intent, 3397 int promiseType, int itemType, CursorIconInfo iconInfo, Context context) { 3398 final ShortcutInfo info = new ShortcutInfo(); 3399 info.user = UserHandleCompat.myUserHandle(); 3400 3401 Bitmap icon = iconInfo.loadIcon(c, info, context); 3402 // the fallback icon 3403 if (icon == null) { 3404 mIconCache.getTitleAndIcon(info, intent, info.user, false /* useLowResIcon */); 3405 } else { 3406 info.setIcon(icon); 3407 } 3408 3409 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) { 3410 String title = (c != null) ? c.getString(titleIndex) : null; 3411 if (!TextUtils.isEmpty(title)) { 3412 info.title = Utilities.trim(title); 3413 } 3414 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) { 3415 if (TextUtils.isEmpty(info.title)) { 3416 info.title = (c != null) ? Utilities.trim(c.getString(titleIndex)) : ""; 3417 } 3418 } else { 3419 throw new InvalidParameterException("Invalid restoreType " + promiseType); 3420 } 3421 3422 info.contentDescription = mUserManager.getBadgedLabelForUser(info.title, info.user); 3423 info.itemType = itemType; 3424 info.promisedIntent = intent; 3425 info.status = promiseType; 3426 return info; 3427 } 3428 3429 /** 3430 * Make an Intent object for a restored application or shortcut item that points 3431 * to the market page for the item. 3432 */ 3433 @Thunk Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) { 3434 ComponentName componentName = intent.getComponent(); 3435 return getMarketIntent(componentName.getPackageName()); 3436 } 3437 3438 static Intent getMarketIntent(String packageName) { 3439 return new Intent(Intent.ACTION_VIEW) 3440 .setData(new Uri.Builder() 3441 .scheme("market") 3442 .authority("details") 3443 .appendQueryParameter("id", packageName) 3444 .build()); 3445 } 3446 3447 /** 3448 * Make an ShortcutInfo object for a shortcut that is an application. 3449 * 3450 * If c is not null, then it will be used to fill in missing data like the title and icon. 3451 */ 3452 public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent, 3453 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex, 3454 boolean allowMissingTarget, boolean useLowResIcon) { 3455 if (user == null) { 3456 Log.d(TAG, "Null user found in getShortcutInfo"); 3457 return null; 3458 } 3459 3460 ComponentName componentName = intent.getComponent(); 3461 if (componentName == null) { 3462 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName); 3463 return null; 3464 } 3465 3466 Intent newIntent = new Intent(intent.getAction(), null); 3467 newIntent.addCategory(Intent.CATEGORY_LAUNCHER); 3468 newIntent.setComponent(componentName); 3469 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user); 3470 if ((lai == null) && !allowMissingTarget) { 3471 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName); 3472 return null; 3473 } 3474 3475 final ShortcutInfo info = new ShortcutInfo(); 3476 mIconCache.getTitleAndIcon(info, componentName, lai, user, false, useLowResIcon); 3477 if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) { 3478 Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context); 3479 info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon); 3480 } 3481 3482 // from the db 3483 if (TextUtils.isEmpty(info.title) && c != null) { 3484 info.title = Utilities.trim(c.getString(titleIndex)); 3485 } 3486 3487 // fall back to the class name of the activity 3488 if (info.title == null) { 3489 info.title = componentName.getClassName(); 3490 } 3491 3492 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; 3493 info.user = user; 3494 info.contentDescription = mUserManager.getBadgedLabelForUser(info.title, info.user); 3495 if (lai != null) { 3496 info.flags = AppInfo.initFlags(lai); 3497 } 3498 return info; 3499 } 3500 3501 static ArrayList<ItemInfo> filterItemInfos(Iterable<ItemInfo> infos, 3502 ItemInfoFilter f) { 3503 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>(); 3504 for (ItemInfo i : infos) { 3505 if (i instanceof ShortcutInfo) { 3506 ShortcutInfo info = (ShortcutInfo) i; 3507 ComponentName cn = info.getTargetComponent(); 3508 if (cn != null && f.filterItem(null, info, cn)) { 3509 filtered.add(info); 3510 } 3511 } else if (i instanceof FolderInfo) { 3512 FolderInfo info = (FolderInfo) i; 3513 for (ShortcutInfo s : info.contents) { 3514 ComponentName cn = s.getTargetComponent(); 3515 if (cn != null && f.filterItem(info, s, cn)) { 3516 filtered.add(s); 3517 } 3518 } 3519 } else if (i instanceof LauncherAppWidgetInfo) { 3520 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i; 3521 ComponentName cn = info.providerName; 3522 if (cn != null && f.filterItem(null, info, cn)) { 3523 filtered.add(info); 3524 } 3525 } 3526 } 3527 return new ArrayList<ItemInfo>(filtered); 3528 } 3529 3530 @Thunk ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname, 3531 final UserHandleCompat user) { 3532 ItemInfoFilter filter = new ItemInfoFilter() { 3533 @Override 3534 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { 3535 if (info.user == null) { 3536 return cn.equals(cname); 3537 } else { 3538 return cn.equals(cname) && info.user.equals(user); 3539 } 3540 } 3541 }; 3542 return filterItemInfos(sBgItemsIdMap, filter); 3543 } 3544 3545 /** 3546 * Make an ShortcutInfo object for a shortcut that isn't an application. 3547 */ 3548 @Thunk ShortcutInfo getShortcutInfo(Cursor c, Context context, 3549 int titleIndex, CursorIconInfo iconInfo) { 3550 final ShortcutInfo info = new ShortcutInfo(); 3551 // Non-app shortcuts are only supported for current user. 3552 info.user = UserHandleCompat.myUserHandle(); 3553 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; 3554 3555 // TODO: If there's an explicit component and we can't install that, delete it. 3556 3557 info.title = Utilities.trim(c.getString(titleIndex)); 3558 3559 Bitmap icon = iconInfo.loadIcon(c, info, context); 3560 // the fallback icon 3561 if (icon == null) { 3562 icon = mIconCache.getDefaultIcon(info.user); 3563 info.usingFallbackIcon = true; 3564 } 3565 info.setIcon(icon); 3566 return info; 3567 } 3568 3569 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) { 3570 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); 3571 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); 3572 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); 3573 3574 if (intent == null) { 3575 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null 3576 Log.e(TAG, "Can't construct ShorcutInfo with null intent"); 3577 return null; 3578 } 3579 3580 Bitmap icon = null; 3581 boolean customIcon = false; 3582 ShortcutIconResource iconResource = null; 3583 3584 if (bitmap instanceof Bitmap) { 3585 icon = Utilities.createIconBitmap((Bitmap) bitmap, context); 3586 customIcon = true; 3587 } else { 3588 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); 3589 if (extra instanceof ShortcutIconResource) { 3590 iconResource = (ShortcutIconResource) extra; 3591 icon = Utilities.createIconBitmap(iconResource.packageName, 3592 iconResource.resourceName, context); 3593 } 3594 } 3595 3596 final ShortcutInfo info = new ShortcutInfo(); 3597 3598 // Only support intents for current user for now. Intents sent from other 3599 // users wouldn't get here without intent forwarding anyway. 3600 info.user = UserHandleCompat.myUserHandle(); 3601 if (icon == null) { 3602 icon = mIconCache.getDefaultIcon(info.user); 3603 info.usingFallbackIcon = true; 3604 } 3605 info.setIcon(icon); 3606 3607 info.title = Utilities.trim(name); 3608 info.contentDescription = mUserManager.getBadgedLabelForUser(info.title, info.user); 3609 info.intent = intent; 3610 info.customIcon = customIcon; 3611 info.iconResource = iconResource; 3612 3613 return info; 3614 } 3615 3616 /** 3617 * Return an existing FolderInfo object if we have encountered this ID previously, 3618 * or make a new one. 3619 */ 3620 @Thunk static FolderInfo findOrMakeFolder(LongArrayMap<FolderInfo> folders, long id) { 3621 // See if a placeholder was created for us already 3622 FolderInfo folderInfo = folders.get(id); 3623 if (folderInfo == null) { 3624 // No placeholder -- create a new instance 3625 folderInfo = new FolderInfo(); 3626 folders.put(id, folderInfo); 3627 } 3628 return folderInfo; 3629 } 3630 3631 3632 static boolean isValidProvider(AppWidgetProviderInfo provider) { 3633 return (provider != null) && (provider.provider != null) 3634 && (provider.provider.getPackageName() != null); 3635 } 3636 3637 public void dumpState() { 3638 Log.d(TAG, "mCallbacks=" + mCallbacks); 3639 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); 3640 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); 3641 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); 3642 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); 3643 if (mLoaderTask != null) { 3644 mLoaderTask.dumpState(); 3645 } else { 3646 Log.d(TAG, "mLoaderTask=null"); 3647 } 3648 } 3649 3650 public Callbacks getCallback() { 3651 return mCallbacks != null ? mCallbacks.get() : null; 3652 } 3653 3654 /** 3655 * @return {@link FolderInfo} if its already loaded. 3656 */ 3657 public FolderInfo findFolderById(Long folderId) { 3658 synchronized (sBgLock) { 3659 return sBgFolders.get(folderId); 3660 } 3661 } 3662 3663 /** 3664 * @return the looper for the worker thread which can be used to start background tasks. 3665 */ 3666 public static Looper getWorkerLooper() { 3667 return sWorkerThread.getLooper(); 3668 } 3669} 3670