blob: 0b69a09c962b945252438680b1870a080bbd3255 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
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
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Narayan Kamathcb1a4772011-06-28 13:46:59 +010019import android.app.SearchManager;
Romain Guy629de3e2010-01-13 12:20:59 -080020import android.appwidget.AppWidgetManager;
21import android.appwidget.AppWidgetProviderInfo;
Winson Chungc9168342013-06-26 14:54:55 -070022import android.content.*;
Joe Onorato0589f0f2010-02-08 13:44:00 -080023import android.content.Intent.ShortcutIconResource;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080024import android.content.pm.ActivityInfo;
Adam Cohen00fcb492011-11-02 21:53:47 -070025import android.content.pm.PackageInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.pm.PackageManager;
Adam Cohen00fcb492011-11-02 21:53:47 -070027import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080028import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070029import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080030import android.content.res.Resources;
31import android.database.Cursor;
32import android.graphics.Bitmap;
33import android.graphics.BitmapFactory;
34import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080035import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040036import android.os.Handler;
37import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080038import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070040import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040041import android.os.SystemClock;
Winson Chungaafa03c2010-06-11 17:34:16 -070042import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070043import android.util.Pair;
Daniel Sandler325dc232013-06-05 22:57:57 -040044import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
Romain Guyedcce092010-03-04 13:03:17 -080045
Michael Jurkac2f801e2011-07-12 14:19:46 -070046import java.lang.ref.WeakReference;
47import java.net.URISyntaxException;
48import java.text.Collator;
49import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070050import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070051import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070052import java.util.Collections;
53import java.util.Comparator;
54import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070055import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070056import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070057import java.util.List;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070058import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070059import java.util.TreeMap;
Michael Jurkac2f801e2011-07-12 14:19:46 -070060
The Android Open Source Project31dd5032009-03-03 19:32:27 -080061/**
62 * Maintains in-memory state of the Launcher. It is expected that there should be only one
63 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070064 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065 */
Joe Onoratof99f8c12009-10-31 17:27:36 -040066public class LauncherModel extends BroadcastReceiver {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080067 static final boolean DEBUG_LOADERS = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -040068 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070069
Joe Onorato36115782010-06-17 13:28:48 -040070 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Joe Onorato17a89222011-02-08 17:26:11 -080071 private final boolean mAppsCanBeOnExternalStorage;
Daniel Sandlerdca66122010-04-13 16:23:58 -040072
Daniel Sandlercc8befa2013-06-11 14:45:48 -040073 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -040074 private final Object mLock = new Object();
75 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -040076 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070077 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +020078 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Winson Chung81b52252012-08-27 15:34:29 -070080 // Specific runnable types that are run on the main thread deferred handler, this allows us to
81 // clear all queued binding runnables when the Launcher activity is destroyed.
82 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
83 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
84
85
Brad Fitzpatrick700889f2010-10-11 09:40:44 -070086 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
87 static {
88 sWorkerThread.start();
89 }
90 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
91
Joe Onoratocc67f472010-06-08 10:54:30 -070092 // We start off with everything not loaded. After that, we assume that
93 // our monitoring of the package manager provides all updates and we never
94 // need to do a requery. These are only ever touched from the loader thread.
95 private boolean mWorkspaceLoaded;
96 private boolean mAllAppsLoaded;
97
Winson Chungb8b2a5a2012-07-12 17:55:31 -070098 // When we are loading pages synchronously, we can't just post the binding of items on the side
99 // pages as this delays the rotation process. Instead, we wait for a callback from the first
100 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
101 // a normal load, we also clear this set of Runnables.
102 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
103
Joe Onorato9c1289c2009-08-17 11:03:03 -0400104 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800105
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700106 // < only access in worker thread >
Adam Cohen487f7dd2012-06-28 18:12:10 -0700107 private AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800108
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700109 // The lock that must be acquired before referencing any static bg data structures. Unlike
110 // other locks, this one can generally be held long-term because we never expect any of these
111 // static data structures to be referenced outside of the worker thread except on the first
112 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700113 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700114
Adam Cohen487f7dd2012-06-28 18:12:10 -0700115 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700116 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700117 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700118
Adam Cohen487f7dd2012-06-28 18:12:10 -0700119 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
120 // created by LauncherModel that are directly on the home screen (however, no widgets or
121 // shortcuts within folders).
122 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700123
Adam Cohen487f7dd2012-06-28 18:12:10 -0700124 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
125 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700126 new ArrayList<LauncherAppWidgetInfo>();
127
Adam Cohen487f7dd2012-06-28 18:12:10 -0700128 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
129 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700130
Adam Cohen487f7dd2012-06-28 18:12:10 -0700131 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
132 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700133
134 // sBgWorkspaceScreens is the ordered set of workspace screens.
135 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
136
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 // </ only access in worker thread >
138
139 private IconCache mIconCache;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800140 private Bitmap mDefaultIcon;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800141
Adam Cohend22015c2010-07-26 22:02:18 -0700142 private static int mCellCountX;
143 private static int mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700144
Reena Lee99a73f32011-10-24 17:27:37 -0700145 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700146
Joe Onorato9c1289c2009-08-17 11:03:03 -0400147 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700148 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400149 public int getCurrentWorkspaceScreen();
150 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700151 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
152 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700153 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700154 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500155 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700156 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400157 public void bindAppWidget(LauncherAppWidgetInfo info);
158 public void bindAllApplications(ArrayList<ApplicationInfo> apps);
Joe Onorato64e6be72010-03-05 15:05:52 -0500159 public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
Winson Chung83892cc2013-05-01 16:53:33 -0700160 public void bindComponentsRemoved(ArrayList<String> packageNames,
161 ArrayList<ApplicationInfo> appInfos,
162 boolean matchPackageNamesOnly);
Michael Jurkac402cd92013-05-20 15:49:32 +0200163 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100164 public void bindSearchablesChanged();
Adam Cohen1462de32012-07-24 22:34:36 -0700165 public void onPageBoundSynchronously(int page);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400166 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800167
Winson Chung64359a52013-07-08 17:17:08 -0700168 public interface ItemInfoFilter {
169 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
170 }
171
Daniel Sandlere4f98912013-06-25 15:13:26 -0400172 LauncherModel(LauncherAppState app, IconCache iconCache) {
173 final Context context = app.getContext();
174
Joe Onorato17a89222011-02-08 17:26:11 -0800175 mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400176 mApp = app;
Adam Cohen487f7dd2012-06-28 18:12:10 -0700177 mBgAllAppsList = new AllAppsList(iconCache);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800178 mIconCache = iconCache;
179
180 mDefaultIcon = Utilities.createIconBitmap(
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400181 mIconCache.getFullResDefaultActivityIcon(), context);
Daniel Sandler2ff10b32010-04-16 15:06:06 -0400182
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400183 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700184 Configuration config = res.getConfiguration();
185 mPreviousConfigMcc = config.mcc;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800186 }
187
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700188 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
189 * posted on the main thread handler. */
190 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700191 runOnMainThread(r, 0);
192 }
193 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700194 if (sWorkerThread.getThreadId() == Process.myTid()) {
195 // If we are on the worker thread, post onto the main handler
196 mHandler.post(r);
197 } else {
198 r.run();
199 }
200 }
201
202 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
203 * posted on the worker thread handler. */
204 private static void runOnWorkerThread(Runnable r) {
205 if (sWorkerThread.getThreadId() == Process.myTid()) {
206 r.run();
207 } else {
208 // If we are not on the worker thread, then post to the worker handler
209 sWorker.post(r);
210 }
211 }
212
Winson Chungc9168342013-06-26 14:54:55 -0700213 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
214 long screen) {
215 final int xCount = LauncherModel.getCellCountX();
216 final int yCount = LauncherModel.getCellCountY();
217 boolean[][] occupied = new boolean[xCount][yCount];
218
219 int cellX, cellY, spanX, spanY;
220 for (int i = 0; i < items.size(); ++i) {
221 final ItemInfo item = items.get(i);
222 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
223 if (item.screenId == screen) {
224 cellX = item.cellX;
225 cellY = item.cellY;
226 spanX = item.spanX;
227 spanY = item.spanY;
228 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
229 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
230 occupied[x][y] = true;
231 }
232 }
233 }
234 }
235 }
236
237 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
238 }
239 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
240 Intent launchIntent) {
241 // Lock on the app so that we don't try and get the items while apps are being added
242 LauncherAppState app = LauncherAppState.getInstance();
243 LauncherModel model = app.getModel();
244 boolean found = false;
245 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700246 if (sWorkerThread.getThreadId() != Process.myTid()) {
247 // Flush the LauncherModel worker thread, so that if we just did another
248 // processInstallShortcut, we give it time for its shortcut to get added to the
249 // database (getItemsInLocalCoordinates reads the database)
250 model.flushWorkerThread();
251 }
Winson Chungc9168342013-06-26 14:54:55 -0700252 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700253
254 // Try adding to the workspace screens incrementally, starting at the default or center
255 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
256 for (int screen = 0; screen < sBgWorkspaceScreens.size() && !found; screen++) {
257 int[] tmpCoordinates = new int[2];
258 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
259 sBgWorkspaceScreens.get(screen))) {
260 // Update the Launcher db
261 return new Pair<Long, int[]>(sBgWorkspaceScreens.get(screen), tmpCoordinates);
262 }
263 }
264 }
265 // XXX: Create a new page and add it to the first spot
266 return null;
267 }
268
Winson Chung64359a52013-07-08 17:17:08 -0700269 public void addAndBindAddedApps(final Context context, final ArrayList<ApplicationInfo> added,
270 final Callbacks callbacks) {
271 // Process the newly added applications and add them to the database first
272 Runnable r = new Runnable() {
273 public void run() {
274 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
275 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
276
277 synchronized(sBgLock) {
278 Iterator<ApplicationInfo> iter = added.iterator();
279 while (iter.hasNext()) {
280 ApplicationInfo a = iter.next();
281 final String name = a.title.toString();
282 final Intent launchIntent = a.intent;
283
284 // Short-circuit this logic if the icon exists somewhere on the workspace
285 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
286 continue;
287 }
288
289 // Add this icon to the db, creating a new page if necessary
290 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
291 name, launchIntent);
292 if (coords == null) {
293 // If we can't find a valid position, then just add a new screen.
294 // This takes time so we need to re-queue the add until the new
295 // page is added.
296 LauncherAppState appState = LauncherAppState.getInstance();
297 LauncherProvider lp = appState.getLauncherProvider();
298 long screenId = lp.generateNewScreenId();
299 // Update the model
300 sBgWorkspaceScreens.add(screenId);
301 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
302 // Save the screen id for binding in the workspace
303 addedWorkspaceScreensFinal.add(screenId);
304 // Find the coordinate again
305 coords = LauncherModel.findNextAvailableIconSpace(context,
306 a.title.toString(), a.intent);
307 }
308 if (coords == null) {
309 throw new RuntimeException("Coordinates should not be null");
310 }
311
312 final ShortcutInfo shortcutInfo = a.makeShortcut();
313 // Add the shortcut to the db
314 addItemToDatabase(context, shortcutInfo,
315 LauncherSettings.Favorites.CONTAINER_DESKTOP,
316 coords.first, coords.second[0], coords.second[1], false);
317 // Save the ShortcutInfo for binding in the workspace
318 addedShortcutsFinal.add(shortcutInfo);
319 }
320 }
321
322 runOnMainThread(new Runnable() {
323 public void run() {
324 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
325 if (callbacks == cb && cb != null) {
326 callbacks.bindAddScreens(addedWorkspaceScreensFinal);
327 callbacks.bindItems(addedShortcutsFinal, 0,
328 addedShortcutsFinal.size(), true);
329 }
330 }
331 });
332 }
333 };
334 runOnWorkerThread(r);
335 }
336
Joe Onorato56d82912010-03-07 14:32:10 -0500337 public Bitmap getFallbackIcon() {
Joe Onorato0589f0f2010-02-08 13:44:00 -0800338 return Bitmap.createBitmap(mDefaultIcon);
Joe Onoratof99f8c12009-10-31 17:27:36 -0400339 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800340
Winson Chung81b52252012-08-27 15:34:29 -0700341 public void unbindItemInfosAndClearQueuedBindRunnables() {
342 if (sWorkerThread.getThreadId() == Process.myTid()) {
343 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
344 "main thread");
345 }
346
347 // Clear any deferred bind runnables
348 mDeferredBindRunnables.clear();
349 // Remove any queued bind runnables
350 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
351 // Unbind all the workspace items
352 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700353 }
354
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700355 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700356 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700357 // Ensure that we don't use the same workspace items data structure on the main thread
358 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700359 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
360 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700361 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700362 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
363 tmpAppWidgets.addAll(sBgAppWidgets);
364 }
365 Runnable r = new Runnable() {
366 @Override
367 public void run() {
368 for (ItemInfo item : tmpWorkspaceItems) {
369 item.unbind();
370 }
371 for (ItemInfo item : tmpAppWidgets) {
372 item.unbind();
373 }
374 }
375 };
376 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700377 }
378
Joe Onorato9c1289c2009-08-17 11:03:03 -0400379 /**
380 * Adds an item to the DB if it was not created previously, or move it to a new
381 * <container, screen, cellX, cellY>
382 */
383 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700384 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400385 if (item.container == ItemInfo.NO_ID) {
386 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700387 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400388 } else {
389 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700390 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800391 }
392 }
393
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700394 static void checkItemInfoLocked(
395 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
396 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
397 if (modelItem != null && item != modelItem) {
398 // check all the data is consistent
399 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
400 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
401 ShortcutInfo shortcut = (ShortcutInfo) item;
402 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
403 modelShortcut.intent.filterEquals(shortcut.intent) &&
404 modelShortcut.id == shortcut.id &&
405 modelShortcut.itemType == shortcut.itemType &&
406 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700407 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700408 modelShortcut.cellX == shortcut.cellX &&
409 modelShortcut.cellY == shortcut.cellY &&
410 modelShortcut.spanX == shortcut.spanX &&
411 modelShortcut.spanY == shortcut.spanY &&
412 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
413 (modelShortcut.dropPos != null &&
414 shortcut.dropPos != null &&
415 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
416 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
417 // For all intents and purposes, this is the same object
418 return;
419 }
420 }
421
422 // the modelItem needs to match up perfectly with item if our model is
423 // to be consistent with the database-- for now, just require
424 // modelItem == item or the equality check above
425 String msg = "item: " + ((item != null) ? item.toString() : "null") +
426 "modelItem: " +
427 ((modelItem != null) ? modelItem.toString() : "null") +
428 "Error: ItemInfo passed to checkItemInfo doesn't match original";
429 RuntimeException e = new RuntimeException(msg);
430 if (stackTrace != null) {
431 e.setStackTrace(stackTrace);
432 }
Adam Cohene25af792013-06-06 23:08:25 -0700433 // TODO: something breaks this in the upgrade path
434 //throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700435 }
436 }
437
Michael Jurka816474f2012-06-25 14:49:02 -0700438 static void checkItemInfo(final ItemInfo item) {
439 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
440 final long itemId = item.id;
441 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700442 public void run() {
443 synchronized (sBgLock) {
444 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700445 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700446 }
447 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700448 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700449 }
450
Michael Jurkac9d95c52011-08-29 14:03:34 -0700451 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
452 final ItemInfo item, final String callingFunction) {
453 final long itemId = item.id;
454 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
455 final ContentResolver cr = context.getContentResolver();
456
Adam Cohen487f7dd2012-06-28 18:12:10 -0700457 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700458 Runnable r = new Runnable() {
459 public void run() {
460 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700461 updateItemArrays(item, itemId, stackTrace);
462 }
463 };
464 runOnWorkerThread(r);
465 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700466
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700467 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
468 final ArrayList<ItemInfo> items, final String callingFunction) {
469 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700470
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700471 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
472 Runnable r = new Runnable() {
473 public void run() {
474 ArrayList<ContentProviderOperation> ops =
475 new ArrayList<ContentProviderOperation>();
476 int count = items.size();
477 for (int i = 0; i < count; i++) {
478 ItemInfo item = items.get(i);
479 final long itemId = item.id;
480 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
481 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700482
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700483 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
484 updateItemArrays(item, itemId, stackTrace);
485
486 }
487 try {
488 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
489 } catch (Exception e) {
490 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700491 }
492 }
493 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700494 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700495 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700496
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700497 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
498 // Lock on mBgLock *after* the db operation
499 synchronized (sBgLock) {
500 checkItemInfoLocked(itemId, item, stackTrace);
501
502 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
503 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
504 // Item is in a folder, make sure this folder exists
505 if (!sBgFolders.containsKey(item.container)) {
506 // An items container is being set to a that of an item which is not in
507 // the list of Folders.
508 String msg = "item: " + item + " container being set to: " +
509 item.container + ", not in the list of folders";
510 Log.e(TAG, msg);
511 Launcher.dumpDebugLogsToConsole();
512 }
513 }
514
515 // Items are added/removed from the corresponding FolderInfo elsewhere, such
516 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
517 // that are on the desktop, as appropriate
518 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
519 if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
520 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
521 switch (modelItem.itemType) {
522 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
523 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
524 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
525 if (!sBgWorkspaceItems.contains(modelItem)) {
526 sBgWorkspaceItems.add(modelItem);
527 }
528 break;
529 default:
530 break;
531 }
532 } else {
533 sBgWorkspaceItems.remove(modelItem);
534 }
535 }
536 }
537
Michael Jurkac7700af2013-05-14 20:17:58 +0200538 public void flushWorkerThread() {
539 mFlushingWorkerThread = true;
540 Runnable waiter = new Runnable() {
541 public void run() {
542 synchronized (this) {
543 notifyAll();
544 mFlushingWorkerThread = false;
545 }
546 }
547 };
548
549 synchronized(waiter) {
550 runOnWorkerThread(waiter);
551 if (mLoaderTask != null) {
552 synchronized(mLoaderTask) {
553 mLoaderTask.notify();
554 }
555 }
556 boolean success = false;
557 while (!success) {
558 try {
559 waiter.wait();
560 success = true;
561 } catch (InterruptedException e) {
562 }
563 }
564 }
565 }
566
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800567 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400568 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700569 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700570 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700571 final long screenId, final int cellX, final int cellY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700572 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
Adam Cohendcd297f2013-06-18 13:13:40 -0700573 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
574 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Adam Cohen487f7dd2012-06-28 18:12:10 -0700575 Launcher.sDumpLogs.add(transaction);
576 Log.d(TAG, transaction);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400577 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400578 item.cellX = cellX;
579 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700580
Winson Chung3d503fb2011-07-13 17:25:49 -0700581 // We store hotseat items in canonical form which is this orientation invariant position
582 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700583 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700584 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700585 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700586 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700587 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700588 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400589
590 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400591 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700592 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
593 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700594 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400595
Michael Jurkac9d95c52011-08-29 14:03:34 -0700596 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700597 }
598
599 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700600 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
601 * cellX, cellY have already been updated on the ItemInfos.
602 */
603 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
604 final long container, final int screen) {
605
606 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
607 int count = items.size();
608
609 for (int i = 0; i < count; i++) {
610 ItemInfo item = items.get(i);
611 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700612 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700613 + ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", "
614 + item.cellX + ", " + item.cellY + ")";
615 Launcher.sDumpLogs.add(transaction);
616 item.container = container;
617
618 // We store hotseat items in canonical form which is this orientation invariant position
619 // in the hotseat
620 if (context instanceof Launcher && screen < 0 &&
621 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700622 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700623 item.cellY);
624 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700625 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700626 }
627
628 final ContentValues values = new ContentValues();
629 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
630 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
631 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700632 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700633
634 contentValues.add(values);
635 }
636 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
637 }
638
639 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700640 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800641 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700642 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700643 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700644 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
Adam Cohendcd297f2013-06-18 13:13:40 -0700645 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
646 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Adam Cohen487f7dd2012-06-28 18:12:10 -0700647 Launcher.sDumpLogs.add(transaction);
648 Log.d(TAG, transaction);
Adam Cohend4844c32011-02-18 19:25:06 -0800649 item.cellX = cellX;
650 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700651 item.spanX = spanX;
652 item.spanY = spanY;
653
654 // We store hotseat items in canonical form which is this orientation invariant position
655 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700656 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700657 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700658 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700659 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700660 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700661 }
Adam Cohend4844c32011-02-18 19:25:06 -0800662
Adam Cohend4844c32011-02-18 19:25:06 -0800663 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800664 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700665 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
666 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
667 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
668 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700669 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800670
Michael Jurka816474f2012-06-25 14:49:02 -0700671 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700672 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700673
674 /**
675 * Update an item to the database in a specified container.
676 */
677 static void updateItemInDatabase(Context context, final ItemInfo item) {
678 final ContentValues values = new ContentValues();
679 item.onAddToDatabase(values);
680 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
681 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800682 }
683
684 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400685 * Returns true if the shortcuts already exists in the database.
686 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800687 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400688 static boolean shortcutExists(Context context, String title, Intent intent) {
689 final ContentResolver cr = context.getContentResolver();
690 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
691 new String[] { "title", "intent" }, "title=? and intent=?",
692 new String[] { title, intent.toUri(0) }, null);
693 boolean result = false;
694 try {
695 result = c.moveToFirst();
696 } finally {
697 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800698 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400699 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700700 }
701
Joe Onorato9c1289c2009-08-17 11:03:03 -0400702 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700703 * Returns an ItemInfo array containing all the items in the LauncherModel.
704 * The ItemInfo.id is not set through this function.
705 */
706 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
707 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
708 final ContentResolver cr = context.getContentResolver();
709 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
710 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
711 LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
712 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
713
714 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
715 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
716 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
717 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
718 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
719 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
720 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
721
722 try {
723 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700724 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700725 item.cellX = c.getInt(cellXIndex);
726 item.cellY = c.getInt(cellYIndex);
727 item.spanX = c.getInt(spanXIndex);
728 item.spanY = c.getInt(spanYIndex);
729 item.container = c.getInt(containerIndex);
730 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700731 item.screenId = c.getInt(screenIndex);
Winson Chungaafa03c2010-06-11 17:34:16 -0700732
733 items.add(item);
734 }
735 } catch (Exception e) {
736 items.clear();
737 } finally {
738 c.close();
739 }
740
741 return items;
742 }
743
744 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400745 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
746 */
747 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
748 final ContentResolver cr = context.getContentResolver();
749 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
750 "_id=? and (itemType=? or itemType=?)",
751 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700752 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700753
Joe Onorato9c1289c2009-08-17 11:03:03 -0400754 try {
755 if (c.moveToFirst()) {
756 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
757 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
758 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
759 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
760 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
761 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800762
Joe Onorato9c1289c2009-08-17 11:03:03 -0400763 FolderInfo folderInfo = null;
764 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700765 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
766 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400767 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700768 }
769
Joe Onorato9c1289c2009-08-17 11:03:03 -0400770 folderInfo.title = c.getString(titleIndex);
771 folderInfo.id = id;
772 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700773 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700774 folderInfo.cellX = c.getInt(cellXIndex);
775 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400776
777 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700778 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400779 } finally {
780 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700781 }
782
783 return null;
784 }
785
Joe Onorato9c1289c2009-08-17 11:03:03 -0400786 /**
787 * Add an item to the database in a specified container. Sets the container, screen, cellX and
788 * cellY fields of the item. Also assigns an ID to the item.
789 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700790 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700791 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400792 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400793 item.cellX = cellX;
794 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700795 // We store hotseat items in canonical form which is this orientation invariant position
796 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700797 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700798 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700799 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700800 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700801 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700802 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400803
804 final ContentValues values = new ContentValues();
805 final ContentResolver cr = context.getContentResolver();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400806 item.onAddToDatabase(values);
807
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400808 LauncherAppState app = LauncherAppState.getInstance();
Adam Cohendcd297f2013-06-18 13:13:40 -0700809 item.id = app.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700810 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -0700811 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -0700812
Michael Jurkac9d95c52011-08-29 14:03:34 -0700813 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700814 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700815 String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700816 + item.id + " (" + container + ", " + screenId + ", " + cellX + ", "
Adam Cohen487f7dd2012-06-28 18:12:10 -0700817 + cellY + ")";
818 Launcher.sDumpLogs.add(transaction);
819 Log.d(TAG, transaction);
820
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700821 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
822 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400823
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700824 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700825 synchronized (sBgLock) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700826 checkItemInfoLocked(item.id, item, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700827 sBgItemsIdMap.put(item.id, item);
828 switch (item.itemType) {
829 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
830 sBgFolders.put(item.id, (FolderInfo) item);
831 // Fall through
832 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
833 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
834 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
835 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
836 sBgWorkspaceItems.add(item);
837 } else {
838 if (!sBgFolders.containsKey(item.container)) {
839 // Adding an item to a folder that doesn't exist.
840 String msg = "adding item: " + item + " to a folder that " +
841 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -0700842 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700843 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700844 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700845 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700846 break;
847 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
848 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
849 break;
850 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700851 }
852 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700853 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700854 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700855 }
856
Joe Onorato9c1289c2009-08-17 11:03:03 -0400857 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700858 * Creates a new unique child id, for a given cell span across all layouts.
859 */
Michael Jurka845ba3b2010-09-28 17:09:46 -0700860 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -0700861 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -0700862 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -0700863 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -0700864 }
865
Adam Cohend22015c2010-07-26 22:02:18 -0700866 static int getCellCountX() {
867 return mCellCountX;
Winson Chungaafa03c2010-06-11 17:34:16 -0700868 }
869
Adam Cohend22015c2010-07-26 22:02:18 -0700870 static int getCellCountY() {
871 return mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700872 }
873
874 /**
875 * Updates the model orientation helper to take into account the current layout dimensions
876 * when performing local/canonical coordinate transformations.
877 */
878 static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
Adam Cohend22015c2010-07-26 22:02:18 -0700879 mCellCountX = shortAxisCellCount;
880 mCellCountY = longAxisCellCount;
Winson Chungaafa03c2010-06-11 17:34:16 -0700881 }
882
883 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -0700884 * Removes the specified item from the database
885 * @param context
886 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -0400887 */
Michael Jurkac9d95c52011-08-29 14:03:34 -0700888 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400889 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700890 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -0700891
Michael Jurka83df1882011-08-31 20:59:26 -0700892 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700893 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700894 String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700895 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX +
Adam Cohen487f7dd2012-06-28 18:12:10 -0700896 ", " + item.cellY + ")";
897 Launcher.sDumpLogs.add(transaction);
898 Log.d(TAG, transaction);
899
Michael Jurkac9d95c52011-08-29 14:03:34 -0700900 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700901
902 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700903 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700904 switch (item.itemType) {
905 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
906 sBgFolders.remove(item.id);
907 for (ItemInfo info: sBgItemsIdMap.values()) {
908 if (info.container == item.id) {
909 // We are deleting a folder which still contains items that
910 // think they are contained by that folder.
911 String msg = "deleting a folder (" + item + ") which still " +
912 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -0700913 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700914 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700915 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700916 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700917 sBgWorkspaceItems.remove(item);
918 break;
919 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
920 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
921 sBgWorkspaceItems.remove(item);
922 break;
923 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
924 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
925 break;
926 }
927 sBgItemsIdMap.remove(item.id);
928 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700929 }
930 }
Michael Jurka83df1882011-08-31 20:59:26 -0700931 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700932 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400933 }
934
935 /**
Adam Cohendcd297f2013-06-18 13:13:40 -0700936 * Update the order of the workspace screens in the database. The array list contains
937 * a list of screen ids in the order that they should appear.
938 */
Winson Chungc9168342013-06-26 14:54:55 -0700939 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chung64359a52013-07-08 17:17:08 -0700940 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -0700941 final ContentResolver cr = context.getContentResolver();
942 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
943
944 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -0700945 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -0700946 while (iter.hasNext()) {
947 long id = iter.next();
948 if (id < 0) {
949 iter.remove();
950 }
951 }
952
953 Runnable r = new Runnable() {
954 @Override
955 public void run() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700956 // Clear the table
957 cr.delete(uri, null, null);
958 int count = screens.size();
959 ContentValues[] values = new ContentValues[count];
960 for (int i = 0; i < count; i++) {
961 ContentValues v = new ContentValues();
962 long screenId = screens.get(i);
963 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
964 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Adam Cohendcd297f2013-06-18 13:13:40 -0700965 values[i] = v;
966 }
967 cr.bulkInsert(uri, values);
968 sBgWorkspaceScreens.clear();
969 sBgWorkspaceScreens.addAll(screensCopy);
970 }
971 };
972 runOnWorkerThread(r);
973 }
974
975 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400976 * Remove the contents of the specified folder from the database
977 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700978 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400979 final ContentResolver cr = context.getContentResolver();
980
Michael Jurkac9d95c52011-08-29 14:03:34 -0700981 Runnable r = new Runnable() {
982 public void run() {
983 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700984 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700985 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700986 sBgItemsIdMap.remove(info.id);
987 sBgFolders.remove(info.id);
988 sBgDbIconCache.remove(info);
989 sBgWorkspaceItems.remove(info);
990 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700991
Michael Jurkac9d95c52011-08-29 14:03:34 -0700992 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
993 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700994 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700995 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700996 for (ItemInfo childInfo : info.contents) {
997 sBgItemsIdMap.remove(childInfo.id);
998 sBgDbIconCache.remove(childInfo);
999 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001000 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001001 }
1002 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001003 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001004 }
1005
1006 /**
1007 * Set this as the current Launcher activity object for the loader.
1008 */
1009 public void initialize(Callbacks callbacks) {
1010 synchronized (mLock) {
1011 mCallbacks = new WeakReference<Callbacks>(callbacks);
1012 }
1013 }
1014
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001015 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001016 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1017 * ACTION_PACKAGE_CHANGED.
1018 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001019 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001020 public void onReceive(Context context, Intent intent) {
Joe Onorato36115782010-06-17 13:28:48 -04001021 if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001022
Joe Onorato36115782010-06-17 13:28:48 -04001023 final String action = intent.getAction();
Joe Onoratof99f8c12009-10-31 17:27:36 -04001024
Joe Onorato36115782010-06-17 13:28:48 -04001025 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
1026 || Intent.ACTION_PACKAGE_REMOVED.equals(action)
1027 || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1028 final String packageName = intent.getData().getSchemeSpecificPart();
1029 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001030
Joe Onorato36115782010-06-17 13:28:48 -04001031 int op = PackageUpdatedTask.OP_NONE;
1032
1033 if (packageName == null || packageName.length() == 0) {
1034 // they sent us a bad intent
1035 return;
1036 }
1037
1038 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1039 op = PackageUpdatedTask.OP_UPDATE;
1040 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1041 if (!replacing) {
1042 op = PackageUpdatedTask.OP_REMOVE;
1043 }
1044 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1045 // later, we will update the package at this time
1046 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1047 if (!replacing) {
1048 op = PackageUpdatedTask.OP_ADD;
1049 } else {
1050 op = PackageUpdatedTask.OP_UPDATE;
1051 }
1052 }
1053
1054 if (op != PackageUpdatedTask.OP_NONE) {
1055 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
1056 }
1057
1058 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Joe Onoratocec58332010-10-07 14:37:40 -04001059 // First, schedule to add these apps back in.
1060 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1061 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
1062 // Then, rebind everything.
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001063 startLoaderFromBackground();
Joe Onorato36115782010-06-17 13:28:48 -04001064 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1065 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1066 enqueuePackageUpdated(new PackageUpdatedTask(
1067 PackageUpdatedTask.OP_UNAVAILABLE, packages));
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001068 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001069 // If we have changed locale we need to clear out the labels in all apps/workspace.
1070 forceReload();
1071 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1072 // Check if configuration change was an mcc/mnc change which would affect app resources
1073 // and we would need to clear out the labels in all apps/workspace. Same handling as
1074 // above for ACTION_LOCALE_CHANGED
1075 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001076 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001077 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001078 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001079 forceReload();
1080 }
1081 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001082 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001083 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1084 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001085 if (mCallbacks != null) {
1086 Callbacks callbacks = mCallbacks.get();
1087 if (callbacks != null) {
1088 callbacks.bindSearchablesChanged();
1089 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001090 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001091 }
1092 }
1093
Reena Lee93f824a2011-09-23 17:20:28 -07001094 private void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001095 resetLoadedState(true, true);
1096
Reena Lee93f824a2011-09-23 17:20:28 -07001097 // Do this here because if the launcher activity is running it will be restarted.
1098 // If it's not running startLoaderFromBackground will merely tell it that it needs
1099 // to reload.
1100 startLoaderFromBackground();
1101 }
1102
Winson Chungf0c6ae02012-03-21 16:10:31 -07001103 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1104 synchronized (mLock) {
1105 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1106 // mWorkspaceLoaded to true later
1107 stopLoaderLocked();
1108 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1109 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1110 }
1111 }
1112
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001113 /**
1114 * When the launcher is in the background, it's possible for it to miss paired
1115 * configuration changes. So whenever we trigger the loader from the background
1116 * tell the launcher that it needs to re-run the loader when it comes back instead
1117 * of doing it now.
1118 */
1119 public void startLoaderFromBackground() {
1120 boolean runLoader = false;
1121 if (mCallbacks != null) {
1122 Callbacks callbacks = mCallbacks.get();
1123 if (callbacks != null) {
1124 // Only actually run the loader if they're not paused.
1125 if (!callbacks.setLoadOnResume()) {
1126 runLoader = true;
1127 }
1128 }
1129 }
1130 if (runLoader) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001131 startLoader(false, -1);
Joe Onorato790c2d92010-06-11 00:14:11 -07001132 }
Joe Onorato36115782010-06-17 13:28:48 -04001133 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001134
Reena Lee93f824a2011-09-23 17:20:28 -07001135 // If there is already a loader task running, tell it to stop.
1136 // returns true if isLaunching() was true on the old task
1137 private boolean stopLoaderLocked() {
1138 boolean isLaunching = false;
1139 LoaderTask oldTask = mLoaderTask;
1140 if (oldTask != null) {
1141 if (oldTask.isLaunching()) {
1142 isLaunching = true;
1143 }
1144 oldTask.stopLocked();
1145 }
1146 return isLaunching;
1147 }
1148
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001149 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Joe Onorato36115782010-06-17 13:28:48 -04001150 synchronized (mLock) {
1151 if (DEBUG_LOADERS) {
1152 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1153 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001154
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001155 // Clear any deferred bind-runnables from the synchronized load process
1156 // We must do this before any loading/binding is scheduled below.
1157 mDeferredBindRunnables.clear();
1158
Joe Onorato36115782010-06-17 13:28:48 -04001159 // Don't bother to start the thread if we know it's not going to do anything
1160 if (mCallbacks != null && mCallbacks.get() != null) {
1161 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001162 // also, don't downgrade isLaunching if we're already running
1163 isLaunching = isLaunching || stopLoaderLocked();
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001164 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001165 if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
1166 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1167 } else {
1168 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1169 sWorker.post(mLoaderTask);
1170 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001171 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001172 }
1173 }
1174
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001175 void bindRemainingSynchronousPages() {
1176 // Post the remaining side pages to be loaded
1177 if (!mDeferredBindRunnables.isEmpty()) {
1178 for (final Runnable r : mDeferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001179 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001180 }
1181 mDeferredBindRunnables.clear();
1182 }
1183 }
1184
Joe Onorato36115782010-06-17 13:28:48 -04001185 public void stopLoader() {
1186 synchronized (mLock) {
1187 if (mLoaderTask != null) {
1188 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001189 }
1190 }
Joe Onorato36115782010-06-17 13:28:48 -04001191 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001192
Michael Jurkac57b7a82011-08-09 22:02:20 -07001193 public boolean isAllAppsLoaded() {
1194 return mAllAppsLoaded;
1195 }
1196
Winson Chung36a62fe2012-05-06 18:04:42 -07001197 boolean isLoadingWorkspace() {
1198 synchronized (mLock) {
1199 if (mLoaderTask != null) {
1200 return mLoaderTask.isLoadingWorkspace();
1201 }
1202 }
1203 return false;
1204 }
1205
Joe Onorato36115782010-06-17 13:28:48 -04001206 /**
1207 * Runnable for the thread that loads the contents of the launcher:
1208 * - workspace icons
1209 * - widgets
1210 * - all apps icons
1211 */
1212 private class LoaderTask implements Runnable {
1213 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001214 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001215 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001216 private boolean mStopped;
1217 private boolean mLoadAndBindStepFinished;
Adam Cohene25af792013-06-06 23:08:25 -07001218 private boolean mIsUpgradePath;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001219
Winson Chungc3eecff2011-07-11 17:44:15 -07001220 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001221
1222 LoaderTask(Context context, boolean isLaunching) {
1223 mContext = context;
1224 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001225 mLabelCache = new HashMap<Object, CharSequence>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001226 }
1227
Joe Onorato36115782010-06-17 13:28:48 -04001228 boolean isLaunching() {
1229 return mIsLaunching;
1230 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001231
Winson Chung36a62fe2012-05-06 18:04:42 -07001232 boolean isLoadingWorkspace() {
1233 return mIsLoadingAndBindingWorkspace;
1234 }
1235
Joe Onorato36115782010-06-17 13:28:48 -04001236 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001237 mIsLoadingAndBindingWorkspace = true;
1238
Joe Onorato36115782010-06-17 13:28:48 -04001239 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001240 if (DEBUG_LOADERS) {
1241 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001242 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001243
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001244 if (!mWorkspaceLoaded) {
Joe Onorato36115782010-06-17 13:28:48 -04001245 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001246 synchronized (LoaderTask.this) {
1247 if (mStopped) {
1248 return;
1249 }
1250 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001251 }
1252 }
1253
Joe Onorato36115782010-06-17 13:28:48 -04001254 // Bind the workspace
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001255 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001256 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001257
Joe Onorato36115782010-06-17 13:28:48 -04001258 private void waitForIdle() {
1259 // Wait until the either we're stopped or the other threads are done.
1260 // This way we don't start loading all apps until the workspace has settled
1261 // down.
1262 synchronized (LoaderTask.this) {
1263 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001264
Joe Onorato36115782010-06-17 13:28:48 -04001265 mHandler.postIdle(new Runnable() {
1266 public void run() {
1267 synchronized (LoaderTask.this) {
1268 mLoadAndBindStepFinished = true;
1269 if (DEBUG_LOADERS) {
1270 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001271 }
Joe Onorato36115782010-06-17 13:28:48 -04001272 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001273 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001274 }
Joe Onorato36115782010-06-17 13:28:48 -04001275 });
1276
Michael Jurkac7700af2013-05-14 20:17:58 +02001277 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001278 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001279 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1280 // wait no longer than 1sec at a time
1281 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001282 } catch (InterruptedException ex) {
1283 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001284 }
1285 }
Joe Onorato36115782010-06-17 13:28:48 -04001286 if (DEBUG_LOADERS) {
1287 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001288 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001289 + "ms for previous step to finish binding");
1290 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001291 }
Joe Onorato36115782010-06-17 13:28:48 -04001292 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001293
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001294 void runBindSynchronousPage(int synchronousBindPage) {
1295 if (synchronousBindPage < 0) {
1296 // Ensure that we have a valid page index to load synchronously
1297 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1298 "valid page index");
1299 }
1300 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1301 // Ensure that we don't try and bind a specified page when the pages have not been
1302 // loaded already (we should load everything asynchronously in that case)
1303 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1304 }
1305 synchronized (mLock) {
1306 if (mIsLoaderTaskRunning) {
1307 // Ensure that we are never running the background loading at this point since
1308 // we also touch the background collections
1309 throw new RuntimeException("Error! Background loading is already running");
1310 }
1311 }
1312
1313 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1314 // data structures, we can't allow any other thread to touch that data, but because
1315 // this call is synchronous, we can get away with not locking).
1316
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001317 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001318 // operations from the previous activity. We need to ensure that all queued operations
1319 // are executed before any synchronous binding work is done.
1320 mHandler.flush();
1321
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001322 // Divide the set of loaded items into those that we are binding synchronously, and
1323 // everything else that is to be bound normally (asynchronously).
1324 bindWorkspace(synchronousBindPage);
1325 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1326 // arise from that.
1327 onlyBindAllApps();
1328 }
1329
Joe Onorato36115782010-06-17 13:28:48 -04001330 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001331 synchronized (mLock) {
1332 mIsLoaderTaskRunning = true;
1333 }
Joe Onorato36115782010-06-17 13:28:48 -04001334 // Optimize for end-user experience: if the Launcher is up and // running with the
1335 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1336 // workspace first (default).
1337 final Callbacks cbk = mCallbacks.get();
Joe Onorato36115782010-06-17 13:28:48 -04001338 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001339 // Elevate priority when Home launches for the first time to avoid
1340 // starving at boot time. Staring at a blank home is not cool.
1341 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001342 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1343 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001344 android.os.Process.setThreadPriority(mIsLaunching
1345 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1346 }
Winson Chung64359a52013-07-08 17:17:08 -07001347 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
1348 loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001349
Joe Onorato36115782010-06-17 13:28:48 -04001350 if (mStopped) {
1351 break keep_running;
1352 }
1353
1354 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1355 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001356 synchronized (mLock) {
1357 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001358 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001359 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1360 }
1361 }
Joe Onorato36115782010-06-17 13:28:48 -04001362 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001363
1364 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001365 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1366 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001367
1368 // Restore the default thread priority after we are done loading items
1369 synchronized (mLock) {
1370 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1371 }
Joe Onorato36115782010-06-17 13:28:48 -04001372 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001373
Winson Chungaac01e12011-08-17 10:37:13 -07001374 // Update the saved icons if necessary
1375 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001376 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001377 for (Object key : sBgDbIconCache.keySet()) {
1378 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1379 }
1380 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001381 }
Winson Chungaac01e12011-08-17 10:37:13 -07001382
Joe Onorato36115782010-06-17 13:28:48 -04001383 // Clear out this reference, otherwise we end up holding it until all of the
1384 // callback runnables are done.
1385 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001386
Joe Onorato36115782010-06-17 13:28:48 -04001387 synchronized (mLock) {
1388 // If we are still the last one to be scheduled, remove ourselves.
1389 if (mLoaderTask == this) {
1390 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001391 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001392 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001393 }
Joe Onorato36115782010-06-17 13:28:48 -04001394 }
1395
1396 public void stopLocked() {
1397 synchronized (LoaderTask.this) {
1398 mStopped = true;
1399 this.notify();
1400 }
1401 }
1402
1403 /**
1404 * Gets the callbacks object. If we've been stopped, or if the launcher object
1405 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1406 * object that was around when the deferred message was scheduled, and if there's
1407 * a new Callbacks object around then also return null. This will save us from
1408 * calling onto it with data that will be ignored.
1409 */
1410 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1411 synchronized (mLock) {
1412 if (mStopped) {
1413 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001414 }
Joe Onorato36115782010-06-17 13:28:48 -04001415
1416 if (mCallbacks == null) {
1417 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001418 }
Joe Onorato36115782010-06-17 13:28:48 -04001419
1420 final Callbacks callbacks = mCallbacks.get();
1421 if (callbacks != oldCallbacks) {
1422 return null;
1423 }
1424 if (callbacks == null) {
1425 Log.w(TAG, "no mCallbacks");
1426 return null;
1427 }
1428
1429 return callbacks;
1430 }
1431 }
1432
1433 // check & update map of what's occupied; used to discard overlapping/invalid items
Adam Cohendcd297f2013-06-18 13:13:40 -07001434 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
1435 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001436 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001437 if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
1438 if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1439 [(int) item.screenId][0] != null) {
1440 Log.e(TAG, "Error loading shortcut into hotseat " + item
1441 + " into position (" + item.screenId + ":" + item.cellX + ","
1442 + item.cellY + ") occupied by "
1443 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1444 [(int) item.screenId][0]);
1445 return false;
1446 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001447 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001448 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1449 items[(int) item.screenId][0] = item;
1450 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001451 return true;
1452 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001453 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1454 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001455 return true;
1456 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001457
Adam Cohendcd297f2013-06-18 13:13:40 -07001458 if (!occupied.containsKey(item.screenId)) {
1459 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1460 occupied.put(item.screenId, items);
1461 }
1462
1463 ItemInfo[][] screens = occupied.get(item.screenId);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001464 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001465 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1466 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001467 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001468 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001469 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001470 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001471 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001472 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001473 return false;
1474 }
1475 }
1476 }
1477 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1478 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001479 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001480 }
1481 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001482
Joe Onorato36115782010-06-17 13:28:48 -04001483 return true;
1484 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001485
Joe Onorato36115782010-06-17 13:28:48 -04001486 private void loadWorkspace() {
1487 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001488
Joe Onorato36115782010-06-17 13:28:48 -04001489 final Context context = mContext;
1490 final ContentResolver contentResolver = context.getContentResolver();
1491 final PackageManager manager = context.getPackageManager();
1492 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1493 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001494
Michael Jurkab85f8a42012-04-25 15:48:32 -07001495 // Make sure the default workspace is loaded, if needed
Adam Cohene25af792013-06-06 23:08:25 -07001496 boolean loadOldDb = mApp.getLauncherProvider().shouldLoadOldDb();
1497 Uri contentUri = loadOldDb ? LauncherSettings.Favorites.OLD_CONTENT_URI :
1498 LauncherSettings.Favorites.CONTENT_URI;
1499
1500 mIsUpgradePath = loadOldDb;
Michael Jurkab85f8a42012-04-25 15:48:32 -07001501
Winson Chung2abf94d2012-07-18 18:16:38 -07001502 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001503 sBgWorkspaceItems.clear();
1504 sBgAppWidgets.clear();
1505 sBgFolders.clear();
1506 sBgItemsIdMap.clear();
1507 sBgDbIconCache.clear();
Adam Cohendcd297f2013-06-18 13:13:40 -07001508 sBgWorkspaceScreens.clear();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001509
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001510 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001511
Adam Cohene25af792013-06-06 23:08:25 -07001512 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001513
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001514 // +1 for the hotseat (it can be larger than the workspace)
1515 // Load workspace in reverse order to ensure that latest items are loaded first (and
1516 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001517 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001518
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001519 try {
1520 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1521 final int intentIndex = c.getColumnIndexOrThrow
1522 (LauncherSettings.Favorites.INTENT);
1523 final int titleIndex = c.getColumnIndexOrThrow
1524 (LauncherSettings.Favorites.TITLE);
1525 final int iconTypeIndex = c.getColumnIndexOrThrow(
1526 LauncherSettings.Favorites.ICON_TYPE);
1527 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1528 final int iconPackageIndex = c.getColumnIndexOrThrow(
1529 LauncherSettings.Favorites.ICON_PACKAGE);
1530 final int iconResourceIndex = c.getColumnIndexOrThrow(
1531 LauncherSettings.Favorites.ICON_RESOURCE);
1532 final int containerIndex = c.getColumnIndexOrThrow(
1533 LauncherSettings.Favorites.CONTAINER);
1534 final int itemTypeIndex = c.getColumnIndexOrThrow(
1535 LauncherSettings.Favorites.ITEM_TYPE);
1536 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1537 LauncherSettings.Favorites.APPWIDGET_ID);
1538 final int screenIndex = c.getColumnIndexOrThrow(
1539 LauncherSettings.Favorites.SCREEN);
1540 final int cellXIndex = c.getColumnIndexOrThrow
1541 (LauncherSettings.Favorites.CELLX);
1542 final int cellYIndex = c.getColumnIndexOrThrow
1543 (LauncherSettings.Favorites.CELLY);
1544 final int spanXIndex = c.getColumnIndexOrThrow
1545 (LauncherSettings.Favorites.SPANX);
1546 final int spanYIndex = c.getColumnIndexOrThrow(
1547 LauncherSettings.Favorites.SPANY);
1548 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1549 //final int displayModeIndex = c.getColumnIndexOrThrow(
1550 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001551
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001552 ShortcutInfo info;
1553 String intentDescription;
1554 LauncherAppWidgetInfo appWidgetInfo;
1555 int container;
1556 long id;
1557 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001558
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001559 while (!mStopped && c.moveToNext()) {
1560 try {
1561 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001562
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001563 switch (itemType) {
1564 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1565 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1566 intentDescription = c.getString(intentIndex);
1567 try {
1568 intent = Intent.parseUri(intentDescription, 0);
1569 } catch (URISyntaxException e) {
1570 continue;
1571 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001572
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001573 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1574 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1575 titleIndex, mLabelCache);
1576 } else {
1577 info = getShortcutInfo(c, context, iconTypeIndex,
1578 iconPackageIndex, iconResourceIndex, iconIndex,
1579 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001580
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001581 // App shortcuts that used to be automatically added to Launcher
1582 // didn't always have the correct intent flags set, so do that
1583 // here
1584 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001585 intent.getCategories() != null &&
1586 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001587 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001588 intent.addFlags(
1589 Intent.FLAG_ACTIVITY_NEW_TASK |
1590 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1591 }
Michael Jurka96879562012-03-22 05:54:33 -07001592 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001593
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001594 if (info != null) {
1595 info.intent = intent;
1596 info.id = c.getLong(idIndex);
1597 container = c.getInt(containerIndex);
1598 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001599 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001600 info.cellX = c.getInt(cellXIndex);
1601 info.cellY = c.getInt(cellYIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001602 // check & update map of what's occupied
1603 if (!checkItemPlacement(occupied, info)) {
1604 break;
1605 }
1606
1607 switch (container) {
1608 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1609 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1610 sBgWorkspaceItems.add(info);
1611 break;
1612 default:
1613 // Item is in a user folder
1614 FolderInfo folderInfo =
1615 findOrMakeFolder(sBgFolders, container);
1616 folderInfo.add(info);
1617 break;
1618 }
Adam Cohene25af792013-06-06 23:08:25 -07001619 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
1620 loadOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001621 info.screenId = permuteScreens(info.screenId);
Adam Cohene25af792013-06-06 23:08:25 -07001622 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001623 sBgItemsIdMap.put(info.id, info);
1624
1625 // now that we've loaded everthing re-save it with the
1626 // icon in case it disappears somehow.
1627 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
1628 } else {
1629 // Failed to load the shortcut, probably because the
1630 // activity manager couldn't resolve it (maybe the app
1631 // was uninstalled), or the db row was somehow screwed up.
1632 // Delete it.
1633 id = c.getLong(idIndex);
1634 Log.e(TAG, "Error loading shortcut " + id + ", removing it");
1635 contentResolver.delete(LauncherSettings.Favorites.getContentUri(
1636 id, false), null, null);
1637 }
1638 break;
1639
1640 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1641 id = c.getLong(idIndex);
1642 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1643
1644 folderInfo.title = c.getString(titleIndex);
1645 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001646 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001647 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001648 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001649 folderInfo.cellX = c.getInt(cellXIndex);
1650 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001651
Daniel Sandler8802e962010-05-26 16:28:16 -04001652 // check & update map of what's occupied
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001653 if (!checkItemPlacement(occupied, folderInfo)) {
Daniel Sandler8802e962010-05-26 16:28:16 -04001654 break;
1655 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001656 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001657 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1658 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1659 sBgWorkspaceItems.add(folderInfo);
1660 break;
Joe Onorato36115782010-06-17 13:28:48 -04001661 }
Adam Cohene25af792013-06-06 23:08:25 -07001662 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
1663 loadOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001664 folderInfo.screenId = permuteScreens(folderInfo.screenId);
Adam Cohene25af792013-06-06 23:08:25 -07001665 }
Joe Onorato17a89222011-02-08 17:26:11 -08001666
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001667 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1668 sBgFolders.put(folderInfo.id, folderInfo);
1669 break;
1670
1671 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1672 // Read all Launcher-specific widget details
1673 int appWidgetId = c.getInt(appWidgetIdIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001674 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001675
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001676 final AppWidgetProviderInfo provider =
1677 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001678
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001679 if (!isSafeMode && (provider == null || provider.provider == null ||
1680 provider.provider.getPackageName() == null)) {
1681 String log = "Deleting widget that isn't installed anymore: id="
1682 + id + " appWidgetId=" + appWidgetId;
1683 Log.e(TAG, log);
1684 Launcher.sDumpLogs.add(log);
1685 itemsToRemove.add(id);
1686 } else {
1687 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1688 provider.provider);
1689 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07001690 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001691 appWidgetInfo.cellX = c.getInt(cellXIndex);
1692 appWidgetInfo.cellY = c.getInt(cellYIndex);
1693 appWidgetInfo.spanX = c.getInt(spanXIndex);
1694 appWidgetInfo.spanY = c.getInt(spanYIndex);
1695 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1696 appWidgetInfo.minSpanX = minSpan[0];
1697 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001698
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001699 container = c.getInt(containerIndex);
1700 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1701 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1702 Log.e(TAG, "Widget found where container != " +
1703 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1704 continue;
1705 }
Adam Cohene25af792013-06-06 23:08:25 -07001706 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
1707 loadOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001708 appWidgetInfo.screenId =
1709 permuteScreens(appWidgetInfo.screenId);
Adam Cohene25af792013-06-06 23:08:25 -07001710 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001711
Adam Cohene25af792013-06-06 23:08:25 -07001712 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001713 // check & update map of what's occupied
1714 if (!checkItemPlacement(occupied, appWidgetInfo)) {
1715 break;
1716 }
1717 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1718 sBgAppWidgets.add(appWidgetInfo);
1719 }
Joe Onorato36115782010-06-17 13:28:48 -04001720 break;
1721 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001722 } catch (Exception e) {
1723 Log.w(TAG, "Desktop items loading interrupted:", e);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001724 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001725 }
1726 } finally {
1727 c.close();
1728 }
1729
1730 if (itemsToRemove.size() > 0) {
1731 ContentProviderClient client = contentResolver.acquireContentProviderClient(
1732 LauncherSettings.Favorites.CONTENT_URI);
1733 // Remove dead items
1734 for (long id : itemsToRemove) {
1735 if (DEBUG_LOADERS) {
1736 Log.d(TAG, "Removed id = " + id);
1737 }
1738 // Don't notify content observers
1739 try {
1740 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1741 null, null);
1742 } catch (RemoteException e) {
1743 Log.w(TAG, "Could not remove id = " + id);
1744 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001745 }
1746 }
1747
Adam Cohendcd297f2013-06-18 13:13:40 -07001748 if (loadOldDb) {
1749 long maxScreenId = 0;
1750 // If we're importing we use the old screen order.
1751 for (ItemInfo item: sBgItemsIdMap.values()) {
1752 long screenId = item.screenId;
1753 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1754 !sBgWorkspaceScreens.contains(screenId)) {
1755 sBgWorkspaceScreens.add(screenId);
1756 if (screenId > maxScreenId) {
1757 maxScreenId = screenId;
1758 }
1759 }
1760 }
1761 Collections.sort(sBgWorkspaceScreens);
1762 mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
1763 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1764 } else {
1765 Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1766 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1767 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1768
1769 try {
1770 final int idIndex = sc.getColumnIndexOrThrow(
1771 LauncherSettings.WorkspaceScreens._ID);
1772 final int rankIndex = sc.getColumnIndexOrThrow(
1773 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1774 while (sc.moveToNext()) {
1775 try {
1776 long screenId = sc.getLong(idIndex);
1777 int rank = sc.getInt(rankIndex);
1778
1779 orderedScreens.put(rank, screenId);
1780 } catch (Exception e) {
1781 Log.w(TAG, "Desktop items loading interrupted:", e);
1782 }
1783 }
1784 } finally {
1785 sc.close();
1786 }
1787
1788 Iterator<Integer> iter = orderedScreens.keySet().iterator();
1789 while (iter.hasNext()) {
1790 sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
1791 }
1792
1793 // Remove any empty screens
1794 ArrayList<Long> unusedScreens = new ArrayList<Long>();
1795 unusedScreens.addAll(sBgWorkspaceScreens);
1796
1797 for (ItemInfo item: sBgItemsIdMap.values()) {
1798 long screenId = item.screenId;
1799
1800 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1801 unusedScreens.contains(screenId)) {
1802 unusedScreens.remove(screenId);
1803 }
1804 }
1805
1806 // If there are any empty screens remove them, and update.
1807 if (unusedScreens.size() != 0) {
1808 sBgWorkspaceScreens.removeAll(unusedScreens);
1809 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1810 }
1811 }
1812
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001813 if (DEBUG_LOADERS) {
1814 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1815 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07001816 int nScreens = occupied.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001817 for (int y = 0; y < mCellCountY; y++) {
1818 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07001819
Daniel Sandler566da102013-06-25 23:43:45 -04001820 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07001821 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001822 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07001823 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001824 line += " | ";
1825 }
1826 for (int x = 0; x < mCellCountX; x++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001827 line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001828 }
Joe Onorato36115782010-06-17 13:28:48 -04001829 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001830 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04001831 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001832 }
Joe Onorato36115782010-06-17 13:28:48 -04001833 }
1834 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001835
Adam Cohene25af792013-06-06 23:08:25 -07001836 // We rearrange the screens from the old launcher
1837 // 12345 -> 34512
Adam Cohendcd297f2013-06-18 13:13:40 -07001838 private long permuteScreens(long screen) {
Adam Cohene25af792013-06-06 23:08:25 -07001839 if (screen >= 2) {
1840 return screen - 2;
1841 } else {
1842 return screen + 3;
1843 }
1844 }
1845
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001846 /** Filters the set of items who are directly or indirectly (via another container) on the
1847 * specified screen. */
1848 private void filterCurrentWorkspaceItems(int currentScreen,
1849 ArrayList<ItemInfo> allWorkspaceItems,
1850 ArrayList<ItemInfo> currentScreenItems,
1851 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001852 // Purge any null ItemInfos
1853 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1854 while (iter.hasNext()) {
1855 ItemInfo i = iter.next();
1856 if (i == null) {
1857 iter.remove();
1858 }
1859 }
1860
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001861 // If we aren't filtering on a screen, then the set of items to load is the full set of
1862 // items given.
1863 if (currentScreen < 0) {
1864 currentScreenItems.addAll(allWorkspaceItems);
Joe Onorato36115782010-06-17 13:28:48 -04001865 }
1866
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001867 // Order the set of items by their containers first, this allows use to walk through the
1868 // list sequentially, build up a list of containers that are in the specified screen,
1869 // as well as all items in those containers.
1870 Set<Long> itemsOnScreen = new HashSet<Long>();
1871 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1872 @Override
1873 public int compare(ItemInfo lhs, ItemInfo rhs) {
1874 return (int) (lhs.container - rhs.container);
1875 }
1876 });
1877 for (ItemInfo info : allWorkspaceItems) {
1878 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001879 if (info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001880 currentScreenItems.add(info);
1881 itemsOnScreen.add(info.id);
1882 } else {
1883 otherScreenItems.add(info);
1884 }
1885 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1886 currentScreenItems.add(info);
1887 itemsOnScreen.add(info.id);
1888 } else {
1889 if (itemsOnScreen.contains(info.container)) {
1890 currentScreenItems.add(info);
1891 itemsOnScreen.add(info.id);
1892 } else {
1893 otherScreenItems.add(info);
1894 }
1895 }
1896 }
1897 }
1898
1899 /** Filters the set of widgets which are on the specified screen. */
1900 private void filterCurrentAppWidgets(int currentScreen,
1901 ArrayList<LauncherAppWidgetInfo> appWidgets,
1902 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1903 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1904 // If we aren't filtering on a screen, then the set of items to load is the full set of
1905 // widgets given.
1906 if (currentScreen < 0) {
1907 currentScreenWidgets.addAll(appWidgets);
1908 }
1909
1910 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001911 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001912 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07001913 widget.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001914 currentScreenWidgets.add(widget);
1915 } else {
1916 otherScreenWidgets.add(widget);
1917 }
1918 }
1919 }
1920
1921 /** Filters the set of folders which are on the specified screen. */
1922 private void filterCurrentFolders(int currentScreen,
1923 HashMap<Long, ItemInfo> itemsIdMap,
1924 HashMap<Long, FolderInfo> folders,
1925 HashMap<Long, FolderInfo> currentScreenFolders,
1926 HashMap<Long, FolderInfo> otherScreenFolders) {
1927 // If we aren't filtering on a screen, then the set of items to load is the full set of
1928 // widgets given.
1929 if (currentScreen < 0) {
1930 currentScreenFolders.putAll(folders);
1931 }
1932
1933 for (long id : folders.keySet()) {
1934 ItemInfo info = itemsIdMap.get(id);
1935 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07001936 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001937 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07001938 info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001939 currentScreenFolders.put(id, folder);
1940 } else {
1941 otherScreenFolders.put(id, folder);
1942 }
1943 }
1944 }
1945
1946 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
1947 * right) */
1948 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
1949 // XXX: review this
1950 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07001951 @Override
1952 public int compare(ItemInfo lhs, ItemInfo rhs) {
1953 int cellCountX = LauncherModel.getCellCountX();
1954 int cellCountY = LauncherModel.getCellCountY();
1955 int screenOffset = cellCountX * cellCountY;
1956 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001957 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07001958 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07001959 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07001960 rhs.cellY * cellCountX + rhs.cellX);
1961 return (int) (lr - rr);
1962 }
1963 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001964 }
Winson Chungdb8a8942012-04-03 14:08:41 -07001965
Adam Cohendcd297f2013-06-18 13:13:40 -07001966 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
1967 final ArrayList<Long> orderedScreens) {
1968
1969 final Runnable r = new Runnable() {
1970 @Override
1971 public void run() {
1972 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1973 if (callbacks != null) {
1974 callbacks.bindScreens(orderedScreens);
1975 }
1976 }
1977 };
1978 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
1979 }
1980
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001981 private void bindWorkspaceItems(final Callbacks oldCallbacks,
1982 final ArrayList<ItemInfo> workspaceItems,
1983 final ArrayList<LauncherAppWidgetInfo> appWidgets,
1984 final HashMap<Long, FolderInfo> folders,
1985 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07001986
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001987 final boolean postOnMainThread = (deferredBindRunnables != null);
1988
1989 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07001990 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001991 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04001992 final int start = i;
1993 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001994 final Runnable r = new Runnable() {
1995 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04001996 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08001997 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001998 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07001999 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2000 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002001 }
2002 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002003 };
2004 if (postOnMainThread) {
2005 deferredBindRunnables.add(r);
2006 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002007 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002008 }
Joe Onorato36115782010-06-17 13:28:48 -04002009 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002010
2011 // Bind the folders
2012 if (!folders.isEmpty()) {
2013 final Runnable r = new Runnable() {
2014 public void run() {
2015 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2016 if (callbacks != null) {
2017 callbacks.bindFolders(folders);
2018 }
2019 }
2020 };
2021 if (postOnMainThread) {
2022 deferredBindRunnables.add(r);
2023 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002024 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002025 }
2026 }
2027
2028 // Bind the widgets, one at a time
2029 N = appWidgets.size();
2030 for (int i = 0; i < N; i++) {
2031 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2032 final Runnable r = new Runnable() {
2033 public void run() {
2034 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2035 if (callbacks != null) {
2036 callbacks.bindAppWidget(widget);
2037 }
2038 }
2039 };
2040 if (postOnMainThread) {
2041 deferredBindRunnables.add(r);
2042 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002043 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002044 }
2045 }
2046 }
2047
2048 /**
2049 * Binds all loaded data to actual views on the main thread.
2050 */
2051 private void bindWorkspace(int synchronizeBindPage) {
2052 final long t = SystemClock.uptimeMillis();
2053 Runnable r;
2054
2055 // Don't use these two variables in any of the callback runnables.
2056 // Otherwise we hold a reference to them.
2057 final Callbacks oldCallbacks = mCallbacks.get();
2058 if (oldCallbacks == null) {
2059 // This launcher has exited and nobody bothered to tell us. Just bail.
2060 Log.w(TAG, "LoaderTask running with no launcher");
2061 return;
2062 }
2063
Winson Chung4a2afa32012-07-19 14:53:05 -07002064 final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
2065 final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002066 oldCallbacks.getCurrentWorkspaceScreen();
2067
2068 // Load all the items that are on the current page first (and in the process, unbind
2069 // all the existing workspace items before we call startBinding() below.
2070 unbindWorkspaceItemsOnMainThread();
2071 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2072 ArrayList<LauncherAppWidgetInfo> appWidgets =
2073 new ArrayList<LauncherAppWidgetInfo>();
2074 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2075 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002076 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002077 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002078 workspaceItems.addAll(sBgWorkspaceItems);
2079 appWidgets.addAll(sBgAppWidgets);
2080 folders.putAll(sBgFolders);
2081 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002082 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002083 }
2084
2085 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2086 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2087 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2088 new ArrayList<LauncherAppWidgetInfo>();
2089 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2090 new ArrayList<LauncherAppWidgetInfo>();
2091 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2092 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2093
2094 // Separate the items that are on the current screen, and all the other remaining items
2095 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
2096 otherWorkspaceItems);
2097 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
2098 otherAppWidgets);
2099 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
2100 otherFolders);
2101 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2102 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2103
2104 // Tell the workspace that we're about to start binding items
2105 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002106 public void run() {
2107 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2108 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002109 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002110 }
2111 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002112 };
Winson Chung81b52252012-08-27 15:34:29 -07002113 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002114
Adam Cohendcd297f2013-06-18 13:13:40 -07002115 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2116
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002117 // Load items on the current page
2118 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2119 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002120 if (isLoadingSynchronously) {
2121 r = new Runnable() {
2122 public void run() {
2123 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2124 if (callbacks != null) {
2125 callbacks.onPageBoundSynchronously(currentScreen);
2126 }
2127 }
2128 };
Winson Chung81b52252012-08-27 15:34:29 -07002129 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002130 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002131
Winson Chung4a2afa32012-07-19 14:53:05 -07002132 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2133 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002134 mDeferredBindRunnables.clear();
2135 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002136 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002137
2138 // Tell the workspace that we're done binding items
2139 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002140 public void run() {
2141 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2142 if (callbacks != null) {
Adam Cohene25af792013-06-06 23:08:25 -07002143 callbacks.finishBindingItems(mIsUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002144 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002145
Winson Chung98e030b2012-05-07 16:01:11 -07002146 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002147 if (DEBUG_LOADERS) {
2148 Log.d(TAG, "bound workspace in "
2149 + (SystemClock.uptimeMillis()-t) + "ms");
2150 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002151
2152 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002153 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002154 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002155 if (isLoadingSynchronously) {
2156 mDeferredBindRunnables.add(r);
2157 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002158 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002159 }
Joe Onorato36115782010-06-17 13:28:48 -04002160 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002161
Joe Onorato36115782010-06-17 13:28:48 -04002162 private void loadAndBindAllApps() {
2163 if (DEBUG_LOADERS) {
2164 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2165 }
2166 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002167 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002168 synchronized (LoaderTask.this) {
2169 if (mStopped) {
2170 return;
2171 }
2172 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002173 }
Joe Onorato36115782010-06-17 13:28:48 -04002174 } else {
2175 onlyBindAllApps();
2176 }
2177 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002178
Joe Onorato36115782010-06-17 13:28:48 -04002179 private void onlyBindAllApps() {
2180 final Callbacks oldCallbacks = mCallbacks.get();
2181 if (oldCallbacks == null) {
2182 // This launcher has exited and nobody bothered to tell us. Just bail.
2183 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2184 return;
2185 }
2186
2187 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002188 @SuppressWarnings("unchecked")
Joe Onorato36115782010-06-17 13:28:48 -04002189 final ArrayList<ApplicationInfo> list
Adam Cohen487f7dd2012-06-28 18:12:10 -07002190 = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002191 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002192 public void run() {
2193 final long t = SystemClock.uptimeMillis();
2194 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2195 if (callbacks != null) {
2196 callbacks.bindAllApplications(list);
2197 }
2198 if (DEBUG_LOADERS) {
2199 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2200 + (SystemClock.uptimeMillis()-t) + "ms");
2201 }
2202 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002203 };
2204 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002205 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002206 r.run();
2207 } else {
2208 mHandler.post(r);
2209 }
Joe Onorato36115782010-06-17 13:28:48 -04002210 }
2211
Winson Chung64359a52013-07-08 17:17:08 -07002212 private void loadAllApps() {
2213 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002214
2215 // Don't use these two variables in any of the callback runnables.
2216 // Otherwise we hold a reference to them.
2217 final Callbacks oldCallbacks = mCallbacks.get();
2218 if (oldCallbacks == null) {
2219 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002220 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002221 return;
2222 }
2223
Winson Chung64359a52013-07-08 17:17:08 -07002224 final PackageManager packageManager = mContext.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04002225 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2226 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2227
Winson Chung64359a52013-07-08 17:17:08 -07002228 // Clear the list of apps
2229 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002230
Winson Chung64359a52013-07-08 17:17:08 -07002231 // Query for the set of apps
2232 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2233 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2234 if (DEBUG_LOADERS) {
2235 Log.d(TAG, "queryIntentActivities took "
2236 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2237 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2238 }
2239 // Fail if we don't have any apps
2240 if (apps == null || apps.isEmpty()) {
2241 return;
2242 }
2243 // Sort the applications by name
2244 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2245 Collections.sort(apps,
2246 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2247 if (DEBUG_LOADERS) {
2248 Log.d(TAG, "sort took "
2249 + (SystemClock.uptimeMillis()-sortTime) + "ms");
Joe Onorato9c1289c2009-08-17 11:03:03 -04002250 }
2251
Winson Chung64359a52013-07-08 17:17:08 -07002252 // Create the ApplicationInfos
2253 final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2254 for (int i = 0; i < apps.size(); i++) {
2255 // This builds the icon bitmaps.
2256 mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
2257 mIconCache, mLabelCache));
2258 }
2259
2260 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2261 final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
2262 mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
2263
2264 // Post callback on main thread
2265 mHandler.post(new Runnable() {
2266 public void run() {
2267 final long bindTime = SystemClock.uptimeMillis();
2268 if (callbacks != null) {
2269 callbacks.bindAllApplications(added);
2270 if (DEBUG_LOADERS) {
2271 Log.d(TAG, "bound " + added.size() + " apps in "
2272 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2273 }
2274 } else {
2275 Log.i(TAG, "not binding apps: no Launcher activity");
2276 }
2277 }
2278 });
2279
Joe Onorato36115782010-06-17 13:28:48 -04002280 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002281 Log.d(TAG, "Icons processed in "
2282 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002283 }
2284 }
2285
2286 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002287 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002288 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2289 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2290 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2291 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2292 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2293 }
Joe Onorato36115782010-06-17 13:28:48 -04002294 }
2295 }
2296
2297 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002298 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002299 }
2300
2301 private class PackageUpdatedTask implements Runnable {
2302 int mOp;
2303 String[] mPackages;
2304
2305 public static final int OP_NONE = 0;
2306 public static final int OP_ADD = 1;
2307 public static final int OP_UPDATE = 2;
2308 public static final int OP_REMOVE = 3; // uninstlled
2309 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2310
2311
2312 public PackageUpdatedTask(int op, String[] packages) {
2313 mOp = op;
2314 mPackages = packages;
2315 }
2316
2317 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002318 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002319
2320 final String[] packages = mPackages;
2321 final int N = packages.length;
2322 switch (mOp) {
2323 case OP_ADD:
2324 for (int i=0; i<N; i++) {
2325 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002326 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002327 }
2328 break;
2329 case OP_UPDATE:
2330 for (int i=0; i<N; i++) {
2331 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002332 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002333 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002334 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002335 }
2336 break;
2337 case OP_REMOVE:
2338 case OP_UNAVAILABLE:
2339 for (int i=0; i<N; i++) {
2340 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002341 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002342 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002343 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002344 }
2345 break;
2346 }
2347
2348 ArrayList<ApplicationInfo> added = null;
Joe Onorato36115782010-06-17 13:28:48 -04002349 ArrayList<ApplicationInfo> modified = null;
Winson Chung83892cc2013-05-01 16:53:33 -07002350 final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002351
Adam Cohen487f7dd2012-06-28 18:12:10 -07002352 if (mBgAllAppsList.added.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002353 added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
2354 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002355 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002356 if (mBgAllAppsList.modified.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002357 modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
2358 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002359 }
Winson Chung5d55f332012-07-16 20:45:03 -07002360 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002361 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002362 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002363 }
2364
Joe Onorato36115782010-06-17 13:28:48 -04002365 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2366 if (callbacks == null) {
2367 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2368 return;
2369 }
2370
2371 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002372 // Ensure that we add all the workspace applications to the db
2373 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2374 addAndBindAddedApps(context, added, cb);
Joe Onorato36115782010-06-17 13:28:48 -04002375 }
2376 if (modified != null) {
2377 final ArrayList<ApplicationInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002378
2379 // Update the launcher db to reflect the changes
2380 for (ApplicationInfo a : modifiedFinal) {
2381 ArrayList<ItemInfo> infos =
2382 getItemInfoForComponentName(a.componentName);
2383 for (ItemInfo i : infos) {
2384 if (isShortcutInfoUpdateable(i)) {
2385 ShortcutInfo info = (ShortcutInfo) i;
2386 info.title = a.title.toString();
2387 updateItemInDatabase(context, info);
2388 }
2389 }
2390 }
2391
Joe Onorato36115782010-06-17 13:28:48 -04002392 mHandler.post(new Runnable() {
2393 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002394 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2395 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002396 callbacks.bindAppsUpdated(modifiedFinal);
2397 }
2398 }
2399 });
2400 }
Winson Chung83892cc2013-05-01 16:53:33 -07002401 // If a package has been removed, or an app has been removed as a result of
2402 // an update (for example), make the removed callback.
2403 if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
Winson Chung64359a52013-07-08 17:17:08 -07002404 final boolean packageRemoved = (mOp == OP_REMOVE);
Winson Chung83892cc2013-05-01 16:53:33 -07002405 final ArrayList<String> removedPackageNames =
2406 new ArrayList<String>(Arrays.asList(packages));
2407
Winson Chung64359a52013-07-08 17:17:08 -07002408 // Update the launcher db to reflect the removal of apps
2409 if (packageRemoved) {
2410 for (String pn : removedPackageNames) {
2411 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2412 for (ItemInfo i : infos) {
2413 deleteItemFromDatabase(context, i);
2414 }
2415 }
2416 } else {
2417 for (ApplicationInfo a : removedApps) {
2418 ArrayList<ItemInfo> infos =
2419 getItemInfoForComponentName(a.componentName);
2420 for (ItemInfo i : infos) {
2421 deleteItemFromDatabase(context, i);
2422 }
2423 }
2424 }
2425
Joe Onorato36115782010-06-17 13:28:48 -04002426 mHandler.post(new Runnable() {
2427 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002428 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2429 if (callbacks == cb && cb != null) {
Winson Chung83892cc2013-05-01 16:53:33 -07002430 callbacks.bindComponentsRemoved(removedPackageNames,
Winson Chung64359a52013-07-08 17:17:08 -07002431 removedApps, packageRemoved);
Joe Onorato36115782010-06-17 13:28:48 -04002432 }
2433 }
2434 });
Joe Onoratobe386092009-11-17 17:32:16 -08002435 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002436
Michael Jurkac402cd92013-05-20 15:49:32 +02002437 final ArrayList<Object> widgetsAndShortcuts =
2438 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002439 mHandler.post(new Runnable() {
2440 @Override
2441 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002442 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2443 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002444 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002445 }
2446 }
2447 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002448 }
2449 }
2450
Michael Jurkac402cd92013-05-20 15:49:32 +02002451 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2452 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2453 PackageManager packageManager = context.getPackageManager();
2454 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2455 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2456 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2457 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2458 Collections.sort(widgetsAndShortcuts,
2459 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2460 return widgetsAndShortcuts;
2461 }
2462
Joe Onorato9c1289c2009-08-17 11:03:03 -04002463 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002464 * This is called from the code that adds shortcuts from the intent receiver. This
2465 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002466 */
Joe Onorato56d82912010-03-07 14:32:10 -05002467 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002468 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002469 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002470
Joe Onorato56d82912010-03-07 14:32:10 -05002471 /**
2472 * Make an ShortcutInfo object for a shortcut that is an application.
2473 *
2474 * If c is not null, then it will be used to fill in missing data like the title and icon.
2475 */
2476 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002477 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002478 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002479 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002480
2481 ComponentName componentName = intent.getComponent();
2482 if (componentName == null) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002483 return null;
2484 }
2485
Adam Cohen00fcb492011-11-02 21:53:47 -07002486 try {
2487 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2488 if (!pi.applicationInfo.enabled) {
2489 // If we return null here, the corresponding item will be removed from the launcher
2490 // db and will not appear in the workspace.
2491 return null;
2492 }
2493 } catch (NameNotFoundException e) {
2494 Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
2495 }
2496
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002497 // TODO: See if the PackageManager knows about this case. If it doesn't
2498 // then return null & delete this.
2499
Joe Onorato56d82912010-03-07 14:32:10 -05002500 // the resource -- This may implicitly give us back the fallback icon,
2501 // but don't worry about that. All we're doing with usingFallbackIcon is
2502 // to avoid saving lots of copies of that in the database, and most apps
2503 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002504
2505 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2506 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2507 // via resolveActivity().
2508 ResolveInfo resolveInfo = null;
2509 ComponentName oldComponent = intent.getComponent();
2510 Intent newIntent = new Intent(intent.getAction(), null);
2511 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2512 newIntent.setPackage(oldComponent.getPackageName());
2513 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2514 for (ResolveInfo i : infos) {
2515 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2516 i.activityInfo.name);
2517 if (cn.equals(oldComponent)) {
2518 resolveInfo = i;
2519 }
2520 }
2521 if (resolveInfo == null) {
2522 resolveInfo = manager.resolveActivity(intent, 0);
2523 }
Joe Onorato56d82912010-03-07 14:32:10 -05002524 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002525 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002526 }
Joe Onorato56d82912010-03-07 14:32:10 -05002527 // the db
2528 if (icon == null) {
2529 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002530 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002531 }
2532 }
2533 // the fallback icon
2534 if (icon == null) {
2535 icon = getFallbackIcon();
2536 info.usingFallbackIcon = true;
2537 }
2538 info.setIcon(icon);
2539
2540 // from the resource
2541 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002542 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2543 if (labelCache != null && labelCache.containsKey(key)) {
2544 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002545 } else {
2546 info.title = resolveInfo.activityInfo.loadLabel(manager);
2547 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002548 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002549 }
2550 }
Joe Onorato56d82912010-03-07 14:32:10 -05002551 }
2552 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002553 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002554 if (c != null) {
2555 info.title = c.getString(titleIndex);
2556 }
2557 }
2558 // fall back to the class name of the activity
2559 if (info.title == null) {
2560 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002561 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002562 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2563 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002564 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002565
Winson Chung64359a52013-07-08 17:17:08 -07002566 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2567 ItemInfoFilter f) {
2568 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2569 for (ItemInfo i : infos) {
2570 if (i instanceof ShortcutInfo) {
2571 ShortcutInfo info = (ShortcutInfo) i;
2572 ComponentName cn = info.intent.getComponent();
2573 if (cn != null && f.filterItem(null, info, cn)) {
2574 filtered.add(info);
2575 }
2576 } else if (i instanceof FolderInfo) {
2577 FolderInfo info = (FolderInfo) i;
2578 for (ShortcutInfo s : info.contents) {
2579 ComponentName cn = s.intent.getComponent();
2580 if (cn != null && f.filterItem(info, s, cn)) {
2581 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07002582 }
2583 }
Winson Chung64359a52013-07-08 17:17:08 -07002584 } else if (i instanceof LauncherAppWidgetInfo) {
2585 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2586 ComponentName cn = info.providerName;
2587 if (cn != null && f.filterItem(null, info, cn)) {
2588 filtered.add(info);
2589 }
Winson Chung8a435102012-08-30 17:16:53 -07002590 }
2591 }
Winson Chung64359a52013-07-08 17:17:08 -07002592 return new ArrayList<ItemInfo>(filtered);
2593 }
2594
2595 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
2596 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2597 ItemInfoFilter filter = new ItemInfoFilter() {
2598 @Override
2599 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2600 return cn.getPackageName().equals(pn);
2601 }
2602 };
2603 return filterItemInfos(sBgItemsIdMap.values(), filter);
2604 }
2605
2606 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
2607 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2608 ItemInfoFilter filter = new ItemInfoFilter() {
2609 @Override
2610 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2611 return cn.equals(cname);
2612 }
2613 };
2614 return filterItemInfos(sBgItemsIdMap.values(), filter);
2615 }
2616
2617 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2618 if (i instanceof ShortcutInfo) {
2619 ShortcutInfo info = (ShortcutInfo) i;
2620 // We need to check for ACTION_MAIN otherwise getComponent() might
2621 // return null for some shortcuts (for instance, for shortcuts to
2622 // web pages.)
2623 Intent intent = info.intent;
2624 ComponentName name = intent.getComponent();
2625 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2626 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2627 return true;
2628 }
2629 }
2630 return false;
Winson Chung8a435102012-08-30 17:16:53 -07002631 }
2632
2633 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002634 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002635 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002636 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002637 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2638 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002639
Joe Onorato56d82912010-03-07 14:32:10 -05002640 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002641 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002642 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002643
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002644 // TODO: If there's an explicit component and we can't install that, delete it.
2645
Joe Onorato56d82912010-03-07 14:32:10 -05002646 info.title = c.getString(titleIndex);
2647
Joe Onorato9c1289c2009-08-17 11:03:03 -04002648 int iconType = c.getInt(iconTypeIndex);
2649 switch (iconType) {
2650 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2651 String packageName = c.getString(iconPackageIndex);
2652 String resourceName = c.getString(iconResourceIndex);
2653 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002654 info.customIcon = false;
2655 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002656 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002657 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002658 if (resources != null) {
2659 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002660 icon = Utilities.createIconBitmap(
2661 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002662 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002663 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002664 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002665 }
Joe Onorato56d82912010-03-07 14:32:10 -05002666 // the db
2667 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002668 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002669 }
2670 // the fallback icon
2671 if (icon == null) {
2672 icon = getFallbackIcon();
2673 info.usingFallbackIcon = true;
2674 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002675 break;
2676 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002677 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002678 if (icon == null) {
2679 icon = getFallbackIcon();
2680 info.customIcon = false;
2681 info.usingFallbackIcon = true;
2682 } else {
2683 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002684 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002685 break;
2686 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002687 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002688 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002689 info.customIcon = false;
2690 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002691 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002692 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002693 return info;
2694 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002695
Michael Jurka931dc972011-08-05 15:08:15 -07002696 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002697 @SuppressWarnings("all") // suppress dead code warning
2698 final boolean debug = false;
2699 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002700 Log.d(TAG, "getIconFromCursor app="
2701 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2702 }
2703 byte[] data = c.getBlob(iconIndex);
2704 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002705 return Utilities.createIconBitmap(
2706 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002707 } catch (Exception e) {
2708 return null;
2709 }
2710 }
2711
Winson Chung3d503fb2011-07-13 17:25:49 -07002712 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2713 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002714 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002715 if (info == null) {
2716 return null;
2717 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002718 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002719
2720 return info;
2721 }
2722
Winson Chunga9abd0e2010-10-27 17:18:37 -07002723 /**
Winson Chung55cef262010-10-28 14:14:18 -07002724 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2725 */
2726 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2727 ComponentName component) {
2728 List<AppWidgetProviderInfo> widgets =
2729 AppWidgetManager.getInstance(context).getInstalledProviders();
2730 for (AppWidgetProviderInfo info : widgets) {
2731 if (info.provider.equals(component)) {
2732 return info;
2733 }
2734 }
2735 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002736 }
2737
Winson Chung68846fd2010-10-29 11:00:27 -07002738 /**
2739 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2740 */
2741 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2742 final PackageManager packageManager = context.getPackageManager();
2743 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2744 new ArrayList<WidgetMimeTypeHandlerData>();
2745
2746 final Intent supportsIntent =
2747 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2748 supportsIntent.setType(mimeType);
2749
2750 // Create a set of widget configuration components that we can test against
2751 final List<AppWidgetProviderInfo> widgets =
2752 AppWidgetManager.getInstance(context).getInstalledProviders();
2753 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2754 new HashMap<ComponentName, AppWidgetProviderInfo>();
2755 for (AppWidgetProviderInfo info : widgets) {
2756 configurationComponentToWidget.put(info.configure, info);
2757 }
2758
2759 // Run through each of the intents that can handle this type of clip data, and cross
2760 // reference them with the components that are actual configuration components
2761 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2762 PackageManager.MATCH_DEFAULT_ONLY);
2763 for (ResolveInfo info : activities) {
2764 final ActivityInfo activityInfo = info.activityInfo;
2765 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2766 activityInfo.name);
2767 if (configurationComponentToWidget.containsKey(infoComponent)) {
2768 supportedConfigurationActivities.add(
2769 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2770 configurationComponentToWidget.get(infoComponent)));
2771 }
2772 }
2773 return supportedConfigurationActivities;
2774 }
2775
Winson Chunga9abd0e2010-10-27 17:18:37 -07002776 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08002777 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2778 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2779 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2780
Adam Cohend9198822011-11-22 16:42:47 -08002781 if (intent == null) {
2782 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2783 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2784 return null;
2785 }
2786
Joe Onorato0589f0f2010-02-08 13:44:00 -08002787 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08002788 boolean customIcon = false;
2789 ShortcutIconResource iconResource = null;
2790
2791 if (bitmap != null && bitmap instanceof Bitmap) {
2792 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002793 customIcon = true;
2794 } else {
2795 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2796 if (extra != null && extra instanceof ShortcutIconResource) {
2797 try {
2798 iconResource = (ShortcutIconResource) extra;
2799 final PackageManager packageManager = context.getPackageManager();
2800 Resources resources = packageManager.getResourcesForApplication(
2801 iconResource.packageName);
2802 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002803 icon = Utilities.createIconBitmap(
2804 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002805 } catch (Exception e) {
2806 Log.w(TAG, "Could not load shortcut icon: " + extra);
2807 }
2808 }
2809 }
2810
Michael Jurkac9d95c52011-08-29 14:03:34 -07002811 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002812
2813 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002814 if (fallbackIcon != null) {
2815 icon = fallbackIcon;
2816 } else {
2817 icon = getFallbackIcon();
2818 info.usingFallbackIcon = true;
2819 }
Joe Onorato56d82912010-03-07 14:32:10 -05002820 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08002821 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05002822
Joe Onorato0589f0f2010-02-08 13:44:00 -08002823 info.title = name;
2824 info.intent = intent;
2825 info.customIcon = customIcon;
2826 info.iconResource = iconResource;
2827
2828 return info;
2829 }
2830
Winson Chungaac01e12011-08-17 10:37:13 -07002831 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2832 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08002833 // If apps can't be on SD, don't even bother.
2834 if (!mAppsCanBeOnExternalStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07002835 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08002836 }
Joe Onorato56d82912010-03-07 14:32:10 -05002837 // If this icon doesn't have a custom icon, check to see
2838 // what's stored in the DB, and if it doesn't match what
2839 // we're going to show, store what we are going to show back
2840 // into the DB. We do this so when we're loading, if the
2841 // package manager can't find an icon (for example because
2842 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07002843 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07002844 cache.put(info, c.getBlob(iconIndex));
2845 return true;
2846 }
2847 return false;
2848 }
2849 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2850 boolean needSave = false;
2851 try {
2852 if (data != null) {
2853 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2854 Bitmap loaded = info.getIcon(mIconCache);
2855 needSave = !saved.sameAs(loaded);
2856 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05002857 needSave = true;
2858 }
Winson Chungaac01e12011-08-17 10:37:13 -07002859 } catch (Exception e) {
2860 needSave = true;
2861 }
2862 if (needSave) {
2863 Log.d(TAG, "going to save icon bitmap for info=" + info);
2864 // This is slower than is ideal, but this only happens once
2865 // or when the app is updated with a new icon.
2866 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05002867 }
2868 }
2869
Joe Onorato9c1289c2009-08-17 11:03:03 -04002870 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07002871 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04002872 * or make a new one.
2873 */
Adam Cohendf2cc412011-04-27 16:56:57 -07002874 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002875 // See if a placeholder was created for us already
2876 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07002877 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002878 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07002879 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002880 folders.put(id, folderInfo);
2881 }
Adam Cohendf2cc412011-04-27 16:56:57 -07002882 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002883 }
2884
Winson Chung11904872012-09-17 16:58:46 -07002885 public static final Comparator<ApplicationInfo> getAppNameComparator() {
2886 final Collator collator = Collator.getInstance();
2887 return new Comparator<ApplicationInfo>() {
2888 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2889 int result = collator.compare(a.title.toString(), b.title.toString());
2890 if (result == 0) {
2891 result = a.componentName.compareTo(b.componentName);
2892 }
2893 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07002894 }
Winson Chung11904872012-09-17 16:58:46 -07002895 };
2896 }
Winson Chung78403fe2011-01-21 15:38:02 -08002897 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2898 = new Comparator<ApplicationInfo>() {
2899 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2900 if (a.firstInstallTime < b.firstInstallTime) return 1;
2901 if (a.firstInstallTime > b.firstInstallTime) return -1;
2902 return 0;
2903 }
2904 };
Winson Chung11904872012-09-17 16:58:46 -07002905 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
2906 final Collator collator = Collator.getInstance();
2907 return new Comparator<AppWidgetProviderInfo>() {
2908 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
2909 return collator.compare(a.label.toString(), b.label.toString());
2910 }
2911 };
2912 }
Winson Chung5308f242011-08-18 12:12:41 -07002913 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
2914 if (info.activityInfo != null) {
2915 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
2916 } else {
2917 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
2918 }
2919 }
Winson Chung785d2eb2011-04-14 16:08:02 -07002920 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07002921 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07002922 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07002923 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07002924 ShortcutNameComparator(PackageManager pm) {
2925 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07002926 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07002927 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07002928 }
2929 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
2930 mPackageManager = pm;
2931 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07002932 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07002933 }
2934 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002935 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07002936 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
2937 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
2938 if (mLabelCache.containsKey(keyA)) {
2939 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002940 } else {
2941 labelA = a.loadLabel(mPackageManager).toString();
2942
Winson Chung5308f242011-08-18 12:12:41 -07002943 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002944 }
Winson Chung5308f242011-08-18 12:12:41 -07002945 if (mLabelCache.containsKey(keyB)) {
2946 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002947 } else {
2948 labelB = b.loadLabel(mPackageManager).toString();
2949
Winson Chung5308f242011-08-18 12:12:41 -07002950 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002951 }
Winson Chung11904872012-09-17 16:58:46 -07002952 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07002953 }
2954 };
Winson Chung1ed747a2011-05-03 16:18:34 -07002955 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07002956 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07002957 private PackageManager mPackageManager;
2958 private HashMap<Object, String> mLabelCache;
2959 WidgetAndShortcutNameComparator(PackageManager pm) {
2960 mPackageManager = pm;
2961 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07002962 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07002963 }
2964 public final int compare(Object a, Object b) {
2965 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07002966 if (mLabelCache.containsKey(a)) {
2967 labelA = mLabelCache.get(a);
2968 } else {
2969 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002970 ((AppWidgetProviderInfo) a).label :
2971 ((ResolveInfo) a).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002972 mLabelCache.put(a, labelA);
2973 }
2974 if (mLabelCache.containsKey(b)) {
2975 labelB = mLabelCache.get(b);
2976 } else {
2977 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002978 ((AppWidgetProviderInfo) b).label :
2979 ((ResolveInfo) b).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002980 mLabelCache.put(b, labelB);
2981 }
Winson Chung11904872012-09-17 16:58:46 -07002982 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07002983 }
2984 };
Joe Onoratobe386092009-11-17 17:32:16 -08002985
2986 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08002987 Log.d(TAG, "mCallbacks=" + mCallbacks);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002988 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
2989 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
2990 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
2991 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04002992 if (mLoaderTask != null) {
2993 mLoaderTask.dumpState();
2994 } else {
2995 Log.d(TAG, "mLoaderTask=null");
2996 }
Joe Onoratobe386092009-11-17 17:32:16 -08002997 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002998}