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