blob: d4b7f7652e2d3dbc131a5abf1cd109c88881025d [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
921 // Divide the set of loaded items into those that we are binding synchronously, and
922 // everything else that is to be bound normally (asynchronously).
923 bindWorkspace(synchronousBindPage);
924 // XXX: For now, continue posting the binding of AllApps as there are other issues that
925 // arise from that.
926 onlyBindAllApps();
927 }
928
Joe Onorato36115782010-06-17 13:28:48 -0400929 public void run() {
Adam Cohend7d37b12012-07-18 16:15:08 -0700930 synchronized (mLock) {
931 mIsLoaderTaskRunning = true;
932 }
Joe Onorato36115782010-06-17 13:28:48 -0400933 // Optimize for end-user experience: if the Launcher is up and // running with the
934 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
935 // workspace first (default).
936 final Callbacks cbk = mCallbacks.get();
937 final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
Daniel Sandler843e8602010-06-07 14:59:01 -0400938
Joe Onorato36115782010-06-17 13:28:48 -0400939 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -0400940 // Elevate priority when Home launches for the first time to avoid
941 // starving at boot time. Staring at a blank home is not cool.
942 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -0700943 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
944 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -0400945 android.os.Process.setThreadPriority(mIsLaunching
946 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
947 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400948 if (loadWorkspaceFirst) {
949 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
950 loadAndBindWorkspace();
951 } else {
952 if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
Joe Onoratocc67f472010-06-08 10:54:30 -0700953 loadAndBindAllApps();
Daniel Sandler843e8602010-06-07 14:59:01 -0400954 }
955
Joe Onorato36115782010-06-17 13:28:48 -0400956 if (mStopped) {
957 break keep_running;
958 }
959
960 // Whew! Hard work done. Slow us down, and wait until the UI thread has
961 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -0400962 synchronized (mLock) {
963 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -0700964 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -0400965 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
966 }
967 }
Joe Onorato36115782010-06-17 13:28:48 -0400968 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -0400969
970 // second step
971 if (loadWorkspaceFirst) {
972 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
Joe Onoratocc67f472010-06-08 10:54:30 -0700973 loadAndBindAllApps();
Daniel Sandler843e8602010-06-07 14:59:01 -0400974 } else {
975 if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
976 loadAndBindWorkspace();
977 }
Winson Chung7ed37742011-09-08 15:45:51 -0700978
979 // Restore the default thread priority after we are done loading items
980 synchronized (mLock) {
981 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
982 }
Joe Onorato36115782010-06-17 13:28:48 -0400983 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400984
Winson Chungaac01e12011-08-17 10:37:13 -0700985
986 // Update the saved icons if necessary
987 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Adam Cohend7d37b12012-07-18 16:15:08 -0700988 synchronized (sBgLock) {
989 for (Object key : sBgDbIconCache.keySet()) {
990 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
991 }
992 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -0700993 }
Winson Chungaac01e12011-08-17 10:37:13 -0700994
Joe Onorato36115782010-06-17 13:28:48 -0400995 // Clear out this reference, otherwise we end up holding it until all of the
996 // callback runnables are done.
997 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400998
Joe Onorato36115782010-06-17 13:28:48 -0400999 synchronized (mLock) {
1000 // If we are still the last one to be scheduled, remove ourselves.
1001 if (mLoaderTask == this) {
1002 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001003 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001004 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001005 }
Joe Onorato36115782010-06-17 13:28:48 -04001006 }
1007
1008 public void stopLocked() {
1009 synchronized (LoaderTask.this) {
1010 mStopped = true;
1011 this.notify();
1012 }
1013 }
1014
1015 /**
1016 * Gets the callbacks object. If we've been stopped, or if the launcher object
1017 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1018 * object that was around when the deferred message was scheduled, and if there's
1019 * a new Callbacks object around then also return null. This will save us from
1020 * calling onto it with data that will be ignored.
1021 */
1022 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1023 synchronized (mLock) {
1024 if (mStopped) {
1025 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001026 }
Joe Onorato36115782010-06-17 13:28:48 -04001027
1028 if (mCallbacks == null) {
1029 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001030 }
Joe Onorato36115782010-06-17 13:28:48 -04001031
1032 final Callbacks callbacks = mCallbacks.get();
1033 if (callbacks != oldCallbacks) {
1034 return null;
1035 }
1036 if (callbacks == null) {
1037 Log.w(TAG, "no mCallbacks");
1038 return null;
1039 }
1040
1041 return callbacks;
1042 }
1043 }
1044
1045 // check & update map of what's occupied; used to discard overlapping/invalid items
1046 private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001047 int containerIndex = item.screen;
1048 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001049 // Return early if we detect that an item is under the hotseat button
Andrew Flynn0dca1ec2012-02-29 13:33:22 -08001050 if (mCallbacks == null || mCallbacks.get().isAllAppsButtonRank(item.screen)) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001051 return false;
1052 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001053
1054 // We use the last index to refer to the hotseat and the screen as the rank, so
1055 // test and update the occupied state accordingly
1056 if (occupied[Launcher.SCREEN_COUNT][item.screen][0] != null) {
1057 Log.e(TAG, "Error loading shortcut into hotseat " + item
1058 + " into position (" + item.screen + ":" + item.cellX + "," + item.cellY
1059 + ") occupied by " + occupied[Launcher.SCREEN_COUNT][item.screen][0]);
1060 return false;
1061 } else {
1062 occupied[Launcher.SCREEN_COUNT][item.screen][0] = item;
1063 return true;
1064 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001065 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1066 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001067 return true;
1068 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001069
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001070 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001071 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1072 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001073 if (occupied[containerIndex][x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001074 Log.e(TAG, "Error loading shortcut " + item
Winson Chungf30ad5f2011-08-08 10:55:42 -07001075 + " into cell (" + containerIndex + "-" + item.screen + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001076 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001077 + ") occupied by "
Winson Chungf30ad5f2011-08-08 10:55:42 -07001078 + occupied[containerIndex][x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001079 return false;
1080 }
1081 }
1082 }
1083 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1084 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001085 occupied[containerIndex][x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001086 }
1087 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001088
Joe Onorato36115782010-06-17 13:28:48 -04001089 return true;
1090 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001091
Joe Onorato36115782010-06-17 13:28:48 -04001092 private void loadWorkspace() {
1093 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001094
Joe Onorato36115782010-06-17 13:28:48 -04001095 final Context context = mContext;
1096 final ContentResolver contentResolver = context.getContentResolver();
1097 final PackageManager manager = context.getPackageManager();
1098 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1099 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001100
Michael Jurkab85f8a42012-04-25 15:48:32 -07001101 // Make sure the default workspace is loaded, if needed
1102 mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary();
1103
Adam Cohend7d37b12012-07-18 16:15:08 -07001104 synchronized (sBgLock) {
1105 sBgWorkspaceItems.clear();
1106 sBgAppWidgets.clear();
1107 sBgFolders.clear();
1108 sBgItemsIdMap.clear();
1109 sBgDbIconCache.clear();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001110
Adam Cohend7d37b12012-07-18 16:15:08 -07001111 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001112
Adam Cohend7d37b12012-07-18 16:15:08 -07001113 final Cursor c = contentResolver.query(
1114 LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001115
Adam Cohend7d37b12012-07-18 16:15:08 -07001116 // +1 for the hotseat (it can be larger than the workspace)
1117 // Load workspace in reverse order to ensure that latest items are loaded first (and
1118 // before any earlier duplicates)
1119 final ItemInfo occupied[][][] =
1120 new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1];
Joe Onorato9c1289c2009-08-17 11:03:03 -04001121
Adam Cohend7d37b12012-07-18 16:15:08 -07001122 try {
1123 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1124 final int intentIndex = c.getColumnIndexOrThrow
1125 (LauncherSettings.Favorites.INTENT);
1126 final int titleIndex = c.getColumnIndexOrThrow
1127 (LauncherSettings.Favorites.TITLE);
1128 final int iconTypeIndex = c.getColumnIndexOrThrow(
1129 LauncherSettings.Favorites.ICON_TYPE);
1130 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1131 final int iconPackageIndex = c.getColumnIndexOrThrow(
1132 LauncherSettings.Favorites.ICON_PACKAGE);
1133 final int iconResourceIndex = c.getColumnIndexOrThrow(
1134 LauncherSettings.Favorites.ICON_RESOURCE);
1135 final int containerIndex = c.getColumnIndexOrThrow(
1136 LauncherSettings.Favorites.CONTAINER);
1137 final int itemTypeIndex = c.getColumnIndexOrThrow(
1138 LauncherSettings.Favorites.ITEM_TYPE);
1139 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1140 LauncherSettings.Favorites.APPWIDGET_ID);
1141 final int screenIndex = c.getColumnIndexOrThrow(
1142 LauncherSettings.Favorites.SCREEN);
1143 final int cellXIndex = c.getColumnIndexOrThrow
1144 (LauncherSettings.Favorites.CELLX);
1145 final int cellYIndex = c.getColumnIndexOrThrow
1146 (LauncherSettings.Favorites.CELLY);
1147 final int spanXIndex = c.getColumnIndexOrThrow
1148 (LauncherSettings.Favorites.SPANX);
1149 final int spanYIndex = c.getColumnIndexOrThrow(
1150 LauncherSettings.Favorites.SPANY);
1151 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1152 //final int displayModeIndex = c.getColumnIndexOrThrow(
1153 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001154
Adam Cohend7d37b12012-07-18 16:15:08 -07001155 ShortcutInfo info;
1156 String intentDescription;
1157 LauncherAppWidgetInfo appWidgetInfo;
1158 int container;
1159 long id;
1160 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001161
Adam Cohend7d37b12012-07-18 16:15:08 -07001162 while (!mStopped && c.moveToNext()) {
1163 try {
1164 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001165
Adam Cohend7d37b12012-07-18 16:15:08 -07001166 switch (itemType) {
1167 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1168 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1169 intentDescription = c.getString(intentIndex);
1170 try {
1171 intent = Intent.parseUri(intentDescription, 0);
1172 } catch (URISyntaxException e) {
1173 continue;
1174 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001175
Adam Cohend7d37b12012-07-18 16:15:08 -07001176 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1177 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1178 titleIndex, mLabelCache);
1179 } else {
1180 info = getShortcutInfo(c, context, iconTypeIndex,
1181 iconPackageIndex, iconResourceIndex, iconIndex,
1182 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001183
Adam Cohend7d37b12012-07-18 16:15:08 -07001184 // App shortcuts that used to be automatically added to Launcher
1185 // didn't always have the correct intent flags set, so do that
1186 // here
1187 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001188 intent.getCategories() != null &&
1189 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001190 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Adam Cohend7d37b12012-07-18 16:15:08 -07001191 intent.addFlags(
1192 Intent.FLAG_ACTIVITY_NEW_TASK |
1193 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1194 }
Michael Jurka96879562012-03-22 05:54:33 -07001195 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001196
Adam Cohend7d37b12012-07-18 16:15:08 -07001197 if (info != null) {
1198 info.intent = intent;
1199 info.id = c.getLong(idIndex);
1200 container = c.getInt(containerIndex);
1201 info.container = container;
1202 info.screen = c.getInt(screenIndex);
1203 info.cellX = c.getInt(cellXIndex);
1204 info.cellY = c.getInt(cellYIndex);
1205
1206 // check & update map of what's occupied
1207 if (!checkItemPlacement(occupied, info)) {
1208 break;
1209 }
1210
1211 switch (container) {
1212 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1213 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1214 sBgWorkspaceItems.add(info);
1215 break;
1216 default:
1217 // Item is in a user folder
1218 FolderInfo folderInfo =
1219 findOrMakeFolder(sBgFolders, container);
1220 folderInfo.add(info);
1221 break;
1222 }
1223 sBgItemsIdMap.put(info.id, info);
1224
1225 // now that we've loaded everthing re-save it with the
1226 // icon in case it disappears somehow.
1227 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
1228 } else {
1229 // Failed to load the shortcut, probably because the
1230 // activity manager couldn't resolve it (maybe the app
1231 // was uninstalled), or the db row was somehow screwed up.
1232 // Delete it.
1233 id = c.getLong(idIndex);
1234 Log.e(TAG, "Error loading shortcut " + id + ", removing it");
1235 contentResolver.delete(LauncherSettings.Favorites.getContentUri(
1236 id, false), null, null);
1237 }
1238 break;
1239
1240 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1241 id = c.getLong(idIndex);
1242 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1243
1244 folderInfo.title = c.getString(titleIndex);
1245 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001246 container = c.getInt(containerIndex);
Adam Cohend7d37b12012-07-18 16:15:08 -07001247 folderInfo.container = container;
1248 folderInfo.screen = c.getInt(screenIndex);
1249 folderInfo.cellX = c.getInt(cellXIndex);
1250 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001251
Daniel Sandler8802e962010-05-26 16:28:16 -04001252 // check & update map of what's occupied
Adam Cohend7d37b12012-07-18 16:15:08 -07001253 if (!checkItemPlacement(occupied, folderInfo)) {
Daniel Sandler8802e962010-05-26 16:28:16 -04001254 break;
1255 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001256 switch (container) {
Adam Cohend7d37b12012-07-18 16:15:08 -07001257 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1258 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1259 sBgWorkspaceItems.add(folderInfo);
1260 break;
Joe Onorato36115782010-06-17 13:28:48 -04001261 }
Joe Onorato17a89222011-02-08 17:26:11 -08001262
Adam Cohend7d37b12012-07-18 16:15:08 -07001263 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1264 sBgFolders.put(folderInfo.id, folderInfo);
1265 break;
1266
1267 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1268 // Read all Launcher-specific widget details
1269 int appWidgetId = c.getInt(appWidgetIdIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001270 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001271
Adam Cohend7d37b12012-07-18 16:15:08 -07001272 final AppWidgetProviderInfo provider =
1273 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001274
Adam Cohend7d37b12012-07-18 16:15:08 -07001275 if (!isSafeMode && (provider == null || provider.provider == null ||
1276 provider.provider.getPackageName() == null)) {
1277 String log = "Deleting widget that isn't installed anymore: id="
1278 + id + " appWidgetId=" + appWidgetId;
1279 Log.e(TAG, log);
1280 Launcher.sDumpLogs.add(log);
1281 itemsToRemove.add(id);
1282 } else {
1283 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1284 provider.provider);
1285 appWidgetInfo.id = id;
1286 appWidgetInfo.screen = c.getInt(screenIndex);
1287 appWidgetInfo.cellX = c.getInt(cellXIndex);
1288 appWidgetInfo.cellY = c.getInt(cellYIndex);
1289 appWidgetInfo.spanX = c.getInt(spanXIndex);
1290 appWidgetInfo.spanY = c.getInt(spanYIndex);
1291 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1292 appWidgetInfo.minSpanX = minSpan[0];
1293 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001294
Adam Cohend7d37b12012-07-18 16:15:08 -07001295 container = c.getInt(containerIndex);
1296 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1297 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1298 Log.e(TAG, "Widget found where container != " +
1299 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1300 continue;
1301 }
1302 appWidgetInfo.container = c.getInt(containerIndex);
1303
1304 // check & update map of what's occupied
1305 if (!checkItemPlacement(occupied, appWidgetInfo)) {
1306 break;
1307 }
1308 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1309 sBgAppWidgets.add(appWidgetInfo);
1310 }
Joe Onorato36115782010-06-17 13:28:48 -04001311 break;
1312 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001313 } catch (Exception e) {
1314 Log.w(TAG, "Desktop items loading interrupted:", e);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001315 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001316 }
1317 } finally {
1318 c.close();
1319 }
1320
1321 if (itemsToRemove.size() > 0) {
1322 ContentProviderClient client = contentResolver.acquireContentProviderClient(
1323 LauncherSettings.Favorites.CONTENT_URI);
1324 // Remove dead items
1325 for (long id : itemsToRemove) {
1326 if (DEBUG_LOADERS) {
1327 Log.d(TAG, "Removed id = " + id);
1328 }
1329 // Don't notify content observers
1330 try {
1331 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1332 null, null);
1333 } catch (RemoteException e) {
1334 Log.w(TAG, "Could not remove id = " + id);
1335 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001336 }
1337 }
1338
Adam Cohend7d37b12012-07-18 16:15:08 -07001339 if (DEBUG_LOADERS) {
1340 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1341 Log.d(TAG, "workspace layout: ");
1342 for (int y = 0; y < mCellCountY; y++) {
1343 String line = "";
1344 for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
1345 if (s > 0) {
1346 line += " | ";
1347 }
1348 for (int x = 0; x < mCellCountX; x++) {
1349 line += ((occupied[s][x][y] != null) ? "#" : ".");
1350 }
Joe Onorato36115782010-06-17 13:28:48 -04001351 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001352 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04001353 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001354 }
Joe Onorato36115782010-06-17 13:28:48 -04001355 }
1356 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001357
Adam Cohend7d37b12012-07-18 16:15:08 -07001358 /** Filters the set of items who are directly or indirectly (via another container) on the
1359 * specified screen. */
1360 private void filterCurrentWorkspaceItems(int currentScreen,
1361 ArrayList<ItemInfo> allWorkspaceItems,
1362 ArrayList<ItemInfo> currentScreenItems,
1363 ArrayList<ItemInfo> otherScreenItems) {
1364 // Purge any null ItemInfos
1365 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1366 while (iter.hasNext()) {
1367 ItemInfo i = iter.next();
1368 if (i == null) {
1369 iter.remove();
1370 }
Joe Onorato36115782010-06-17 13:28:48 -04001371 }
1372
Adam Cohend7d37b12012-07-18 16:15:08 -07001373 // If we aren't filtering on a screen, then the set of items to load is the full set of
1374 // items given.
1375 if (currentScreen < 0) {
1376 currentScreenItems.addAll(allWorkspaceItems);
1377 }
1378
1379 // Order the set of items by their containers first, this allows use to walk through the
1380 // list sequentially, build up a list of containers that are in the specified screen,
1381 // as well as all items in those containers.
1382 Set<Long> itemsOnScreen = new HashSet<Long>();
1383 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1384 @Override
1385 public int compare(ItemInfo lhs, ItemInfo rhs) {
1386 return (int) (lhs.container - rhs.container);
1387 }
1388 });
1389 for (ItemInfo info : allWorkspaceItems) {
1390 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1391 if (info.screen == currentScreen) {
1392 currentScreenItems.add(info);
1393 itemsOnScreen.add(info.id);
1394 } else {
1395 otherScreenItems.add(info);
1396 }
1397 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1398 currentScreenItems.add(info);
1399 itemsOnScreen.add(info.id);
1400 } else {
1401 if (itemsOnScreen.contains(info.container)) {
1402 currentScreenItems.add(info);
1403 itemsOnScreen.add(info.id);
1404 } else {
1405 otherScreenItems.add(info);
1406 }
1407 }
1408 }
1409 }
1410
1411 /** Filters the set of widgets which are on the specified screen. */
1412 private void filterCurrentAppWidgets(int currentScreen,
1413 ArrayList<LauncherAppWidgetInfo> appWidgets,
1414 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1415 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1416 // If we aren't filtering on a screen, then the set of items to load is the full set of
1417 // widgets given.
1418 if (currentScreen < 0) {
1419 currentScreenWidgets.addAll(appWidgets);
1420 }
1421
1422 for (LauncherAppWidgetInfo widget : appWidgets) {
1423 if (widget == null) continue;
1424 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1425 widget.screen == currentScreen) {
1426 currentScreenWidgets.add(widget);
1427 } else {
1428 otherScreenWidgets.add(widget);
1429 }
1430 }
1431 }
1432
1433 /** Filters the set of folders which are on the specified screen. */
1434 private void filterCurrentFolders(int currentScreen,
1435 HashMap<Long, ItemInfo> itemsIdMap,
1436 HashMap<Long, FolderInfo> folders,
1437 HashMap<Long, FolderInfo> currentScreenFolders,
1438 HashMap<Long, FolderInfo> otherScreenFolders) {
1439 // If we aren't filtering on a screen, then the set of items to load is the full set of
1440 // widgets given.
1441 if (currentScreen < 0) {
1442 currentScreenFolders.putAll(folders);
1443 }
1444
1445 for (long id : folders.keySet()) {
1446 ItemInfo info = itemsIdMap.get(id);
1447 FolderInfo folder = folders.get(id);
1448 if (info == null || folder == null) continue;
1449 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1450 info.screen == currentScreen) {
1451 currentScreenFolders.put(id, folder);
1452 } else {
1453 otherScreenFolders.put(id, folder);
1454 }
1455 }
1456 }
1457
1458 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
1459 * right) */
1460 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
1461 // XXX: review this
1462 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07001463 @Override
1464 public int compare(ItemInfo lhs, ItemInfo rhs) {
1465 int cellCountX = LauncherModel.getCellCountX();
1466 int cellCountY = LauncherModel.getCellCountY();
1467 int screenOffset = cellCountX * cellCountY;
1468 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
1469 long lr = (lhs.container * containerOffset + lhs.screen * screenOffset +
1470 lhs.cellY * cellCountX + lhs.cellX);
1471 long rr = (rhs.container * containerOffset + rhs.screen * screenOffset +
1472 rhs.cellY * cellCountX + rhs.cellX);
1473 return (int) (lr - rr);
1474 }
1475 });
Adam Cohend7d37b12012-07-18 16:15:08 -07001476 }
Winson Chungdb8a8942012-04-03 14:08:41 -07001477
Adam Cohend7d37b12012-07-18 16:15:08 -07001478 private void bindWorkspaceItems(final Callbacks oldCallbacks,
1479 final ArrayList<ItemInfo> workspaceItems,
1480 final ArrayList<LauncherAppWidgetInfo> appWidgets,
1481 final HashMap<Long, FolderInfo> folders,
1482 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07001483
Adam Cohend7d37b12012-07-18 16:15:08 -07001484 final boolean postOnMainThread = (deferredBindRunnables != null);
1485
1486 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07001487 int N = workspaceItems.size();
Adam Cohend7d37b12012-07-18 16:15:08 -07001488 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04001489 final int start = i;
1490 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Adam Cohend7d37b12012-07-18 16:15:08 -07001491 final Runnable r = new Runnable() {
1492 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04001493 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08001494 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001495 if (callbacks != null) {
Winson Chung603bcb92011-09-02 11:45:39 -07001496 callbacks.bindItems(workspaceItems, start, start+chunkSize);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001497 }
1498 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001499 };
1500 if (postOnMainThread) {
1501 deferredBindRunnables.add(r);
1502 } else {
1503 runOnMainThread(r);
1504 }
Joe Onorato36115782010-06-17 13:28:48 -04001505 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001506
1507 // Bind the folders
1508 if (!folders.isEmpty()) {
1509 final Runnable r = new Runnable() {
1510 public void run() {
1511 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1512 if (callbacks != null) {
1513 callbacks.bindFolders(folders);
1514 }
1515 }
1516 };
1517 if (postOnMainThread) {
1518 deferredBindRunnables.add(r);
1519 } else {
1520 runOnMainThread(r);
1521 }
1522 }
1523
1524 // Bind the widgets, one at a time
1525 N = appWidgets.size();
1526 for (int i = 0; i < N; i++) {
1527 final LauncherAppWidgetInfo widget = appWidgets.get(i);
1528 final Runnable r = new Runnable() {
1529 public void run() {
1530 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1531 if (callbacks != null) {
1532 callbacks.bindAppWidget(widget);
1533 }
1534 }
1535 };
1536 if (postOnMainThread) {
1537 deferredBindRunnables.add(r);
1538 } else {
1539 runOnMainThread(r);
1540 }
1541 }
1542 }
1543
1544 /**
1545 * Binds all loaded data to actual views on the main thread.
1546 */
1547 private void bindWorkspace(int synchronizeBindPage) {
1548 final long t = SystemClock.uptimeMillis();
1549 Runnable r;
1550
1551 // Don't use these two variables in any of the callback runnables.
1552 // Otherwise we hold a reference to them.
1553 final Callbacks oldCallbacks = mCallbacks.get();
1554 if (oldCallbacks == null) {
1555 // This launcher has exited and nobody bothered to tell us. Just bail.
1556 Log.w(TAG, "LoaderTask running with no launcher");
1557 return;
1558 }
1559
Winson Chung36e6c5b2012-07-19 14:53:05 -07001560 final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
1561 final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
Adam Cohend7d37b12012-07-18 16:15:08 -07001562 oldCallbacks.getCurrentWorkspaceScreen();
1563
1564 // Load all the items that are on the current page first (and in the process, unbind
1565 // all the existing workspace items before we call startBinding() below.
1566 unbindWorkspaceItemsOnMainThread();
1567 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
1568 ArrayList<LauncherAppWidgetInfo> appWidgets =
1569 new ArrayList<LauncherAppWidgetInfo>();
1570 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
1571 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
1572 synchronized (sBgLock) {
1573 workspaceItems.addAll(sBgWorkspaceItems);
1574 appWidgets.addAll(sBgAppWidgets);
1575 folders.putAll(sBgFolders);
1576 itemsIdMap.putAll(sBgItemsIdMap);
1577 }
1578
1579 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
1580 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
1581 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
1582 new ArrayList<LauncherAppWidgetInfo>();
1583 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
1584 new ArrayList<LauncherAppWidgetInfo>();
1585 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
1586 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
1587
1588 // Separate the items that are on the current screen, and all the other remaining items
1589 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
1590 otherWorkspaceItems);
1591 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
1592 otherAppWidgets);
1593 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
1594 otherFolders);
1595 sortWorkspaceItemsSpatially(currentWorkspaceItems);
1596 sortWorkspaceItemsSpatially(otherWorkspaceItems);
1597
1598 // Tell the workspace that we're about to start binding items
1599 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001600 public void run() {
1601 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1602 if (callbacks != null) {
Adam Cohend7d37b12012-07-18 16:15:08 -07001603 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04001604 }
1605 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001606 };
1607 runOnMainThread(r);
1608
1609 // Load items on the current page
1610 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
1611 currentFolders, null);
1612
Winson Chung36e6c5b2012-07-19 14:53:05 -07001613 // Load all the remaining pages (if we are loading synchronously, we want to defer this
1614 // work until after the first render)
Adam Cohend7d37b12012-07-18 16:15:08 -07001615 mDeferredBindRunnables.clear();
1616 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung36e6c5b2012-07-19 14:53:05 -07001617 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Adam Cohend7d37b12012-07-18 16:15:08 -07001618
1619 // Tell the workspace that we're done binding items
1620 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001621 public void run() {
1622 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1623 if (callbacks != null) {
1624 callbacks.finishBindingItems();
1625 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001626
Winson Chung98e030b2012-05-07 16:01:11 -07001627 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04001628 if (DEBUG_LOADERS) {
1629 Log.d(TAG, "bound workspace in "
1630 + (SystemClock.uptimeMillis()-t) + "ms");
1631 }
Winson Chung36a62fe2012-05-06 18:04:42 -07001632
1633 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04001634 }
Adam Cohend7d37b12012-07-18 16:15:08 -07001635 };
Winson Chung36e6c5b2012-07-19 14:53:05 -07001636 if (isLoadingSynchronously) {
1637 mDeferredBindRunnables.add(r);
1638 } else {
1639 runOnMainThread(r);
1640 }
Joe Onorato36115782010-06-17 13:28:48 -04001641 }
Joe Onoratocc67f472010-06-08 10:54:30 -07001642
Joe Onorato36115782010-06-17 13:28:48 -04001643 private void loadAndBindAllApps() {
1644 if (DEBUG_LOADERS) {
1645 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
1646 }
1647 if (!mAllAppsLoaded) {
1648 loadAllAppsByBatch();
Reena Lee93f824a2011-09-23 17:20:28 -07001649 synchronized (LoaderTask.this) {
1650 if (mStopped) {
1651 return;
1652 }
1653 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07001654 }
Joe Onorato36115782010-06-17 13:28:48 -04001655 } else {
1656 onlyBindAllApps();
1657 }
1658 }
Joe Onoratocc67f472010-06-08 10:54:30 -07001659
Joe Onorato36115782010-06-17 13:28:48 -04001660 private void onlyBindAllApps() {
1661 final Callbacks oldCallbacks = mCallbacks.get();
1662 if (oldCallbacks == null) {
1663 // This launcher has exited and nobody bothered to tell us. Just bail.
1664 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
1665 return;
1666 }
1667
1668 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07001669 @SuppressWarnings("unchecked")
Joe Onorato36115782010-06-17 13:28:48 -04001670 final ArrayList<ApplicationInfo> list
Michael Jurka92f3d462011-11-22 21:02:29 -08001671 = (ArrayList<ApplicationInfo>) mAllAppsList.data.clone();
Joe Onorato36115782010-06-17 13:28:48 -04001672 mHandler.post(new Runnable() {
1673 public void run() {
1674 final long t = SystemClock.uptimeMillis();
1675 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1676 if (callbacks != null) {
1677 callbacks.bindAllApplications(list);
1678 }
1679 if (DEBUG_LOADERS) {
1680 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
1681 + (SystemClock.uptimeMillis()-t) + "ms");
1682 }
1683 }
1684 });
Joe Onorato36115782010-06-17 13:28:48 -04001685 }
1686
1687 private void loadAllAppsByBatch() {
1688 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1689
1690 // Don't use these two variables in any of the callback runnables.
1691 // Otherwise we hold a reference to them.
1692 final Callbacks oldCallbacks = mCallbacks.get();
1693 if (oldCallbacks == null) {
1694 // This launcher has exited and nobody bothered to tell us. Just bail.
1695 Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
1696 return;
1697 }
1698
1699 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1700 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1701
1702 final PackageManager packageManager = mContext.getPackageManager();
1703 List<ResolveInfo> apps = null;
1704
1705 int N = Integer.MAX_VALUE;
1706
1707 int startIndex;
1708 int i=0;
1709 int batchSize = -1;
1710 while (i < N && !mStopped) {
1711 if (i == 0) {
1712 mAllAppsList.clear();
1713 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1714 apps = packageManager.queryIntentActivities(mainIntent, 0);
1715 if (DEBUG_LOADERS) {
1716 Log.d(TAG, "queryIntentActivities took "
1717 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
1718 }
1719 if (apps == null) {
1720 return;
1721 }
1722 N = apps.size();
1723 if (DEBUG_LOADERS) {
1724 Log.d(TAG, "queryIntentActivities got " + N + " apps");
1725 }
1726 if (N == 0) {
1727 // There are no apps?!?
1728 return;
1729 }
1730 if (mBatchSize == 0) {
1731 batchSize = N;
1732 } else {
1733 batchSize = mBatchSize;
1734 }
1735
1736 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1737 Collections.sort(apps,
Winson Chungc3eecff2011-07-11 17:44:15 -07001738 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
Joe Onorato36115782010-06-17 13:28:48 -04001739 if (DEBUG_LOADERS) {
1740 Log.d(TAG, "sort took "
1741 + (SystemClock.uptimeMillis()-sortTime) + "ms");
1742 }
1743 }
1744
1745 final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1746
1747 startIndex = i;
1748 for (int j=0; i<N && j<batchSize; j++) {
1749 // This builds the icon bitmaps.
Winson Chungc3eecff2011-07-11 17:44:15 -07001750 mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
Michael Jurkac9d95c52011-08-29 14:03:34 -07001751 mIconCache, mLabelCache));
Joe Onorato36115782010-06-17 13:28:48 -04001752 i++;
1753 }
1754
1755 final boolean first = i <= batchSize;
1756 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1757 final ArrayList<ApplicationInfo> added = mAllAppsList.added;
1758 mAllAppsList.added = new ArrayList<ApplicationInfo>();
1759
Joe Onoratocc67f472010-06-08 10:54:30 -07001760 mHandler.post(new Runnable() {
1761 public void run() {
1762 final long t = SystemClock.uptimeMillis();
Joe Onoratocc67f472010-06-08 10:54:30 -07001763 if (callbacks != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001764 if (first) {
1765 callbacks.bindAllApplications(added);
1766 } else {
1767 callbacks.bindAppsAdded(added);
1768 }
1769 if (DEBUG_LOADERS) {
1770 Log.d(TAG, "bound " + added.size() + " apps in "
1771 + (SystemClock.uptimeMillis() - t) + "ms");
1772 }
1773 } else {
1774 Log.i(TAG, "not binding apps: no Launcher activity");
Joe Onoratocc67f472010-06-08 10:54:30 -07001775 }
1776 }
1777 });
1778
Daniel Sandlerdca66122010-04-13 16:23:58 -04001779 if (DEBUG_LOADERS) {
Joe Onorato36115782010-06-17 13:28:48 -04001780 Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
1781 + (SystemClock.uptimeMillis()-t2) + "ms");
1782 }
1783
1784 if (mAllAppsLoadDelay > 0 && i < N) {
1785 try {
1786 if (DEBUG_LOADERS) {
1787 Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
1788 }
1789 Thread.sleep(mAllAppsLoadDelay);
1790 } catch (InterruptedException exc) { }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001791 }
1792 }
1793
Joe Onorato36115782010-06-17 13:28:48 -04001794 if (DEBUG_LOADERS) {
1795 Log.d(TAG, "cached all " + N + " apps in "
1796 + (SystemClock.uptimeMillis()-t) + "ms"
1797 + (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
Joe Onoratobe386092009-11-17 17:32:16 -08001798 }
1799 }
1800
1801 public void dumpState() {
Adam Cohend7d37b12012-07-18 16:15:08 -07001802 synchronized (sBgLock) {
1803 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
1804 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
1805 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
1806 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
1807 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
1808 }
Joe Onorato36115782010-06-17 13:28:48 -04001809 }
1810 }
1811
1812 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07001813 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04001814 }
1815
1816 private class PackageUpdatedTask implements Runnable {
1817 int mOp;
1818 String[] mPackages;
1819
1820 public static final int OP_NONE = 0;
1821 public static final int OP_ADD = 1;
1822 public static final int OP_UPDATE = 2;
1823 public static final int OP_REMOVE = 3; // uninstlled
1824 public static final int OP_UNAVAILABLE = 4; // external media unmounted
1825
1826
1827 public PackageUpdatedTask(int op, String[] packages) {
1828 mOp = op;
1829 mPackages = packages;
1830 }
1831
1832 public void run() {
1833 final Context context = mApp;
1834
1835 final String[] packages = mPackages;
1836 final int N = packages.length;
1837 switch (mOp) {
1838 case OP_ADD:
1839 for (int i=0; i<N; i++) {
1840 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
1841 mAllAppsList.addPackage(context, packages[i]);
1842 }
1843 break;
1844 case OP_UPDATE:
1845 for (int i=0; i<N; i++) {
1846 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
1847 mAllAppsList.updatePackage(context, packages[i]);
1848 }
1849 break;
1850 case OP_REMOVE:
1851 case OP_UNAVAILABLE:
1852 for (int i=0; i<N; i++) {
1853 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
1854 mAllAppsList.removePackage(packages[i]);
1855 }
1856 break;
1857 }
1858
1859 ArrayList<ApplicationInfo> added = null;
1860 ArrayList<ApplicationInfo> removed = null;
1861 ArrayList<ApplicationInfo> modified = null;
1862
1863 if (mAllAppsList.added.size() > 0) {
1864 added = mAllAppsList.added;
1865 mAllAppsList.added = new ArrayList<ApplicationInfo>();
1866 }
1867 if (mAllAppsList.removed.size() > 0) {
1868 removed = mAllAppsList.removed;
1869 mAllAppsList.removed = new ArrayList<ApplicationInfo>();
1870 for (ApplicationInfo info: removed) {
1871 mIconCache.remove(info.intent.getComponent());
1872 }
1873 }
1874 if (mAllAppsList.modified.size() > 0) {
1875 modified = mAllAppsList.modified;
1876 mAllAppsList.modified = new ArrayList<ApplicationInfo>();
1877 }
1878
1879 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
1880 if (callbacks == null) {
1881 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
1882 return;
1883 }
1884
1885 if (added != null) {
1886 final ArrayList<ApplicationInfo> addedFinal = added;
1887 mHandler.post(new Runnable() {
1888 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07001889 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1890 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001891 callbacks.bindAppsAdded(addedFinal);
1892 }
1893 }
1894 });
1895 }
1896 if (modified != null) {
1897 final ArrayList<ApplicationInfo> modifiedFinal = modified;
1898 mHandler.post(new Runnable() {
1899 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07001900 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1901 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001902 callbacks.bindAppsUpdated(modifiedFinal);
1903 }
1904 }
1905 });
1906 }
1907 if (removed != null) {
1908 final boolean permanent = mOp != OP_UNAVAILABLE;
1909 final ArrayList<ApplicationInfo> removedFinal = removed;
1910 mHandler.post(new Runnable() {
1911 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07001912 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1913 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001914 callbacks.bindAppsRemoved(removedFinal, permanent);
1915 }
1916 }
1917 });
Joe Onoratobe386092009-11-17 17:32:16 -08001918 }
Winson Chung80baf5a2010-08-09 16:03:15 -07001919
1920 mHandler.post(new Runnable() {
1921 @Override
1922 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07001923 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1924 if (callbacks == cb && cb != null) {
Winson Chung80baf5a2010-08-09 16:03:15 -07001925 callbacks.bindPackagesUpdated();
1926 }
1927 }
1928 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04001929 }
1930 }
1931
1932 /**
Winson Chung2efec4e2012-05-03 12:31:48 -07001933 * Returns all the Workspace ShortcutInfos associated with a particular package.
1934 * @param intent
1935 * @return
1936 */
1937 ArrayList<ShortcutInfo> getShortcutInfosForPackage(String packageName) {
1938 ArrayList<ShortcutInfo> infos = new ArrayList<ShortcutInfo>();
Adam Cohend7d37b12012-07-18 16:15:08 -07001939 synchronized (sBgLock) {
1940 for (ItemInfo i : sBgWorkspaceItems) {
1941 if (i instanceof ShortcutInfo) {
1942 ShortcutInfo info = (ShortcutInfo) i;
1943 if (packageName.equals(info.getPackageName())) {
1944 infos.add(info);
1945 }
Winson Chung2efec4e2012-05-03 12:31:48 -07001946 }
1947 }
1948 }
1949 return infos;
1950 }
1951
1952 /**
Joe Onorato56d82912010-03-07 14:32:10 -05001953 * This is called from the code that adds shortcuts from the intent receiver. This
1954 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04001955 */
Joe Onorato56d82912010-03-07 14:32:10 -05001956 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07001957 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05001958 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001959
Joe Onorato56d82912010-03-07 14:32:10 -05001960 /**
1961 * Make an ShortcutInfo object for a shortcut that is an application.
1962 *
1963 * If c is not null, then it will be used to fill in missing data like the title and icon.
1964 */
1965 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07001966 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05001967 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07001968 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05001969
1970 ComponentName componentName = intent.getComponent();
1971 if (componentName == null) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001972 return null;
1973 }
1974
Adam Cohen00fcb492011-11-02 21:53:47 -07001975 try {
1976 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
1977 if (!pi.applicationInfo.enabled) {
1978 // If we return null here, the corresponding item will be removed from the launcher
1979 // db and will not appear in the workspace.
1980 return null;
1981 }
1982 } catch (NameNotFoundException e) {
1983 Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
1984 }
1985
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07001986 // TODO: See if the PackageManager knows about this case. If it doesn't
1987 // then return null & delete this.
1988
Joe Onorato56d82912010-03-07 14:32:10 -05001989 // the resource -- This may implicitly give us back the fallback icon,
1990 // but don't worry about that. All we're doing with usingFallbackIcon is
1991 // to avoid saving lots of copies of that in the database, and most apps
1992 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07001993
1994 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
1995 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
1996 // via resolveActivity().
1997 ResolveInfo resolveInfo = null;
1998 ComponentName oldComponent = intent.getComponent();
1999 Intent newIntent = new Intent(intent.getAction(), null);
2000 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2001 newIntent.setPackage(oldComponent.getPackageName());
2002 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2003 for (ResolveInfo i : infos) {
2004 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2005 i.activityInfo.name);
2006 if (cn.equals(oldComponent)) {
2007 resolveInfo = i;
2008 }
2009 }
2010 if (resolveInfo == null) {
2011 resolveInfo = manager.resolveActivity(intent, 0);
2012 }
Joe Onorato56d82912010-03-07 14:32:10 -05002013 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002014 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002015 }
Joe Onorato56d82912010-03-07 14:32:10 -05002016 // the db
2017 if (icon == null) {
2018 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002019 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002020 }
2021 }
2022 // the fallback icon
2023 if (icon == null) {
2024 icon = getFallbackIcon();
2025 info.usingFallbackIcon = true;
2026 }
2027 info.setIcon(icon);
2028
2029 // from the resource
2030 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002031 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2032 if (labelCache != null && labelCache.containsKey(key)) {
2033 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002034 } else {
2035 info.title = resolveInfo.activityInfo.loadLabel(manager);
2036 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002037 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002038 }
2039 }
Joe Onorato56d82912010-03-07 14:32:10 -05002040 }
2041 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002042 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002043 if (c != null) {
2044 info.title = c.getString(titleIndex);
2045 }
2046 }
2047 // fall back to the class name of the activity
2048 if (info.title == null) {
2049 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002050 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002051 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2052 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002053 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002054
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002055 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002056 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002057 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002058 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002059 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2060 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002061
Joe Onorato56d82912010-03-07 14:32:10 -05002062 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002063 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002064 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002065
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002066 // TODO: If there's an explicit component and we can't install that, delete it.
2067
Joe Onorato56d82912010-03-07 14:32:10 -05002068 info.title = c.getString(titleIndex);
2069
Joe Onorato9c1289c2009-08-17 11:03:03 -04002070 int iconType = c.getInt(iconTypeIndex);
2071 switch (iconType) {
2072 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2073 String packageName = c.getString(iconPackageIndex);
2074 String resourceName = c.getString(iconResourceIndex);
2075 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002076 info.customIcon = false;
2077 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002078 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002079 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002080 if (resources != null) {
2081 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002082 icon = Utilities.createIconBitmap(
2083 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002084 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002085 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002086 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002087 }
Joe Onorato56d82912010-03-07 14:32:10 -05002088 // the db
2089 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002090 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002091 }
2092 // the fallback icon
2093 if (icon == null) {
2094 icon = getFallbackIcon();
2095 info.usingFallbackIcon = true;
2096 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002097 break;
2098 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002099 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002100 if (icon == null) {
2101 icon = getFallbackIcon();
2102 info.customIcon = false;
2103 info.usingFallbackIcon = true;
2104 } else {
2105 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002106 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002107 break;
2108 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002109 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002110 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002111 info.customIcon = false;
2112 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002113 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002114 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002115 return info;
2116 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002117
Michael Jurka931dc972011-08-05 15:08:15 -07002118 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002119 @SuppressWarnings("all") // suppress dead code warning
2120 final boolean debug = false;
2121 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002122 Log.d(TAG, "getIconFromCursor app="
2123 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2124 }
2125 byte[] data = c.getBlob(iconIndex);
2126 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002127 return Utilities.createIconBitmap(
2128 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002129 } catch (Exception e) {
2130 return null;
2131 }
2132 }
2133
Winson Chung3d503fb2011-07-13 17:25:49 -07002134 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2135 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002136 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002137 if (info == null) {
2138 return null;
2139 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002140 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002141
2142 return info;
2143 }
2144
Winson Chunga9abd0e2010-10-27 17:18:37 -07002145 /**
Winson Chung55cef262010-10-28 14:14:18 -07002146 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2147 */
2148 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2149 ComponentName component) {
2150 List<AppWidgetProviderInfo> widgets =
2151 AppWidgetManager.getInstance(context).getInstalledProviders();
2152 for (AppWidgetProviderInfo info : widgets) {
2153 if (info.provider.equals(component)) {
2154 return info;
2155 }
2156 }
2157 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002158 }
2159
Winson Chung68846fd2010-10-29 11:00:27 -07002160 /**
2161 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2162 */
2163 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2164 final PackageManager packageManager = context.getPackageManager();
2165 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2166 new ArrayList<WidgetMimeTypeHandlerData>();
2167
2168 final Intent supportsIntent =
2169 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2170 supportsIntent.setType(mimeType);
2171
2172 // Create a set of widget configuration components that we can test against
2173 final List<AppWidgetProviderInfo> widgets =
2174 AppWidgetManager.getInstance(context).getInstalledProviders();
2175 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2176 new HashMap<ComponentName, AppWidgetProviderInfo>();
2177 for (AppWidgetProviderInfo info : widgets) {
2178 configurationComponentToWidget.put(info.configure, info);
2179 }
2180
2181 // Run through each of the intents that can handle this type of clip data, and cross
2182 // reference them with the components that are actual configuration components
2183 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2184 PackageManager.MATCH_DEFAULT_ONLY);
2185 for (ResolveInfo info : activities) {
2186 final ActivityInfo activityInfo = info.activityInfo;
2187 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2188 activityInfo.name);
2189 if (configurationComponentToWidget.containsKey(infoComponent)) {
2190 supportedConfigurationActivities.add(
2191 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2192 configurationComponentToWidget.get(infoComponent)));
2193 }
2194 }
2195 return supportedConfigurationActivities;
2196 }
2197
Winson Chunga9abd0e2010-10-27 17:18:37 -07002198 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08002199 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2200 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2201 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2202
Adam Cohend9198822011-11-22 16:42:47 -08002203 if (intent == null) {
2204 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2205 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2206 return null;
2207 }
2208
Joe Onorato0589f0f2010-02-08 13:44:00 -08002209 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08002210 boolean customIcon = false;
2211 ShortcutIconResource iconResource = null;
2212
2213 if (bitmap != null && bitmap instanceof Bitmap) {
2214 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002215 customIcon = true;
2216 } else {
2217 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2218 if (extra != null && extra instanceof ShortcutIconResource) {
2219 try {
2220 iconResource = (ShortcutIconResource) extra;
2221 final PackageManager packageManager = context.getPackageManager();
2222 Resources resources = packageManager.getResourcesForApplication(
2223 iconResource.packageName);
2224 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002225 icon = Utilities.createIconBitmap(
2226 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002227 } catch (Exception e) {
2228 Log.w(TAG, "Could not load shortcut icon: " + extra);
2229 }
2230 }
2231 }
2232
Michael Jurkac9d95c52011-08-29 14:03:34 -07002233 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002234
2235 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002236 if (fallbackIcon != null) {
2237 icon = fallbackIcon;
2238 } else {
2239 icon = getFallbackIcon();
2240 info.usingFallbackIcon = true;
2241 }
Joe Onorato56d82912010-03-07 14:32:10 -05002242 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08002243 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05002244
Joe Onorato0589f0f2010-02-08 13:44:00 -08002245 info.title = name;
2246 info.intent = intent;
2247 info.customIcon = customIcon;
2248 info.iconResource = iconResource;
2249
2250 return info;
2251 }
2252
Winson Chungaac01e12011-08-17 10:37:13 -07002253 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2254 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08002255 // If apps can't be on SD, don't even bother.
2256 if (!mAppsCanBeOnExternalStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07002257 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08002258 }
Joe Onorato56d82912010-03-07 14:32:10 -05002259 // If this icon doesn't have a custom icon, check to see
2260 // what's stored in the DB, and if it doesn't match what
2261 // we're going to show, store what we are going to show back
2262 // into the DB. We do this so when we're loading, if the
2263 // package manager can't find an icon (for example because
2264 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07002265 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07002266 cache.put(info, c.getBlob(iconIndex));
2267 return true;
2268 }
2269 return false;
2270 }
2271 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2272 boolean needSave = false;
2273 try {
2274 if (data != null) {
2275 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2276 Bitmap loaded = info.getIcon(mIconCache);
2277 needSave = !saved.sameAs(loaded);
2278 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05002279 needSave = true;
2280 }
Winson Chungaac01e12011-08-17 10:37:13 -07002281 } catch (Exception e) {
2282 needSave = true;
2283 }
2284 if (needSave) {
2285 Log.d(TAG, "going to save icon bitmap for info=" + info);
2286 // This is slower than is ideal, but this only happens once
2287 // or when the app is updated with a new icon.
2288 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05002289 }
2290 }
2291
Joe Onorato9c1289c2009-08-17 11:03:03 -04002292 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07002293 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04002294 * or make a new one.
2295 */
Adam Cohendf2cc412011-04-27 16:56:57 -07002296 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002297 // See if a placeholder was created for us already
2298 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07002299 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002300 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07002301 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002302 folders.put(id, folderInfo);
2303 }
Adam Cohendf2cc412011-04-27 16:56:57 -07002304 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002305 }
2306
Joe Onorato9c1289c2009-08-17 11:03:03 -04002307 private static final Collator sCollator = Collator.getInstance();
Joe Onoratob0c27f22009-12-01 16:19:38 -08002308 public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
Joe Onorato9c1289c2009-08-17 11:03:03 -04002309 = new Comparator<ApplicationInfo>() {
2310 public final int compare(ApplicationInfo a, ApplicationInfo b) {
Michael Jurka5b1808d2011-07-11 19:59:46 -07002311 int result = sCollator.compare(a.title.toString(), b.title.toString());
2312 if (result == 0) {
2313 result = a.componentName.compareTo(b.componentName);
2314 }
2315 return result;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002316 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002317 };
Winson Chung78403fe2011-01-21 15:38:02 -08002318 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2319 = new Comparator<ApplicationInfo>() {
2320 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2321 if (a.firstInstallTime < b.firstInstallTime) return 1;
2322 if (a.firstInstallTime > b.firstInstallTime) return -1;
2323 return 0;
2324 }
2325 };
Winson Chung785d2eb2011-04-14 16:08:02 -07002326 public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
2327 = new Comparator<AppWidgetProviderInfo>() {
2328 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
2329 return sCollator.compare(a.label.toString(), b.label.toString());
2330 }
2331 };
Winson Chung5308f242011-08-18 12:12:41 -07002332 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
2333 if (info.activityInfo != null) {
2334 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
2335 } else {
2336 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
2337 }
2338 }
Winson Chung785d2eb2011-04-14 16:08:02 -07002339 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
2340 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07002341 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07002342 ShortcutNameComparator(PackageManager pm) {
2343 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07002344 mLabelCache = new HashMap<Object, CharSequence>();
2345 }
2346 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
2347 mPackageManager = pm;
2348 mLabelCache = labelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07002349 }
2350 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002351 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07002352 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
2353 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
2354 if (mLabelCache.containsKey(keyA)) {
2355 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002356 } else {
2357 labelA = a.loadLabel(mPackageManager).toString();
2358
Winson Chung5308f242011-08-18 12:12:41 -07002359 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002360 }
Winson Chung5308f242011-08-18 12:12:41 -07002361 if (mLabelCache.containsKey(keyB)) {
2362 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002363 } else {
2364 labelB = b.loadLabel(mPackageManager).toString();
2365
Winson Chung5308f242011-08-18 12:12:41 -07002366 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002367 }
Winson Chung785d2eb2011-04-14 16:08:02 -07002368 return sCollator.compare(labelA, labelB);
2369 }
2370 };
Winson Chung1ed747a2011-05-03 16:18:34 -07002371 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
2372 private PackageManager mPackageManager;
2373 private HashMap<Object, String> mLabelCache;
2374 WidgetAndShortcutNameComparator(PackageManager pm) {
2375 mPackageManager = pm;
2376 mLabelCache = new HashMap<Object, String>();
2377 }
2378 public final int compare(Object a, Object b) {
2379 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07002380 if (mLabelCache.containsKey(a)) {
2381 labelA = mLabelCache.get(a);
2382 } else {
2383 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002384 ((AppWidgetProviderInfo) a).label :
2385 ((ResolveInfo) a).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002386 mLabelCache.put(a, labelA);
2387 }
2388 if (mLabelCache.containsKey(b)) {
2389 labelB = mLabelCache.get(b);
2390 } else {
2391 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002392 ((AppWidgetProviderInfo) b).label :
2393 ((ResolveInfo) b).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002394 mLabelCache.put(b, labelB);
2395 }
Winson Chung1ed747a2011-05-03 16:18:34 -07002396 return sCollator.compare(labelA, labelB);
2397 }
2398 };
Joe Onoratobe386092009-11-17 17:32:16 -08002399
2400 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08002401 Log.d(TAG, "mCallbacks=" + mCallbacks);
2402 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
2403 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
2404 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
2405 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04002406 if (mLoaderTask != null) {
2407 mLoaderTask.dumpState();
2408 } else {
2409 Log.d(TAG, "mLoaderTask=null");
2410 }
Joe Onoratobe386092009-11-17 17:32:16 -08002411 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002412}