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