blob: e8674cedcd201743863758e56df57945131809cc [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
Joe Onoratoa5902522009-07-30 13:37:37 -070017package com.android.launcher2;
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;
Joe Onoratof99f8c12009-10-31 17:27:36 -040022import android.content.BroadcastReceiver;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080023import android.content.ComponentName;
Romain Guy5c16f3e2010-01-12 17:24:58 -080024import android.content.ContentProviderClient;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080025import android.content.ContentResolver;
26import android.content.ContentValues;
Winson Chungaafa03c2010-06-11 17:34:16 -070027import android.content.Context;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080028import android.content.Intent;
Joe Onorato0589f0f2010-02-08 13:44:00 -080029import android.content.Intent.ShortcutIconResource;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080030import android.content.pm.ActivityInfo;
Adam Cohen00fcb492011-11-02 21:53:47 -070031import android.content.pm.PackageInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080032import android.content.pm.PackageManager;
Adam Cohen00fcb492011-11-02 21:53:47 -070033import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070035import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.content.res.Resources;
37import android.database.Cursor;
38import android.graphics.Bitmap;
39import android.graphics.BitmapFactory;
40import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080041import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040042import android.os.Handler;
43import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080044import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080045import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070046import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040047import android.os.SystemClock;
Winson Chungaafa03c2010-06-11 17:34:16 -070048import android.util.Log;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049
Winson Chung68846fd2010-10-29 11:00:27 -070050import com.android.launcher.R;
51import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
Romain Guyedcce092010-03-04 13:03:17 -080052
Michael Jurkac2f801e2011-07-12 14:19:46 -070053import java.lang.ref.WeakReference;
54import java.net.URISyntaxException;
55import java.text.Collator;
56import java.util.ArrayList;
57import java.util.Collections;
58import java.util.Comparator;
59import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070060import java.util.HashSet;
Michael Jurkac2f801e2011-07-12 14:19:46 -070061import java.util.List;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070062import java.util.Map;
63import java.util.Set;
Michael Jurkac2f801e2011-07-12 14:19:46 -070064
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065/**
66 * Maintains in-memory state of the Launcher. It is expected that there should be only one
67 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070068 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069 */
Joe Onoratof99f8c12009-10-31 17:27:36 -040070public class LauncherModel extends BroadcastReceiver {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080071 static final boolean DEBUG_LOADERS = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -040072 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070073
Joe Onorato36115782010-06-17 13:28:48 -040074 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Joe Onorato17a89222011-02-08 17:26:11 -080075 private final boolean mAppsCanBeOnExternalStorage;
Joe Onoratod65d08e2010-04-20 15:43:37 -040076 private int mBatchSize; // 0 is all apps at once
Daniel Sandler2ff10b32010-04-16 15:06:06 -040077 private int mAllAppsLoadDelay; // milliseconds between batches
Daniel Sandlerdca66122010-04-13 16:23:58 -040078
Joe Onoratof99f8c12009-10-31 17:27:36 -040079 private final LauncherApplication mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -040080 private final Object mLock = new Object();
81 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -040082 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070083 private boolean mIsLoaderTaskRunning;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084
Brad Fitzpatrick700889f2010-10-11 09:40:44 -070085 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
86 static {
87 sWorkerThread.start();
88 }
89 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
90
Joe Onoratocc67f472010-06-08 10:54:30 -070091 // We start off with everything not loaded. After that, we assume that
92 // our monitoring of the package manager provides all updates and we never
93 // need to do a requery. These are only ever touched from the loader thread.
94 private boolean mWorkspaceLoaded;
95 private boolean mAllAppsLoaded;
96
Winson Chungb8b2a5a2012-07-12 17:55:31 -070097 // When we are loading pages synchronously, we can't just post the binding of items on the side
98 // pages as this delays the rotation process. Instead, we wait for a callback from the first
99 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
100 // a normal load, we also clear this set of Runnables.
101 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
102
Joe Onorato9c1289c2009-08-17 11:03:03 -0400103 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800104
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700105 // < only access in worker thread >
Adam Cohen487f7dd2012-06-28 18:12:10 -0700106 private AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800107
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700108 // The lock that must be acquired before referencing any static bg data structures. Unlike
109 // other locks, this one can generally be held long-term because we never expect any of these
110 // static data structures to be referenced outside of the worker thread except on the first
111 // load after configuration change.
112 static final Object mBgLock = new Object();
113
Adam Cohen487f7dd2012-06-28 18:12:10 -0700114 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700115 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700116 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700117
Adam Cohen487f7dd2012-06-28 18:12:10 -0700118 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
119 // created by LauncherModel that are directly on the home screen (however, no widgets or
120 // shortcuts within folders).
121 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700122
Adam Cohen487f7dd2012-06-28 18:12:10 -0700123 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
124 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700125 new ArrayList<LauncherAppWidgetInfo>();
126
Adam Cohen487f7dd2012-06-28 18:12:10 -0700127 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
128 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700129
Adam Cohen487f7dd2012-06-28 18:12:10 -0700130 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
131 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700132 // </ only access in worker thread >
133
134 private IconCache mIconCache;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800135 private Bitmap mDefaultIcon;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800136
Adam Cohend22015c2010-07-26 22:02:18 -0700137 private static int mCellCountX;
138 private static int mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700139
Reena Lee99a73f32011-10-24 17:27:37 -0700140 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700141
Joe Onorato9c1289c2009-08-17 11:03:03 -0400142 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700143 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400144 public int getCurrentWorkspaceScreen();
145 public void startBinding();
146 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
Joe Onoratoad72e172009-11-06 16:25:04 -0500147 public void bindFolders(HashMap<Long,FolderInfo> folders);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400148 public void finishBindingItems();
149 public void bindAppWidget(LauncherAppWidgetInfo info);
150 public void bindAllApplications(ArrayList<ApplicationInfo> apps);
Joe Onorato64e6be72010-03-05 15:05:52 -0500151 public void bindAppsAdded(ArrayList<ApplicationInfo> apps);
152 public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
Winson Chungcd810732012-06-18 16:45:43 -0700153 public void bindAppsRemoved(ArrayList<String> packageNames, boolean permanent);
Winson Chung80baf5a2010-08-09 16:03:15 -0700154 public void bindPackagesUpdated();
Daniel Sandler843e8602010-06-07 14:59:01 -0400155 public boolean isAllAppsVisible();
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800156 public boolean isAllAppsButtonRank(int rank);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100157 public void bindSearchablesChanged();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400158 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800159
Joe Onorato0589f0f2010-02-08 13:44:00 -0800160 LauncherModel(LauncherApplication app, IconCache iconCache) {
Joe Onorato17a89222011-02-08 17:26:11 -0800161 mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated();
Joe Onoratof99f8c12009-10-31 17:27:36 -0400162 mApp = app;
Adam Cohen487f7dd2012-06-28 18:12:10 -0700163 mBgAllAppsList = new AllAppsList(iconCache);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800164 mIconCache = iconCache;
165
166 mDefaultIcon = Utilities.createIconBitmap(
Michael Jurkac9a96192010-11-01 11:52:08 -0700167 mIconCache.getFullResDefaultActivityIcon(), app);
Daniel Sandler2ff10b32010-04-16 15:06:06 -0400168
Reena Lee93f824a2011-09-23 17:20:28 -0700169 final Resources res = app.getResources();
170 mAllAppsLoadDelay = res.getInteger(R.integer.config_allAppsBatchLoadDelay);
171 mBatchSize = res.getInteger(R.integer.config_allAppsBatchSize);
Reena Lee99a73f32011-10-24 17:27:37 -0700172 Configuration config = res.getConfiguration();
173 mPreviousConfigMcc = config.mcc;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800174 }
175
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700176 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
177 * posted on the main thread handler. */
178 private void runOnMainThread(Runnable r) {
179 if (sWorkerThread.getThreadId() == Process.myTid()) {
180 // If we are on the worker thread, post onto the main handler
181 mHandler.post(r);
182 } else {
183 r.run();
184 }
185 }
186
187 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
188 * posted on the worker thread handler. */
189 private static void runOnWorkerThread(Runnable r) {
190 if (sWorkerThread.getThreadId() == Process.myTid()) {
191 r.run();
192 } else {
193 // If we are not on the worker thread, then post to the worker handler
194 sWorker.post(r);
195 }
196 }
197
Joe Onorato56d82912010-03-07 14:32:10 -0500198 public Bitmap getFallbackIcon() {
Joe Onorato0589f0f2010-02-08 13:44:00 -0800199 return Bitmap.createBitmap(mDefaultIcon);
Joe Onoratof99f8c12009-10-31 17:27:36 -0400200 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800201
Winson Chung603bcb92011-09-02 11:45:39 -0700202 public void unbindWorkspaceItems() {
203 sWorker.post(new Runnable() {
204 @Override
205 public void run() {
206 unbindWorkspaceItemsOnMainThread();
207 }
208 });
209 }
210
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700211 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
212 private void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700213 // Ensure that we don't use the same workspace items data structure on the main thread
214 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700215 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
216 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
217 synchronized (mBgLock) {
218 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
219 tmpAppWidgets.addAll(sBgAppWidgets);
220 }
221 Runnable r = new Runnable() {
222 @Override
223 public void run() {
224 for (ItemInfo item : tmpWorkspaceItems) {
225 item.unbind();
226 }
227 for (ItemInfo item : tmpAppWidgets) {
228 item.unbind();
229 }
230 }
231 };
232 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700233 }
234
Joe Onorato9c1289c2009-08-17 11:03:03 -0400235 /**
236 * Adds an item to the DB if it was not created previously, or move it to a new
237 * <container, screen, cellX, cellY>
238 */
239 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
240 int screen, int cellX, int cellY) {
241 if (item.container == ItemInfo.NO_ID) {
242 // From all apps
243 addItemToDatabase(context, item, container, screen, cellX, cellY, false);
244 } else {
245 // From somewhere else
246 moveItemInDatabase(context, item, container, screen, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800247 }
248 }
249
Michael Jurka816474f2012-06-25 14:49:02 -0700250 static void checkItemInfo(final ItemInfo item) {
251 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
252 final long itemId = item.id;
253 Runnable r = new Runnable() {
254 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700255 synchronized (mBgLock) {
256 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
257 if (modelItem != null && item != modelItem) {
258 // the modelItem needs to match up perfectly with item if our model is
259 // to be consistent with the database-- for now, just require
260 // modelItem == item
261 String msg = "item: " + ((item != null) ? item.toString() : "null") +
262 "modelItem: " +
263 ((modelItem != null) ? modelItem.toString() : "null") +
264 "Error: ItemInfo passed to checkItemInfo doesn't match original";
265 RuntimeException e = new RuntimeException(msg);
266 e.setStackTrace(stackTrace);
267 throw e;
268 }
Michael Jurka816474f2012-06-25 14:49:02 -0700269 }
270 }
271 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700272 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700273 }
274
Michael Jurkac9d95c52011-08-29 14:03:34 -0700275 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
276 final ItemInfo item, final String callingFunction) {
277 final long itemId = item.id;
278 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
279 final ContentResolver cr = context.getContentResolver();
280
Adam Cohen487f7dd2012-06-28 18:12:10 -0700281 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700282 Runnable r = new Runnable() {
283 public void run() {
284 cr.update(uri, values, null, null);
285
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700286 // Lock on mBgLock *after* the db operation
287 synchronized (mBgLock) {
288 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
289 if (item != modelItem) {
290 // the modelItem needs to match up perfectly with item if our model is to be
291 // consistent with the database-- for now, just require modelItem == item
292 String msg = "item: " + ((item != null) ? item.toString() : "null") +
293 "modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") +
294 "Error: ItemInfo passed to " + callingFunction + " doesn't match " +
295 "original";
296 throw new RuntimeException(msg);
Adam Cohen487f7dd2012-06-28 18:12:10 -0700297 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700298
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700299 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
300 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
301 // Item is in a folder, make sure this folder exists
302 if (!sBgFolders.containsKey(item.container)) {
303 // An items container is being set to a that of an item which is not in
304 // the list of Folders.
305 String msg = "item: " + item + " container being set to: " +
306 item.container + ", not in the list of folders";
307 RuntimeException e = new RuntimeException(msg);
308 e.setStackTrace(stackTrace);
309 Launcher.dumpDebugLogsToConsole();
310 throw e;
311 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700312 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700313
314 // Items are added/removed from the corresponding FolderInfo elsewhere, such
315 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
316 // that are on the desktop, as appropriate
317 if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
318 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
319 switch (modelItem.itemType) {
320 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
321 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
322 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
323 if (!sBgWorkspaceItems.contains(modelItem)) {
324 sBgWorkspaceItems.add(modelItem);
325 }
326 break;
327 default:
328 break;
329 }
330 } else {
331 sBgWorkspaceItems.remove(modelItem);
332 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700333 }
334 }
335 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700336 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700337 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700338
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800339 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400340 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700341 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700342 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
343 final int screen, final int cellX, final int cellY) {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700344 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
345 " (" + item.container + ", " + item.screen + ", " + item.cellX + ", " + item.cellY +
346 ") --> " + "(" + container + ", " + screen + ", " + cellX + ", " + cellY + ")";
347 Launcher.sDumpLogs.add(transaction);
348 Log.d(TAG, transaction);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400349 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400350 item.cellX = cellX;
351 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700352
Winson Chung3d503fb2011-07-13 17:25:49 -0700353 // We store hotseat items in canonical form which is this orientation invariant position
354 // in the hotseat
355 if (context instanceof Launcher && screen < 0 &&
356 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
357 item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
358 } else {
359 item.screen = screen;
360 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400361
362 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400363 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700364 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
365 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400366 values.put(LauncherSettings.Favorites.SCREEN, item.screen);
367
Michael Jurkac9d95c52011-08-29 14:03:34 -0700368 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700369 }
370
371 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700372 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800373 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700374 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
375 final int screen, final int cellX, final int cellY, final int spanX, final int spanY) {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700376 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
377 " (" + item.container + ", " + item.screen + ", " + item.cellX + ", " + item.cellY +
378 ") --> " + "(" + container + ", " + screen + ", " + cellX + ", " + cellY + ")";
379 Launcher.sDumpLogs.add(transaction);
380 Log.d(TAG, transaction);
Adam Cohend4844c32011-02-18 19:25:06 -0800381 item.cellX = cellX;
382 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700383 item.spanX = spanX;
384 item.spanY = spanY;
385
386 // We store hotseat items in canonical form which is this orientation invariant position
387 // in the hotseat
388 if (context instanceof Launcher && screen < 0 &&
389 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
390 item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
391 } else {
392 item.screen = screen;
393 }
Adam Cohend4844c32011-02-18 19:25:06 -0800394
Adam Cohend4844c32011-02-18 19:25:06 -0800395 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800396 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700397 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
398 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
399 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
400 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
401 values.put(LauncherSettings.Favorites.SCREEN, item.screen);
Adam Cohend4844c32011-02-18 19:25:06 -0800402
Michael Jurka816474f2012-06-25 14:49:02 -0700403 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700404 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700405
406 /**
407 * Update an item to the database in a specified container.
408 */
409 static void updateItemInDatabase(Context context, final ItemInfo item) {
410 final ContentValues values = new ContentValues();
411 item.onAddToDatabase(values);
412 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
413 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800414 }
415
416 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400417 * Returns true if the shortcuts already exists in the database.
418 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800419 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400420 static boolean shortcutExists(Context context, String title, Intent intent) {
421 final ContentResolver cr = context.getContentResolver();
422 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
423 new String[] { "title", "intent" }, "title=? and intent=?",
424 new String[] { title, intent.toUri(0) }, null);
425 boolean result = false;
426 try {
427 result = c.moveToFirst();
428 } finally {
429 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800430 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400431 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700432 }
433
Joe Onorato9c1289c2009-08-17 11:03:03 -0400434 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700435 * Returns an ItemInfo array containing all the items in the LauncherModel.
436 * The ItemInfo.id is not set through this function.
437 */
438 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
439 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
440 final ContentResolver cr = context.getContentResolver();
441 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
442 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
443 LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
444 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
445
446 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
447 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
448 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
449 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
450 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
451 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
452 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
453
454 try {
455 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700456 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700457 item.cellX = c.getInt(cellXIndex);
458 item.cellY = c.getInt(cellYIndex);
459 item.spanX = c.getInt(spanXIndex);
460 item.spanY = c.getInt(spanYIndex);
461 item.container = c.getInt(containerIndex);
462 item.itemType = c.getInt(itemTypeIndex);
463 item.screen = c.getInt(screenIndex);
464
465 items.add(item);
466 }
467 } catch (Exception e) {
468 items.clear();
469 } finally {
470 c.close();
471 }
472
473 return items;
474 }
475
476 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400477 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
478 */
479 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
480 final ContentResolver cr = context.getContentResolver();
481 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
482 "_id=? and (itemType=? or itemType=?)",
483 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700484 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700485
Joe Onorato9c1289c2009-08-17 11:03:03 -0400486 try {
487 if (c.moveToFirst()) {
488 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
489 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
490 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
491 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
492 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
493 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800494
Joe Onorato9c1289c2009-08-17 11:03:03 -0400495 FolderInfo folderInfo = null;
496 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700497 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
498 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400499 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700500 }
501
Joe Onorato9c1289c2009-08-17 11:03:03 -0400502 folderInfo.title = c.getString(titleIndex);
503 folderInfo.id = id;
504 folderInfo.container = c.getInt(containerIndex);
505 folderInfo.screen = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700506 folderInfo.cellX = c.getInt(cellXIndex);
507 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400508
509 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700510 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400511 } finally {
512 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700513 }
514
515 return null;
516 }
517
Joe Onorato9c1289c2009-08-17 11:03:03 -0400518 /**
519 * Add an item to the database in a specified container. Sets the container, screen, cellX and
520 * cellY fields of the item. Also assigns an ID to the item.
521 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700522 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
523 final int screen, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400524 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400525 item.cellX = cellX;
526 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700527 // We store hotseat items in canonical form which is this orientation invariant position
528 // in the hotseat
529 if (context instanceof Launcher && screen < 0 &&
530 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
531 item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
532 } else {
533 item.screen = screen;
534 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400535
536 final ContentValues values = new ContentValues();
537 final ContentResolver cr = context.getContentResolver();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400538 item.onAddToDatabase(values);
539
Michael Jurka7578ec62011-08-03 14:11:54 -0700540 LauncherApplication app = (LauncherApplication) context.getApplicationContext();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700541 item.id = app.getLauncherProvider().generateNewId();
542 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -0700543 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -0700544
Adam Cohen487f7dd2012-06-28 18:12:10 -0700545 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
546
Michael Jurkac9d95c52011-08-29 14:03:34 -0700547 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700548 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700549 String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
550 + item.id + " (" + container + ", " + screen + ", " + cellX + ", "
551 + cellY + ")";
552 Launcher.sDumpLogs.add(transaction);
553 Log.d(TAG, transaction);
554
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700555 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
556 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400557
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700558 // Lock on mBgLock *after* the db operation
559 synchronized (mBgLock) {
560 if (sBgItemsIdMap.containsKey(item.id)) {
561 // we should not be adding new items in the db with the same id
562 throw new RuntimeException("Error: ItemInfo id (" + item.id + ") passed to " +
563 "addItemToDatabase already exists." + item.toString());
564 }
565 sBgItemsIdMap.put(item.id, item);
566 switch (item.itemType) {
567 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
568 sBgFolders.put(item.id, (FolderInfo) item);
569 // Fall through
570 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
571 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
572 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
573 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
574 sBgWorkspaceItems.add(item);
575 } else {
576 if (!sBgFolders.containsKey(item.container)) {
577 // Adding an item to a folder that doesn't exist.
578 String msg = "adding item: " + item + " to a folder that " +
579 " doesn't exist";
580 RuntimeException e = new RuntimeException(msg);
581 e.setStackTrace(stackTrace);
582 Launcher.dumpDebugLogsToConsole();
583 throw e;
584 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700585 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700586 break;
587 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
588 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
589 break;
590 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700591 }
592 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700593 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700594 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700595 }
596
Joe Onorato9c1289c2009-08-17 11:03:03 -0400597 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700598 * Creates a new unique child id, for a given cell span across all layouts.
599 */
Michael Jurka845ba3b2010-09-28 17:09:46 -0700600 static int getCellLayoutChildId(
Winson Chung3d503fb2011-07-13 17:25:49 -0700601 long container, int screen, int localCellX, int localCellY, int spanX, int spanY) {
602 return (((int) container & 0xFF) << 24)
Michael Jurka845ba3b2010-09-28 17:09:46 -0700603 | (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -0700604 }
605
Adam Cohend22015c2010-07-26 22:02:18 -0700606 static int getCellCountX() {
607 return mCellCountX;
Winson Chungaafa03c2010-06-11 17:34:16 -0700608 }
609
Adam Cohend22015c2010-07-26 22:02:18 -0700610 static int getCellCountY() {
611 return mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700612 }
613
614 /**
615 * Updates the model orientation helper to take into account the current layout dimensions
616 * when performing local/canonical coordinate transformations.
617 */
618 static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
Adam Cohend22015c2010-07-26 22:02:18 -0700619 mCellCountX = shortAxisCellCount;
620 mCellCountY = longAxisCellCount;
Winson Chungaafa03c2010-06-11 17:34:16 -0700621 }
622
623 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -0700624 * Removes the specified item from the database
625 * @param context
626 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -0400627 */
Michael Jurkac9d95c52011-08-29 14:03:34 -0700628 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400629 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700630 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -0700631 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
632
Michael Jurka83df1882011-08-31 20:59:26 -0700633 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700634 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700635 String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
636 + item.id + " (" + item.container + ", " + item.screen + ", " + item.cellX +
637 ", " + item.cellY + ")";
638 Launcher.sDumpLogs.add(transaction);
639 Log.d(TAG, transaction);
640
Michael Jurkac9d95c52011-08-29 14:03:34 -0700641 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700642
643 // Lock on mBgLock *after* the db operation
644 synchronized (mBgLock) {
645 switch (item.itemType) {
646 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
647 sBgFolders.remove(item.id);
648 for (ItemInfo info: sBgItemsIdMap.values()) {
649 if (info.container == item.id) {
650 // We are deleting a folder which still contains items that
651 // think they are contained by that folder.
652 String msg = "deleting a folder (" + item + ") which still " +
653 "contains items (" + info + ")";
654 RuntimeException e = new RuntimeException(msg);
655 e.setStackTrace(stackTrace);
656 Launcher.dumpDebugLogsToConsole();
657 throw e;
658 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700659 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700660 sBgWorkspaceItems.remove(item);
661 break;
662 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
663 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
664 sBgWorkspaceItems.remove(item);
665 break;
666 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
667 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
668 break;
669 }
670 sBgItemsIdMap.remove(item.id);
671 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700672 }
673 }
Michael Jurka83df1882011-08-31 20:59:26 -0700674 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700675 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400676 }
677
678 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400679 * Remove the contents of the specified folder from the database
680 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700681 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400682 final ContentResolver cr = context.getContentResolver();
683
Michael Jurkac9d95c52011-08-29 14:03:34 -0700684 Runnable r = new Runnable() {
685 public void run() {
686 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700687 // Lock on mBgLock *after* the db operation
688 synchronized (mBgLock) {
689 sBgItemsIdMap.remove(info.id);
690 sBgFolders.remove(info.id);
691 sBgDbIconCache.remove(info);
692 sBgWorkspaceItems.remove(info);
693 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700694
Michael Jurkac9d95c52011-08-29 14:03:34 -0700695 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
696 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700697 // Lock on mBgLock *after* the db operation
698 synchronized (mBgLock) {
699 for (ItemInfo childInfo : info.contents) {
700 sBgItemsIdMap.remove(childInfo.id);
701 sBgDbIconCache.remove(childInfo);
702 }
Adam Cohenafb01ee2011-06-23 15:38:03 -0700703 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700704 }
705 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700706 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400707 }
708
709 /**
710 * Set this as the current Launcher activity object for the loader.
711 */
712 public void initialize(Callbacks callbacks) {
713 synchronized (mLock) {
714 mCallbacks = new WeakReference<Callbacks>(callbacks);
715 }
716 }
717
Joe Onorato1d8e7bb2009-10-15 19:49:43 -0700718 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400719 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
720 * ACTION_PACKAGE_CHANGED.
721 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100722 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -0400723 public void onReceive(Context context, Intent intent) {
Joe Onorato36115782010-06-17 13:28:48 -0400724 if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -0700725
Joe Onorato36115782010-06-17 13:28:48 -0400726 final String action = intent.getAction();
Joe Onoratof99f8c12009-10-31 17:27:36 -0400727
Joe Onorato36115782010-06-17 13:28:48 -0400728 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
729 || Intent.ACTION_PACKAGE_REMOVED.equals(action)
730 || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
731 final String packageName = intent.getData().getSchemeSpecificPart();
732 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400733
Joe Onorato36115782010-06-17 13:28:48 -0400734 int op = PackageUpdatedTask.OP_NONE;
735
736 if (packageName == null || packageName.length() == 0) {
737 // they sent us a bad intent
738 return;
739 }
740
741 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
742 op = PackageUpdatedTask.OP_UPDATE;
743 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
744 if (!replacing) {
745 op = PackageUpdatedTask.OP_REMOVE;
746 }
747 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
748 // later, we will update the package at this time
749 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
750 if (!replacing) {
751 op = PackageUpdatedTask.OP_ADD;
752 } else {
753 op = PackageUpdatedTask.OP_UPDATE;
754 }
755 }
756
757 if (op != PackageUpdatedTask.OP_NONE) {
758 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
759 }
760
761 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Joe Onoratocec58332010-10-07 14:37:40 -0400762 // First, schedule to add these apps back in.
763 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
764 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
765 // Then, rebind everything.
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700766 startLoaderFromBackground();
Joe Onorato36115782010-06-17 13:28:48 -0400767 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
768 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
769 enqueuePackageUpdated(new PackageUpdatedTask(
770 PackageUpdatedTask.OP_UNAVAILABLE, packages));
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700771 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -0700772 // If we have changed locale we need to clear out the labels in all apps/workspace.
773 forceReload();
774 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
775 // Check if configuration change was an mcc/mnc change which would affect app resources
776 // and we would need to clear out the labels in all apps/workspace. Same handling as
777 // above for ACTION_LOCALE_CHANGED
778 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -0700779 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -0700780 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -0700781 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -0700782 forceReload();
783 }
784 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -0700785 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -0700786 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
787 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -0700788 if (mCallbacks != null) {
789 Callbacks callbacks = mCallbacks.get();
790 if (callbacks != null) {
791 callbacks.bindSearchablesChanged();
792 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -0700793 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700794 }
795 }
796
Reena Lee93f824a2011-09-23 17:20:28 -0700797 private void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -0700798 resetLoadedState(true, true);
799
Reena Lee93f824a2011-09-23 17:20:28 -0700800 // Do this here because if the launcher activity is running it will be restarted.
801 // If it's not running startLoaderFromBackground will merely tell it that it needs
802 // to reload.
803 startLoaderFromBackground();
804 }
805
Winson Chungf0c6ae02012-03-21 16:10:31 -0700806 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
807 synchronized (mLock) {
808 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
809 // mWorkspaceLoaded to true later
810 stopLoaderLocked();
811 if (resetAllAppsLoaded) mAllAppsLoaded = false;
812 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
813 }
814 }
815
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700816 /**
817 * When the launcher is in the background, it's possible for it to miss paired
818 * configuration changes. So whenever we trigger the loader from the background
819 * tell the launcher that it needs to re-run the loader when it comes back instead
820 * of doing it now.
821 */
822 public void startLoaderFromBackground() {
823 boolean runLoader = false;
824 if (mCallbacks != null) {
825 Callbacks callbacks = mCallbacks.get();
826 if (callbacks != null) {
827 // Only actually run the loader if they're not paused.
828 if (!callbacks.setLoadOnResume()) {
829 runLoader = true;
830 }
831 }
832 }
833 if (runLoader) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700834 startLoader(false, -1);
Joe Onorato790c2d92010-06-11 00:14:11 -0700835 }
Joe Onorato36115782010-06-17 13:28:48 -0400836 }
Joe Onoratof99f8c12009-10-31 17:27:36 -0400837
Reena Lee93f824a2011-09-23 17:20:28 -0700838 // If there is already a loader task running, tell it to stop.
839 // returns true if isLaunching() was true on the old task
840 private boolean stopLoaderLocked() {
841 boolean isLaunching = false;
842 LoaderTask oldTask = mLoaderTask;
843 if (oldTask != null) {
844 if (oldTask.isLaunching()) {
845 isLaunching = true;
846 }
847 oldTask.stopLocked();
848 }
849 return isLaunching;
850 }
851
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700852 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Joe Onorato36115782010-06-17 13:28:48 -0400853 synchronized (mLock) {
854 if (DEBUG_LOADERS) {
855 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
856 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400857
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700858 // Clear any deferred bind-runnables from the synchronized load process
859 // We must do this before any loading/binding is scheduled below.
860 mDeferredBindRunnables.clear();
861
Joe Onorato36115782010-06-17 13:28:48 -0400862 // Don't bother to start the thread if we know it's not going to do anything
863 if (mCallbacks != null && mCallbacks.get() != null) {
864 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -0700865 // also, don't downgrade isLaunching if we're already running
866 isLaunching = isLaunching || stopLoaderLocked();
Winson Chungf0c6ae02012-03-21 16:10:31 -0700867 mLoaderTask = new LoaderTask(mApp, isLaunching);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700868 if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
869 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
870 } else {
871 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
872 sWorker.post(mLoaderTask);
873 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400874 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400875 }
876 }
877
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700878 void bindRemainingSynchronousPages() {
879 // Post the remaining side pages to be loaded
880 if (!mDeferredBindRunnables.isEmpty()) {
881 for (final Runnable r : mDeferredBindRunnables) {
882 mHandler.post(r);
883 }
884 mDeferredBindRunnables.clear();
885 }
886 }
887
Joe Onorato36115782010-06-17 13:28:48 -0400888 public void stopLoader() {
889 synchronized (mLock) {
890 if (mLoaderTask != null) {
891 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400892 }
893 }
Joe Onorato36115782010-06-17 13:28:48 -0400894 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400895
Michael Jurkac57b7a82011-08-09 22:02:20 -0700896 public boolean isAllAppsLoaded() {
897 return mAllAppsLoaded;
898 }
899
Winson Chung36a62fe2012-05-06 18:04:42 -0700900 boolean isLoadingWorkspace() {
901 synchronized (mLock) {
902 if (mLoaderTask != null) {
903 return mLoaderTask.isLoadingWorkspace();
904 }
905 }
906 return false;
907 }
908
Joe Onorato36115782010-06-17 13:28:48 -0400909 /**
910 * Runnable for the thread that loads the contents of the launcher:
911 * - workspace icons
912 * - widgets
913 * - all apps icons
914 */
915 private class LoaderTask implements Runnable {
916 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -0400917 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -0700918 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -0400919 private boolean mStopped;
920 private boolean mLoadAndBindStepFinished;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700921
Winson Chungc3eecff2011-07-11 17:44:15 -0700922 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -0400923
924 LoaderTask(Context context, boolean isLaunching) {
925 mContext = context;
926 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -0700927 mLabelCache = new HashMap<Object, CharSequence>();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400928 }
929
Joe Onorato36115782010-06-17 13:28:48 -0400930 boolean isLaunching() {
931 return mIsLaunching;
932 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400933
Winson Chung36a62fe2012-05-06 18:04:42 -0700934 boolean isLoadingWorkspace() {
935 return mIsLoadingAndBindingWorkspace;
936 }
937
Joe Onorato36115782010-06-17 13:28:48 -0400938 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -0700939 mIsLoadingAndBindingWorkspace = true;
940
Joe Onorato36115782010-06-17 13:28:48 -0400941 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -0400942 if (DEBUG_LOADERS) {
943 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400944 }
Michael Jurka288a36b2011-07-12 16:53:48 -0700945
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700946 if (!mWorkspaceLoaded) {
Joe Onorato36115782010-06-17 13:28:48 -0400947 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -0700948 synchronized (LoaderTask.this) {
949 if (mStopped) {
950 return;
951 }
952 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400953 }
954 }
955
Joe Onorato36115782010-06-17 13:28:48 -0400956 // Bind the workspace
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700957 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -0400958 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400959
Joe Onorato36115782010-06-17 13:28:48 -0400960 private void waitForIdle() {
961 // Wait until the either we're stopped or the other threads are done.
962 // This way we don't start loading all apps until the workspace has settled
963 // down.
964 synchronized (LoaderTask.this) {
965 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -0700966
Joe Onorato36115782010-06-17 13:28:48 -0400967 mHandler.postIdle(new Runnable() {
968 public void run() {
969 synchronized (LoaderTask.this) {
970 mLoadAndBindStepFinished = true;
971 if (DEBUG_LOADERS) {
972 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -0400973 }
Joe Onorato36115782010-06-17 13:28:48 -0400974 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -0400975 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400976 }
Joe Onorato36115782010-06-17 13:28:48 -0400977 });
978
979 while (!mStopped && !mLoadAndBindStepFinished) {
980 try {
981 this.wait();
982 } catch (InterruptedException ex) {
983 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -0400984 }
985 }
Joe Onorato36115782010-06-17 13:28:48 -0400986 if (DEBUG_LOADERS) {
987 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -0700988 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -0400989 + "ms for previous step to finish binding");
990 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400991 }
Joe Onorato36115782010-06-17 13:28:48 -0400992 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400993
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700994 void runBindSynchronousPage(int synchronousBindPage) {
995 if (synchronousBindPage < 0) {
996 // Ensure that we have a valid page index to load synchronously
997 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
998 "valid page index");
999 }
1000 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1001 // Ensure that we don't try and bind a specified page when the pages have not been
1002 // loaded already (we should load everything asynchronously in that case)
1003 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1004 }
1005 synchronized (mLock) {
1006 if (mIsLoaderTaskRunning) {
1007 // Ensure that we are never running the background loading at this point since
1008 // we also touch the background collections
1009 throw new RuntimeException("Error! Background loading is already running");
1010 }
1011 }
1012
1013 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1014 // data structures, we can't allow any other thread to touch that data, but because
1015 // this call is synchronous, we can get away with not locking).
1016
1017 // Divide the set of loaded items into those that we are binding synchronously, and
1018 // everything else that is to be bound normally (asynchronously).
1019 bindWorkspace(synchronousBindPage);
1020 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1021 // arise from that.
1022 onlyBindAllApps();
1023 }
1024
Joe Onorato36115782010-06-17 13:28:48 -04001025 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001026 synchronized (mLock) {
1027 mIsLoaderTaskRunning = true;
1028 }
Joe Onorato36115782010-06-17 13:28:48 -04001029 // Optimize for end-user experience: if the Launcher is up and // running with the
1030 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1031 // workspace first (default).
1032 final Callbacks cbk = mCallbacks.get();
1033 final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
Daniel Sandler843e8602010-06-07 14:59:01 -04001034
Joe Onorato36115782010-06-17 13:28:48 -04001035 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001036 // Elevate priority when Home launches for the first time to avoid
1037 // starving at boot time. Staring at a blank home is not cool.
1038 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001039 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1040 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001041 android.os.Process.setThreadPriority(mIsLaunching
1042 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1043 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001044 if (loadWorkspaceFirst) {
1045 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
1046 loadAndBindWorkspace();
1047 } else {
1048 if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
Joe Onoratocc67f472010-06-08 10:54:30 -07001049 loadAndBindAllApps();
Daniel Sandler843e8602010-06-07 14:59:01 -04001050 }
1051
Joe Onorato36115782010-06-17 13:28:48 -04001052 if (mStopped) {
1053 break keep_running;
1054 }
1055
1056 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1057 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001058 synchronized (mLock) {
1059 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001060 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001061 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1062 }
1063 }
Joe Onorato36115782010-06-17 13:28:48 -04001064 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001065
1066 // second step
1067 if (loadWorkspaceFirst) {
1068 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
Joe Onoratocc67f472010-06-08 10:54:30 -07001069 loadAndBindAllApps();
Daniel Sandler843e8602010-06-07 14:59:01 -04001070 } else {
1071 if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
1072 loadAndBindWorkspace();
1073 }
Winson Chung7ed37742011-09-08 15:45:51 -07001074
1075 // Restore the default thread priority after we are done loading items
1076 synchronized (mLock) {
1077 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1078 }
Joe Onorato36115782010-06-17 13:28:48 -04001079 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001080
Winson Chungaac01e12011-08-17 10:37:13 -07001081
1082 // Update the saved icons if necessary
1083 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001084 synchronized (mBgLock) {
1085 for (Object key : sBgDbIconCache.keySet()) {
1086 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1087 }
1088 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001089 }
Winson Chungaac01e12011-08-17 10:37:13 -07001090
Joe Onorato36115782010-06-17 13:28:48 -04001091 // Clear out this reference, otherwise we end up holding it until all of the
1092 // callback runnables are done.
1093 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001094
Joe Onorato36115782010-06-17 13:28:48 -04001095 synchronized (mLock) {
1096 // If we are still the last one to be scheduled, remove ourselves.
1097 if (mLoaderTask == this) {
1098 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001099 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001100 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001101 }
Joe Onorato36115782010-06-17 13:28:48 -04001102 }
1103
1104 public void stopLocked() {
1105 synchronized (LoaderTask.this) {
1106 mStopped = true;
1107 this.notify();
1108 }
1109 }
1110
1111 /**
1112 * Gets the callbacks object. If we've been stopped, or if the launcher object
1113 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1114 * object that was around when the deferred message was scheduled, and if there's
1115 * a new Callbacks object around then also return null. This will save us from
1116 * calling onto it with data that will be ignored.
1117 */
1118 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1119 synchronized (mLock) {
1120 if (mStopped) {
1121 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001122 }
Joe Onorato36115782010-06-17 13:28:48 -04001123
1124 if (mCallbacks == null) {
1125 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001126 }
Joe Onorato36115782010-06-17 13:28:48 -04001127
1128 final Callbacks callbacks = mCallbacks.get();
1129 if (callbacks != oldCallbacks) {
1130 return null;
1131 }
1132 if (callbacks == null) {
1133 Log.w(TAG, "no mCallbacks");
1134 return null;
1135 }
1136
1137 return callbacks;
1138 }
1139 }
1140
1141 // check & update map of what's occupied; used to discard overlapping/invalid items
1142 private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001143 int containerIndex = item.screen;
1144 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001145 // Return early if we detect that an item is under the hotseat button
Andrew Flynn0dca1ec2012-02-29 13:33:22 -08001146 if (mCallbacks == null || mCallbacks.get().isAllAppsButtonRank(item.screen)) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001147 return false;
1148 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001149
1150 // We use the last index to refer to the hotseat and the screen as the rank, so
1151 // test and update the occupied state accordingly
1152 if (occupied[Launcher.SCREEN_COUNT][item.screen][0] != null) {
1153 Log.e(TAG, "Error loading shortcut into hotseat " + item
1154 + " into position (" + item.screen + ":" + item.cellX + "," + item.cellY
1155 + ") occupied by " + occupied[Launcher.SCREEN_COUNT][item.screen][0]);
1156 return false;
1157 } else {
1158 occupied[Launcher.SCREEN_COUNT][item.screen][0] = item;
1159 return true;
1160 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001161 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1162 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001163 return true;
1164 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001165
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001166 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001167 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1168 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001169 if (occupied[containerIndex][x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001170 Log.e(TAG, "Error loading shortcut " + item
Winson Chungf30ad5f2011-08-08 10:55:42 -07001171 + " into cell (" + containerIndex + "-" + item.screen + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001172 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001173 + ") occupied by "
Winson Chungf30ad5f2011-08-08 10:55:42 -07001174 + occupied[containerIndex][x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001175 return false;
1176 }
1177 }
1178 }
1179 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1180 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001181 occupied[containerIndex][x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001182 }
1183 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001184
Joe Onorato36115782010-06-17 13:28:48 -04001185 return true;
1186 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001187
Joe Onorato36115782010-06-17 13:28:48 -04001188 private void loadWorkspace() {
1189 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001190
Joe Onorato36115782010-06-17 13:28:48 -04001191 final Context context = mContext;
1192 final ContentResolver contentResolver = context.getContentResolver();
1193 final PackageManager manager = context.getPackageManager();
1194 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1195 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001196
Michael Jurkab85f8a42012-04-25 15:48:32 -07001197 // Make sure the default workspace is loaded, if needed
1198 mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary();
1199
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001200 synchronized (mBgLock) {
1201 sBgWorkspaceItems.clear();
1202 sBgAppWidgets.clear();
1203 sBgFolders.clear();
1204 sBgItemsIdMap.clear();
1205 sBgDbIconCache.clear();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001206
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001207 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001208
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001209 final Cursor c = contentResolver.query(
1210 LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001211
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001212 // +1 for the hotseat (it can be larger than the workspace)
1213 // Load workspace in reverse order to ensure that latest items are loaded first (and
1214 // before any earlier duplicates)
1215 final ItemInfo occupied[][][] =
1216 new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1];
Joe Onorato9c1289c2009-08-17 11:03:03 -04001217
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001218 try {
1219 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1220 final int intentIndex = c.getColumnIndexOrThrow
1221 (LauncherSettings.Favorites.INTENT);
1222 final int titleIndex = c.getColumnIndexOrThrow
1223 (LauncherSettings.Favorites.TITLE);
1224 final int iconTypeIndex = c.getColumnIndexOrThrow(
1225 LauncherSettings.Favorites.ICON_TYPE);
1226 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1227 final int iconPackageIndex = c.getColumnIndexOrThrow(
1228 LauncherSettings.Favorites.ICON_PACKAGE);
1229 final int iconResourceIndex = c.getColumnIndexOrThrow(
1230 LauncherSettings.Favorites.ICON_RESOURCE);
1231 final int containerIndex = c.getColumnIndexOrThrow(
1232 LauncherSettings.Favorites.CONTAINER);
1233 final int itemTypeIndex = c.getColumnIndexOrThrow(
1234 LauncherSettings.Favorites.ITEM_TYPE);
1235 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1236 LauncherSettings.Favorites.APPWIDGET_ID);
1237 final int screenIndex = c.getColumnIndexOrThrow(
1238 LauncherSettings.Favorites.SCREEN);
1239 final int cellXIndex = c.getColumnIndexOrThrow
1240 (LauncherSettings.Favorites.CELLX);
1241 final int cellYIndex = c.getColumnIndexOrThrow
1242 (LauncherSettings.Favorites.CELLY);
1243 final int spanXIndex = c.getColumnIndexOrThrow
1244 (LauncherSettings.Favorites.SPANX);
1245 final int spanYIndex = c.getColumnIndexOrThrow(
1246 LauncherSettings.Favorites.SPANY);
1247 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1248 //final int displayModeIndex = c.getColumnIndexOrThrow(
1249 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001250
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001251 ShortcutInfo info;
1252 String intentDescription;
1253 LauncherAppWidgetInfo appWidgetInfo;
1254 int container;
1255 long id;
1256 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001257
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001258 while (!mStopped && c.moveToNext()) {
1259 try {
1260 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001261
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001262 switch (itemType) {
1263 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1264 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1265 intentDescription = c.getString(intentIndex);
1266 try {
1267 intent = Intent.parseUri(intentDescription, 0);
1268 } catch (URISyntaxException e) {
1269 continue;
1270 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001271
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001272 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1273 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1274 titleIndex, mLabelCache);
1275 } else {
1276 info = getShortcutInfo(c, context, iconTypeIndex,
1277 iconPackageIndex, iconResourceIndex, iconIndex,
1278 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001279
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001280 // App shortcuts that used to be automatically added to Launcher
1281 // didn't always have the correct intent flags set, so do that
1282 // here
1283 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001284 intent.getCategories() != null &&
1285 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001286 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001287 intent.addFlags(
1288 Intent.FLAG_ACTIVITY_NEW_TASK |
1289 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1290 }
Michael Jurka96879562012-03-22 05:54:33 -07001291 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001292
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001293 if (info != null) {
1294 info.intent = intent;
1295 info.id = c.getLong(idIndex);
1296 container = c.getInt(containerIndex);
1297 info.container = container;
1298 info.screen = c.getInt(screenIndex);
1299 info.cellX = c.getInt(cellXIndex);
1300 info.cellY = c.getInt(cellYIndex);
1301
1302 // check & update map of what's occupied
1303 if (!checkItemPlacement(occupied, info)) {
1304 break;
1305 }
1306
1307 switch (container) {
1308 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1309 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1310 sBgWorkspaceItems.add(info);
1311 break;
1312 default:
1313 // Item is in a user folder
1314 FolderInfo folderInfo =
1315 findOrMakeFolder(sBgFolders, container);
1316 folderInfo.add(info);
1317 break;
1318 }
1319 sBgItemsIdMap.put(info.id, info);
1320
1321 // now that we've loaded everthing re-save it with the
1322 // icon in case it disappears somehow.
1323 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
1324 } else {
1325 // Failed to load the shortcut, probably because the
1326 // activity manager couldn't resolve it (maybe the app
1327 // was uninstalled), or the db row was somehow screwed up.
1328 // Delete it.
1329 id = c.getLong(idIndex);
1330 Log.e(TAG, "Error loading shortcut " + id + ", removing it");
1331 contentResolver.delete(LauncherSettings.Favorites.getContentUri(
1332 id, false), null, null);
1333 }
1334 break;
1335
1336 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1337 id = c.getLong(idIndex);
1338 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1339
1340 folderInfo.title = c.getString(titleIndex);
1341 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001342 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001343 folderInfo.container = container;
1344 folderInfo.screen = c.getInt(screenIndex);
1345 folderInfo.cellX = c.getInt(cellXIndex);
1346 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001347
Daniel Sandler8802e962010-05-26 16:28:16 -04001348 // check & update map of what's occupied
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001349 if (!checkItemPlacement(occupied, folderInfo)) {
Daniel Sandler8802e962010-05-26 16:28:16 -04001350 break;
1351 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001352 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001353 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1354 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1355 sBgWorkspaceItems.add(folderInfo);
1356 break;
Joe Onorato36115782010-06-17 13:28:48 -04001357 }
Joe Onorato17a89222011-02-08 17:26:11 -08001358
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001359 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1360 sBgFolders.put(folderInfo.id, folderInfo);
1361 break;
1362
1363 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1364 // Read all Launcher-specific widget details
1365 int appWidgetId = c.getInt(appWidgetIdIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001366 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001367
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001368 final AppWidgetProviderInfo provider =
1369 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001370
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001371 if (!isSafeMode && (provider == null || provider.provider == null ||
1372 provider.provider.getPackageName() == null)) {
1373 String log = "Deleting widget that isn't installed anymore: id="
1374 + id + " appWidgetId=" + appWidgetId;
1375 Log.e(TAG, log);
1376 Launcher.sDumpLogs.add(log);
1377 itemsToRemove.add(id);
1378 } else {
1379 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1380 provider.provider);
1381 appWidgetInfo.id = id;
1382 appWidgetInfo.screen = c.getInt(screenIndex);
1383 appWidgetInfo.cellX = c.getInt(cellXIndex);
1384 appWidgetInfo.cellY = c.getInt(cellYIndex);
1385 appWidgetInfo.spanX = c.getInt(spanXIndex);
1386 appWidgetInfo.spanY = c.getInt(spanYIndex);
1387 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1388 appWidgetInfo.minSpanX = minSpan[0];
1389 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001390
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001391 container = c.getInt(containerIndex);
1392 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1393 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1394 Log.e(TAG, "Widget found where container != " +
1395 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1396 continue;
1397 }
1398 appWidgetInfo.container = c.getInt(containerIndex);
1399
1400 // check & update map of what's occupied
1401 if (!checkItemPlacement(occupied, appWidgetInfo)) {
1402 break;
1403 }
1404 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1405 sBgAppWidgets.add(appWidgetInfo);
1406 }
Joe Onorato36115782010-06-17 13:28:48 -04001407 break;
1408 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001409 } catch (Exception e) {
1410 Log.w(TAG, "Desktop items loading interrupted:", e);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001411 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001412 }
1413 } finally {
1414 c.close();
1415 }
1416
1417 if (itemsToRemove.size() > 0) {
1418 ContentProviderClient client = contentResolver.acquireContentProviderClient(
1419 LauncherSettings.Favorites.CONTENT_URI);
1420 // Remove dead items
1421 for (long id : itemsToRemove) {
1422 if (DEBUG_LOADERS) {
1423 Log.d(TAG, "Removed id = " + id);
1424 }
1425 // Don't notify content observers
1426 try {
1427 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1428 null, null);
1429 } catch (RemoteException e) {
1430 Log.w(TAG, "Could not remove id = " + id);
1431 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001432 }
1433 }
1434
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001435 if (DEBUG_LOADERS) {
1436 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1437 Log.d(TAG, "workspace layout: ");
1438 for (int y = 0; y < mCellCountY; y++) {
1439 String line = "";
1440 for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
1441 if (s > 0) {
1442 line += " | ";
1443 }
1444 for (int x = 0; x < mCellCountX; x++) {
1445 line += ((occupied[s][x][y] != null) ? "#" : ".");
1446 }
Joe Onorato36115782010-06-17 13:28:48 -04001447 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001448 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04001449 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001450 }
Joe Onorato36115782010-06-17 13:28:48 -04001451 }
1452 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001453
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001454 /** Filters the set of items who are directly or indirectly (via another container) on the
1455 * specified screen. */
1456 private void filterCurrentWorkspaceItems(int currentScreen,
1457 ArrayList<ItemInfo> allWorkspaceItems,
1458 ArrayList<ItemInfo> currentScreenItems,
1459 ArrayList<ItemInfo> otherScreenItems) {
1460 // If we aren't filtering on a screen, then the set of items to load is the full set of
1461 // items given.
1462 if (currentScreen < 0) {
1463 currentScreenItems.addAll(allWorkspaceItems);
Joe Onorato36115782010-06-17 13:28:48 -04001464 }
1465
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001466 // Order the set of items by their containers first, this allows use to walk through the
1467 // list sequentially, build up a list of containers that are in the specified screen,
1468 // as well as all items in those containers.
1469 Set<Long> itemsOnScreen = new HashSet<Long>();
1470 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1471 @Override
1472 public int compare(ItemInfo lhs, ItemInfo rhs) {
1473 return (int) (lhs.container - rhs.container);
1474 }
1475 });
1476 for (ItemInfo info : allWorkspaceItems) {
1477 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1478 if (info.screen == currentScreen) {
1479 currentScreenItems.add(info);
1480 itemsOnScreen.add(info.id);
1481 } else {
1482 otherScreenItems.add(info);
1483 }
1484 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1485 currentScreenItems.add(info);
1486 itemsOnScreen.add(info.id);
1487 } else {
1488 if (itemsOnScreen.contains(info.container)) {
1489 currentScreenItems.add(info);
1490 itemsOnScreen.add(info.id);
1491 } else {
1492 otherScreenItems.add(info);
1493 }
1494 }
1495 }
1496 }
1497
1498 /** Filters the set of widgets which are on the specified screen. */
1499 private void filterCurrentAppWidgets(int currentScreen,
1500 ArrayList<LauncherAppWidgetInfo> appWidgets,
1501 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1502 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1503 // If we aren't filtering on a screen, then the set of items to load is the full set of
1504 // widgets given.
1505 if (currentScreen < 0) {
1506 currentScreenWidgets.addAll(appWidgets);
1507 }
1508
1509 for (LauncherAppWidgetInfo widget : appWidgets) {
1510 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1511 widget.screen == currentScreen) {
1512 currentScreenWidgets.add(widget);
1513 } else {
1514 otherScreenWidgets.add(widget);
1515 }
1516 }
1517 }
1518
1519 /** Filters the set of folders which are on the specified screen. */
1520 private void filterCurrentFolders(int currentScreen,
1521 HashMap<Long, ItemInfo> itemsIdMap,
1522 HashMap<Long, FolderInfo> folders,
1523 HashMap<Long, FolderInfo> currentScreenFolders,
1524 HashMap<Long, FolderInfo> otherScreenFolders) {
1525 // If we aren't filtering on a screen, then the set of items to load is the full set of
1526 // widgets given.
1527 if (currentScreen < 0) {
1528 currentScreenFolders.putAll(folders);
1529 }
1530
1531 for (long id : folders.keySet()) {
1532 ItemInfo info = itemsIdMap.get(id);
1533 FolderInfo folder = folders.get(id);
1534 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1535 info.screen == currentScreen) {
1536 currentScreenFolders.put(id, folder);
1537 } else {
1538 otherScreenFolders.put(id, folder);
1539 }
1540 }
1541 }
1542
1543 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
1544 * right) */
1545 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
1546 // XXX: review this
1547 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07001548 @Override
1549 public int compare(ItemInfo lhs, ItemInfo rhs) {
1550 int cellCountX = LauncherModel.getCellCountX();
1551 int cellCountY = LauncherModel.getCellCountY();
1552 int screenOffset = cellCountX * cellCountY;
1553 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
1554 long lr = (lhs.container * containerOffset + lhs.screen * screenOffset +
1555 lhs.cellY * cellCountX + lhs.cellX);
1556 long rr = (rhs.container * containerOffset + rhs.screen * screenOffset +
1557 rhs.cellY * cellCountX + rhs.cellX);
1558 return (int) (lr - rr);
1559 }
1560 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001561 }
Winson Chungdb8a8942012-04-03 14:08:41 -07001562
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001563 private void bindWorkspaceItems(final Callbacks oldCallbacks,
1564 final ArrayList<ItemInfo> workspaceItems,
1565 final ArrayList<LauncherAppWidgetInfo> appWidgets,
1566 final HashMap<Long, FolderInfo> folders,
1567 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07001568
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001569 final boolean postOnMainThread = (deferredBindRunnables != null);
1570
1571 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07001572 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001573 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04001574 final int start = i;
1575 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001576 final Runnable r = new Runnable() {
1577 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04001578 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08001579 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001580 if (callbacks != null) {
Winson Chung603bcb92011-09-02 11:45:39 -07001581 callbacks.bindItems(workspaceItems, start, start+chunkSize);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001582 }
1583 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001584 };
1585 if (postOnMainThread) {
1586 deferredBindRunnables.add(r);
1587 } else {
1588 runOnMainThread(r);
1589 }
Joe Onorato36115782010-06-17 13:28:48 -04001590 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001591
1592 // Bind the folders
1593 if (!folders.isEmpty()) {
1594 final Runnable r = new Runnable() {
1595 public void run() {
1596 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1597 if (callbacks != null) {
1598 callbacks.bindFolders(folders);
1599 }
1600 }
1601 };
1602 if (postOnMainThread) {
1603 deferredBindRunnables.add(r);
1604 } else {
1605 runOnMainThread(r);
1606 }
1607 }
1608
1609 // Bind the widgets, one at a time
1610 N = appWidgets.size();
1611 for (int i = 0; i < N; i++) {
1612 final LauncherAppWidgetInfo widget = appWidgets.get(i);
1613 final Runnable r = new Runnable() {
1614 public void run() {
1615 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1616 if (callbacks != null) {
1617 callbacks.bindAppWidget(widget);
1618 }
1619 }
1620 };
1621 if (postOnMainThread) {
1622 deferredBindRunnables.add(r);
1623 } else {
1624 runOnMainThread(r);
1625 }
1626 }
1627 }
1628
1629 /**
1630 * Binds all loaded data to actual views on the main thread.
1631 */
1632 private void bindWorkspace(int synchronizeBindPage) {
1633 final long t = SystemClock.uptimeMillis();
1634 Runnable r;
1635
1636 // Don't use these two variables in any of the callback runnables.
1637 // Otherwise we hold a reference to them.
1638 final Callbacks oldCallbacks = mCallbacks.get();
1639 if (oldCallbacks == null) {
1640 // This launcher has exited and nobody bothered to tell us. Just bail.
1641 Log.w(TAG, "LoaderTask running with no launcher");
1642 return;
1643 }
1644
1645 final int currentScreen = (synchronizeBindPage > -1) ? synchronizeBindPage :
1646 oldCallbacks.getCurrentWorkspaceScreen();
1647
1648 // Load all the items that are on the current page first (and in the process, unbind
1649 // all the existing workspace items before we call startBinding() below.
1650 unbindWorkspaceItemsOnMainThread();
1651 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
1652 ArrayList<LauncherAppWidgetInfo> appWidgets =
1653 new ArrayList<LauncherAppWidgetInfo>();
1654 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
1655 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
1656 synchronized (mBgLock) {
1657 workspaceItems.addAll(sBgWorkspaceItems);
1658 appWidgets.addAll(sBgAppWidgets);
1659 folders.putAll(sBgFolders);
1660 itemsIdMap.putAll(sBgItemsIdMap);
1661 }
1662
1663 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
1664 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
1665 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
1666 new ArrayList<LauncherAppWidgetInfo>();
1667 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
1668 new ArrayList<LauncherAppWidgetInfo>();
1669 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
1670 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
1671
1672 // Separate the items that are on the current screen, and all the other remaining items
1673 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
1674 otherWorkspaceItems);
1675 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
1676 otherAppWidgets);
1677 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
1678 otherFolders);
1679 sortWorkspaceItemsSpatially(currentWorkspaceItems);
1680 sortWorkspaceItemsSpatially(otherWorkspaceItems);
1681
1682 // Tell the workspace that we're about to start binding items
1683 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001684 public void run() {
1685 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1686 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001687 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04001688 }
1689 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001690 };
1691 runOnMainThread(r);
1692
1693 // Load items on the current page
1694 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
1695 currentFolders, null);
1696
1697 // Load all the remaining pages
1698 mDeferredBindRunnables.clear();
1699 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
1700 mDeferredBindRunnables);
1701
1702 // Tell the workspace that we're done binding items
1703 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001704 public void run() {
1705 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1706 if (callbacks != null) {
1707 callbacks.finishBindingItems();
1708 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001709
Winson Chung98e030b2012-05-07 16:01:11 -07001710 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04001711 if (DEBUG_LOADERS) {
1712 Log.d(TAG, "bound workspace in "
1713 + (SystemClock.uptimeMillis()-t) + "ms");
1714 }
Winson Chung36a62fe2012-05-06 18:04:42 -07001715
1716 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04001717 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001718 };
1719 mDeferredBindRunnables.add(r);
Joe Onorato36115782010-06-17 13:28:48 -04001720 }
Joe Onoratocc67f472010-06-08 10:54:30 -07001721
Joe Onorato36115782010-06-17 13:28:48 -04001722 private void loadAndBindAllApps() {
1723 if (DEBUG_LOADERS) {
1724 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
1725 }
1726 if (!mAllAppsLoaded) {
1727 loadAllAppsByBatch();
Reena Lee93f824a2011-09-23 17:20:28 -07001728 synchronized (LoaderTask.this) {
1729 if (mStopped) {
1730 return;
1731 }
1732 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07001733 }
Joe Onorato36115782010-06-17 13:28:48 -04001734 } else {
1735 onlyBindAllApps();
1736 }
1737 }
Joe Onoratocc67f472010-06-08 10:54:30 -07001738
Joe Onorato36115782010-06-17 13:28:48 -04001739 private void onlyBindAllApps() {
1740 final Callbacks oldCallbacks = mCallbacks.get();
1741 if (oldCallbacks == null) {
1742 // This launcher has exited and nobody bothered to tell us. Just bail.
1743 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
1744 return;
1745 }
1746
1747 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07001748 @SuppressWarnings("unchecked")
Joe Onorato36115782010-06-17 13:28:48 -04001749 final ArrayList<ApplicationInfo> list
Adam Cohen487f7dd2012-06-28 18:12:10 -07001750 = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Joe Onorato36115782010-06-17 13:28:48 -04001751 mHandler.post(new Runnable() {
1752 public void run() {
1753 final long t = SystemClock.uptimeMillis();
1754 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1755 if (callbacks != null) {
1756 callbacks.bindAllApplications(list);
1757 }
1758 if (DEBUG_LOADERS) {
1759 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
1760 + (SystemClock.uptimeMillis()-t) + "ms");
1761 }
1762 }
1763 });
Joe Onorato36115782010-06-17 13:28:48 -04001764 }
1765
1766 private void loadAllAppsByBatch() {
1767 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1768
1769 // Don't use these two variables in any of the callback runnables.
1770 // Otherwise we hold a reference to them.
1771 final Callbacks oldCallbacks = mCallbacks.get();
1772 if (oldCallbacks == null) {
1773 // This launcher has exited and nobody bothered to tell us. Just bail.
1774 Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
1775 return;
1776 }
1777
1778 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1779 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1780
1781 final PackageManager packageManager = mContext.getPackageManager();
1782 List<ResolveInfo> apps = null;
1783
1784 int N = Integer.MAX_VALUE;
1785
1786 int startIndex;
1787 int i=0;
1788 int batchSize = -1;
1789 while (i < N && !mStopped) {
1790 if (i == 0) {
Adam Cohen487f7dd2012-06-28 18:12:10 -07001791 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04001792 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1793 apps = packageManager.queryIntentActivities(mainIntent, 0);
1794 if (DEBUG_LOADERS) {
1795 Log.d(TAG, "queryIntentActivities took "
1796 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
1797 }
1798 if (apps == null) {
1799 return;
1800 }
1801 N = apps.size();
1802 if (DEBUG_LOADERS) {
1803 Log.d(TAG, "queryIntentActivities got " + N + " apps");
1804 }
1805 if (N == 0) {
1806 // There are no apps?!?
1807 return;
1808 }
1809 if (mBatchSize == 0) {
1810 batchSize = N;
1811 } else {
1812 batchSize = mBatchSize;
1813 }
1814
1815 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1816 Collections.sort(apps,
Winson Chungc3eecff2011-07-11 17:44:15 -07001817 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
Joe Onorato36115782010-06-17 13:28:48 -04001818 if (DEBUG_LOADERS) {
1819 Log.d(TAG, "sort took "
1820 + (SystemClock.uptimeMillis()-sortTime) + "ms");
1821 }
1822 }
1823
1824 final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1825
1826 startIndex = i;
1827 for (int j=0; i<N && j<batchSize; j++) {
1828 // This builds the icon bitmaps.
Adam Cohen487f7dd2012-06-28 18:12:10 -07001829 mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
Michael Jurkac9d95c52011-08-29 14:03:34 -07001830 mIconCache, mLabelCache));
Joe Onorato36115782010-06-17 13:28:48 -04001831 i++;
1832 }
1833
1834 final boolean first = i <= batchSize;
1835 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Adam Cohen487f7dd2012-06-28 18:12:10 -07001836 final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
1837 mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04001838
Joe Onoratocc67f472010-06-08 10:54:30 -07001839 mHandler.post(new Runnable() {
1840 public void run() {
1841 final long t = SystemClock.uptimeMillis();
Joe Onoratocc67f472010-06-08 10:54:30 -07001842 if (callbacks != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001843 if (first) {
1844 callbacks.bindAllApplications(added);
1845 } else {
1846 callbacks.bindAppsAdded(added);
1847 }
1848 if (DEBUG_LOADERS) {
1849 Log.d(TAG, "bound " + added.size() + " apps in "
1850 + (SystemClock.uptimeMillis() - t) + "ms");
1851 }
1852 } else {
1853 Log.i(TAG, "not binding apps: no Launcher activity");
Joe Onoratocc67f472010-06-08 10:54:30 -07001854 }
1855 }
1856 });
1857
Daniel Sandlerdca66122010-04-13 16:23:58 -04001858 if (DEBUG_LOADERS) {
Joe Onorato36115782010-06-17 13:28:48 -04001859 Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
1860 + (SystemClock.uptimeMillis()-t2) + "ms");
1861 }
1862
1863 if (mAllAppsLoadDelay > 0 && i < N) {
1864 try {
1865 if (DEBUG_LOADERS) {
1866 Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
1867 }
1868 Thread.sleep(mAllAppsLoadDelay);
1869 } catch (InterruptedException exc) { }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001870 }
1871 }
1872
Joe Onorato36115782010-06-17 13:28:48 -04001873 if (DEBUG_LOADERS) {
1874 Log.d(TAG, "cached all " + N + " apps in "
1875 + (SystemClock.uptimeMillis()-t) + "ms"
1876 + (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
Joe Onoratobe386092009-11-17 17:32:16 -08001877 }
1878 }
1879
1880 public void dumpState() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001881 synchronized (mBgLock) {
1882 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
1883 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
1884 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
1885 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
1886 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
1887 }
Joe Onorato36115782010-06-17 13:28:48 -04001888 }
1889 }
1890
1891 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07001892 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04001893 }
1894
1895 private class PackageUpdatedTask implements Runnable {
1896 int mOp;
1897 String[] mPackages;
1898
1899 public static final int OP_NONE = 0;
1900 public static final int OP_ADD = 1;
1901 public static final int OP_UPDATE = 2;
1902 public static final int OP_REMOVE = 3; // uninstlled
1903 public static final int OP_UNAVAILABLE = 4; // external media unmounted
1904
1905
1906 public PackageUpdatedTask(int op, String[] packages) {
1907 mOp = op;
1908 mPackages = packages;
1909 }
1910
1911 public void run() {
1912 final Context context = mApp;
1913
1914 final String[] packages = mPackages;
1915 final int N = packages.length;
1916 switch (mOp) {
1917 case OP_ADD:
1918 for (int i=0; i<N; i++) {
1919 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07001920 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04001921 }
1922 break;
1923 case OP_UPDATE:
1924 for (int i=0; i<N; i++) {
1925 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07001926 mBgAllAppsList.updatePackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04001927 }
1928 break;
1929 case OP_REMOVE:
1930 case OP_UNAVAILABLE:
1931 for (int i=0; i<N; i++) {
1932 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07001933 mBgAllAppsList.removePackage(packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04001934 }
1935 break;
1936 }
1937
1938 ArrayList<ApplicationInfo> added = null;
Joe Onorato36115782010-06-17 13:28:48 -04001939 ArrayList<ApplicationInfo> modified = null;
1940
Adam Cohen487f7dd2012-06-28 18:12:10 -07001941 if (mBgAllAppsList.added.size() > 0) {
1942 added = mBgAllAppsList.added;
1943 mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04001944 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001945 if (mBgAllAppsList.modified.size() > 0) {
1946 modified = mBgAllAppsList.modified;
1947 mBgAllAppsList.modified = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04001948 }
1949
Winson Chungcd810732012-06-18 16:45:43 -07001950 // We may be removing packages that have no associated launcher application, so we
1951 // pass through the removed package names directly.
1952 // NOTE: We flush the icon cache aggressively in removePackage() above.
1953 final ArrayList<String> removedPackageNames = new ArrayList<String>();
1954 for (int i = 0; i < N; ++i) {
1955 removedPackageNames.add(packages[i]);
1956 }
1957
Joe Onorato36115782010-06-17 13:28:48 -04001958 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
1959 if (callbacks == null) {
1960 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
1961 return;
1962 }
1963
1964 if (added != null) {
1965 final ArrayList<ApplicationInfo> addedFinal = added;
1966 mHandler.post(new Runnable() {
1967 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07001968 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1969 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001970 callbacks.bindAppsAdded(addedFinal);
1971 }
1972 }
1973 });
1974 }
1975 if (modified != null) {
1976 final ArrayList<ApplicationInfo> modifiedFinal = modified;
1977 mHandler.post(new Runnable() {
1978 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07001979 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1980 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001981 callbacks.bindAppsUpdated(modifiedFinal);
1982 }
1983 }
1984 });
1985 }
Winson Chungcd810732012-06-18 16:45:43 -07001986 if (!removedPackageNames.isEmpty()) {
Joe Onorato36115782010-06-17 13:28:48 -04001987 final boolean permanent = mOp != OP_UNAVAILABLE;
Joe Onorato36115782010-06-17 13:28:48 -04001988 mHandler.post(new Runnable() {
1989 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07001990 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1991 if (callbacks == cb && cb != null) {
Winson Chungcd810732012-06-18 16:45:43 -07001992 callbacks.bindAppsRemoved(removedPackageNames, permanent);
Joe Onorato36115782010-06-17 13:28:48 -04001993 }
1994 }
1995 });
Joe Onoratobe386092009-11-17 17:32:16 -08001996 }
Winson Chung80baf5a2010-08-09 16:03:15 -07001997
1998 mHandler.post(new Runnable() {
1999 @Override
2000 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002001 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2002 if (callbacks == cb && cb != null) {
Winson Chung80baf5a2010-08-09 16:03:15 -07002003 callbacks.bindPackagesUpdated();
2004 }
2005 }
2006 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002007 }
2008 }
2009
2010 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002011 * This is called from the code that adds shortcuts from the intent receiver. This
2012 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002013 */
Joe Onorato56d82912010-03-07 14:32:10 -05002014 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002015 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002016 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002017
Joe Onorato56d82912010-03-07 14:32:10 -05002018 /**
2019 * Make an ShortcutInfo object for a shortcut that is an application.
2020 *
2021 * If c is not null, then it will be used to fill in missing data like the title and icon.
2022 */
2023 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002024 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002025 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002026 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002027
2028 ComponentName componentName = intent.getComponent();
2029 if (componentName == null) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002030 return null;
2031 }
2032
Adam Cohen00fcb492011-11-02 21:53:47 -07002033 try {
2034 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2035 if (!pi.applicationInfo.enabled) {
2036 // If we return null here, the corresponding item will be removed from the launcher
2037 // db and will not appear in the workspace.
2038 return null;
2039 }
2040 } catch (NameNotFoundException e) {
2041 Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
2042 }
2043
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002044 // TODO: See if the PackageManager knows about this case. If it doesn't
2045 // then return null & delete this.
2046
Joe Onorato56d82912010-03-07 14:32:10 -05002047 // the resource -- This may implicitly give us back the fallback icon,
2048 // but don't worry about that. All we're doing with usingFallbackIcon is
2049 // to avoid saving lots of copies of that in the database, and most apps
2050 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002051
2052 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2053 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2054 // via resolveActivity().
2055 ResolveInfo resolveInfo = null;
2056 ComponentName oldComponent = intent.getComponent();
2057 Intent newIntent = new Intent(intent.getAction(), null);
2058 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2059 newIntent.setPackage(oldComponent.getPackageName());
2060 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2061 for (ResolveInfo i : infos) {
2062 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2063 i.activityInfo.name);
2064 if (cn.equals(oldComponent)) {
2065 resolveInfo = i;
2066 }
2067 }
2068 if (resolveInfo == null) {
2069 resolveInfo = manager.resolveActivity(intent, 0);
2070 }
Joe Onorato56d82912010-03-07 14:32:10 -05002071 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002072 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002073 }
Joe Onorato56d82912010-03-07 14:32:10 -05002074 // the db
2075 if (icon == null) {
2076 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002077 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002078 }
2079 }
2080 // the fallback icon
2081 if (icon == null) {
2082 icon = getFallbackIcon();
2083 info.usingFallbackIcon = true;
2084 }
2085 info.setIcon(icon);
2086
2087 // from the resource
2088 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002089 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2090 if (labelCache != null && labelCache.containsKey(key)) {
2091 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002092 } else {
2093 info.title = resolveInfo.activityInfo.loadLabel(manager);
2094 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002095 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002096 }
2097 }
Joe Onorato56d82912010-03-07 14:32:10 -05002098 }
2099 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002100 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002101 if (c != null) {
2102 info.title = c.getString(titleIndex);
2103 }
2104 }
2105 // fall back to the class name of the activity
2106 if (info.title == null) {
2107 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002108 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002109 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2110 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002111 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002112
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002113 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002114 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002115 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002116 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002117 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2118 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002119
Joe Onorato56d82912010-03-07 14:32:10 -05002120 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002121 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002122 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002123
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002124 // TODO: If there's an explicit component and we can't install that, delete it.
2125
Joe Onorato56d82912010-03-07 14:32:10 -05002126 info.title = c.getString(titleIndex);
2127
Joe Onorato9c1289c2009-08-17 11:03:03 -04002128 int iconType = c.getInt(iconTypeIndex);
2129 switch (iconType) {
2130 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2131 String packageName = c.getString(iconPackageIndex);
2132 String resourceName = c.getString(iconResourceIndex);
2133 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002134 info.customIcon = false;
2135 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002136 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002137 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002138 if (resources != null) {
2139 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002140 icon = Utilities.createIconBitmap(
2141 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002142 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002143 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002144 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002145 }
Joe Onorato56d82912010-03-07 14:32:10 -05002146 // the db
2147 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002148 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002149 }
2150 // the fallback icon
2151 if (icon == null) {
2152 icon = getFallbackIcon();
2153 info.usingFallbackIcon = true;
2154 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002155 break;
2156 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002157 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002158 if (icon == null) {
2159 icon = getFallbackIcon();
2160 info.customIcon = false;
2161 info.usingFallbackIcon = true;
2162 } else {
2163 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002164 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002165 break;
2166 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002167 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002168 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002169 info.customIcon = false;
2170 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002171 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002172 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002173 return info;
2174 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002175
Michael Jurka931dc972011-08-05 15:08:15 -07002176 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002177 @SuppressWarnings("all") // suppress dead code warning
2178 final boolean debug = false;
2179 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002180 Log.d(TAG, "getIconFromCursor app="
2181 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2182 }
2183 byte[] data = c.getBlob(iconIndex);
2184 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002185 return Utilities.createIconBitmap(
2186 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002187 } catch (Exception e) {
2188 return null;
2189 }
2190 }
2191
Winson Chung3d503fb2011-07-13 17:25:49 -07002192 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2193 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002194 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002195 if (info == null) {
2196 return null;
2197 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002198 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002199
2200 return info;
2201 }
2202
Winson Chunga9abd0e2010-10-27 17:18:37 -07002203 /**
Winson Chung55cef262010-10-28 14:14:18 -07002204 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2205 */
2206 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2207 ComponentName component) {
2208 List<AppWidgetProviderInfo> widgets =
2209 AppWidgetManager.getInstance(context).getInstalledProviders();
2210 for (AppWidgetProviderInfo info : widgets) {
2211 if (info.provider.equals(component)) {
2212 return info;
2213 }
2214 }
2215 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002216 }
2217
Winson Chung68846fd2010-10-29 11:00:27 -07002218 /**
2219 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2220 */
2221 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2222 final PackageManager packageManager = context.getPackageManager();
2223 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2224 new ArrayList<WidgetMimeTypeHandlerData>();
2225
2226 final Intent supportsIntent =
2227 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2228 supportsIntent.setType(mimeType);
2229
2230 // Create a set of widget configuration components that we can test against
2231 final List<AppWidgetProviderInfo> widgets =
2232 AppWidgetManager.getInstance(context).getInstalledProviders();
2233 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2234 new HashMap<ComponentName, AppWidgetProviderInfo>();
2235 for (AppWidgetProviderInfo info : widgets) {
2236 configurationComponentToWidget.put(info.configure, info);
2237 }
2238
2239 // Run through each of the intents that can handle this type of clip data, and cross
2240 // reference them with the components that are actual configuration components
2241 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2242 PackageManager.MATCH_DEFAULT_ONLY);
2243 for (ResolveInfo info : activities) {
2244 final ActivityInfo activityInfo = info.activityInfo;
2245 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2246 activityInfo.name);
2247 if (configurationComponentToWidget.containsKey(infoComponent)) {
2248 supportedConfigurationActivities.add(
2249 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2250 configurationComponentToWidget.get(infoComponent)));
2251 }
2252 }
2253 return supportedConfigurationActivities;
2254 }
2255
Winson Chunga9abd0e2010-10-27 17:18:37 -07002256 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08002257 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2258 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2259 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2260
Adam Cohend9198822011-11-22 16:42:47 -08002261 if (intent == null) {
2262 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2263 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2264 return null;
2265 }
2266
Joe Onorato0589f0f2010-02-08 13:44:00 -08002267 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08002268 boolean customIcon = false;
2269 ShortcutIconResource iconResource = null;
2270
2271 if (bitmap != null && bitmap instanceof Bitmap) {
2272 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002273 customIcon = true;
2274 } else {
2275 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2276 if (extra != null && extra instanceof ShortcutIconResource) {
2277 try {
2278 iconResource = (ShortcutIconResource) extra;
2279 final PackageManager packageManager = context.getPackageManager();
2280 Resources resources = packageManager.getResourcesForApplication(
2281 iconResource.packageName);
2282 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002283 icon = Utilities.createIconBitmap(
2284 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002285 } catch (Exception e) {
2286 Log.w(TAG, "Could not load shortcut icon: " + extra);
2287 }
2288 }
2289 }
2290
Michael Jurkac9d95c52011-08-29 14:03:34 -07002291 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002292
2293 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002294 if (fallbackIcon != null) {
2295 icon = fallbackIcon;
2296 } else {
2297 icon = getFallbackIcon();
2298 info.usingFallbackIcon = true;
2299 }
Joe Onorato56d82912010-03-07 14:32:10 -05002300 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08002301 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05002302
Joe Onorato0589f0f2010-02-08 13:44:00 -08002303 info.title = name;
2304 info.intent = intent;
2305 info.customIcon = customIcon;
2306 info.iconResource = iconResource;
2307
2308 return info;
2309 }
2310
Winson Chungaac01e12011-08-17 10:37:13 -07002311 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2312 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08002313 // If apps can't be on SD, don't even bother.
2314 if (!mAppsCanBeOnExternalStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07002315 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08002316 }
Joe Onorato56d82912010-03-07 14:32:10 -05002317 // If this icon doesn't have a custom icon, check to see
2318 // what's stored in the DB, and if it doesn't match what
2319 // we're going to show, store what we are going to show back
2320 // into the DB. We do this so when we're loading, if the
2321 // package manager can't find an icon (for example because
2322 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07002323 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07002324 cache.put(info, c.getBlob(iconIndex));
2325 return true;
2326 }
2327 return false;
2328 }
2329 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2330 boolean needSave = false;
2331 try {
2332 if (data != null) {
2333 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2334 Bitmap loaded = info.getIcon(mIconCache);
2335 needSave = !saved.sameAs(loaded);
2336 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05002337 needSave = true;
2338 }
Winson Chungaac01e12011-08-17 10:37:13 -07002339 } catch (Exception e) {
2340 needSave = true;
2341 }
2342 if (needSave) {
2343 Log.d(TAG, "going to save icon bitmap for info=" + info);
2344 // This is slower than is ideal, but this only happens once
2345 // or when the app is updated with a new icon.
2346 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05002347 }
2348 }
2349
Joe Onorato9c1289c2009-08-17 11:03:03 -04002350 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07002351 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04002352 * or make a new one.
2353 */
Adam Cohendf2cc412011-04-27 16:56:57 -07002354 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002355 // See if a placeholder was created for us already
2356 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07002357 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002358 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07002359 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002360 folders.put(id, folderInfo);
2361 }
Adam Cohendf2cc412011-04-27 16:56:57 -07002362 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002363 }
2364
Joe Onorato9c1289c2009-08-17 11:03:03 -04002365 private static final Collator sCollator = Collator.getInstance();
Joe Onoratob0c27f22009-12-01 16:19:38 -08002366 public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
Joe Onorato9c1289c2009-08-17 11:03:03 -04002367 = new Comparator<ApplicationInfo>() {
2368 public final int compare(ApplicationInfo a, ApplicationInfo b) {
Michael Jurka5b1808d2011-07-11 19:59:46 -07002369 int result = sCollator.compare(a.title.toString(), b.title.toString());
2370 if (result == 0) {
2371 result = a.componentName.compareTo(b.componentName);
2372 }
2373 return result;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002374 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002375 };
Winson Chung78403fe2011-01-21 15:38:02 -08002376 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2377 = new Comparator<ApplicationInfo>() {
2378 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2379 if (a.firstInstallTime < b.firstInstallTime) return 1;
2380 if (a.firstInstallTime > b.firstInstallTime) return -1;
2381 return 0;
2382 }
2383 };
Winson Chung785d2eb2011-04-14 16:08:02 -07002384 public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
2385 = new Comparator<AppWidgetProviderInfo>() {
2386 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
2387 return sCollator.compare(a.label.toString(), b.label.toString());
2388 }
2389 };
Winson Chung5308f242011-08-18 12:12:41 -07002390 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
2391 if (info.activityInfo != null) {
2392 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
2393 } else {
2394 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
2395 }
2396 }
Winson Chung785d2eb2011-04-14 16:08:02 -07002397 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
2398 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07002399 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07002400 ShortcutNameComparator(PackageManager pm) {
2401 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07002402 mLabelCache = new HashMap<Object, CharSequence>();
2403 }
2404 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
2405 mPackageManager = pm;
2406 mLabelCache = labelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07002407 }
2408 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002409 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07002410 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
2411 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
2412 if (mLabelCache.containsKey(keyA)) {
2413 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002414 } else {
2415 labelA = a.loadLabel(mPackageManager).toString();
2416
Winson Chung5308f242011-08-18 12:12:41 -07002417 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002418 }
Winson Chung5308f242011-08-18 12:12:41 -07002419 if (mLabelCache.containsKey(keyB)) {
2420 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002421 } else {
2422 labelB = b.loadLabel(mPackageManager).toString();
2423
Winson Chung5308f242011-08-18 12:12:41 -07002424 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002425 }
Winson Chung785d2eb2011-04-14 16:08:02 -07002426 return sCollator.compare(labelA, labelB);
2427 }
2428 };
Winson Chung1ed747a2011-05-03 16:18:34 -07002429 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
2430 private PackageManager mPackageManager;
2431 private HashMap<Object, String> mLabelCache;
2432 WidgetAndShortcutNameComparator(PackageManager pm) {
2433 mPackageManager = pm;
2434 mLabelCache = new HashMap<Object, String>();
2435 }
2436 public final int compare(Object a, Object b) {
2437 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07002438 if (mLabelCache.containsKey(a)) {
2439 labelA = mLabelCache.get(a);
2440 } else {
2441 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002442 ((AppWidgetProviderInfo) a).label :
2443 ((ResolveInfo) a).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002444 mLabelCache.put(a, labelA);
2445 }
2446 if (mLabelCache.containsKey(b)) {
2447 labelB = mLabelCache.get(b);
2448 } else {
2449 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002450 ((AppWidgetProviderInfo) b).label :
2451 ((ResolveInfo) b).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002452 mLabelCache.put(b, labelB);
2453 }
Winson Chung1ed747a2011-05-03 16:18:34 -07002454 return sCollator.compare(labelA, labelB);
2455 }
2456 };
Joe Onoratobe386092009-11-17 17:32:16 -08002457
2458 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08002459 Log.d(TAG, "mCallbacks=" + mCallbacks);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002460 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
2461 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
2462 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
2463 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04002464 if (mLoaderTask != null) {
2465 mLoaderTask.dumpState();
2466 } else {
2467 Log.d(TAG, "mLoaderTask=null");
2468 }
Joe Onoratobe386092009-11-17 17:32:16 -08002469 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002470}