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