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