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