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