blob: ab29fc68803cb5db1b3c549e501b1300ba7cda96 [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;
Adam Cohend7d37b12012-07-18 16:15:08 -070060import java.util.HashSet;
61import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070062import java.util.List;
Adam Cohend7d37b12012-07-18 16:15:08 -070063import 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;
Adam Cohend7d37b12012-07-18 16:15:08 -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
Adam Cohend7d37b12012-07-18 16:15:08 -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 >
106 private AllAppsList mAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800107
Adam Cohend7d37b12012-07-18 16:15:08 -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 sBgLock = new Object();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700113
Adam Cohend7d37b12012-07-18 16:15:08 -0700114 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
115 // LauncherModel to their ids
116 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
117
118 // sBgItems is passed to bindItems, which expects a list of all folders and shortcuts created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700119 // LauncherModel that are directly on the home screen (however, no widgets or shortcuts
120 // within folders).
Adam Cohend7d37b12012-07-18 16:15:08 -0700121 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700122
Adam Cohend7d37b12012-07-18 16:15:08 -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 Cohend7d37b12012-07-18 16:15:08 -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 Cohend7d37b12012-07-18 16:15:08 -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[]>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700132
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700133 // </ only access in worker thread >
134
135 private IconCache mIconCache;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800136 private Bitmap mDefaultIcon;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800137
Adam Cohend22015c2010-07-26 22:02:18 -0700138 private static int mCellCountX;
139 private static int mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700140
Reena Lee99a73f32011-10-24 17:27:37 -0700141 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700142
Joe Onorato9c1289c2009-08-17 11:03:03 -0400143 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700144 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400145 public int getCurrentWorkspaceScreen();
146 public void startBinding();
147 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
Joe Onoratoad72e172009-11-06 16:25:04 -0500148 public void bindFolders(HashMap<Long,FolderInfo> folders);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400149 public void finishBindingItems();
150 public void bindAppWidget(LauncherAppWidgetInfo info);
151 public void bindAllApplications(ArrayList<ApplicationInfo> apps);
Joe Onorato64e6be72010-03-05 15:05:52 -0500152 public void bindAppsAdded(ArrayList<ApplicationInfo> apps);
153 public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
Joe Onorato36115782010-06-17 13:28:48 -0400154 public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent);
Winson Chung80baf5a2010-08-09 16:03:15 -0700155 public void bindPackagesUpdated();
Daniel Sandler843e8602010-06-07 14:59:01 -0400156 public boolean isAllAppsVisible();
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800157 public boolean isAllAppsButtonRank(int rank);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100158 public void bindSearchablesChanged();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400159 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800160
Joe Onorato0589f0f2010-02-08 13:44:00 -0800161 LauncherModel(LauncherApplication app, IconCache iconCache) {
Joe Onorato17a89222011-02-08 17:26:11 -0800162 mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated();
Joe Onoratof99f8c12009-10-31 17:27:36 -0400163 mApp = app;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800164 mAllAppsList = new AllAppsList(iconCache);
165 mIconCache = iconCache;
166
167 mDefaultIcon = Utilities.createIconBitmap(
Michael Jurkac9a96192010-11-01 11:52:08 -0700168 mIconCache.getFullResDefaultActivityIcon(), app);
Daniel Sandler2ff10b32010-04-16 15:06:06 -0400169
Reena Lee93f824a2011-09-23 17:20:28 -0700170 final Resources res = app.getResources();
171 mAllAppsLoadDelay = res.getInteger(R.integer.config_allAppsBatchLoadDelay);
172 mBatchSize = res.getInteger(R.integer.config_allAppsBatchSize);
Reena Lee99a73f32011-10-24 17:27:37 -0700173 Configuration config = res.getConfiguration();
174 mPreviousConfigMcc = config.mcc;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800175 }
176
Adam Cohend7d37b12012-07-18 16:15:08 -0700177 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
178 * posted on the main thread handler. */
179 private void runOnMainThread(Runnable r) {
180 if (sWorkerThread.getThreadId() == Process.myTid()) {
181 // If we are on the worker thread, post onto the main handler
182 mHandler.post(r);
183 } else {
184 r.run();
185 }
186 }
187
188 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
189 * posted on the worker thread handler. */
190 private static void runOnWorkerThread(Runnable r) {
191 if (sWorkerThread.getThreadId() == Process.myTid()) {
192 r.run();
193 } else {
194 // If we are not on the worker thread, then post to the worker handler
195 sWorker.post(r);
196 }
197 }
198
Joe Onorato56d82912010-03-07 14:32:10 -0500199 public Bitmap getFallbackIcon() {
Joe Onorato0589f0f2010-02-08 13:44:00 -0800200 return Bitmap.createBitmap(mDefaultIcon);
Joe Onoratof99f8c12009-10-31 17:27:36 -0400201 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800202
Winson Chung603bcb92011-09-02 11:45:39 -0700203 public void unbindWorkspaceItems() {
204 sWorker.post(new Runnable() {
205 @Override
206 public void run() {
207 unbindWorkspaceItemsOnMainThread();
208 }
209 });
210 }
211
Adam Cohend7d37b12012-07-18 16:15:08 -0700212 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
213 private void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700214 // Ensure that we don't use the same workspace items data structure on the main thread
215 // by making a copy of workspace items first.
Adam Cohend7d37b12012-07-18 16:15:08 -0700216 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
217 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
218 synchronized (sBgLock) {
219 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
220 tmpAppWidgets.addAll(sBgAppWidgets);
221 }
222 Runnable r = new Runnable() {
223 @Override
224 public void run() {
225 for (ItemInfo item : tmpWorkspaceItems) {
226 item.unbind();
227 }
228 for (ItemInfo item : tmpAppWidgets) {
229 item.unbind();
230 }
231 }
232 };
233 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700234 }
235
Joe Onorato9c1289c2009-08-17 11:03:03 -0400236 /**
237 * Adds an item to the DB if it was not created previously, or move it to a new
238 * <container, screen, cellX, cellY>
239 */
240 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
241 int screen, int cellX, int cellY) {
242 if (item.container == ItemInfo.NO_ID) {
243 // From all apps
244 addItemToDatabase(context, item, container, screen, cellX, cellY, false);
245 } else {
246 // From somewhere else
247 moveItemInDatabase(context, item, container, screen, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800248 }
249 }
250
Michael Jurkac9d95c52011-08-29 14:03:34 -0700251 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
252 final ItemInfo item, final String callingFunction) {
253 final long itemId = item.id;
254 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
255 final ContentResolver cr = context.getContentResolver();
256
257 Runnable r = new Runnable() {
258 public void run() {
259 cr.update(uri, values, null, null);
260
Adam Cohend7d37b12012-07-18 16:15:08 -0700261 // Lock on mBgLock *after* the db operation
262 synchronized (sBgLock) {
263 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
264 if (item != modelItem) {
265 // the modelItem needs to match up perfectly with item if our model is to be
266 // consistent with the database-- for now, just require modelItem == item
267 String msg = "item: " + ((item != null) ? item.toString() : "null") +
268 "modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") +
269 "Error: ItemInfo passed to " + callingFunction + " doesn't match " +
270 "original";
271 throw new RuntimeException(msg);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700272 }
Adam Cohend7d37b12012-07-18 16:15:08 -0700273
274 // Items are added/removed from the corresponding FolderInfo elsewhere, such
275 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
276 // that are on the desktop, as appropriate
277 if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
278 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
279 if (!sBgWorkspaceItems.contains(modelItem)) {
280 sBgWorkspaceItems.add(modelItem);
281
282 }
283 } else {
284 sBgWorkspaceItems.remove(modelItem);
285 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700286 }
287 }
288 };
Adam Cohend7d37b12012-07-18 16:15:08 -0700289 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700290 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700291
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800292 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400293 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700294 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700295 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
296 final int screen, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400297 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400298 item.cellX = cellX;
299 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700300
Winson Chung3d503fb2011-07-13 17:25:49 -0700301 // We store hotseat items in canonical form which is this orientation invariant position
302 // in the hotseat
303 if (context instanceof Launcher && screen < 0 &&
304 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
305 item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
306 } else {
307 item.screen = screen;
308 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400309
310 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400311 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700312 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
313 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400314 values.put(LauncherSettings.Favorites.SCREEN, item.screen);
315
Michael Jurkac9d95c52011-08-29 14:03:34 -0700316 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700317 }
318
319 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700320 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800321 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700322 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
323 final int screen, final int cellX, final int cellY, final int spanX, final int spanY) {
324 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800325 item.cellX = cellX;
326 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700327 item.spanX = spanX;
328 item.spanY = spanY;
329
330 // We store hotseat items in canonical form which is this orientation invariant position
331 // in the hotseat
332 if (context instanceof Launcher && screen < 0 &&
333 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
334 item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
335 } else {
336 item.screen = screen;
337 }
Adam Cohend4844c32011-02-18 19:25:06 -0800338
Adam Cohend4844c32011-02-18 19:25:06 -0800339 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800340 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700341 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
342 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
343 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
344 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
345 values.put(LauncherSettings.Favorites.SCREEN, item.screen);
Adam Cohend4844c32011-02-18 19:25:06 -0800346
Adam Cohenbebf0422012-04-11 18:06:28 -0700347 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
348 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700349
350 /**
351 * Update an item to the database in a specified container.
352 */
353 static void updateItemInDatabase(Context context, final ItemInfo item) {
354 final ContentValues values = new ContentValues();
355 item.onAddToDatabase(values);
356 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
357 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800358 }
359
360 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400361 * Returns true if the shortcuts already exists in the database.
362 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800363 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400364 static boolean shortcutExists(Context context, String title, Intent intent) {
365 final ContentResolver cr = context.getContentResolver();
366 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
367 new String[] { "title", "intent" }, "title=? and intent=?",
368 new String[] { title, intent.toUri(0) }, null);
369 boolean result = false;
370 try {
371 result = c.moveToFirst();
372 } finally {
373 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800374 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400375 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700376 }
377
Joe Onorato9c1289c2009-08-17 11:03:03 -0400378 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700379 * Returns an ItemInfo array containing all the items in the LauncherModel.
380 * The ItemInfo.id is not set through this function.
381 */
382 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
383 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
384 final ContentResolver cr = context.getContentResolver();
385 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
386 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
387 LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
388 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
389
390 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
391 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
392 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
393 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
394 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
395 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
396 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
397
398 try {
399 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700400 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700401 item.cellX = c.getInt(cellXIndex);
402 item.cellY = c.getInt(cellYIndex);
403 item.spanX = c.getInt(spanXIndex);
404 item.spanY = c.getInt(spanYIndex);
405 item.container = c.getInt(containerIndex);
406 item.itemType = c.getInt(itemTypeIndex);
407 item.screen = c.getInt(screenIndex);
408
409 items.add(item);
410 }
411 } catch (Exception e) {
412 items.clear();
413 } finally {
414 c.close();
415 }
416
417 return items;
418 }
419
420 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400421 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
422 */
423 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
424 final ContentResolver cr = context.getContentResolver();
425 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
426 "_id=? and (itemType=? or itemType=?)",
427 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700428 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700429
Joe Onorato9c1289c2009-08-17 11:03:03 -0400430 try {
431 if (c.moveToFirst()) {
432 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
433 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
434 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
435 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
436 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
437 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800438
Joe Onorato9c1289c2009-08-17 11:03:03 -0400439 FolderInfo folderInfo = null;
440 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700441 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
442 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400443 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700444 }
445
Joe Onorato9c1289c2009-08-17 11:03:03 -0400446 folderInfo.title = c.getString(titleIndex);
447 folderInfo.id = id;
448 folderInfo.container = c.getInt(containerIndex);
449 folderInfo.screen = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700450 folderInfo.cellX = c.getInt(cellXIndex);
451 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400452
453 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700454 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400455 } finally {
456 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700457 }
458
459 return null;
460 }
461
Joe Onorato9c1289c2009-08-17 11:03:03 -0400462 /**
463 * Add an item to the database in a specified container. Sets the container, screen, cellX and
464 * cellY fields of the item. Also assigns an ID to the item.
465 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700466 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
467 final int screen, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400468 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400469 item.cellX = cellX;
470 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700471 // We store hotseat items in canonical form which is this orientation invariant position
472 // in the hotseat
473 if (context instanceof Launcher && screen < 0 &&
474 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
475 item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
476 } else {
477 item.screen = screen;
478 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400479
480 final ContentValues values = new ContentValues();
481 final ContentResolver cr = context.getContentResolver();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400482 item.onAddToDatabase(values);
483
Michael Jurka7578ec62011-08-03 14:11:54 -0700484 LauncherApplication app = (LauncherApplication) context.getApplicationContext();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700485 item.id = app.getLauncherProvider().generateNewId();
486 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -0700487 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -0700488
Michael Jurkac9d95c52011-08-29 14:03:34 -0700489 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700490 public void run() {
491 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
492 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Adam Cohend7d37b12012-07-18 16:15:08 -0700493 // Lock on mBgLock *after* the db operation
494 synchronized (sBgLock) {
495 if (sBgItemsIdMap.containsKey(item.id)) {
496 // we should not be adding new items in the db with the same id
497 throw new RuntimeException("Error: ItemInfo id (" + item.id + ") passed to " +
498 "addItemToDatabase already exists." + item.toString());
499 }
500 sBgItemsIdMap.put(item.id, item);
501 switch (item.itemType) {
502 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
503 sBgFolders.put(item.id, (FolderInfo) item);
504 // Fall through
505 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
506 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
507 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
508 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
509 sBgWorkspaceItems.add(item);
510 }
511 break;
512 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
513 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
514 break;
515 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700516 }
517 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700518 };
Adam Cohend7d37b12012-07-18 16:15:08 -0700519 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700520 }
521
Joe Onorato9c1289c2009-08-17 11:03:03 -0400522 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700523 * Creates a new unique child id, for a given cell span across all layouts.
524 */
Michael Jurka845ba3b2010-09-28 17:09:46 -0700525 static int getCellLayoutChildId(
Winson Chung3d503fb2011-07-13 17:25:49 -0700526 long container, int screen, int localCellX, int localCellY, int spanX, int spanY) {
527 return (((int) container & 0xFF) << 24)
Michael Jurka845ba3b2010-09-28 17:09:46 -0700528 | (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -0700529 }
530
Adam Cohend22015c2010-07-26 22:02:18 -0700531 static int getCellCountX() {
532 return mCellCountX;
Winson Chungaafa03c2010-06-11 17:34:16 -0700533 }
534
Adam Cohend22015c2010-07-26 22:02:18 -0700535 static int getCellCountY() {
536 return mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700537 }
538
539 /**
540 * Updates the model orientation helper to take into account the current layout dimensions
541 * when performing local/canonical coordinate transformations.
542 */
543 static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
Adam Cohend22015c2010-07-26 22:02:18 -0700544 mCellCountX = shortAxisCellCount;
545 mCellCountY = longAxisCellCount;
Winson Chungaafa03c2010-06-11 17:34:16 -0700546 }
547
548 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -0700549 * Removes the specified item from the database
550 * @param context
551 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -0400552 */
Michael Jurkac9d95c52011-08-29 14:03:34 -0700553 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400554 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700555 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Michael Jurka83df1882011-08-31 20:59:26 -0700556 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700557 public void run() {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700558 cr.delete(uriToDelete, null, null);
Adam Cohend7d37b12012-07-18 16:15:08 -0700559 // Lock on mBgLock *after* the db operation
560 synchronized (sBgLock) {
561 switch (item.itemType) {
562 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
563 sBgFolders.remove(item.id);
564 sBgWorkspaceItems.remove(item);
565 break;
566 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
567 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
568 sBgWorkspaceItems.remove(item);
569 break;
570 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
571 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
572 break;
573 }
574 sBgItemsIdMap.remove(item.id);
575 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700576 }
577 }
Michael Jurka83df1882011-08-31 20:59:26 -0700578 };
Adam Cohend7d37b12012-07-18 16:15:08 -0700579 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400580 }
581
582 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400583 * Remove the contents of the specified folder from the database
584 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700585 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400586 final ContentResolver cr = context.getContentResolver();
587
Michael Jurkac9d95c52011-08-29 14:03:34 -0700588 Runnable r = new Runnable() {
589 public void run() {
590 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Adam Cohend7d37b12012-07-18 16:15:08 -0700591 // Lock on mBgLock *after* the db operation
592 synchronized (sBgLock) {
593 sBgItemsIdMap.remove(info.id);
594 sBgFolders.remove(info.id);
595 sBgDbIconCache.remove(info);
596 sBgWorkspaceItems.remove(info);
597 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700598
Michael Jurkac9d95c52011-08-29 14:03:34 -0700599 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
600 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Adam Cohend7d37b12012-07-18 16:15:08 -0700601 // Lock on mBgLock *after* the db operation
602 synchronized (sBgLock) {
603 for (ItemInfo childInfo : info.contents) {
604 sBgItemsIdMap.remove(childInfo.id);
605 sBgDbIconCache.remove(childInfo);
606 }
Adam Cohenafb01ee2011-06-23 15:38:03 -0700607 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700608 }
609 };
Adam Cohend7d37b12012-07-18 16:15:08 -0700610 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400611 }
612
613 /**
614 * Set this as the current Launcher activity object for the loader.
615 */
616 public void initialize(Callbacks callbacks) {
617 synchronized (mLock) {
618 mCallbacks = new WeakReference<Callbacks>(callbacks);
619 }
620 }
621
Joe Onorato1d8e7bb2009-10-15 19:49:43 -0700622 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400623 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
624 * ACTION_PACKAGE_CHANGED.
625 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100626 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -0400627 public void onReceive(Context context, Intent intent) {
Joe Onorato36115782010-06-17 13:28:48 -0400628 if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -0700629
Joe Onorato36115782010-06-17 13:28:48 -0400630 final String action = intent.getAction();
Joe Onoratof99f8c12009-10-31 17:27:36 -0400631
Joe Onorato36115782010-06-17 13:28:48 -0400632 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
633 || Intent.ACTION_PACKAGE_REMOVED.equals(action)
634 || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
635 final String packageName = intent.getData().getSchemeSpecificPart();
636 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400637
Joe Onorato36115782010-06-17 13:28:48 -0400638 int op = PackageUpdatedTask.OP_NONE;
639
640 if (packageName == null || packageName.length() == 0) {
641 // they sent us a bad intent
642 return;
643 }
644
645 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
646 op = PackageUpdatedTask.OP_UPDATE;
647 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
648 if (!replacing) {
649 op = PackageUpdatedTask.OP_REMOVE;
650 }
651 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
652 // later, we will update the package at this time
653 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
654 if (!replacing) {
655 op = PackageUpdatedTask.OP_ADD;
656 } else {
657 op = PackageUpdatedTask.OP_UPDATE;
658 }
659 }
660
661 if (op != PackageUpdatedTask.OP_NONE) {
662 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
663 }
664
665 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Joe Onoratocec58332010-10-07 14:37:40 -0400666 // First, schedule to add these apps back in.
667 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
668 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
669 // Then, rebind everything.
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700670 startLoaderFromBackground();
Joe Onorato36115782010-06-17 13:28:48 -0400671 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
672 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
673 enqueuePackageUpdated(new PackageUpdatedTask(
674 PackageUpdatedTask.OP_UNAVAILABLE, packages));
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700675 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -0700676 // If we have changed locale we need to clear out the labels in all apps/workspace.
677 forceReload();
678 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
679 // Check if configuration change was an mcc/mnc change which would affect app resources
680 // and we would need to clear out the labels in all apps/workspace. Same handling as
681 // above for ACTION_LOCALE_CHANGED
682 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -0700683 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -0700684 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -0700685 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -0700686 forceReload();
687 }
688 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -0700689 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -0700690 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
691 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -0700692 if (mCallbacks != null) {
693 Callbacks callbacks = mCallbacks.get();
694 if (callbacks != null) {
695 callbacks.bindSearchablesChanged();
696 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -0700697 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700698 }
699 }
700
Reena Lee93f824a2011-09-23 17:20:28 -0700701 private void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -0700702 resetLoadedState(true, true);
703
Reena Lee93f824a2011-09-23 17:20:28 -0700704 // Do this here because if the launcher activity is running it will be restarted.
705 // If it's not running startLoaderFromBackground will merely tell it that it needs
706 // to reload.
707 startLoaderFromBackground();
708 }
709
Winson Chungf0c6ae02012-03-21 16:10:31 -0700710 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
711 synchronized (mLock) {
712 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
713 // mWorkspaceLoaded to true later
714 stopLoaderLocked();
715 if (resetAllAppsLoaded) mAllAppsLoaded = false;
716 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
717 }
718 }
719
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700720 /**
721 * When the launcher is in the background, it's possible for it to miss paired
722 * configuration changes. So whenever we trigger the loader from the background
723 * tell the launcher that it needs to re-run the loader when it comes back instead
724 * of doing it now.
725 */
726 public void startLoaderFromBackground() {
727 boolean runLoader = false;
728 if (mCallbacks != null) {
729 Callbacks callbacks = mCallbacks.get();
730 if (callbacks != null) {
731 // Only actually run the loader if they're not paused.
732 if (!callbacks.setLoadOnResume()) {
733 runLoader = true;
734 }
735 }
736 }
737 if (runLoader) {
Adam Cohend7d37b12012-07-18 16:15:08 -0700738 startLoader(false, -1);
Joe Onorato790c2d92010-06-11 00:14:11 -0700739 }
Joe Onorato36115782010-06-17 13:28:48 -0400740 }
Joe Onoratof99f8c12009-10-31 17:27:36 -0400741
Reena Lee93f824a2011-09-23 17:20:28 -0700742 // If there is already a loader task running, tell it to stop.
743 // returns true if isLaunching() was true on the old task
744 private boolean stopLoaderLocked() {
745 boolean isLaunching = false;
746 LoaderTask oldTask = mLoaderTask;
747 if (oldTask != null) {
748 if (oldTask.isLaunching()) {
749 isLaunching = true;
750 }
751 oldTask.stopLocked();
752 }
753 return isLaunching;
754 }
755
Adam Cohend7d37b12012-07-18 16:15:08 -0700756 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Joe Onorato36115782010-06-17 13:28:48 -0400757 synchronized (mLock) {
758 if (DEBUG_LOADERS) {
759 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
760 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400761
Adam Cohend7d37b12012-07-18 16:15:08 -0700762 // Clear any deferred bind-runnables from the synchronized load process
763 // We must do this before any loading/binding is scheduled below.
764 mDeferredBindRunnables.clear();
765
Joe Onorato36115782010-06-17 13:28:48 -0400766 // Don't bother to start the thread if we know it's not going to do anything
767 if (mCallbacks != null && mCallbacks.get() != null) {
768 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -0700769 // also, don't downgrade isLaunching if we're already running
770 isLaunching = isLaunching || stopLoaderLocked();
Winson Chungf0c6ae02012-03-21 16:10:31 -0700771 mLoaderTask = new LoaderTask(mApp, isLaunching);
Adam Cohend7d37b12012-07-18 16:15:08 -0700772 if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
773 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
774 } else {
775 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
776 sWorker.post(mLoaderTask);
777 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400778 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400779 }
780 }
781
Adam Cohend7d37b12012-07-18 16:15:08 -0700782 void bindRemainingSynchronousPages() {
783 // Post the remaining side pages to be loaded
784 if (!mDeferredBindRunnables.isEmpty()) {
785 for (final Runnable r : mDeferredBindRunnables) {
786 mHandler.post(r);
787 }
788 mDeferredBindRunnables.clear();
789 }
790 }
791
Joe Onorato36115782010-06-17 13:28:48 -0400792 public void stopLoader() {
793 synchronized (mLock) {
794 if (mLoaderTask != null) {
795 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400796 }
797 }
Joe Onorato36115782010-06-17 13:28:48 -0400798 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400799
Michael Jurkac57b7a82011-08-09 22:02:20 -0700800 public boolean isAllAppsLoaded() {
801 return mAllAppsLoaded;
802 }
803
Winson Chung36a62fe2012-05-06 18:04:42 -0700804 boolean isLoadingWorkspace() {
805 synchronized (mLock) {
806 if (mLoaderTask != null) {
807 return mLoaderTask.isLoadingWorkspace();
808 }
809 }
810 return false;
811 }
812
Joe Onorato36115782010-06-17 13:28:48 -0400813 /**
814 * Runnable for the thread that loads the contents of the launcher:
815 * - workspace icons
816 * - widgets
817 * - all apps icons
818 */
819 private class LoaderTask implements Runnable {
820 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -0400821 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -0700822 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -0400823 private boolean mStopped;
824 private boolean mLoadAndBindStepFinished;
Adam Cohend7d37b12012-07-18 16:15:08 -0700825
Winson Chungc3eecff2011-07-11 17:44:15 -0700826 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -0400827
828 LoaderTask(Context context, boolean isLaunching) {
829 mContext = context;
830 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -0700831 mLabelCache = new HashMap<Object, CharSequence>();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400832 }
833
Joe Onorato36115782010-06-17 13:28:48 -0400834 boolean isLaunching() {
835 return mIsLaunching;
836 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400837
Winson Chung36a62fe2012-05-06 18:04:42 -0700838 boolean isLoadingWorkspace() {
839 return mIsLoadingAndBindingWorkspace;
840 }
841
Joe Onorato36115782010-06-17 13:28:48 -0400842 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -0700843 mIsLoadingAndBindingWorkspace = true;
844
Joe Onorato36115782010-06-17 13:28:48 -0400845 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -0400846 if (DEBUG_LOADERS) {
847 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400848 }
Michael Jurka288a36b2011-07-12 16:53:48 -0700849
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700850 if (!mWorkspaceLoaded) {
Joe Onorato36115782010-06-17 13:28:48 -0400851 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -0700852 synchronized (LoaderTask.this) {
853 if (mStopped) {
854 return;
855 }
856 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400857 }
858 }
859
Joe Onorato36115782010-06-17 13:28:48 -0400860 // Bind the workspace
Adam Cohend7d37b12012-07-18 16:15:08 -0700861 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -0400862 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400863
Joe Onorato36115782010-06-17 13:28:48 -0400864 private void waitForIdle() {
865 // Wait until the either we're stopped or the other threads are done.
866 // This way we don't start loading all apps until the workspace has settled
867 // down.
868 synchronized (LoaderTask.this) {
869 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -0700870
Joe Onorato36115782010-06-17 13:28:48 -0400871 mHandler.postIdle(new Runnable() {
872 public void run() {
873 synchronized (LoaderTask.this) {
874 mLoadAndBindStepFinished = true;
875 if (DEBUG_LOADERS) {
876 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -0400877 }
Joe Onorato36115782010-06-17 13:28:48 -0400878 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -0400879 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400880 }
Joe Onorato36115782010-06-17 13:28:48 -0400881 });
882
883 while (!mStopped && !mLoadAndBindStepFinished) {
884 try {
885 this.wait();
886 } catch (InterruptedException ex) {
887 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -0400888 }
889 }
Joe Onorato36115782010-06-17 13:28:48 -0400890 if (DEBUG_LOADERS) {
891 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -0700892 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -0400893 + "ms for previous step to finish binding");
894 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400895 }
Joe Onorato36115782010-06-17 13:28:48 -0400896 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400897
Adam Cohend7d37b12012-07-18 16:15:08 -0700898 void runBindSynchronousPage(int synchronousBindPage) {
899 if (synchronousBindPage < 0) {
900 // Ensure that we have a valid page index to load synchronously
901 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
902 "valid page index");
903 }
904 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
905 // Ensure that we don't try and bind a specified page when the pages have not been
906 // loaded already (we should load everything asynchronously in that case)
907 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
908 }
909 synchronized (mLock) {
910 if (mIsLoaderTaskRunning) {
911 // Ensure that we are never running the background loading at this point since
912 // we also touch the background collections
913 throw new RuntimeException("Error! Background loading is already running");
914 }
915 }
916
917 // XXX: Throw an exception if we are already loading (since we touch the worker thread
918 // data structures, we can't allow any other thread to touch that data, but because
919 // this call is synchronous, we can get away with not locking).
920
Adam Cohena13a2f22012-07-23 14:29:15 -0700921 // The LauncherModel is static in the LauncherApplication and mHandler may have queued
922 // operations from the previous activity. We need to ensure that all queued operations
923 // are executed before any synchronous binding work is done.
924 mHandler.flush();
925
Adam Cohend7d37b12012-07-18 16:15:08 -0700926 // Divide the set of loaded items into those that we are binding synchronously, and
927 // everything else that is to be bound normally (asynchronously).
928 bindWorkspace(synchronousBindPage);
929 // XXX: For now, continue posting the binding of AllApps as there are other issues that
930 // arise from that.
931 onlyBindAllApps();
932 }
933
Joe Onorato36115782010-06-17 13:28:48 -0400934 public void run() {
Adam Cohend7d37b12012-07-18 16:15:08 -0700935 synchronized (mLock) {
936 mIsLoaderTaskRunning = true;
937 }
Joe Onorato36115782010-06-17 13:28:48 -0400938 // Optimize for end-user experience: if the Launcher is up and // running with the
939 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
940 // workspace first (default).
941 final Callbacks cbk = mCallbacks.get();
942 final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
Daniel Sandler843e8602010-06-07 14:59:01 -0400943
Joe Onorato36115782010-06-17 13:28:48 -0400944 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -0400945 // Elevate priority when Home launches for the first time to avoid
946 // starving at boot time. Staring at a blank home is not cool.
947 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -0700948 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
949 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -0400950 android.os.Process.setThreadPriority(mIsLaunching
951 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
952 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400953 if (loadWorkspaceFirst) {
954 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
955 loadAndBindWorkspace();
956 } else {
957 if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
Joe Onoratocc67f472010-06-08 10:54:30 -0700958 loadAndBindAllApps();
Daniel Sandler843e8602010-06-07 14:59:01 -0400959 }
960
Joe Onorato36115782010-06-17 13:28:48 -0400961 if (mStopped) {
962 break keep_running;
963 }
964
965 // Whew! Hard work done. Slow us down, and wait until the UI thread has
966 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -0400967 synchronized (mLock) {
968 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -0700969 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -0400970 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
971 }
972 }
Joe Onorato36115782010-06-17 13:28:48 -0400973 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -0400974
975 // second step
976 if (loadWorkspaceFirst) {
977 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
Joe Onoratocc67f472010-06-08 10:54:30 -0700978 loadAndBindAllApps();
Daniel Sandler843e8602010-06-07 14:59:01 -0400979 } else {
980 if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
981 loadAndBindWorkspace();
982 }
Winson Chung7ed37742011-09-08 15:45:51 -0700983
984 // Restore the default thread priority after we are done loading items
985 synchronized (mLock) {
986 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
987 }
Joe Onorato36115782010-06-17 13:28:48 -0400988 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400989
Winson Chungaac01e12011-08-17 10:37:13 -0700990
991 // Update the saved icons if necessary
992 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Adam Cohend7d37b12012-07-18 16:15:08 -0700993 synchronized (sBgLock) {
994 for (Object key : sBgDbIconCache.keySet()) {
995 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
996 }
997 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -0700998 }
Winson Chungaac01e12011-08-17 10:37:13 -0700999
Joe Onorato36115782010-06-17 13:28:48 -04001000 // Clear out this reference, otherwise we end up holding it until all of the
1001 // callback runnables are done.
1002 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001003
Joe Onorato36115782010-06-17 13:28:48 -04001004 synchronized (mLock) {
1005 // If we are still the last one to be scheduled, remove ourselves.
1006 if (mLoaderTask == this) {
1007 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001008 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001009 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001010 }
Joe Onorato36115782010-06-17 13:28:48 -04001011 }
1012
1013 public void stopLocked() {
1014 synchronized (LoaderTask.this) {
1015 mStopped = true;
1016 this.notify();
1017 }
1018 }
1019
1020 /**
1021 * Gets the callbacks object. If we've been stopped, or if the launcher object
1022 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1023 * object that was around when the deferred message was scheduled, and if there's
1024 * a new Callbacks object around then also return null. This will save us from
1025 * calling onto it with data that will be ignored.
1026 */
1027 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1028 synchronized (mLock) {
1029 if (mStopped) {
1030 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001031 }
Joe Onorato36115782010-06-17 13:28:48 -04001032
1033 if (mCallbacks == null) {
1034 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001035 }
Joe Onorato36115782010-06-17 13:28:48 -04001036
1037 final Callbacks callbacks = mCallbacks.get();
1038 if (callbacks != oldCallbacks) {
1039 return null;
1040 }
1041 if (callbacks == null) {
1042 Log.w(TAG, "no mCallbacks");
1043 return null;
1044 }
1045
1046 return callbacks;
1047 }
1048 }
1049
1050 // check & update map of what's occupied; used to discard overlapping/invalid items
1051 private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001052 int containerIndex = item.screen;
1053 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001054 // Return early if we detect that an item is under the hotseat button
Andrew Flynn0dca1ec2012-02-29 13:33:22 -08001055 if (mCallbacks == null || mCallbacks.get().isAllAppsButtonRank(item.screen)) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001056 return false;
1057 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001058
1059 // We use the last index to refer to the hotseat and the screen as the rank, so
1060 // test and update the occupied state accordingly
1061 if (occupied[Launcher.SCREEN_COUNT][item.screen][0] != null) {
1062 Log.e(TAG, "Error loading shortcut into hotseat " + item
1063 + " into position (" + item.screen + ":" + item.cellX + "," + item.cellY
1064 + ") occupied by " + occupied[Launcher.SCREEN_COUNT][item.screen][0]);
1065 return false;
1066 } else {
1067 occupied[Launcher.SCREEN_COUNT][item.screen][0] = item;
1068 return true;
1069 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001070 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1071 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001072 return true;
1073 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001074
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001075 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001076 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1077 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001078 if (occupied[containerIndex][x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001079 Log.e(TAG, "Error loading shortcut " + item
Winson Chungf30ad5f2011-08-08 10:55:42 -07001080 + " into cell (" + containerIndex + "-" + item.screen + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001081 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001082 + ") occupied by "
Winson Chungf30ad5f2011-08-08 10:55:42 -07001083 + occupied[containerIndex][x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001084 return false;
1085 }
1086 }
1087 }
1088 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1089 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001090 occupied[containerIndex][x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001091 }
1092 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001093
Joe Onorato36115782010-06-17 13:28:48 -04001094 return true;
1095 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001096
Joe Onorato36115782010-06-17 13:28:48 -04001097 private void loadWorkspace() {
1098 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001099
Joe Onorato36115782010-06-17 13:28:48 -04001100 final Context context = mContext;
1101 final ContentResolver contentResolver = context.getContentResolver();
1102 final PackageManager manager = context.getPackageManager();
1103 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1104 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001105
Michael Jurkab85f8a42012-04-25 15:48:32 -07001106 // Make sure the default workspace is loaded, if needed
1107 mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary();
1108
Adam Cohend7d37b12012-07-18 16:15:08 -07001109 synchronized (sBgLock) {
1110 sBgWorkspaceItems.clear();
1111 sBgAppWidgets.clear();
1112 sBgFolders.clear();
1113 sBgItemsIdMap.clear();
1114 sBgDbIconCache.clear();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001115
Adam Cohend7d37b12012-07-18 16:15:08 -07001116 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001117
Adam Cohend7d37b12012-07-18 16:15:08 -07001118 final Cursor c = contentResolver.query(
1119 LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001120
Adam Cohend7d37b12012-07-18 16:15:08 -07001121 // +1 for the hotseat (it can be larger than the workspace)
1122 // Load workspace in reverse order to ensure that latest items are loaded first (and
1123 // before any earlier duplicates)
1124 final ItemInfo occupied[][][] =
1125 new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1];
Joe Onorato9c1289c2009-08-17 11:03:03 -04001126
Adam Cohend7d37b12012-07-18 16:15:08 -07001127 try {
1128 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1129 final int intentIndex = c.getColumnIndexOrThrow
1130 (LauncherSettings.Favorites.INTENT);
1131 final int titleIndex = c.getColumnIndexOrThrow
1132 (LauncherSettings.Favorites.TITLE);
1133 final int iconTypeIndex = c.getColumnIndexOrThrow(
1134 LauncherSettings.Favorites.ICON_TYPE);
1135 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1136 final int iconPackageIndex = c.getColumnIndexOrThrow(
1137 LauncherSettings.Favorites.ICON_PACKAGE);
1138 final int iconResourceIndex = c.getColumnIndexOrThrow(
1139 LauncherSettings.Favorites.ICON_RESOURCE);
1140 final int containerIndex = c.getColumnIndexOrThrow(
1141 LauncherSettings.Favorites.CONTAINER);
1142 final int itemTypeIndex = c.getColumnIndexOrThrow(
1143 LauncherSettings.Favorites.ITEM_TYPE);
1144 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1145 LauncherSettings.Favorites.APPWIDGET_ID);
1146 final int screenIndex = c.getColumnIndexOrThrow(
1147 LauncherSettings.Favorites.SCREEN);
1148 final int cellXIndex = c.getColumnIndexOrThrow
1149 (LauncherSettings.Favorites.CELLX);
1150 final int cellYIndex = c.getColumnIndexOrThrow
1151 (LauncherSettings.Favorites.CELLY);
1152 final int spanXIndex = c.getColumnIndexOrThrow
1153 (LauncherSettings.Favorites.SPANX);
1154 final int spanYIndex = c.getColumnIndexOrThrow(
1155 LauncherSettings.Favorites.SPANY);
1156 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1157 //final int displayModeIndex = c.getColumnIndexOrThrow(
1158 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001159
Adam Cohend7d37b12012-07-18 16:15:08 -07001160 ShortcutInfo info;
1161 String intentDescription;
1162 LauncherAppWidgetInfo appWidgetInfo;
1163 int container;
1164 long id;
1165 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001166
Adam Cohend7d37b12012-07-18 16:15:08 -07001167 while (!mStopped && c.moveToNext()) {
1168 try {
1169 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001170
Adam Cohend7d37b12012-07-18 16:15:08 -07001171 switch (itemType) {
1172 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1173 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1174 intentDescription = c.getString(intentIndex);
1175 try {
1176 intent = Intent.parseUri(intentDescription, 0);
1177 } catch (URISyntaxException e) {
1178 continue;
1179 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001180
Adam Cohend7d37b12012-07-18 16:15:08 -07001181 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1182 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1183 titleIndex, mLabelCache);
1184 } else {
1185 info = getShortcutInfo(c, context, iconTypeIndex,
1186 iconPackageIndex, iconResourceIndex, iconIndex,
1187 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001188
Adam Cohend7d37b12012-07-18 16:15:08 -07001189 // App shortcuts that used to be automatically added to Launcher
1190 // didn't always have the correct intent flags set, so do that
1191 // here
1192 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001193 intent.getCategories() != null &&
1194 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001195 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Adam Cohend7d37b12012-07-18 16:15:08 -07001196 intent.addFlags(
1197 Intent.FLAG_ACTIVITY_NEW_TASK |
1198 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1199 }
Michael Jurka96879562012-03-22 05:54:33 -07001200 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001201
Adam Cohend7d37b12012-07-18 16:15:08 -07001202 if (info != null) {
1203 info.intent = intent;
1204 info.id = c.getLong(idIndex);
1205 container = c.getInt(containerIndex);
1206 info.container = container;
1207 info.screen = c.getInt(screenIndex);
1208 info.cellX = c.getInt(cellXIndex);
1209 info.cellY = c.getInt(cellYIndex);
1210
1211 // check & update map of what's occupied
1212 if (!checkItemPlacement(occupied, info)) {
1213 break;
1214 }
1215
1216 switch (container) {
1217 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1218 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1219 sBgWorkspaceItems.add(info);
1220 break;
1221 default:
1222 // Item is in a user folder
1223 FolderInfo folderInfo =
1224 findOrMakeFolder(sBgFolders, container);
1225 folderInfo.add(info);
1226 break;
1227 }
1228 sBgItemsIdMap.put(info.id, info);
1229
1230 // now that we've loaded everthing re-save it with the
1231 // icon in case it disappears somehow.
1232 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
1233 } else {
1234 // Failed to load the shortcut, probably because the
1235 // activity manager couldn't resolve it (maybe the app
1236 // was uninstalled), or the db row was somehow screwed up.
1237 // Delete it.
1238 id = c.getLong(idIndex);
1239 Log.e(TAG, "Error loading shortcut " + id + ", removing it");
1240 contentResolver.delete(LauncherSettings.Favorites.getContentUri(
1241 id, false), null, null);
1242 }
1243 break;
1244
1245 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1246 id = c.getLong(idIndex);
1247 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1248
1249 folderInfo.title = c.getString(titleIndex);
1250 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001251 container = c.getInt(containerIndex);
Adam Cohend7d37b12012-07-18 16:15:08 -07001252 folderInfo.container = container;
1253 folderInfo.screen = c.getInt(screenIndex);
1254 folderInfo.cellX = c.getInt(cellXIndex);
1255 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001256
Daniel Sandler8802e962010-05-26 16:28:16 -04001257 // check & update map of what's occupied
Adam Cohend7d37b12012-07-18 16:15:08 -07001258 if (!checkItemPlacement(occupied, folderInfo)) {
Daniel Sandler8802e962010-05-26 16:28:16 -04001259 break;
1260 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001261 switch (container) {
Adam Cohend7d37b12012-07-18 16:15:08 -07001262 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1263 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1264 sBgWorkspaceItems.add(folderInfo);
1265 break;
Joe Onorato36115782010-06-17 13:28:48 -04001266 }
Joe Onorato17a89222011-02-08 17:26:11 -08001267
Adam Cohend7d37b12012-07-18 16:15:08 -07001268 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1269 sBgFolders.put(folderInfo.id, folderInfo);
1270 break;
1271
1272 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1273 // Read all Launcher-specific widget details
1274 int appWidgetId = c.getInt(appWidgetIdIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001275 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001276
Adam Cohend7d37b12012-07-18 16:15:08 -07001277 final AppWidgetProviderInfo provider =
1278 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001279
Adam Cohend7d37b12012-07-18 16:15:08 -07001280 if (!isSafeMode && (provider == null || provider.provider == null ||
1281 provider.provider.getPackageName() == null)) {
1282 String log = "Deleting widget that isn't installed anymore: id="
1283 + id + " appWidgetId=" + appWidgetId;
1284 Log.e(TAG, log);
1285 Launcher.sDumpLogs.add(log);
1286 itemsToRemove.add(id);
1287 } else {
1288 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1289 provider.provider);
1290 appWidgetInfo.id = id;
1291 appWidgetInfo.screen = c.getInt(screenIndex);
1292 appWidgetInfo.cellX = c.getInt(cellXIndex);
1293 appWidgetInfo.cellY = c.getInt(cellYIndex);
1294 appWidgetInfo.spanX = c.getInt(spanXIndex);
1295 appWidgetInfo.spanY = c.getInt(spanYIndex);
1296 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1297 appWidgetInfo.minSpanX = minSpan[0];
1298 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001299
Adam Cohend7d37b12012-07-18 16:15:08 -07001300 container = c.getInt(containerIndex);
1301 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1302 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1303 Log.e(TAG, "Widget found where container != " +
1304 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1305 continue;
1306 }
1307 appWidgetInfo.container = c.getInt(containerIndex);
1308
1309 // check & update map of what's occupied
1310 if (!checkItemPlacement(occupied, appWidgetInfo)) {
1311 break;
1312 }
1313 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1314 sBgAppWidgets.add(appWidgetInfo);
1315 }
Joe Onorato36115782010-06-17 13:28:48 -04001316 break;
1317 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001318 } catch (Exception e) {
1319 Log.w(TAG, "Desktop items loading interrupted:", e);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001320 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001321 }
1322 } finally {
1323 c.close();
1324 }
1325
1326 if (itemsToRemove.size() > 0) {
1327 ContentProviderClient client = contentResolver.acquireContentProviderClient(
1328 LauncherSettings.Favorites.CONTENT_URI);
1329 // Remove dead items
1330 for (long id : itemsToRemove) {
1331 if (DEBUG_LOADERS) {
1332 Log.d(TAG, "Removed id = " + id);
1333 }
1334 // Don't notify content observers
1335 try {
1336 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1337 null, null);
1338 } catch (RemoteException e) {
1339 Log.w(TAG, "Could not remove id = " + id);
1340 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001341 }
1342 }
1343
Adam Cohend7d37b12012-07-18 16:15:08 -07001344 if (DEBUG_LOADERS) {
1345 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1346 Log.d(TAG, "workspace layout: ");
1347 for (int y = 0; y < mCellCountY; y++) {
1348 String line = "";
1349 for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
1350 if (s > 0) {
1351 line += " | ";
1352 }
1353 for (int x = 0; x < mCellCountX; x++) {
1354 line += ((occupied[s][x][y] != null) ? "#" : ".");
1355 }
Joe Onorato36115782010-06-17 13:28:48 -04001356 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001357 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04001358 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001359 }
Joe Onorato36115782010-06-17 13:28:48 -04001360 }
1361 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001362
Adam Cohend7d37b12012-07-18 16:15:08 -07001363 /** Filters the set of items who are directly or indirectly (via another container) on the
1364 * specified screen. */
1365 private void filterCurrentWorkspaceItems(int currentScreen,
1366 ArrayList<ItemInfo> allWorkspaceItems,
1367 ArrayList<ItemInfo> currentScreenItems,
1368 ArrayList<ItemInfo> otherScreenItems) {
1369 // Purge any null ItemInfos
1370 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1371 while (iter.hasNext()) {
1372 ItemInfo i = iter.next();
1373 if (i == null) {
1374 iter.remove();
1375 }
Joe Onorato36115782010-06-17 13:28:48 -04001376 }
1377
Adam Cohend7d37b12012-07-18 16:15:08 -07001378 // If we aren't filtering on a screen, then the set of items to load is the full set of
1379 // items given.
1380 if (currentScreen < 0) {
1381 currentScreenItems.addAll(allWorkspaceItems);
1382 }
1383
1384 // Order the set of items by their containers first, this allows use to walk through the
1385 // list sequentially, build up a list of containers that are in the specified screen,
1386 // as well as all items in those containers.
1387 Set<Long> itemsOnScreen = new HashSet<Long>();
1388 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1389 @Override
1390 public int compare(ItemInfo lhs, ItemInfo rhs) {
1391 return (int) (lhs.container - rhs.container);
1392 }
1393 });
1394 for (ItemInfo info : allWorkspaceItems) {
1395 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1396 if (info.screen == currentScreen) {
1397 currentScreenItems.add(info);
1398 itemsOnScreen.add(info.id);
1399 } else {
1400 otherScreenItems.add(info);
1401 }
1402 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1403 currentScreenItems.add(info);
1404 itemsOnScreen.add(info.id);
1405 } else {
1406 if (itemsOnScreen.contains(info.container)) {
1407 currentScreenItems.add(info);
1408 itemsOnScreen.add(info.id);
1409 } else {
1410 otherScreenItems.add(info);
1411 }
1412 }
1413 }
1414 }
1415
1416 /** Filters the set of widgets which are on the specified screen. */
1417 private void filterCurrentAppWidgets(int currentScreen,
1418 ArrayList<LauncherAppWidgetInfo> appWidgets,
1419 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1420 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1421 // If we aren't filtering on a screen, then the set of items to load is the full set of
1422 // widgets given.
1423 if (currentScreen < 0) {
1424 currentScreenWidgets.addAll(appWidgets);
1425 }
1426
1427 for (LauncherAppWidgetInfo widget : appWidgets) {
1428 if (widget == null) continue;
1429 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1430 widget.screen == currentScreen) {
1431 currentScreenWidgets.add(widget);
1432 } else {
1433 otherScreenWidgets.add(widget);
1434 }
1435 }
1436 }
1437
1438 /** Filters the set of folders which are on the specified screen. */
1439 private void filterCurrentFolders(int currentScreen,
1440 HashMap<Long, ItemInfo> itemsIdMap,
1441 HashMap<Long, FolderInfo> folders,
1442 HashMap<Long, FolderInfo> currentScreenFolders,
1443 HashMap<Long, FolderInfo> otherScreenFolders) {
1444 // If we aren't filtering on a screen, then the set of items to load is the full set of
1445 // widgets given.
1446 if (currentScreen < 0) {
1447 currentScreenFolders.putAll(folders);
1448 }
1449
1450 for (long id : folders.keySet()) {
1451 ItemInfo info = itemsIdMap.get(id);
1452 FolderInfo folder = folders.get(id);
1453 if (info == null || folder == null) continue;
1454 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1455 info.screen == currentScreen) {
1456 currentScreenFolders.put(id, folder);
1457 } else {
1458 otherScreenFolders.put(id, folder);
1459 }
1460 }
1461 }
1462
1463 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
1464 * right) */
1465 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
1466 // XXX: review this
1467 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07001468 @Override
1469 public int compare(ItemInfo lhs, ItemInfo rhs) {
1470 int cellCountX = LauncherModel.getCellCountX();
1471 int cellCountY = LauncherModel.getCellCountY();
1472 int screenOffset = cellCountX * cellCountY;
1473 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
1474 long lr = (lhs.container * containerOffset + lhs.screen * screenOffset +
1475 lhs.cellY * cellCountX + lhs.cellX);
1476 long rr = (rhs.container * containerOffset + rhs.screen * screenOffset +
1477 rhs.cellY * cellCountX + rhs.cellX);
1478 return (int) (lr - rr);
1479 }
1480 });
Adam Cohend7d37b12012-07-18 16:15:08 -07001481 }
Winson Chungdb8a8942012-04-03 14:08:41 -07001482
Adam Cohend7d37b12012-07-18 16:15:08 -07001483 private void bindWorkspaceItems(final Callbacks oldCallbacks,
1484 final ArrayList<ItemInfo> workspaceItems,
1485 final ArrayList<LauncherAppWidgetInfo> appWidgets,
1486 final HashMap<Long, FolderInfo> folders,
1487 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07001488
Adam Cohend7d37b12012-07-18 16:15:08 -07001489 final boolean postOnMainThread = (deferredBindRunnables != null);
1490
1491 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07001492 int N = workspaceItems.size();
Adam Cohend7d37b12012-07-18 16:15:08 -07001493 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04001494 final int start = i;
1495 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Adam Cohend7d37b12012-07-18 16:15:08 -07001496 final Runnable r = new Runnable() {
1497 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04001498 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08001499 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001500 if (callbacks != null) {
Winson Chung603bcb92011-09-02 11:45:39 -07001501 callbacks.bindItems(workspaceItems, start, start+chunkSize);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001502 }
1503 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001504 };
1505 if (postOnMainThread) {
1506 deferredBindRunnables.add(r);
1507 } else {
1508 runOnMainThread(r);
1509 }
Joe Onorato36115782010-06-17 13:28:48 -04001510 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001511
1512 // Bind the folders
1513 if (!folders.isEmpty()) {
1514 final Runnable r = new Runnable() {
1515 public void run() {
1516 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1517 if (callbacks != null) {
1518 callbacks.bindFolders(folders);
1519 }
1520 }
1521 };
1522 if (postOnMainThread) {
1523 deferredBindRunnables.add(r);
1524 } else {
1525 runOnMainThread(r);
1526 }
1527 }
1528
1529 // Bind the widgets, one at a time
1530 N = appWidgets.size();
1531 for (int i = 0; i < N; i++) {
1532 final LauncherAppWidgetInfo widget = appWidgets.get(i);
1533 final Runnable r = new Runnable() {
1534 public void run() {
1535 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1536 if (callbacks != null) {
1537 callbacks.bindAppWidget(widget);
1538 }
1539 }
1540 };
1541 if (postOnMainThread) {
1542 deferredBindRunnables.add(r);
1543 } else {
1544 runOnMainThread(r);
1545 }
1546 }
1547 }
1548
1549 /**
1550 * Binds all loaded data to actual views on the main thread.
1551 */
1552 private void bindWorkspace(int synchronizeBindPage) {
1553 final long t = SystemClock.uptimeMillis();
1554 Runnable r;
1555
1556 // Don't use these two variables in any of the callback runnables.
1557 // Otherwise we hold a reference to them.
1558 final Callbacks oldCallbacks = mCallbacks.get();
1559 if (oldCallbacks == null) {
1560 // This launcher has exited and nobody bothered to tell us. Just bail.
1561 Log.w(TAG, "LoaderTask running with no launcher");
1562 return;
1563 }
1564
Winson Chung36e6c5b2012-07-19 14:53:05 -07001565 final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
1566 final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
Adam Cohend7d37b12012-07-18 16:15:08 -07001567 oldCallbacks.getCurrentWorkspaceScreen();
1568
1569 // Load all the items that are on the current page first (and in the process, unbind
1570 // all the existing workspace items before we call startBinding() below.
1571 unbindWorkspaceItemsOnMainThread();
1572 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
1573 ArrayList<LauncherAppWidgetInfo> appWidgets =
1574 new ArrayList<LauncherAppWidgetInfo>();
1575 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
1576 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
1577 synchronized (sBgLock) {
1578 workspaceItems.addAll(sBgWorkspaceItems);
1579 appWidgets.addAll(sBgAppWidgets);
1580 folders.putAll(sBgFolders);
1581 itemsIdMap.putAll(sBgItemsIdMap);
1582 }
1583
1584 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
1585 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
1586 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
1587 new ArrayList<LauncherAppWidgetInfo>();
1588 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
1589 new ArrayList<LauncherAppWidgetInfo>();
1590 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
1591 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
1592
1593 // Separate the items that are on the current screen, and all the other remaining items
1594 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
1595 otherWorkspaceItems);
1596 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
1597 otherAppWidgets);
1598 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
1599 otherFolders);
1600 sortWorkspaceItemsSpatially(currentWorkspaceItems);
1601 sortWorkspaceItemsSpatially(otherWorkspaceItems);
1602
1603 // Tell the workspace that we're about to start binding items
1604 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001605 public void run() {
1606 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1607 if (callbacks != null) {
Adam Cohend7d37b12012-07-18 16:15:08 -07001608 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04001609 }
1610 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001611 };
1612 runOnMainThread(r);
1613
1614 // Load items on the current page
1615 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
1616 currentFolders, null);
1617
Winson Chung36e6c5b2012-07-19 14:53:05 -07001618 // Load all the remaining pages (if we are loading synchronously, we want to defer this
1619 // work until after the first render)
Adam Cohend7d37b12012-07-18 16:15:08 -07001620 mDeferredBindRunnables.clear();
1621 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung36e6c5b2012-07-19 14:53:05 -07001622 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Adam Cohend7d37b12012-07-18 16:15:08 -07001623
1624 // Tell the workspace that we're done binding items
1625 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001626 public void run() {
1627 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1628 if (callbacks != null) {
1629 callbacks.finishBindingItems();
1630 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001631
Winson Chung98e030b2012-05-07 16:01:11 -07001632 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04001633 if (DEBUG_LOADERS) {
1634 Log.d(TAG, "bound workspace in "
1635 + (SystemClock.uptimeMillis()-t) + "ms");
1636 }
Winson Chung36a62fe2012-05-06 18:04:42 -07001637
1638 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04001639 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001640 };
Winson Chung36e6c5b2012-07-19 14:53:05 -07001641 if (isLoadingSynchronously) {
1642 mDeferredBindRunnables.add(r);
1643 } else {
1644 runOnMainThread(r);
1645 }
Joe Onorato36115782010-06-17 13:28:48 -04001646 }
Joe Onoratocc67f472010-06-08 10:54:30 -07001647
Joe Onorato36115782010-06-17 13:28:48 -04001648 private void loadAndBindAllApps() {
1649 if (DEBUG_LOADERS) {
1650 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
1651 }
1652 if (!mAllAppsLoaded) {
1653 loadAllAppsByBatch();
Reena Lee93f824a2011-09-23 17:20:28 -07001654 synchronized (LoaderTask.this) {
1655 if (mStopped) {
1656 return;
1657 }
1658 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07001659 }
Joe Onorato36115782010-06-17 13:28:48 -04001660 } else {
1661 onlyBindAllApps();
1662 }
1663 }
Joe Onoratocc67f472010-06-08 10:54:30 -07001664
Joe Onorato36115782010-06-17 13:28:48 -04001665 private void onlyBindAllApps() {
1666 final Callbacks oldCallbacks = mCallbacks.get();
1667 if (oldCallbacks == null) {
1668 // This launcher has exited and nobody bothered to tell us. Just bail.
1669 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
1670 return;
1671 }
1672
1673 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07001674 @SuppressWarnings("unchecked")
Joe Onorato36115782010-06-17 13:28:48 -04001675 final ArrayList<ApplicationInfo> list
Michael Jurka92f3d462011-11-22 21:02:29 -08001676 = (ArrayList<ApplicationInfo>) mAllAppsList.data.clone();
Joe Onorato36115782010-06-17 13:28:48 -04001677 mHandler.post(new Runnable() {
1678 public void run() {
1679 final long t = SystemClock.uptimeMillis();
1680 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1681 if (callbacks != null) {
1682 callbacks.bindAllApplications(list);
1683 }
1684 if (DEBUG_LOADERS) {
1685 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
1686 + (SystemClock.uptimeMillis()-t) + "ms");
1687 }
1688 }
1689 });
Joe Onorato36115782010-06-17 13:28:48 -04001690 }
1691
1692 private void loadAllAppsByBatch() {
1693 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1694
1695 // Don't use these two variables in any of the callback runnables.
1696 // Otherwise we hold a reference to them.
1697 final Callbacks oldCallbacks = mCallbacks.get();
1698 if (oldCallbacks == null) {
1699 // This launcher has exited and nobody bothered to tell us. Just bail.
1700 Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
1701 return;
1702 }
1703
1704 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1705 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1706
1707 final PackageManager packageManager = mContext.getPackageManager();
1708 List<ResolveInfo> apps = null;
1709
1710 int N = Integer.MAX_VALUE;
1711
1712 int startIndex;
1713 int i=0;
1714 int batchSize = -1;
1715 while (i < N && !mStopped) {
1716 if (i == 0) {
1717 mAllAppsList.clear();
1718 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1719 apps = packageManager.queryIntentActivities(mainIntent, 0);
1720 if (DEBUG_LOADERS) {
1721 Log.d(TAG, "queryIntentActivities took "
1722 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
1723 }
1724 if (apps == null) {
1725 return;
1726 }
1727 N = apps.size();
1728 if (DEBUG_LOADERS) {
1729 Log.d(TAG, "queryIntentActivities got " + N + " apps");
1730 }
1731 if (N == 0) {
1732 // There are no apps?!?
1733 return;
1734 }
1735 if (mBatchSize == 0) {
1736 batchSize = N;
1737 } else {
1738 batchSize = mBatchSize;
1739 }
1740
1741 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1742 Collections.sort(apps,
Winson Chungc3eecff2011-07-11 17:44:15 -07001743 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
Joe Onorato36115782010-06-17 13:28:48 -04001744 if (DEBUG_LOADERS) {
1745 Log.d(TAG, "sort took "
1746 + (SystemClock.uptimeMillis()-sortTime) + "ms");
1747 }
1748 }
1749
1750 final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1751
1752 startIndex = i;
1753 for (int j=0; i<N && j<batchSize; j++) {
1754 // This builds the icon bitmaps.
Winson Chungc3eecff2011-07-11 17:44:15 -07001755 mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
Michael Jurkac9d95c52011-08-29 14:03:34 -07001756 mIconCache, mLabelCache));
Joe Onorato36115782010-06-17 13:28:48 -04001757 i++;
1758 }
1759
1760 final boolean first = i <= batchSize;
1761 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1762 final ArrayList<ApplicationInfo> added = mAllAppsList.added;
1763 mAllAppsList.added = new ArrayList<ApplicationInfo>();
1764
Joe Onoratocc67f472010-06-08 10:54:30 -07001765 mHandler.post(new Runnable() {
1766 public void run() {
1767 final long t = SystemClock.uptimeMillis();
Joe Onoratocc67f472010-06-08 10:54:30 -07001768 if (callbacks != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001769 if (first) {
1770 callbacks.bindAllApplications(added);
1771 } else {
1772 callbacks.bindAppsAdded(added);
1773 }
1774 if (DEBUG_LOADERS) {
1775 Log.d(TAG, "bound " + added.size() + " apps in "
1776 + (SystemClock.uptimeMillis() - t) + "ms");
1777 }
1778 } else {
1779 Log.i(TAG, "not binding apps: no Launcher activity");
Joe Onoratocc67f472010-06-08 10:54:30 -07001780 }
1781 }
1782 });
1783
Daniel Sandlerdca66122010-04-13 16:23:58 -04001784 if (DEBUG_LOADERS) {
Joe Onorato36115782010-06-17 13:28:48 -04001785 Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
1786 + (SystemClock.uptimeMillis()-t2) + "ms");
1787 }
1788
1789 if (mAllAppsLoadDelay > 0 && i < N) {
1790 try {
1791 if (DEBUG_LOADERS) {
1792 Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
1793 }
1794 Thread.sleep(mAllAppsLoadDelay);
1795 } catch (InterruptedException exc) { }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001796 }
1797 }
1798
Joe Onorato36115782010-06-17 13:28:48 -04001799 if (DEBUG_LOADERS) {
1800 Log.d(TAG, "cached all " + N + " apps in "
1801 + (SystemClock.uptimeMillis()-t) + "ms"
1802 + (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
Joe Onoratobe386092009-11-17 17:32:16 -08001803 }
1804 }
1805
1806 public void dumpState() {
Adam Cohend7d37b12012-07-18 16:15:08 -07001807 synchronized (sBgLock) {
1808 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
1809 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
1810 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
1811 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
1812 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
1813 }
Joe Onorato36115782010-06-17 13:28:48 -04001814 }
1815 }
1816
1817 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07001818 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04001819 }
1820
1821 private class PackageUpdatedTask implements Runnable {
1822 int mOp;
1823 String[] mPackages;
1824
1825 public static final int OP_NONE = 0;
1826 public static final int OP_ADD = 1;
1827 public static final int OP_UPDATE = 2;
1828 public static final int OP_REMOVE = 3; // uninstlled
1829 public static final int OP_UNAVAILABLE = 4; // external media unmounted
1830
1831
1832 public PackageUpdatedTask(int op, String[] packages) {
1833 mOp = op;
1834 mPackages = packages;
1835 }
1836
1837 public void run() {
1838 final Context context = mApp;
1839
1840 final String[] packages = mPackages;
1841 final int N = packages.length;
1842 switch (mOp) {
1843 case OP_ADD:
1844 for (int i=0; i<N; i++) {
1845 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
1846 mAllAppsList.addPackage(context, packages[i]);
1847 }
1848 break;
1849 case OP_UPDATE:
1850 for (int i=0; i<N; i++) {
1851 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
1852 mAllAppsList.updatePackage(context, packages[i]);
1853 }
1854 break;
1855 case OP_REMOVE:
1856 case OP_UNAVAILABLE:
1857 for (int i=0; i<N; i++) {
1858 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
1859 mAllAppsList.removePackage(packages[i]);
1860 }
1861 break;
1862 }
1863
1864 ArrayList<ApplicationInfo> added = null;
1865 ArrayList<ApplicationInfo> removed = null;
1866 ArrayList<ApplicationInfo> modified = null;
1867
1868 if (mAllAppsList.added.size() > 0) {
1869 added = mAllAppsList.added;
1870 mAllAppsList.added = new ArrayList<ApplicationInfo>();
1871 }
1872 if (mAllAppsList.removed.size() > 0) {
1873 removed = mAllAppsList.removed;
1874 mAllAppsList.removed = new ArrayList<ApplicationInfo>();
1875 for (ApplicationInfo info: removed) {
1876 mIconCache.remove(info.intent.getComponent());
1877 }
1878 }
1879 if (mAllAppsList.modified.size() > 0) {
1880 modified = mAllAppsList.modified;
1881 mAllAppsList.modified = new ArrayList<ApplicationInfo>();
1882 }
1883
1884 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
1885 if (callbacks == null) {
1886 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
1887 return;
1888 }
1889
1890 if (added != null) {
1891 final ArrayList<ApplicationInfo> addedFinal = added;
1892 mHandler.post(new Runnable() {
1893 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07001894 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1895 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001896 callbacks.bindAppsAdded(addedFinal);
1897 }
1898 }
1899 });
1900 }
1901 if (modified != null) {
1902 final ArrayList<ApplicationInfo> modifiedFinal = modified;
1903 mHandler.post(new Runnable() {
1904 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07001905 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1906 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001907 callbacks.bindAppsUpdated(modifiedFinal);
1908 }
1909 }
1910 });
1911 }
1912 if (removed != null) {
1913 final boolean permanent = mOp != OP_UNAVAILABLE;
1914 final ArrayList<ApplicationInfo> removedFinal = removed;
1915 mHandler.post(new Runnable() {
1916 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07001917 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1918 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001919 callbacks.bindAppsRemoved(removedFinal, permanent);
1920 }
1921 }
1922 });
Joe Onoratobe386092009-11-17 17:32:16 -08001923 }
Winson Chung80baf5a2010-08-09 16:03:15 -07001924
1925 mHandler.post(new Runnable() {
1926 @Override
1927 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07001928 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1929 if (callbacks == cb && cb != null) {
Winson Chung80baf5a2010-08-09 16:03:15 -07001930 callbacks.bindPackagesUpdated();
1931 }
1932 }
1933 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04001934 }
1935 }
1936
1937 /**
Winson Chung2efec4e2012-05-03 12:31:48 -07001938 * Returns all the Workspace ShortcutInfos associated with a particular package.
1939 * @param intent
1940 * @return
1941 */
1942 ArrayList<ShortcutInfo> getShortcutInfosForPackage(String packageName) {
1943 ArrayList<ShortcutInfo> infos = new ArrayList<ShortcutInfo>();
Adam Cohend7d37b12012-07-18 16:15:08 -07001944 synchronized (sBgLock) {
1945 for (ItemInfo i : sBgWorkspaceItems) {
1946 if (i instanceof ShortcutInfo) {
1947 ShortcutInfo info = (ShortcutInfo) i;
1948 if (packageName.equals(info.getPackageName())) {
1949 infos.add(info);
1950 }
Winson Chung2efec4e2012-05-03 12:31:48 -07001951 }
1952 }
1953 }
1954 return infos;
1955 }
1956
1957 /**
Joe Onorato56d82912010-03-07 14:32:10 -05001958 * This is called from the code that adds shortcuts from the intent receiver. This
1959 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04001960 */
Joe Onorato56d82912010-03-07 14:32:10 -05001961 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07001962 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05001963 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001964
Joe Onorato56d82912010-03-07 14:32:10 -05001965 /**
1966 * Make an ShortcutInfo object for a shortcut that is an application.
1967 *
1968 * If c is not null, then it will be used to fill in missing data like the title and icon.
1969 */
1970 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07001971 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05001972 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07001973 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05001974
1975 ComponentName componentName = intent.getComponent();
1976 if (componentName == null) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001977 return null;
1978 }
1979
Adam Cohen00fcb492011-11-02 21:53:47 -07001980 try {
1981 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
1982 if (!pi.applicationInfo.enabled) {
1983 // If we return null here, the corresponding item will be removed from the launcher
1984 // db and will not appear in the workspace.
1985 return null;
1986 }
1987 } catch (NameNotFoundException e) {
1988 Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
1989 }
1990
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07001991 // TODO: See if the PackageManager knows about this case. If it doesn't
1992 // then return null & delete this.
1993
Joe Onorato56d82912010-03-07 14:32:10 -05001994 // the resource -- This may implicitly give us back the fallback icon,
1995 // but don't worry about that. All we're doing with usingFallbackIcon is
1996 // to avoid saving lots of copies of that in the database, and most apps
1997 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07001998
1999 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2000 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2001 // via resolveActivity().
2002 ResolveInfo resolveInfo = null;
2003 ComponentName oldComponent = intent.getComponent();
2004 Intent newIntent = new Intent(intent.getAction(), null);
2005 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2006 newIntent.setPackage(oldComponent.getPackageName());
2007 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2008 for (ResolveInfo i : infos) {
2009 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2010 i.activityInfo.name);
2011 if (cn.equals(oldComponent)) {
2012 resolveInfo = i;
2013 }
2014 }
2015 if (resolveInfo == null) {
2016 resolveInfo = manager.resolveActivity(intent, 0);
2017 }
Joe Onorato56d82912010-03-07 14:32:10 -05002018 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002019 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002020 }
Joe Onorato56d82912010-03-07 14:32:10 -05002021 // the db
2022 if (icon == null) {
2023 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002024 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002025 }
2026 }
2027 // the fallback icon
2028 if (icon == null) {
2029 icon = getFallbackIcon();
2030 info.usingFallbackIcon = true;
2031 }
2032 info.setIcon(icon);
2033
2034 // from the resource
2035 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002036 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2037 if (labelCache != null && labelCache.containsKey(key)) {
2038 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002039 } else {
2040 info.title = resolveInfo.activityInfo.loadLabel(manager);
2041 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002042 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002043 }
2044 }
Joe Onorato56d82912010-03-07 14:32:10 -05002045 }
2046 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002047 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002048 if (c != null) {
2049 info.title = c.getString(titleIndex);
2050 }
2051 }
2052 // fall back to the class name of the activity
2053 if (info.title == null) {
2054 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002055 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002056 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2057 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002058 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002059
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002060 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002061 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002062 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002063 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002064 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2065 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002066
Joe Onorato56d82912010-03-07 14:32:10 -05002067 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002068 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002069 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002070
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002071 // TODO: If there's an explicit component and we can't install that, delete it.
2072
Joe Onorato56d82912010-03-07 14:32:10 -05002073 info.title = c.getString(titleIndex);
2074
Joe Onorato9c1289c2009-08-17 11:03:03 -04002075 int iconType = c.getInt(iconTypeIndex);
2076 switch (iconType) {
2077 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2078 String packageName = c.getString(iconPackageIndex);
2079 String resourceName = c.getString(iconResourceIndex);
2080 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002081 info.customIcon = false;
2082 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002083 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002084 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002085 if (resources != null) {
2086 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002087 icon = Utilities.createIconBitmap(
2088 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002089 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002090 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002091 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002092 }
Joe Onorato56d82912010-03-07 14:32:10 -05002093 // the db
2094 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002095 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002096 }
2097 // the fallback icon
2098 if (icon == null) {
2099 icon = getFallbackIcon();
2100 info.usingFallbackIcon = true;
2101 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002102 break;
2103 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002104 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002105 if (icon == null) {
2106 icon = getFallbackIcon();
2107 info.customIcon = false;
2108 info.usingFallbackIcon = true;
2109 } else {
2110 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002111 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002112 break;
2113 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002114 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002115 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002116 info.customIcon = false;
2117 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002118 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002119 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002120 return info;
2121 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002122
Michael Jurka931dc972011-08-05 15:08:15 -07002123 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002124 @SuppressWarnings("all") // suppress dead code warning
2125 final boolean debug = false;
2126 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002127 Log.d(TAG, "getIconFromCursor app="
2128 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2129 }
2130 byte[] data = c.getBlob(iconIndex);
2131 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002132 return Utilities.createIconBitmap(
2133 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002134 } catch (Exception e) {
2135 return null;
2136 }
2137 }
2138
Winson Chung3d503fb2011-07-13 17:25:49 -07002139 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2140 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002141 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002142 if (info == null) {
2143 return null;
2144 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002145 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002146
2147 return info;
2148 }
2149
Winson Chunga9abd0e2010-10-27 17:18:37 -07002150 /**
Winson Chung55cef262010-10-28 14:14:18 -07002151 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2152 */
2153 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2154 ComponentName component) {
2155 List<AppWidgetProviderInfo> widgets =
2156 AppWidgetManager.getInstance(context).getInstalledProviders();
2157 for (AppWidgetProviderInfo info : widgets) {
2158 if (info.provider.equals(component)) {
2159 return info;
2160 }
2161 }
2162 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002163 }
2164
Winson Chung68846fd2010-10-29 11:00:27 -07002165 /**
2166 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2167 */
2168 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2169 final PackageManager packageManager = context.getPackageManager();
2170 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2171 new ArrayList<WidgetMimeTypeHandlerData>();
2172
2173 final Intent supportsIntent =
2174 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2175 supportsIntent.setType(mimeType);
2176
2177 // Create a set of widget configuration components that we can test against
2178 final List<AppWidgetProviderInfo> widgets =
2179 AppWidgetManager.getInstance(context).getInstalledProviders();
2180 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2181 new HashMap<ComponentName, AppWidgetProviderInfo>();
2182 for (AppWidgetProviderInfo info : widgets) {
2183 configurationComponentToWidget.put(info.configure, info);
2184 }
2185
2186 // Run through each of the intents that can handle this type of clip data, and cross
2187 // reference them with the components that are actual configuration components
2188 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2189 PackageManager.MATCH_DEFAULT_ONLY);
2190 for (ResolveInfo info : activities) {
2191 final ActivityInfo activityInfo = info.activityInfo;
2192 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2193 activityInfo.name);
2194 if (configurationComponentToWidget.containsKey(infoComponent)) {
2195 supportedConfigurationActivities.add(
2196 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2197 configurationComponentToWidget.get(infoComponent)));
2198 }
2199 }
2200 return supportedConfigurationActivities;
2201 }
2202
Winson Chunga9abd0e2010-10-27 17:18:37 -07002203 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08002204 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2205 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2206 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2207
Adam Cohend9198822011-11-22 16:42:47 -08002208 if (intent == null) {
2209 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2210 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2211 return null;
2212 }
2213
Joe Onorato0589f0f2010-02-08 13:44:00 -08002214 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08002215 boolean customIcon = false;
2216 ShortcutIconResource iconResource = null;
2217
2218 if (bitmap != null && bitmap instanceof Bitmap) {
2219 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002220 customIcon = true;
2221 } else {
2222 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2223 if (extra != null && extra instanceof ShortcutIconResource) {
2224 try {
2225 iconResource = (ShortcutIconResource) extra;
2226 final PackageManager packageManager = context.getPackageManager();
2227 Resources resources = packageManager.getResourcesForApplication(
2228 iconResource.packageName);
2229 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002230 icon = Utilities.createIconBitmap(
2231 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002232 } catch (Exception e) {
2233 Log.w(TAG, "Could not load shortcut icon: " + extra);
2234 }
2235 }
2236 }
2237
Michael Jurkac9d95c52011-08-29 14:03:34 -07002238 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002239
2240 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002241 if (fallbackIcon != null) {
2242 icon = fallbackIcon;
2243 } else {
2244 icon = getFallbackIcon();
2245 info.usingFallbackIcon = true;
2246 }
Joe Onorato56d82912010-03-07 14:32:10 -05002247 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08002248 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05002249
Joe Onorato0589f0f2010-02-08 13:44:00 -08002250 info.title = name;
2251 info.intent = intent;
2252 info.customIcon = customIcon;
2253 info.iconResource = iconResource;
2254
2255 return info;
2256 }
2257
Winson Chungaac01e12011-08-17 10:37:13 -07002258 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2259 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08002260 // If apps can't be on SD, don't even bother.
2261 if (!mAppsCanBeOnExternalStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07002262 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08002263 }
Joe Onorato56d82912010-03-07 14:32:10 -05002264 // If this icon doesn't have a custom icon, check to see
2265 // what's stored in the DB, and if it doesn't match what
2266 // we're going to show, store what we are going to show back
2267 // into the DB. We do this so when we're loading, if the
2268 // package manager can't find an icon (for example because
2269 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07002270 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07002271 cache.put(info, c.getBlob(iconIndex));
2272 return true;
2273 }
2274 return false;
2275 }
2276 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2277 boolean needSave = false;
2278 try {
2279 if (data != null) {
2280 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2281 Bitmap loaded = info.getIcon(mIconCache);
2282 needSave = !saved.sameAs(loaded);
2283 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05002284 needSave = true;
2285 }
Winson Chungaac01e12011-08-17 10:37:13 -07002286 } catch (Exception e) {
2287 needSave = true;
2288 }
2289 if (needSave) {
2290 Log.d(TAG, "going to save icon bitmap for info=" + info);
2291 // This is slower than is ideal, but this only happens once
2292 // or when the app is updated with a new icon.
2293 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05002294 }
2295 }
2296
Joe Onorato9c1289c2009-08-17 11:03:03 -04002297 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07002298 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04002299 * or make a new one.
2300 */
Adam Cohendf2cc412011-04-27 16:56:57 -07002301 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002302 // See if a placeholder was created for us already
2303 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07002304 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002305 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07002306 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002307 folders.put(id, folderInfo);
2308 }
Adam Cohendf2cc412011-04-27 16:56:57 -07002309 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002310 }
2311
Joe Onorato9c1289c2009-08-17 11:03:03 -04002312 private static final Collator sCollator = Collator.getInstance();
Joe Onoratob0c27f22009-12-01 16:19:38 -08002313 public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
Joe Onorato9c1289c2009-08-17 11:03:03 -04002314 = new Comparator<ApplicationInfo>() {
2315 public final int compare(ApplicationInfo a, ApplicationInfo b) {
Michael Jurka5b1808d2011-07-11 19:59:46 -07002316 int result = sCollator.compare(a.title.toString(), b.title.toString());
2317 if (result == 0) {
2318 result = a.componentName.compareTo(b.componentName);
2319 }
2320 return result;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002321 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002322 };
Winson Chung78403fe2011-01-21 15:38:02 -08002323 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2324 = new Comparator<ApplicationInfo>() {
2325 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2326 if (a.firstInstallTime < b.firstInstallTime) return 1;
2327 if (a.firstInstallTime > b.firstInstallTime) return -1;
2328 return 0;
2329 }
2330 };
Winson Chung785d2eb2011-04-14 16:08:02 -07002331 public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
2332 = new Comparator<AppWidgetProviderInfo>() {
2333 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
2334 return sCollator.compare(a.label.toString(), b.label.toString());
2335 }
2336 };
Winson Chung5308f242011-08-18 12:12:41 -07002337 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
2338 if (info.activityInfo != null) {
2339 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
2340 } else {
2341 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
2342 }
2343 }
Winson Chung785d2eb2011-04-14 16:08:02 -07002344 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
2345 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07002346 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07002347 ShortcutNameComparator(PackageManager pm) {
2348 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07002349 mLabelCache = new HashMap<Object, CharSequence>();
2350 }
2351 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
2352 mPackageManager = pm;
2353 mLabelCache = labelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07002354 }
2355 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002356 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07002357 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
2358 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
2359 if (mLabelCache.containsKey(keyA)) {
2360 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002361 } else {
2362 labelA = a.loadLabel(mPackageManager).toString();
2363
Winson Chung5308f242011-08-18 12:12:41 -07002364 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002365 }
Winson Chung5308f242011-08-18 12:12:41 -07002366 if (mLabelCache.containsKey(keyB)) {
2367 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002368 } else {
2369 labelB = b.loadLabel(mPackageManager).toString();
2370
Winson Chung5308f242011-08-18 12:12:41 -07002371 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002372 }
Winson Chung785d2eb2011-04-14 16:08:02 -07002373 return sCollator.compare(labelA, labelB);
2374 }
2375 };
Winson Chung1ed747a2011-05-03 16:18:34 -07002376 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
2377 private PackageManager mPackageManager;
2378 private HashMap<Object, String> mLabelCache;
2379 WidgetAndShortcutNameComparator(PackageManager pm) {
2380 mPackageManager = pm;
2381 mLabelCache = new HashMap<Object, String>();
2382 }
2383 public final int compare(Object a, Object b) {
2384 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07002385 if (mLabelCache.containsKey(a)) {
2386 labelA = mLabelCache.get(a);
2387 } else {
2388 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002389 ((AppWidgetProviderInfo) a).label :
2390 ((ResolveInfo) a).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002391 mLabelCache.put(a, labelA);
2392 }
2393 if (mLabelCache.containsKey(b)) {
2394 labelB = mLabelCache.get(b);
2395 } else {
2396 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002397 ((AppWidgetProviderInfo) b).label :
2398 ((ResolveInfo) b).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002399 mLabelCache.put(b, labelB);
2400 }
Winson Chung1ed747a2011-05-03 16:18:34 -07002401 return sCollator.compare(labelA, labelB);
2402 }
2403 };
Joe Onoratobe386092009-11-17 17:32:16 -08002404
2405 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08002406 Log.d(TAG, "mCallbacks=" + mCallbacks);
2407 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
2408 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
2409 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
2410 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04002411 if (mLoaderTask != null) {
2412 mLoaderTask.dumpState();
2413 } else {
2414 Log.d(TAG, "mLoaderTask=null");
2415 }
Joe Onoratobe386092009-11-17 17:32:16 -08002416 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002417}