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