blob: bbdff9e8643b3e1767036a2ad7ee22f722824e80 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Narayan Kamathcb1a4772011-06-28 13:46:59 +010019import android.app.SearchManager;
Romain Guy629de3e2010-01-13 12:20:59 -080020import android.appwidget.AppWidgetManager;
21import android.appwidget.AppWidgetProviderInfo;
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;
Adam Cohenf0f4eda2013-06-06 21:27:03 -070025import android.content.ContentProviderOperation;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.ContentResolver;
27import android.content.ContentValues;
Winson Chungaafa03c2010-06-11 17:34:16 -070028import android.content.Context;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080029import android.content.Intent;
Joe Onorato0589f0f2010-02-08 13:44:00 -080030import android.content.Intent.ShortcutIconResource;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080031import android.content.pm.ActivityInfo;
Adam Cohen00fcb492011-11-02 21:53:47 -070032import android.content.pm.PackageInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.content.pm.PackageManager;
Adam Cohen00fcb492011-11-02 21:53:47 -070034import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070036import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080037import android.content.res.Resources;
38import android.database.Cursor;
39import android.graphics.Bitmap;
40import android.graphics.BitmapFactory;
41import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080042import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040043import android.os.Handler;
44import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080045import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080046import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070047import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040048import android.os.SystemClock;
Winson Chungaafa03c2010-06-11 17:34:16 -070049import android.util.Log;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080050
Daniel Sandler325dc232013-06-05 22:57:57 -040051import com.android.launcher3.R;
52import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
Romain Guyedcce092010-03-04 13:03:17 -080053
Michael Jurkac2f801e2011-07-12 14:19:46 -070054import java.lang.ref.WeakReference;
55import java.net.URISyntaxException;
56import java.text.Collator;
Winson Chung83892cc2013-05-01 16:53:33 -070057import java.util.Arrays;
Michael Jurkac2f801e2011-07-12 14:19:46 -070058import java.util.ArrayList;
59import java.util.Collections;
60import java.util.Comparator;
61import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070062import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070063import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070064import java.util.List;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070065import java.util.Set;
Michael Jurkac2f801e2011-07-12 14:19:46 -070066
The Android Open Source Project31dd5032009-03-03 19:32:27 -080067/**
68 * Maintains in-memory state of the Launcher. It is expected that there should be only one
69 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070070 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071 */
Joe Onoratof99f8c12009-10-31 17:27:36 -040072public class LauncherModel extends BroadcastReceiver {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080073 static final boolean DEBUG_LOADERS = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -040074 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070075
Joe Onorato36115782010-06-17 13:28:48 -040076 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Joe Onorato17a89222011-02-08 17:26:11 -080077 private final boolean mAppsCanBeOnExternalStorage;
Joe Onoratod65d08e2010-04-20 15:43:37 -040078 private int mBatchSize; // 0 is all apps at once
Daniel Sandler2ff10b32010-04-16 15:06:06 -040079 private int mAllAppsLoadDelay; // milliseconds between batches
Daniel Sandlerdca66122010-04-13 16:23:58 -040080
Joe Onoratof99f8c12009-10-31 17:27:36 -040081 private final LauncherApplication mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -040082 private final Object mLock = new Object();
83 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -040084 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070085 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +020086 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
Winson Chung81b52252012-08-27 15:34:29 -070088 // Specific runnable types that are run on the main thread deferred handler, this allows us to
89 // clear all queued binding runnables when the Launcher activity is destroyed.
90 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
91 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
92
93
Brad Fitzpatrick700889f2010-10-11 09:40:44 -070094 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
95 static {
96 sWorkerThread.start();
97 }
98 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
99
Joe Onoratocc67f472010-06-08 10:54:30 -0700100 // We start off with everything not loaded. After that, we assume that
101 // our monitoring of the package manager provides all updates and we never
102 // need to do a requery. These are only ever touched from the loader thread.
103 private boolean mWorkspaceLoaded;
104 private boolean mAllAppsLoaded;
105
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700106 // When we are loading pages synchronously, we can't just post the binding of items on the side
107 // pages as this delays the rotation process. Instead, we wait for a callback from the first
108 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
109 // a normal load, we also clear this set of Runnables.
110 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
111
Joe Onorato9c1289c2009-08-17 11:03:03 -0400112 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800113
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700114 // < only access in worker thread >
Adam Cohen487f7dd2012-06-28 18:12:10 -0700115 private AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800116
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700117 // The lock that must be acquired before referencing any static bg data structures. Unlike
118 // other locks, this one can generally be held long-term because we never expect any of these
119 // static data structures to be referenced outside of the worker thread except on the first
120 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700121 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700122
Adam Cohen487f7dd2012-06-28 18:12:10 -0700123 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700124 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700125 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700126
Adam Cohen487f7dd2012-06-28 18:12:10 -0700127 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
128 // created by LauncherModel that are directly on the home screen (however, no widgets or
129 // shortcuts within folders).
130 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700131
Adam Cohen487f7dd2012-06-28 18:12:10 -0700132 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
133 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700134 new ArrayList<LauncherAppWidgetInfo>();
135
Adam Cohen487f7dd2012-06-28 18:12:10 -0700136 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
137 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700138
Adam Cohen487f7dd2012-06-28 18:12:10 -0700139 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
140 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700141 // </ only access in worker thread >
142
143 private IconCache mIconCache;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800144 private Bitmap mDefaultIcon;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800145
Adam Cohend22015c2010-07-26 22:02:18 -0700146 private static int mCellCountX;
147 private static int mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700148
Reena Lee99a73f32011-10-24 17:27:37 -0700149 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700150
Joe Onorato9c1289c2009-08-17 11:03:03 -0400151 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700152 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400153 public int getCurrentWorkspaceScreen();
154 public void startBinding();
155 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
Joe Onoratoad72e172009-11-06 16:25:04 -0500156 public void bindFolders(HashMap<Long,FolderInfo> folders);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400157 public void finishBindingItems();
158 public void bindAppWidget(LauncherAppWidgetInfo info);
159 public void bindAllApplications(ArrayList<ApplicationInfo> apps);
Joe Onorato64e6be72010-03-05 15:05:52 -0500160 public void bindAppsAdded(ArrayList<ApplicationInfo> apps);
161 public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
Winson Chung83892cc2013-05-01 16:53:33 -0700162 public void bindComponentsRemoved(ArrayList<String> packageNames,
163 ArrayList<ApplicationInfo> appInfos,
164 boolean matchPackageNamesOnly);
Michael Jurkac402cd92013-05-20 15:49:32 +0200165 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Daniel Sandler843e8602010-06-07 14:59:01 -0400166 public boolean isAllAppsVisible();
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800167 public boolean isAllAppsButtonRank(int rank);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100168 public void bindSearchablesChanged();
Adam Cohen1462de32012-07-24 22:34:36 -0700169 public void onPageBoundSynchronously(int page);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400170 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800171
Joe Onorato0589f0f2010-02-08 13:44:00 -0800172 LauncherModel(LauncherApplication app, IconCache iconCache) {
Joe Onorato17a89222011-02-08 17:26:11 -0800173 mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated();
Joe Onoratof99f8c12009-10-31 17:27:36 -0400174 mApp = app;
Adam Cohen487f7dd2012-06-28 18:12:10 -0700175 mBgAllAppsList = new AllAppsList(iconCache);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800176 mIconCache = iconCache;
177
178 mDefaultIcon = Utilities.createIconBitmap(
Michael Jurkac9a96192010-11-01 11:52:08 -0700179 mIconCache.getFullResDefaultActivityIcon(), app);
Daniel Sandler2ff10b32010-04-16 15:06:06 -0400180
Reena Lee93f824a2011-09-23 17:20:28 -0700181 final Resources res = app.getResources();
182 mAllAppsLoadDelay = res.getInteger(R.integer.config_allAppsBatchLoadDelay);
183 mBatchSize = res.getInteger(R.integer.config_allAppsBatchSize);
Reena Lee99a73f32011-10-24 17:27:37 -0700184 Configuration config = res.getConfiguration();
185 mPreviousConfigMcc = config.mcc;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800186 }
187
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700188 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
189 * posted on the main thread handler. */
190 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700191 runOnMainThread(r, 0);
192 }
193 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700194 if (sWorkerThread.getThreadId() == Process.myTid()) {
195 // If we are on the worker thread, post onto the main handler
196 mHandler.post(r);
197 } else {
198 r.run();
199 }
200 }
201
202 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
203 * posted on the worker thread handler. */
204 private static void runOnWorkerThread(Runnable r) {
205 if (sWorkerThread.getThreadId() == Process.myTid()) {
206 r.run();
207 } else {
208 // If we are not on the worker thread, then post to the worker handler
209 sWorker.post(r);
210 }
211 }
212
Joe Onorato56d82912010-03-07 14:32:10 -0500213 public Bitmap getFallbackIcon() {
Joe Onorato0589f0f2010-02-08 13:44:00 -0800214 return Bitmap.createBitmap(mDefaultIcon);
Joe Onoratof99f8c12009-10-31 17:27:36 -0400215 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800216
Winson Chung81b52252012-08-27 15:34:29 -0700217 public void unbindItemInfosAndClearQueuedBindRunnables() {
218 if (sWorkerThread.getThreadId() == Process.myTid()) {
219 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
220 "main thread");
221 }
222
223 // Clear any deferred bind runnables
224 mDeferredBindRunnables.clear();
225 // Remove any queued bind runnables
226 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
227 // Unbind all the workspace items
228 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700229 }
230
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700231 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700232 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700233 // Ensure that we don't use the same workspace items data structure on the main thread
234 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700235 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
236 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700237 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700238 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
239 tmpAppWidgets.addAll(sBgAppWidgets);
240 }
241 Runnable r = new Runnable() {
242 @Override
243 public void run() {
244 for (ItemInfo item : tmpWorkspaceItems) {
245 item.unbind();
246 }
247 for (ItemInfo item : tmpAppWidgets) {
248 item.unbind();
249 }
250 }
251 };
252 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700253 }
254
Joe Onorato9c1289c2009-08-17 11:03:03 -0400255 /**
256 * Adds an item to the DB if it was not created previously, or move it to a new
257 * <container, screen, cellX, cellY>
258 */
259 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
260 int screen, int cellX, int cellY) {
261 if (item.container == ItemInfo.NO_ID) {
262 // From all apps
263 addItemToDatabase(context, item, container, screen, cellX, cellY, false);
264 } else {
265 // From somewhere else
266 moveItemInDatabase(context, item, container, screen, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800267 }
268 }
269
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700270 static void checkItemInfoLocked(
271 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
272 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
273 if (modelItem != null && item != modelItem) {
274 // check all the data is consistent
275 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
276 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
277 ShortcutInfo shortcut = (ShortcutInfo) item;
278 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
279 modelShortcut.intent.filterEquals(shortcut.intent) &&
280 modelShortcut.id == shortcut.id &&
281 modelShortcut.itemType == shortcut.itemType &&
282 modelShortcut.container == shortcut.container &&
283 modelShortcut.screen == shortcut.screen &&
284 modelShortcut.cellX == shortcut.cellX &&
285 modelShortcut.cellY == shortcut.cellY &&
286 modelShortcut.spanX == shortcut.spanX &&
287 modelShortcut.spanY == shortcut.spanY &&
288 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
289 (modelShortcut.dropPos != null &&
290 shortcut.dropPos != null &&
291 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
292 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
293 // For all intents and purposes, this is the same object
294 return;
295 }
296 }
297
298 // the modelItem needs to match up perfectly with item if our model is
299 // to be consistent with the database-- for now, just require
300 // modelItem == item or the equality check above
301 String msg = "item: " + ((item != null) ? item.toString() : "null") +
302 "modelItem: " +
303 ((modelItem != null) ? modelItem.toString() : "null") +
304 "Error: ItemInfo passed to checkItemInfo doesn't match original";
305 RuntimeException e = new RuntimeException(msg);
306 if (stackTrace != null) {
307 e.setStackTrace(stackTrace);
308 }
309 throw e;
310 }
311 }
312
Michael Jurka816474f2012-06-25 14:49:02 -0700313 static void checkItemInfo(final ItemInfo item) {
314 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
315 final long itemId = item.id;
316 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700317 public void run() {
318 synchronized (sBgLock) {
319 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700320 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700321 }
322 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700323 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700324 }
325
Michael Jurkac9d95c52011-08-29 14:03:34 -0700326 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
327 final ItemInfo item, final String callingFunction) {
328 final long itemId = item.id;
329 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
330 final ContentResolver cr = context.getContentResolver();
331
Adam Cohen487f7dd2012-06-28 18:12:10 -0700332 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700333 Runnable r = new Runnable() {
334 public void run() {
335 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700336 updateItemArrays(item, itemId, stackTrace);
337 }
338 };
339 runOnWorkerThread(r);
340 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700341
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700342 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
343 final ArrayList<ItemInfo> items, final String callingFunction) {
344 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700345
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700346 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
347 Runnable r = new Runnable() {
348 public void run() {
349 ArrayList<ContentProviderOperation> ops =
350 new ArrayList<ContentProviderOperation>();
351 int count = items.size();
352 for (int i = 0; i < count; i++) {
353 ItemInfo item = items.get(i);
354 final long itemId = item.id;
355 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
356 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700357
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700358 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
359 updateItemArrays(item, itemId, stackTrace);
360
361 }
362 try {
363 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
364 } catch (Exception e) {
365 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700366 }
367 }
368 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700369 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700370 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700371
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700372 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
373 // Lock on mBgLock *after* the db operation
374 synchronized (sBgLock) {
375 checkItemInfoLocked(itemId, item, stackTrace);
376
377 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
378 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
379 // Item is in a folder, make sure this folder exists
380 if (!sBgFolders.containsKey(item.container)) {
381 // An items container is being set to a that of an item which is not in
382 // the list of Folders.
383 String msg = "item: " + item + " container being set to: " +
384 item.container + ", not in the list of folders";
385 Log.e(TAG, msg);
386 Launcher.dumpDebugLogsToConsole();
387 }
388 }
389
390 // Items are added/removed from the corresponding FolderInfo elsewhere, such
391 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
392 // that are on the desktop, as appropriate
393 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
394 if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
395 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
396 switch (modelItem.itemType) {
397 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
398 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
399 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
400 if (!sBgWorkspaceItems.contains(modelItem)) {
401 sBgWorkspaceItems.add(modelItem);
402 }
403 break;
404 default:
405 break;
406 }
407 } else {
408 sBgWorkspaceItems.remove(modelItem);
409 }
410 }
411 }
412
Michael Jurkac7700af2013-05-14 20:17:58 +0200413 public void flushWorkerThread() {
414 mFlushingWorkerThread = true;
415 Runnable waiter = new Runnable() {
416 public void run() {
417 synchronized (this) {
418 notifyAll();
419 mFlushingWorkerThread = false;
420 }
421 }
422 };
423
424 synchronized(waiter) {
425 runOnWorkerThread(waiter);
426 if (mLoaderTask != null) {
427 synchronized(mLoaderTask) {
428 mLoaderTask.notify();
429 }
430 }
431 boolean success = false;
432 while (!success) {
433 try {
434 waiter.wait();
435 success = true;
436 } catch (InterruptedException e) {
437 }
438 }
439 }
440 }
441
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800442 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400443 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700444 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700445 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
446 final int screen, final int cellX, final int cellY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700447 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
448 " (" + item.container + ", " + item.screen + ", " + item.cellX + ", " + item.cellY +
Adam Cohen487f7dd2012-06-28 18:12:10 -0700449 ") --> " + "(" + container + ", " + screen + ", " + cellX + ", " + cellY + ")";
450 Launcher.sDumpLogs.add(transaction);
451 Log.d(TAG, transaction);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400452 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400453 item.cellX = cellX;
454 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700455
Winson Chung3d503fb2011-07-13 17:25:49 -0700456 // We store hotseat items in canonical form which is this orientation invariant position
457 // in the hotseat
458 if (context instanceof Launcher && screen < 0 &&
459 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
460 item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
461 } else {
462 item.screen = screen;
463 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400464
465 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400466 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700467 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
468 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400469 values.put(LauncherSettings.Favorites.SCREEN, item.screen);
470
Michael Jurkac9d95c52011-08-29 14:03:34 -0700471 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700472 }
473
474 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700475 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
476 * cellX, cellY have already been updated on the ItemInfos.
477 */
478 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
479 final long container, final int screen) {
480
481 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
482 int count = items.size();
483
484 for (int i = 0; i < count; i++) {
485 ItemInfo item = items.get(i);
486 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: "
487 + item.id + " (" + item.container + ", " + item.screen + ", " + item.cellX
488 + ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", "
489 + item.cellX + ", " + item.cellY + ")";
490 Launcher.sDumpLogs.add(transaction);
491 item.container = container;
492
493 // We store hotseat items in canonical form which is this orientation invariant position
494 // in the hotseat
495 if (context instanceof Launcher && screen < 0 &&
496 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
497 item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
498 item.cellY);
499 } else {
500 item.screen = screen;
501 }
502
503 final ContentValues values = new ContentValues();
504 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
505 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
506 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
507 values.put(LauncherSettings.Favorites.SCREEN, item.screen);
508
509 contentValues.add(values);
510 }
511 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
512 }
513
514 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700515 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800516 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700517 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
518 final int screen, final int cellX, final int cellY, final int spanX, final int spanY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700519 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
520 " (" + item.container + ", " + item.screen + ", " + item.cellX + ", " + item.cellY +
Adam Cohen487f7dd2012-06-28 18:12:10 -0700521 ") --> " + "(" + container + ", " + screen + ", " + cellX + ", " + cellY + ")";
522 Launcher.sDumpLogs.add(transaction);
523 Log.d(TAG, transaction);
Adam Cohend4844c32011-02-18 19:25:06 -0800524 item.cellX = cellX;
525 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700526 item.spanX = spanX;
527 item.spanY = spanY;
528
529 // We store hotseat items in canonical form which is this orientation invariant position
530 // in the hotseat
531 if (context instanceof Launcher && screen < 0 &&
532 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
533 item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
534 } else {
535 item.screen = screen;
536 }
Adam Cohend4844c32011-02-18 19:25:06 -0800537
Adam Cohend4844c32011-02-18 19:25:06 -0800538 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800539 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700540 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
541 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
542 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
543 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
544 values.put(LauncherSettings.Favorites.SCREEN, item.screen);
Adam Cohend4844c32011-02-18 19:25:06 -0800545
Michael Jurka816474f2012-06-25 14:49:02 -0700546 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700547 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700548
549 /**
550 * Update an item to the database in a specified container.
551 */
552 static void updateItemInDatabase(Context context, final ItemInfo item) {
553 final ContentValues values = new ContentValues();
554 item.onAddToDatabase(values);
555 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
556 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800557 }
558
559 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400560 * Returns true if the shortcuts already exists in the database.
561 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800562 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400563 static boolean shortcutExists(Context context, String title, Intent intent) {
564 final ContentResolver cr = context.getContentResolver();
565 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
566 new String[] { "title", "intent" }, "title=? and intent=?",
567 new String[] { title, intent.toUri(0) }, null);
568 boolean result = false;
569 try {
570 result = c.moveToFirst();
571 } finally {
572 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800573 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400574 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700575 }
576
Joe Onorato9c1289c2009-08-17 11:03:03 -0400577 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700578 * Returns an ItemInfo array containing all the items in the LauncherModel.
579 * The ItemInfo.id is not set through this function.
580 */
581 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
582 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
583 final ContentResolver cr = context.getContentResolver();
584 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
585 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
586 LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
587 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
588
589 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
590 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
591 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
592 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
593 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
594 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
595 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
596
597 try {
598 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700599 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700600 item.cellX = c.getInt(cellXIndex);
601 item.cellY = c.getInt(cellYIndex);
602 item.spanX = c.getInt(spanXIndex);
603 item.spanY = c.getInt(spanYIndex);
604 item.container = c.getInt(containerIndex);
605 item.itemType = c.getInt(itemTypeIndex);
606 item.screen = c.getInt(screenIndex);
607
608 items.add(item);
609 }
610 } catch (Exception e) {
611 items.clear();
612 } finally {
613 c.close();
614 }
615
616 return items;
617 }
618
619 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400620 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
621 */
622 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
623 final ContentResolver cr = context.getContentResolver();
624 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
625 "_id=? and (itemType=? or itemType=?)",
626 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700627 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700628
Joe Onorato9c1289c2009-08-17 11:03:03 -0400629 try {
630 if (c.moveToFirst()) {
631 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
632 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
633 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
634 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
635 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
636 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800637
Joe Onorato9c1289c2009-08-17 11:03:03 -0400638 FolderInfo folderInfo = null;
639 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700640 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
641 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400642 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700643 }
644
Joe Onorato9c1289c2009-08-17 11:03:03 -0400645 folderInfo.title = c.getString(titleIndex);
646 folderInfo.id = id;
647 folderInfo.container = c.getInt(containerIndex);
648 folderInfo.screen = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700649 folderInfo.cellX = c.getInt(cellXIndex);
650 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400651
652 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700653 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400654 } finally {
655 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700656 }
657
658 return null;
659 }
660
Joe Onorato9c1289c2009-08-17 11:03:03 -0400661 /**
662 * Add an item to the database in a specified container. Sets the container, screen, cellX and
663 * cellY fields of the item. Also assigns an ID to the item.
664 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700665 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
666 final int screen, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400667 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400668 item.cellX = cellX;
669 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700670 // We store hotseat items in canonical form which is this orientation invariant position
671 // in the hotseat
672 if (context instanceof Launcher && screen < 0 &&
673 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
674 item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
675 } else {
676 item.screen = screen;
677 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400678
679 final ContentValues values = new ContentValues();
680 final ContentResolver cr = context.getContentResolver();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400681 item.onAddToDatabase(values);
682
Michael Jurka7578ec62011-08-03 14:11:54 -0700683 LauncherApplication app = (LauncherApplication) context.getApplicationContext();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700684 item.id = app.getLauncherProvider().generateNewId();
685 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -0700686 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -0700687
Michael Jurkac9d95c52011-08-29 14:03:34 -0700688 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700689 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700690 String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
691 + item.id + " (" + container + ", " + screen + ", " + cellX + ", "
692 + cellY + ")";
693 Launcher.sDumpLogs.add(transaction);
694 Log.d(TAG, transaction);
695
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700696 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
697 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400698
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700699 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700700 synchronized (sBgLock) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700701 checkItemInfoLocked(item.id, item, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700702 sBgItemsIdMap.put(item.id, item);
703 switch (item.itemType) {
704 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
705 sBgFolders.put(item.id, (FolderInfo) item);
706 // Fall through
707 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
708 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
709 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
710 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
711 sBgWorkspaceItems.add(item);
712 } else {
713 if (!sBgFolders.containsKey(item.container)) {
714 // Adding an item to a folder that doesn't exist.
715 String msg = "adding item: " + item + " to a folder that " +
716 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -0700717 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700718 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700719 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700720 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700721 break;
722 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
723 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
724 break;
725 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700726 }
727 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700728 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700729 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700730 }
731
Joe Onorato9c1289c2009-08-17 11:03:03 -0400732 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700733 * Creates a new unique child id, for a given cell span across all layouts.
734 */
Michael Jurka845ba3b2010-09-28 17:09:46 -0700735 static int getCellLayoutChildId(
Winson Chung3d503fb2011-07-13 17:25:49 -0700736 long container, int screen, int localCellX, int localCellY, int spanX, int spanY) {
737 return (((int) container & 0xFF) << 24)
Michael Jurka845ba3b2010-09-28 17:09:46 -0700738 | (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -0700739 }
740
Adam Cohend22015c2010-07-26 22:02:18 -0700741 static int getCellCountX() {
742 return mCellCountX;
Winson Chungaafa03c2010-06-11 17:34:16 -0700743 }
744
Adam Cohend22015c2010-07-26 22:02:18 -0700745 static int getCellCountY() {
746 return mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700747 }
748
749 /**
750 * Updates the model orientation helper to take into account the current layout dimensions
751 * when performing local/canonical coordinate transformations.
752 */
753 static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
Adam Cohend22015c2010-07-26 22:02:18 -0700754 mCellCountX = shortAxisCellCount;
755 mCellCountY = longAxisCellCount;
Winson Chungaafa03c2010-06-11 17:34:16 -0700756 }
757
758 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -0700759 * Removes the specified item from the database
760 * @param context
761 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -0400762 */
Michael Jurkac9d95c52011-08-29 14:03:34 -0700763 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400764 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700765 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -0700766
Michael Jurka83df1882011-08-31 20:59:26 -0700767 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700768 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700769 String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
770 + item.id + " (" + item.container + ", " + item.screen + ", " + item.cellX +
771 ", " + item.cellY + ")";
772 Launcher.sDumpLogs.add(transaction);
773 Log.d(TAG, transaction);
774
Michael Jurkac9d95c52011-08-29 14:03:34 -0700775 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700776
777 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700778 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700779 switch (item.itemType) {
780 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
781 sBgFolders.remove(item.id);
782 for (ItemInfo info: sBgItemsIdMap.values()) {
783 if (info.container == item.id) {
784 // We are deleting a folder which still contains items that
785 // think they are contained by that folder.
786 String msg = "deleting a folder (" + item + ") which still " +
787 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -0700788 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700789 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700790 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700791 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700792 sBgWorkspaceItems.remove(item);
793 break;
794 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
795 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
796 sBgWorkspaceItems.remove(item);
797 break;
798 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
799 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
800 break;
801 }
802 sBgItemsIdMap.remove(item.id);
803 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700804 }
805 }
Michael Jurka83df1882011-08-31 20:59:26 -0700806 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700807 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400808 }
809
810 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400811 * Remove the contents of the specified folder from the database
812 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700813 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400814 final ContentResolver cr = context.getContentResolver();
815
Michael Jurkac9d95c52011-08-29 14:03:34 -0700816 Runnable r = new Runnable() {
817 public void run() {
818 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700819 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700820 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700821 sBgItemsIdMap.remove(info.id);
822 sBgFolders.remove(info.id);
823 sBgDbIconCache.remove(info);
824 sBgWorkspaceItems.remove(info);
825 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700826
Michael Jurkac9d95c52011-08-29 14:03:34 -0700827 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
828 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700829 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700830 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700831 for (ItemInfo childInfo : info.contents) {
832 sBgItemsIdMap.remove(childInfo.id);
833 sBgDbIconCache.remove(childInfo);
834 }
Adam Cohenafb01ee2011-06-23 15:38:03 -0700835 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700836 }
837 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700838 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400839 }
840
841 /**
842 * Set this as the current Launcher activity object for the loader.
843 */
844 public void initialize(Callbacks callbacks) {
845 synchronized (mLock) {
846 mCallbacks = new WeakReference<Callbacks>(callbacks);
847 }
848 }
849
Joe Onorato1d8e7bb2009-10-15 19:49:43 -0700850 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400851 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
852 * ACTION_PACKAGE_CHANGED.
853 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100854 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -0400855 public void onReceive(Context context, Intent intent) {
Joe Onorato36115782010-06-17 13:28:48 -0400856 if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -0700857
Joe Onorato36115782010-06-17 13:28:48 -0400858 final String action = intent.getAction();
Joe Onoratof99f8c12009-10-31 17:27:36 -0400859
Joe Onorato36115782010-06-17 13:28:48 -0400860 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
861 || Intent.ACTION_PACKAGE_REMOVED.equals(action)
862 || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
863 final String packageName = intent.getData().getSchemeSpecificPart();
864 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400865
Joe Onorato36115782010-06-17 13:28:48 -0400866 int op = PackageUpdatedTask.OP_NONE;
867
868 if (packageName == null || packageName.length() == 0) {
869 // they sent us a bad intent
870 return;
871 }
872
873 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
874 op = PackageUpdatedTask.OP_UPDATE;
875 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
876 if (!replacing) {
877 op = PackageUpdatedTask.OP_REMOVE;
878 }
879 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
880 // later, we will update the package at this time
881 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
882 if (!replacing) {
883 op = PackageUpdatedTask.OP_ADD;
884 } else {
885 op = PackageUpdatedTask.OP_UPDATE;
886 }
887 }
888
889 if (op != PackageUpdatedTask.OP_NONE) {
890 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
891 }
892
893 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Joe Onoratocec58332010-10-07 14:37:40 -0400894 // First, schedule to add these apps back in.
895 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
896 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
897 // Then, rebind everything.
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700898 startLoaderFromBackground();
Joe Onorato36115782010-06-17 13:28:48 -0400899 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
900 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
901 enqueuePackageUpdated(new PackageUpdatedTask(
902 PackageUpdatedTask.OP_UNAVAILABLE, packages));
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700903 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -0700904 // If we have changed locale we need to clear out the labels in all apps/workspace.
905 forceReload();
906 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
907 // Check if configuration change was an mcc/mnc change which would affect app resources
908 // and we would need to clear out the labels in all apps/workspace. Same handling as
909 // above for ACTION_LOCALE_CHANGED
910 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -0700911 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -0700912 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -0700913 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -0700914 forceReload();
915 }
916 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -0700917 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -0700918 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
919 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -0700920 if (mCallbacks != null) {
921 Callbacks callbacks = mCallbacks.get();
922 if (callbacks != null) {
923 callbacks.bindSearchablesChanged();
924 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -0700925 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700926 }
927 }
928
Reena Lee93f824a2011-09-23 17:20:28 -0700929 private void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -0700930 resetLoadedState(true, true);
931
Reena Lee93f824a2011-09-23 17:20:28 -0700932 // Do this here because if the launcher activity is running it will be restarted.
933 // If it's not running startLoaderFromBackground will merely tell it that it needs
934 // to reload.
935 startLoaderFromBackground();
936 }
937
Winson Chungf0c6ae02012-03-21 16:10:31 -0700938 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
939 synchronized (mLock) {
940 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
941 // mWorkspaceLoaded to true later
942 stopLoaderLocked();
943 if (resetAllAppsLoaded) mAllAppsLoaded = false;
944 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
945 }
946 }
947
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700948 /**
949 * When the launcher is in the background, it's possible for it to miss paired
950 * configuration changes. So whenever we trigger the loader from the background
951 * tell the launcher that it needs to re-run the loader when it comes back instead
952 * of doing it now.
953 */
954 public void startLoaderFromBackground() {
955 boolean runLoader = false;
956 if (mCallbacks != null) {
957 Callbacks callbacks = mCallbacks.get();
958 if (callbacks != null) {
959 // Only actually run the loader if they're not paused.
960 if (!callbacks.setLoadOnResume()) {
961 runLoader = true;
962 }
963 }
964 }
965 if (runLoader) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700966 startLoader(false, -1);
Joe Onorato790c2d92010-06-11 00:14:11 -0700967 }
Joe Onorato36115782010-06-17 13:28:48 -0400968 }
Joe Onoratof99f8c12009-10-31 17:27:36 -0400969
Reena Lee93f824a2011-09-23 17:20:28 -0700970 // If there is already a loader task running, tell it to stop.
971 // returns true if isLaunching() was true on the old task
972 private boolean stopLoaderLocked() {
973 boolean isLaunching = false;
974 LoaderTask oldTask = mLoaderTask;
975 if (oldTask != null) {
976 if (oldTask.isLaunching()) {
977 isLaunching = true;
978 }
979 oldTask.stopLocked();
980 }
981 return isLaunching;
982 }
983
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700984 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Joe Onorato36115782010-06-17 13:28:48 -0400985 synchronized (mLock) {
986 if (DEBUG_LOADERS) {
987 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
988 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400989
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700990 // Clear any deferred bind-runnables from the synchronized load process
991 // We must do this before any loading/binding is scheduled below.
992 mDeferredBindRunnables.clear();
993
Joe Onorato36115782010-06-17 13:28:48 -0400994 // Don't bother to start the thread if we know it's not going to do anything
995 if (mCallbacks != null && mCallbacks.get() != null) {
996 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -0700997 // also, don't downgrade isLaunching if we're already running
998 isLaunching = isLaunching || stopLoaderLocked();
Winson Chungf0c6ae02012-03-21 16:10:31 -0700999 mLoaderTask = new LoaderTask(mApp, isLaunching);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001000 if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
1001 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1002 } else {
1003 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1004 sWorker.post(mLoaderTask);
1005 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001006 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001007 }
1008 }
1009
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001010 void bindRemainingSynchronousPages() {
1011 // Post the remaining side pages to be loaded
1012 if (!mDeferredBindRunnables.isEmpty()) {
1013 for (final Runnable r : mDeferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001014 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001015 }
1016 mDeferredBindRunnables.clear();
1017 }
1018 }
1019
Joe Onorato36115782010-06-17 13:28:48 -04001020 public void stopLoader() {
1021 synchronized (mLock) {
1022 if (mLoaderTask != null) {
1023 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001024 }
1025 }
Joe Onorato36115782010-06-17 13:28:48 -04001026 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001027
Michael Jurkac57b7a82011-08-09 22:02:20 -07001028 public boolean isAllAppsLoaded() {
1029 return mAllAppsLoaded;
1030 }
1031
Winson Chung36a62fe2012-05-06 18:04:42 -07001032 boolean isLoadingWorkspace() {
1033 synchronized (mLock) {
1034 if (mLoaderTask != null) {
1035 return mLoaderTask.isLoadingWorkspace();
1036 }
1037 }
1038 return false;
1039 }
1040
Joe Onorato36115782010-06-17 13:28:48 -04001041 /**
1042 * Runnable for the thread that loads the contents of the launcher:
1043 * - workspace icons
1044 * - widgets
1045 * - all apps icons
1046 */
1047 private class LoaderTask implements Runnable {
1048 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001049 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001050 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001051 private boolean mStopped;
1052 private boolean mLoadAndBindStepFinished;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001053
Winson Chungc3eecff2011-07-11 17:44:15 -07001054 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001055
1056 LoaderTask(Context context, boolean isLaunching) {
1057 mContext = context;
1058 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001059 mLabelCache = new HashMap<Object, CharSequence>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001060 }
1061
Joe Onorato36115782010-06-17 13:28:48 -04001062 boolean isLaunching() {
1063 return mIsLaunching;
1064 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001065
Winson Chung36a62fe2012-05-06 18:04:42 -07001066 boolean isLoadingWorkspace() {
1067 return mIsLoadingAndBindingWorkspace;
1068 }
1069
Joe Onorato36115782010-06-17 13:28:48 -04001070 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001071 mIsLoadingAndBindingWorkspace = true;
1072
Joe Onorato36115782010-06-17 13:28:48 -04001073 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001074 if (DEBUG_LOADERS) {
1075 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001076 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001077
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001078 if (!mWorkspaceLoaded) {
Joe Onorato36115782010-06-17 13:28:48 -04001079 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001080 synchronized (LoaderTask.this) {
1081 if (mStopped) {
1082 return;
1083 }
1084 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001085 }
1086 }
1087
Joe Onorato36115782010-06-17 13:28:48 -04001088 // Bind the workspace
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001089 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001090 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001091
Joe Onorato36115782010-06-17 13:28:48 -04001092 private void waitForIdle() {
1093 // Wait until the either we're stopped or the other threads are done.
1094 // This way we don't start loading all apps until the workspace has settled
1095 // down.
1096 synchronized (LoaderTask.this) {
1097 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001098
Joe Onorato36115782010-06-17 13:28:48 -04001099 mHandler.postIdle(new Runnable() {
1100 public void run() {
1101 synchronized (LoaderTask.this) {
1102 mLoadAndBindStepFinished = true;
1103 if (DEBUG_LOADERS) {
1104 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001105 }
Joe Onorato36115782010-06-17 13:28:48 -04001106 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001107 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001108 }
Joe Onorato36115782010-06-17 13:28:48 -04001109 });
1110
Michael Jurkac7700af2013-05-14 20:17:58 +02001111 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001112 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001113 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1114 // wait no longer than 1sec at a time
1115 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001116 } catch (InterruptedException ex) {
1117 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001118 }
1119 }
Joe Onorato36115782010-06-17 13:28:48 -04001120 if (DEBUG_LOADERS) {
1121 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001122 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001123 + "ms for previous step to finish binding");
1124 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001125 }
Joe Onorato36115782010-06-17 13:28:48 -04001126 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001127
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001128 void runBindSynchronousPage(int synchronousBindPage) {
1129 if (synchronousBindPage < 0) {
1130 // Ensure that we have a valid page index to load synchronously
1131 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1132 "valid page index");
1133 }
1134 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1135 // Ensure that we don't try and bind a specified page when the pages have not been
1136 // loaded already (we should load everything asynchronously in that case)
1137 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1138 }
1139 synchronized (mLock) {
1140 if (mIsLoaderTaskRunning) {
1141 // Ensure that we are never running the background loading at this point since
1142 // we also touch the background collections
1143 throw new RuntimeException("Error! Background loading is already running");
1144 }
1145 }
1146
1147 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1148 // data structures, we can't allow any other thread to touch that data, but because
1149 // this call is synchronous, we can get away with not locking).
1150
Adam Cohena13a2f22012-07-23 14:29:15 -07001151 // The LauncherModel is static in the LauncherApplication and mHandler may have queued
1152 // operations from the previous activity. We need to ensure that all queued operations
1153 // are executed before any synchronous binding work is done.
1154 mHandler.flush();
1155
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001156 // Divide the set of loaded items into those that we are binding synchronously, and
1157 // everything else that is to be bound normally (asynchronously).
1158 bindWorkspace(synchronousBindPage);
1159 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1160 // arise from that.
1161 onlyBindAllApps();
1162 }
1163
Joe Onorato36115782010-06-17 13:28:48 -04001164 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001165 synchronized (mLock) {
1166 mIsLoaderTaskRunning = true;
1167 }
Joe Onorato36115782010-06-17 13:28:48 -04001168 // Optimize for end-user experience: if the Launcher is up and // running with the
1169 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1170 // workspace first (default).
1171 final Callbacks cbk = mCallbacks.get();
1172 final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
Daniel Sandler843e8602010-06-07 14:59:01 -04001173
Joe Onorato36115782010-06-17 13:28:48 -04001174 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001175 // Elevate priority when Home launches for the first time to avoid
1176 // starving at boot time. Staring at a blank home is not cool.
1177 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001178 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1179 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001180 android.os.Process.setThreadPriority(mIsLaunching
1181 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1182 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001183 if (loadWorkspaceFirst) {
1184 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
1185 loadAndBindWorkspace();
1186 } else {
1187 if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
Joe Onoratocc67f472010-06-08 10:54:30 -07001188 loadAndBindAllApps();
Daniel Sandler843e8602010-06-07 14:59:01 -04001189 }
1190
Joe Onorato36115782010-06-17 13:28:48 -04001191 if (mStopped) {
1192 break keep_running;
1193 }
1194
1195 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1196 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001197 synchronized (mLock) {
1198 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001199 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001200 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1201 }
1202 }
Joe Onorato36115782010-06-17 13:28:48 -04001203 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001204
1205 // second step
1206 if (loadWorkspaceFirst) {
1207 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
Joe Onoratocc67f472010-06-08 10:54:30 -07001208 loadAndBindAllApps();
Daniel Sandler843e8602010-06-07 14:59:01 -04001209 } else {
1210 if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
1211 loadAndBindWorkspace();
1212 }
Winson Chung7ed37742011-09-08 15:45:51 -07001213
1214 // Restore the default thread priority after we are done loading items
1215 synchronized (mLock) {
1216 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1217 }
Joe Onorato36115782010-06-17 13:28:48 -04001218 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001219
Winson Chungaac01e12011-08-17 10:37:13 -07001220
1221 // Update the saved icons if necessary
1222 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001223 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001224 for (Object key : sBgDbIconCache.keySet()) {
1225 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1226 }
1227 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001228 }
Winson Chungaac01e12011-08-17 10:37:13 -07001229
Joe Onorato36115782010-06-17 13:28:48 -04001230 // Clear out this reference, otherwise we end up holding it until all of the
1231 // callback runnables are done.
1232 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001233
Joe Onorato36115782010-06-17 13:28:48 -04001234 synchronized (mLock) {
1235 // If we are still the last one to be scheduled, remove ourselves.
1236 if (mLoaderTask == this) {
1237 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001238 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001239 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001240 }
Joe Onorato36115782010-06-17 13:28:48 -04001241 }
1242
1243 public void stopLocked() {
1244 synchronized (LoaderTask.this) {
1245 mStopped = true;
1246 this.notify();
1247 }
1248 }
1249
1250 /**
1251 * Gets the callbacks object. If we've been stopped, or if the launcher object
1252 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1253 * object that was around when the deferred message was scheduled, and if there's
1254 * a new Callbacks object around then also return null. This will save us from
1255 * calling onto it with data that will be ignored.
1256 */
1257 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1258 synchronized (mLock) {
1259 if (mStopped) {
1260 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001261 }
Joe Onorato36115782010-06-17 13:28:48 -04001262
1263 if (mCallbacks == null) {
1264 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001265 }
Joe Onorato36115782010-06-17 13:28:48 -04001266
1267 final Callbacks callbacks = mCallbacks.get();
1268 if (callbacks != oldCallbacks) {
1269 return null;
1270 }
1271 if (callbacks == null) {
1272 Log.w(TAG, "no mCallbacks");
1273 return null;
1274 }
1275
1276 return callbacks;
1277 }
1278 }
1279
1280 // check & update map of what's occupied; used to discard overlapping/invalid items
1281 private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001282 int containerIndex = item.screen;
1283 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001284 // Return early if we detect that an item is under the hotseat button
Andrew Flynn0dca1ec2012-02-29 13:33:22 -08001285 if (mCallbacks == null || mCallbacks.get().isAllAppsButtonRank(item.screen)) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001286 return false;
1287 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001288
1289 // We use the last index to refer to the hotseat and the screen as the rank, so
1290 // test and update the occupied state accordingly
1291 if (occupied[Launcher.SCREEN_COUNT][item.screen][0] != null) {
1292 Log.e(TAG, "Error loading shortcut into hotseat " + item
1293 + " into position (" + item.screen + ":" + item.cellX + "," + item.cellY
1294 + ") occupied by " + occupied[Launcher.SCREEN_COUNT][item.screen][0]);
1295 return false;
1296 } else {
1297 occupied[Launcher.SCREEN_COUNT][item.screen][0] = item;
1298 return true;
1299 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001300 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1301 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001302 return true;
1303 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001304
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001305 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001306 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1307 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001308 if (occupied[containerIndex][x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001309 Log.e(TAG, "Error loading shortcut " + item
Winson Chungf30ad5f2011-08-08 10:55:42 -07001310 + " into cell (" + containerIndex + "-" + item.screen + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001311 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001312 + ") occupied by "
Winson Chungf30ad5f2011-08-08 10:55:42 -07001313 + occupied[containerIndex][x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001314 return false;
1315 }
1316 }
1317 }
1318 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1319 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Winson Chungf30ad5f2011-08-08 10:55:42 -07001320 occupied[containerIndex][x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001321 }
1322 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001323
Joe Onorato36115782010-06-17 13:28:48 -04001324 return true;
1325 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001326
Joe Onorato36115782010-06-17 13:28:48 -04001327 private void loadWorkspace() {
1328 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001329
Joe Onorato36115782010-06-17 13:28:48 -04001330 final Context context = mContext;
1331 final ContentResolver contentResolver = context.getContentResolver();
1332 final PackageManager manager = context.getPackageManager();
1333 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1334 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001335
Michael Jurkab85f8a42012-04-25 15:48:32 -07001336 // Make sure the default workspace is loaded, if needed
Brian Muramatsu5524b492012-10-02 16:55:54 -07001337 mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001338
Winson Chung2abf94d2012-07-18 18:16:38 -07001339 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001340 sBgWorkspaceItems.clear();
1341 sBgAppWidgets.clear();
1342 sBgFolders.clear();
1343 sBgItemsIdMap.clear();
1344 sBgDbIconCache.clear();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001345
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001346 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001347
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001348 final Cursor c = contentResolver.query(
1349 LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001350
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001351 // +1 for the hotseat (it can be larger than the workspace)
1352 // Load workspace in reverse order to ensure that latest items are loaded first (and
1353 // before any earlier duplicates)
1354 final ItemInfo occupied[][][] =
1355 new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1];
Joe Onorato9c1289c2009-08-17 11:03:03 -04001356
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001357 try {
1358 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1359 final int intentIndex = c.getColumnIndexOrThrow
1360 (LauncherSettings.Favorites.INTENT);
1361 final int titleIndex = c.getColumnIndexOrThrow
1362 (LauncherSettings.Favorites.TITLE);
1363 final int iconTypeIndex = c.getColumnIndexOrThrow(
1364 LauncherSettings.Favorites.ICON_TYPE);
1365 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1366 final int iconPackageIndex = c.getColumnIndexOrThrow(
1367 LauncherSettings.Favorites.ICON_PACKAGE);
1368 final int iconResourceIndex = c.getColumnIndexOrThrow(
1369 LauncherSettings.Favorites.ICON_RESOURCE);
1370 final int containerIndex = c.getColumnIndexOrThrow(
1371 LauncherSettings.Favorites.CONTAINER);
1372 final int itemTypeIndex = c.getColumnIndexOrThrow(
1373 LauncherSettings.Favorites.ITEM_TYPE);
1374 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1375 LauncherSettings.Favorites.APPWIDGET_ID);
1376 final int screenIndex = c.getColumnIndexOrThrow(
1377 LauncherSettings.Favorites.SCREEN);
1378 final int cellXIndex = c.getColumnIndexOrThrow
1379 (LauncherSettings.Favorites.CELLX);
1380 final int cellYIndex = c.getColumnIndexOrThrow
1381 (LauncherSettings.Favorites.CELLY);
1382 final int spanXIndex = c.getColumnIndexOrThrow
1383 (LauncherSettings.Favorites.SPANX);
1384 final int spanYIndex = c.getColumnIndexOrThrow(
1385 LauncherSettings.Favorites.SPANY);
1386 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1387 //final int displayModeIndex = c.getColumnIndexOrThrow(
1388 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001389
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001390 ShortcutInfo info;
1391 String intentDescription;
1392 LauncherAppWidgetInfo appWidgetInfo;
1393 int container;
1394 long id;
1395 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001396
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001397 while (!mStopped && c.moveToNext()) {
1398 try {
1399 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001400
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001401 switch (itemType) {
1402 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1403 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1404 intentDescription = c.getString(intentIndex);
1405 try {
1406 intent = Intent.parseUri(intentDescription, 0);
1407 } catch (URISyntaxException e) {
1408 continue;
1409 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001410
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001411 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1412 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1413 titleIndex, mLabelCache);
1414 } else {
1415 info = getShortcutInfo(c, context, iconTypeIndex,
1416 iconPackageIndex, iconResourceIndex, iconIndex,
1417 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001418
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001419 // App shortcuts that used to be automatically added to Launcher
1420 // didn't always have the correct intent flags set, so do that
1421 // here
1422 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001423 intent.getCategories() != null &&
1424 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001425 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001426 intent.addFlags(
1427 Intent.FLAG_ACTIVITY_NEW_TASK |
1428 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1429 }
Michael Jurka96879562012-03-22 05:54:33 -07001430 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001431
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001432 if (info != null) {
1433 info.intent = intent;
1434 info.id = c.getLong(idIndex);
1435 container = c.getInt(containerIndex);
1436 info.container = container;
1437 info.screen = c.getInt(screenIndex);
1438 info.cellX = c.getInt(cellXIndex);
1439 info.cellY = c.getInt(cellYIndex);
1440
1441 // check & update map of what's occupied
1442 if (!checkItemPlacement(occupied, info)) {
1443 break;
1444 }
1445
1446 switch (container) {
1447 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1448 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1449 sBgWorkspaceItems.add(info);
1450 break;
1451 default:
1452 // Item is in a user folder
1453 FolderInfo folderInfo =
1454 findOrMakeFolder(sBgFolders, container);
1455 folderInfo.add(info);
1456 break;
1457 }
1458 sBgItemsIdMap.put(info.id, info);
1459
1460 // now that we've loaded everthing re-save it with the
1461 // icon in case it disappears somehow.
1462 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
1463 } else {
1464 // Failed to load the shortcut, probably because the
1465 // activity manager couldn't resolve it (maybe the app
1466 // was uninstalled), or the db row was somehow screwed up.
1467 // Delete it.
1468 id = c.getLong(idIndex);
1469 Log.e(TAG, "Error loading shortcut " + id + ", removing it");
1470 contentResolver.delete(LauncherSettings.Favorites.getContentUri(
1471 id, false), null, null);
1472 }
1473 break;
1474
1475 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1476 id = c.getLong(idIndex);
1477 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1478
1479 folderInfo.title = c.getString(titleIndex);
1480 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001481 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001482 folderInfo.container = container;
1483 folderInfo.screen = c.getInt(screenIndex);
1484 folderInfo.cellX = c.getInt(cellXIndex);
1485 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001486
Daniel Sandler8802e962010-05-26 16:28:16 -04001487 // check & update map of what's occupied
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001488 if (!checkItemPlacement(occupied, folderInfo)) {
Daniel Sandler8802e962010-05-26 16:28:16 -04001489 break;
1490 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001491 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001492 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1493 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1494 sBgWorkspaceItems.add(folderInfo);
1495 break;
Joe Onorato36115782010-06-17 13:28:48 -04001496 }
Joe Onorato17a89222011-02-08 17:26:11 -08001497
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001498 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1499 sBgFolders.put(folderInfo.id, folderInfo);
1500 break;
1501
1502 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1503 // Read all Launcher-specific widget details
1504 int appWidgetId = c.getInt(appWidgetIdIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001505 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001506
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001507 final AppWidgetProviderInfo provider =
1508 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001509
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001510 if (!isSafeMode && (provider == null || provider.provider == null ||
1511 provider.provider.getPackageName() == null)) {
1512 String log = "Deleting widget that isn't installed anymore: id="
1513 + id + " appWidgetId=" + appWidgetId;
1514 Log.e(TAG, log);
1515 Launcher.sDumpLogs.add(log);
1516 itemsToRemove.add(id);
1517 } else {
1518 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1519 provider.provider);
1520 appWidgetInfo.id = id;
1521 appWidgetInfo.screen = c.getInt(screenIndex);
1522 appWidgetInfo.cellX = c.getInt(cellXIndex);
1523 appWidgetInfo.cellY = c.getInt(cellYIndex);
1524 appWidgetInfo.spanX = c.getInt(spanXIndex);
1525 appWidgetInfo.spanY = c.getInt(spanYIndex);
1526 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1527 appWidgetInfo.minSpanX = minSpan[0];
1528 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001529
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001530 container = c.getInt(containerIndex);
1531 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1532 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1533 Log.e(TAG, "Widget found where container != " +
1534 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1535 continue;
1536 }
1537 appWidgetInfo.container = c.getInt(containerIndex);
1538
1539 // check & update map of what's occupied
1540 if (!checkItemPlacement(occupied, appWidgetInfo)) {
1541 break;
1542 }
1543 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1544 sBgAppWidgets.add(appWidgetInfo);
1545 }
Joe Onorato36115782010-06-17 13:28:48 -04001546 break;
1547 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001548 } catch (Exception e) {
1549 Log.w(TAG, "Desktop items loading interrupted:", e);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001550 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001551 }
1552 } finally {
1553 c.close();
1554 }
1555
1556 if (itemsToRemove.size() > 0) {
1557 ContentProviderClient client = contentResolver.acquireContentProviderClient(
1558 LauncherSettings.Favorites.CONTENT_URI);
1559 // Remove dead items
1560 for (long id : itemsToRemove) {
1561 if (DEBUG_LOADERS) {
1562 Log.d(TAG, "Removed id = " + id);
1563 }
1564 // Don't notify content observers
1565 try {
1566 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1567 null, null);
1568 } catch (RemoteException e) {
1569 Log.w(TAG, "Could not remove id = " + id);
1570 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001571 }
1572 }
1573
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001574 if (DEBUG_LOADERS) {
1575 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1576 Log.d(TAG, "workspace layout: ");
1577 for (int y = 0; y < mCellCountY; y++) {
1578 String line = "";
1579 for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
1580 if (s > 0) {
1581 line += " | ";
1582 }
1583 for (int x = 0; x < mCellCountX; x++) {
1584 line += ((occupied[s][x][y] != null) ? "#" : ".");
1585 }
Joe Onorato36115782010-06-17 13:28:48 -04001586 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001587 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04001588 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001589 }
Joe Onorato36115782010-06-17 13:28:48 -04001590 }
1591 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001592
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001593 /** Filters the set of items who are directly or indirectly (via another container) on the
1594 * specified screen. */
1595 private void filterCurrentWorkspaceItems(int currentScreen,
1596 ArrayList<ItemInfo> allWorkspaceItems,
1597 ArrayList<ItemInfo> currentScreenItems,
1598 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001599 // Purge any null ItemInfos
1600 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1601 while (iter.hasNext()) {
1602 ItemInfo i = iter.next();
1603 if (i == null) {
1604 iter.remove();
1605 }
1606 }
1607
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001608 // If we aren't filtering on a screen, then the set of items to load is the full set of
1609 // items given.
1610 if (currentScreen < 0) {
1611 currentScreenItems.addAll(allWorkspaceItems);
Joe Onorato36115782010-06-17 13:28:48 -04001612 }
1613
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001614 // Order the set of items by their containers first, this allows use to walk through the
1615 // list sequentially, build up a list of containers that are in the specified screen,
1616 // as well as all items in those containers.
1617 Set<Long> itemsOnScreen = new HashSet<Long>();
1618 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1619 @Override
1620 public int compare(ItemInfo lhs, ItemInfo rhs) {
1621 return (int) (lhs.container - rhs.container);
1622 }
1623 });
1624 for (ItemInfo info : allWorkspaceItems) {
1625 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1626 if (info.screen == currentScreen) {
1627 currentScreenItems.add(info);
1628 itemsOnScreen.add(info.id);
1629 } else {
1630 otherScreenItems.add(info);
1631 }
1632 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1633 currentScreenItems.add(info);
1634 itemsOnScreen.add(info.id);
1635 } else {
1636 if (itemsOnScreen.contains(info.container)) {
1637 currentScreenItems.add(info);
1638 itemsOnScreen.add(info.id);
1639 } else {
1640 otherScreenItems.add(info);
1641 }
1642 }
1643 }
1644 }
1645
1646 /** Filters the set of widgets which are on the specified screen. */
1647 private void filterCurrentAppWidgets(int currentScreen,
1648 ArrayList<LauncherAppWidgetInfo> appWidgets,
1649 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1650 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1651 // If we aren't filtering on a screen, then the set of items to load is the full set of
1652 // widgets given.
1653 if (currentScreen < 0) {
1654 currentScreenWidgets.addAll(appWidgets);
1655 }
1656
1657 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001658 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001659 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1660 widget.screen == currentScreen) {
1661 currentScreenWidgets.add(widget);
1662 } else {
1663 otherScreenWidgets.add(widget);
1664 }
1665 }
1666 }
1667
1668 /** Filters the set of folders which are on the specified screen. */
1669 private void filterCurrentFolders(int currentScreen,
1670 HashMap<Long, ItemInfo> itemsIdMap,
1671 HashMap<Long, FolderInfo> folders,
1672 HashMap<Long, FolderInfo> currentScreenFolders,
1673 HashMap<Long, FolderInfo> otherScreenFolders) {
1674 // If we aren't filtering on a screen, then the set of items to load is the full set of
1675 // widgets given.
1676 if (currentScreen < 0) {
1677 currentScreenFolders.putAll(folders);
1678 }
1679
1680 for (long id : folders.keySet()) {
1681 ItemInfo info = itemsIdMap.get(id);
1682 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07001683 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001684 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1685 info.screen == currentScreen) {
1686 currentScreenFolders.put(id, folder);
1687 } else {
1688 otherScreenFolders.put(id, folder);
1689 }
1690 }
1691 }
1692
1693 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
1694 * right) */
1695 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
1696 // XXX: review this
1697 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07001698 @Override
1699 public int compare(ItemInfo lhs, ItemInfo rhs) {
1700 int cellCountX = LauncherModel.getCellCountX();
1701 int cellCountY = LauncherModel.getCellCountY();
1702 int screenOffset = cellCountX * cellCountY;
1703 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
1704 long lr = (lhs.container * containerOffset + lhs.screen * screenOffset +
1705 lhs.cellY * cellCountX + lhs.cellX);
1706 long rr = (rhs.container * containerOffset + rhs.screen * screenOffset +
1707 rhs.cellY * cellCountX + rhs.cellX);
1708 return (int) (lr - rr);
1709 }
1710 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001711 }
Winson Chungdb8a8942012-04-03 14:08:41 -07001712
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001713 private void bindWorkspaceItems(final Callbacks oldCallbacks,
1714 final ArrayList<ItemInfo> workspaceItems,
1715 final ArrayList<LauncherAppWidgetInfo> appWidgets,
1716 final HashMap<Long, FolderInfo> folders,
1717 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07001718
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001719 final boolean postOnMainThread = (deferredBindRunnables != null);
1720
1721 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07001722 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001723 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04001724 final int start = i;
1725 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001726 final Runnable r = new Runnable() {
1727 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04001728 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08001729 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001730 if (callbacks != null) {
Winson Chung603bcb92011-09-02 11:45:39 -07001731 callbacks.bindItems(workspaceItems, start, start+chunkSize);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001732 }
1733 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001734 };
1735 if (postOnMainThread) {
1736 deferredBindRunnables.add(r);
1737 } else {
Winson Chung81b52252012-08-27 15:34:29 -07001738 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001739 }
Joe Onorato36115782010-06-17 13:28:48 -04001740 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001741
1742 // Bind the folders
1743 if (!folders.isEmpty()) {
1744 final Runnable r = new Runnable() {
1745 public void run() {
1746 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1747 if (callbacks != null) {
1748 callbacks.bindFolders(folders);
1749 }
1750 }
1751 };
1752 if (postOnMainThread) {
1753 deferredBindRunnables.add(r);
1754 } else {
Winson Chung81b52252012-08-27 15:34:29 -07001755 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001756 }
1757 }
1758
1759 // Bind the widgets, one at a time
1760 N = appWidgets.size();
1761 for (int i = 0; i < N; i++) {
1762 final LauncherAppWidgetInfo widget = appWidgets.get(i);
1763 final Runnable r = new Runnable() {
1764 public void run() {
1765 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1766 if (callbacks != null) {
1767 callbacks.bindAppWidget(widget);
1768 }
1769 }
1770 };
1771 if (postOnMainThread) {
1772 deferredBindRunnables.add(r);
1773 } else {
Winson Chung81b52252012-08-27 15:34:29 -07001774 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001775 }
1776 }
1777 }
1778
1779 /**
1780 * Binds all loaded data to actual views on the main thread.
1781 */
1782 private void bindWorkspace(int synchronizeBindPage) {
1783 final long t = SystemClock.uptimeMillis();
1784 Runnable r;
1785
1786 // Don't use these two variables in any of the callback runnables.
1787 // Otherwise we hold a reference to them.
1788 final Callbacks oldCallbacks = mCallbacks.get();
1789 if (oldCallbacks == null) {
1790 // This launcher has exited and nobody bothered to tell us. Just bail.
1791 Log.w(TAG, "LoaderTask running with no launcher");
1792 return;
1793 }
1794
Winson Chung4a2afa32012-07-19 14:53:05 -07001795 final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
1796 final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001797 oldCallbacks.getCurrentWorkspaceScreen();
1798
1799 // Load all the items that are on the current page first (and in the process, unbind
1800 // all the existing workspace items before we call startBinding() below.
1801 unbindWorkspaceItemsOnMainThread();
1802 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
1803 ArrayList<LauncherAppWidgetInfo> appWidgets =
1804 new ArrayList<LauncherAppWidgetInfo>();
1805 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
1806 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -07001807 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001808 workspaceItems.addAll(sBgWorkspaceItems);
1809 appWidgets.addAll(sBgAppWidgets);
1810 folders.putAll(sBgFolders);
1811 itemsIdMap.putAll(sBgItemsIdMap);
1812 }
1813
1814 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
1815 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
1816 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
1817 new ArrayList<LauncherAppWidgetInfo>();
1818 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
1819 new ArrayList<LauncherAppWidgetInfo>();
1820 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
1821 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
1822
1823 // Separate the items that are on the current screen, and all the other remaining items
1824 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
1825 otherWorkspaceItems);
1826 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
1827 otherAppWidgets);
1828 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
1829 otherFolders);
1830 sortWorkspaceItemsSpatially(currentWorkspaceItems);
1831 sortWorkspaceItemsSpatially(otherWorkspaceItems);
1832
1833 // Tell the workspace that we're about to start binding items
1834 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001835 public void run() {
1836 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1837 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001838 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04001839 }
1840 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001841 };
Winson Chung81b52252012-08-27 15:34:29 -07001842 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001843
1844 // Load items on the current page
1845 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
1846 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07001847 if (isLoadingSynchronously) {
1848 r = new Runnable() {
1849 public void run() {
1850 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1851 if (callbacks != null) {
1852 callbacks.onPageBoundSynchronously(currentScreen);
1853 }
1854 }
1855 };
Winson Chung81b52252012-08-27 15:34:29 -07001856 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07001857 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001858
Winson Chung4a2afa32012-07-19 14:53:05 -07001859 // Load all the remaining pages (if we are loading synchronously, we want to defer this
1860 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001861 mDeferredBindRunnables.clear();
1862 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07001863 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001864
1865 // Tell the workspace that we're done binding items
1866 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001867 public void run() {
1868 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1869 if (callbacks != null) {
1870 callbacks.finishBindingItems();
1871 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001872
Winson Chung98e030b2012-05-07 16:01:11 -07001873 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04001874 if (DEBUG_LOADERS) {
1875 Log.d(TAG, "bound workspace in "
1876 + (SystemClock.uptimeMillis()-t) + "ms");
1877 }
Winson Chung36a62fe2012-05-06 18:04:42 -07001878
1879 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04001880 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001881 };
Winson Chung4a2afa32012-07-19 14:53:05 -07001882 if (isLoadingSynchronously) {
1883 mDeferredBindRunnables.add(r);
1884 } else {
Winson Chung81b52252012-08-27 15:34:29 -07001885 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07001886 }
Joe Onorato36115782010-06-17 13:28:48 -04001887 }
Joe Onoratocc67f472010-06-08 10:54:30 -07001888
Joe Onorato36115782010-06-17 13:28:48 -04001889 private void loadAndBindAllApps() {
1890 if (DEBUG_LOADERS) {
1891 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
1892 }
1893 if (!mAllAppsLoaded) {
1894 loadAllAppsByBatch();
Reena Lee93f824a2011-09-23 17:20:28 -07001895 synchronized (LoaderTask.this) {
1896 if (mStopped) {
1897 return;
1898 }
1899 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07001900 }
Joe Onorato36115782010-06-17 13:28:48 -04001901 } else {
1902 onlyBindAllApps();
1903 }
1904 }
Joe Onoratocc67f472010-06-08 10:54:30 -07001905
Joe Onorato36115782010-06-17 13:28:48 -04001906 private void onlyBindAllApps() {
1907 final Callbacks oldCallbacks = mCallbacks.get();
1908 if (oldCallbacks == null) {
1909 // This launcher has exited and nobody bothered to tell us. Just bail.
1910 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
1911 return;
1912 }
1913
1914 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07001915 @SuppressWarnings("unchecked")
Joe Onorato36115782010-06-17 13:28:48 -04001916 final ArrayList<ApplicationInfo> list
Adam Cohen487f7dd2012-06-28 18:12:10 -07001917 = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07001918 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001919 public void run() {
1920 final long t = SystemClock.uptimeMillis();
1921 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1922 if (callbacks != null) {
1923 callbacks.bindAllApplications(list);
1924 }
1925 if (DEBUG_LOADERS) {
1926 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
1927 + (SystemClock.uptimeMillis()-t) + "ms");
1928 }
1929 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07001930 };
1931 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
1932 if (oldCallbacks.isAllAppsVisible() && isRunningOnMainThread) {
1933 r.run();
1934 } else {
1935 mHandler.post(r);
1936 }
Joe Onorato36115782010-06-17 13:28:48 -04001937 }
1938
1939 private void loadAllAppsByBatch() {
1940 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1941
1942 // Don't use these two variables in any of the callback runnables.
1943 // Otherwise we hold a reference to them.
1944 final Callbacks oldCallbacks = mCallbacks.get();
1945 if (oldCallbacks == null) {
1946 // This launcher has exited and nobody bothered to tell us. Just bail.
1947 Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
1948 return;
1949 }
1950
1951 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1952 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1953
1954 final PackageManager packageManager = mContext.getPackageManager();
1955 List<ResolveInfo> apps = null;
1956
1957 int N = Integer.MAX_VALUE;
1958
1959 int startIndex;
1960 int i=0;
1961 int batchSize = -1;
1962 while (i < N && !mStopped) {
1963 if (i == 0) {
Adam Cohen487f7dd2012-06-28 18:12:10 -07001964 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04001965 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1966 apps = packageManager.queryIntentActivities(mainIntent, 0);
1967 if (DEBUG_LOADERS) {
1968 Log.d(TAG, "queryIntentActivities took "
1969 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
1970 }
1971 if (apps == null) {
1972 return;
1973 }
1974 N = apps.size();
1975 if (DEBUG_LOADERS) {
1976 Log.d(TAG, "queryIntentActivities got " + N + " apps");
1977 }
1978 if (N == 0) {
1979 // There are no apps?!?
1980 return;
1981 }
1982 if (mBatchSize == 0) {
1983 batchSize = N;
1984 } else {
1985 batchSize = mBatchSize;
1986 }
1987
1988 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1989 Collections.sort(apps,
Winson Chungc3eecff2011-07-11 17:44:15 -07001990 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
Joe Onorato36115782010-06-17 13:28:48 -04001991 if (DEBUG_LOADERS) {
1992 Log.d(TAG, "sort took "
1993 + (SystemClock.uptimeMillis()-sortTime) + "ms");
1994 }
1995 }
1996
1997 final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
1998
1999 startIndex = i;
2000 for (int j=0; i<N && j<batchSize; j++) {
2001 // This builds the icon bitmaps.
Adam Cohen487f7dd2012-06-28 18:12:10 -07002002 mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
Michael Jurkac9d95c52011-08-29 14:03:34 -07002003 mIconCache, mLabelCache));
Joe Onorato36115782010-06-17 13:28:48 -04002004 i++;
2005 }
2006
2007 final boolean first = i <= batchSize;
2008 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002009 final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
2010 mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002011
Joe Onoratocc67f472010-06-08 10:54:30 -07002012 mHandler.post(new Runnable() {
2013 public void run() {
2014 final long t = SystemClock.uptimeMillis();
Joe Onoratocc67f472010-06-08 10:54:30 -07002015 if (callbacks != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002016 if (first) {
2017 callbacks.bindAllApplications(added);
2018 } else {
2019 callbacks.bindAppsAdded(added);
2020 }
2021 if (DEBUG_LOADERS) {
2022 Log.d(TAG, "bound " + added.size() + " apps in "
2023 + (SystemClock.uptimeMillis() - t) + "ms");
2024 }
2025 } else {
2026 Log.i(TAG, "not binding apps: no Launcher activity");
Joe Onoratocc67f472010-06-08 10:54:30 -07002027 }
2028 }
2029 });
2030
Daniel Sandlerdca66122010-04-13 16:23:58 -04002031 if (DEBUG_LOADERS) {
Joe Onorato36115782010-06-17 13:28:48 -04002032 Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
2033 + (SystemClock.uptimeMillis()-t2) + "ms");
2034 }
2035
2036 if (mAllAppsLoadDelay > 0 && i < N) {
2037 try {
2038 if (DEBUG_LOADERS) {
2039 Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
2040 }
2041 Thread.sleep(mAllAppsLoadDelay);
2042 } catch (InterruptedException exc) { }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002043 }
2044 }
2045
Joe Onorato36115782010-06-17 13:28:48 -04002046 if (DEBUG_LOADERS) {
2047 Log.d(TAG, "cached all " + N + " apps in "
2048 + (SystemClock.uptimeMillis()-t) + "ms"
2049 + (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
Joe Onoratobe386092009-11-17 17:32:16 -08002050 }
2051 }
2052
2053 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002054 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002055 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2056 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2057 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2058 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2059 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2060 }
Joe Onorato36115782010-06-17 13:28:48 -04002061 }
2062 }
2063
2064 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002065 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002066 }
2067
2068 private class PackageUpdatedTask implements Runnable {
2069 int mOp;
2070 String[] mPackages;
2071
2072 public static final int OP_NONE = 0;
2073 public static final int OP_ADD = 1;
2074 public static final int OP_UPDATE = 2;
2075 public static final int OP_REMOVE = 3; // uninstlled
2076 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2077
2078
2079 public PackageUpdatedTask(int op, String[] packages) {
2080 mOp = op;
2081 mPackages = packages;
2082 }
2083
2084 public void run() {
2085 final Context context = mApp;
2086
2087 final String[] packages = mPackages;
2088 final int N = packages.length;
2089 switch (mOp) {
2090 case OP_ADD:
2091 for (int i=0; i<N; i++) {
2092 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002093 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002094 }
2095 break;
2096 case OP_UPDATE:
2097 for (int i=0; i<N; i++) {
2098 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002099 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002100 LauncherApplication app =
2101 (LauncherApplication) context.getApplicationContext();
2102 WidgetPreviewLoader.removeFromDb(
2103 app.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002104 }
2105 break;
2106 case OP_REMOVE:
2107 case OP_UNAVAILABLE:
2108 for (int i=0; i<N; i++) {
2109 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002110 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002111 LauncherApplication app =
2112 (LauncherApplication) context.getApplicationContext();
2113 WidgetPreviewLoader.removeFromDb(
2114 app.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002115 }
2116 break;
2117 }
2118
2119 ArrayList<ApplicationInfo> added = null;
Joe Onorato36115782010-06-17 13:28:48 -04002120 ArrayList<ApplicationInfo> modified = null;
Winson Chung83892cc2013-05-01 16:53:33 -07002121 final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002122
Adam Cohen487f7dd2012-06-28 18:12:10 -07002123 if (mBgAllAppsList.added.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002124 added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
2125 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002126 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002127 if (mBgAllAppsList.modified.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002128 modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
2129 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002130 }
Winson Chung5d55f332012-07-16 20:45:03 -07002131 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002132 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002133 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002134 }
2135
Joe Onorato36115782010-06-17 13:28:48 -04002136 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2137 if (callbacks == null) {
2138 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2139 return;
2140 }
2141
2142 if (added != null) {
2143 final ArrayList<ApplicationInfo> addedFinal = added;
2144 mHandler.post(new Runnable() {
2145 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002146 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2147 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002148 callbacks.bindAppsAdded(addedFinal);
2149 }
2150 }
2151 });
2152 }
2153 if (modified != null) {
2154 final ArrayList<ApplicationInfo> modifiedFinal = modified;
2155 mHandler.post(new Runnable() {
2156 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002157 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2158 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002159 callbacks.bindAppsUpdated(modifiedFinal);
2160 }
2161 }
2162 });
2163 }
Winson Chung83892cc2013-05-01 16:53:33 -07002164 // If a package has been removed, or an app has been removed as a result of
2165 // an update (for example), make the removed callback.
2166 if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
2167 final boolean permanent = (mOp == OP_REMOVE);
2168 final ArrayList<String> removedPackageNames =
2169 new ArrayList<String>(Arrays.asList(packages));
2170
Joe Onorato36115782010-06-17 13:28:48 -04002171 mHandler.post(new Runnable() {
2172 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002173 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2174 if (callbacks == cb && cb != null) {
Winson Chung83892cc2013-05-01 16:53:33 -07002175 callbacks.bindComponentsRemoved(removedPackageNames,
2176 removedApps, permanent);
Joe Onorato36115782010-06-17 13:28:48 -04002177 }
2178 }
2179 });
Joe Onoratobe386092009-11-17 17:32:16 -08002180 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002181
Michael Jurkac402cd92013-05-20 15:49:32 +02002182 final ArrayList<Object> widgetsAndShortcuts =
2183 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002184 mHandler.post(new Runnable() {
2185 @Override
2186 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002187 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2188 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002189 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002190 }
2191 }
2192 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002193 }
2194 }
2195
Michael Jurkac402cd92013-05-20 15:49:32 +02002196 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2197 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2198 PackageManager packageManager = context.getPackageManager();
2199 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2200 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2201 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2202 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2203 Collections.sort(widgetsAndShortcuts,
2204 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2205 return widgetsAndShortcuts;
2206 }
2207
Joe Onorato9c1289c2009-08-17 11:03:03 -04002208 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002209 * This is called from the code that adds shortcuts from the intent receiver. This
2210 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002211 */
Joe Onorato56d82912010-03-07 14:32:10 -05002212 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002213 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002214 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002215
Joe Onorato56d82912010-03-07 14:32:10 -05002216 /**
2217 * Make an ShortcutInfo object for a shortcut that is an application.
2218 *
2219 * If c is not null, then it will be used to fill in missing data like the title and icon.
2220 */
2221 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002222 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002223 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002224 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002225
2226 ComponentName componentName = intent.getComponent();
2227 if (componentName == null) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002228 return null;
2229 }
2230
Adam Cohen00fcb492011-11-02 21:53:47 -07002231 try {
2232 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2233 if (!pi.applicationInfo.enabled) {
2234 // If we return null here, the corresponding item will be removed from the launcher
2235 // db and will not appear in the workspace.
2236 return null;
2237 }
2238 } catch (NameNotFoundException e) {
2239 Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
2240 }
2241
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002242 // TODO: See if the PackageManager knows about this case. If it doesn't
2243 // then return null & delete this.
2244
Joe Onorato56d82912010-03-07 14:32:10 -05002245 // the resource -- This may implicitly give us back the fallback icon,
2246 // but don't worry about that. All we're doing with usingFallbackIcon is
2247 // to avoid saving lots of copies of that in the database, and most apps
2248 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002249
2250 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2251 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2252 // via resolveActivity().
2253 ResolveInfo resolveInfo = null;
2254 ComponentName oldComponent = intent.getComponent();
2255 Intent newIntent = new Intent(intent.getAction(), null);
2256 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2257 newIntent.setPackage(oldComponent.getPackageName());
2258 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2259 for (ResolveInfo i : infos) {
2260 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2261 i.activityInfo.name);
2262 if (cn.equals(oldComponent)) {
2263 resolveInfo = i;
2264 }
2265 }
2266 if (resolveInfo == null) {
2267 resolveInfo = manager.resolveActivity(intent, 0);
2268 }
Joe Onorato56d82912010-03-07 14:32:10 -05002269 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002270 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002271 }
Joe Onorato56d82912010-03-07 14:32:10 -05002272 // the db
2273 if (icon == null) {
2274 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002275 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002276 }
2277 }
2278 // the fallback icon
2279 if (icon == null) {
2280 icon = getFallbackIcon();
2281 info.usingFallbackIcon = true;
2282 }
2283 info.setIcon(icon);
2284
2285 // from the resource
2286 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002287 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2288 if (labelCache != null && labelCache.containsKey(key)) {
2289 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002290 } else {
2291 info.title = resolveInfo.activityInfo.loadLabel(manager);
2292 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002293 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002294 }
2295 }
Joe Onorato56d82912010-03-07 14:32:10 -05002296 }
2297 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002298 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002299 if (c != null) {
2300 info.title = c.getString(titleIndex);
2301 }
2302 }
2303 // fall back to the class name of the activity
2304 if (info.title == null) {
2305 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002306 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002307 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2308 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002309 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002310
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002311 /**
Winson Chung8a435102012-08-30 17:16:53 -07002312 * Returns the set of workspace ShortcutInfos with the specified intent.
2313 */
2314 static ArrayList<ItemInfo> getWorkspaceShortcutItemInfosWithIntent(Intent intent) {
2315 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
2316 synchronized (sBgLock) {
2317 for (ItemInfo info : sBgWorkspaceItems) {
2318 if (info instanceof ShortcutInfo) {
2319 ShortcutInfo shortcut = (ShortcutInfo) info;
2320 if (shortcut.intent.toUri(0).equals(intent.toUri(0))) {
2321 items.add(shortcut);
2322 }
2323 }
2324 }
2325 }
2326 return items;
2327 }
2328
2329 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002330 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002331 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002332 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002333 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2334 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002335
Joe Onorato56d82912010-03-07 14:32:10 -05002336 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002337 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002338 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002339
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002340 // TODO: If there's an explicit component and we can't install that, delete it.
2341
Joe Onorato56d82912010-03-07 14:32:10 -05002342 info.title = c.getString(titleIndex);
2343
Joe Onorato9c1289c2009-08-17 11:03:03 -04002344 int iconType = c.getInt(iconTypeIndex);
2345 switch (iconType) {
2346 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2347 String packageName = c.getString(iconPackageIndex);
2348 String resourceName = c.getString(iconResourceIndex);
2349 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002350 info.customIcon = false;
2351 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002352 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002353 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002354 if (resources != null) {
2355 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002356 icon = Utilities.createIconBitmap(
2357 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002358 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002359 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002360 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002361 }
Joe Onorato56d82912010-03-07 14:32:10 -05002362 // the db
2363 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002364 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002365 }
2366 // the fallback icon
2367 if (icon == null) {
2368 icon = getFallbackIcon();
2369 info.usingFallbackIcon = true;
2370 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002371 break;
2372 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002373 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002374 if (icon == null) {
2375 icon = getFallbackIcon();
2376 info.customIcon = false;
2377 info.usingFallbackIcon = true;
2378 } else {
2379 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002380 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002381 break;
2382 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002383 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002384 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002385 info.customIcon = false;
2386 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002387 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002388 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002389 return info;
2390 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002391
Michael Jurka931dc972011-08-05 15:08:15 -07002392 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002393 @SuppressWarnings("all") // suppress dead code warning
2394 final boolean debug = false;
2395 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002396 Log.d(TAG, "getIconFromCursor app="
2397 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2398 }
2399 byte[] data = c.getBlob(iconIndex);
2400 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002401 return Utilities.createIconBitmap(
2402 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002403 } catch (Exception e) {
2404 return null;
2405 }
2406 }
2407
Winson Chung3d503fb2011-07-13 17:25:49 -07002408 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2409 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002410 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002411 if (info == null) {
2412 return null;
2413 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002414 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002415
2416 return info;
2417 }
2418
Winson Chunga9abd0e2010-10-27 17:18:37 -07002419 /**
Winson Chung55cef262010-10-28 14:14:18 -07002420 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2421 */
2422 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2423 ComponentName component) {
2424 List<AppWidgetProviderInfo> widgets =
2425 AppWidgetManager.getInstance(context).getInstalledProviders();
2426 for (AppWidgetProviderInfo info : widgets) {
2427 if (info.provider.equals(component)) {
2428 return info;
2429 }
2430 }
2431 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002432 }
2433
Winson Chung68846fd2010-10-29 11:00:27 -07002434 /**
2435 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2436 */
2437 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2438 final PackageManager packageManager = context.getPackageManager();
2439 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2440 new ArrayList<WidgetMimeTypeHandlerData>();
2441
2442 final Intent supportsIntent =
2443 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2444 supportsIntent.setType(mimeType);
2445
2446 // Create a set of widget configuration components that we can test against
2447 final List<AppWidgetProviderInfo> widgets =
2448 AppWidgetManager.getInstance(context).getInstalledProviders();
2449 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2450 new HashMap<ComponentName, AppWidgetProviderInfo>();
2451 for (AppWidgetProviderInfo info : widgets) {
2452 configurationComponentToWidget.put(info.configure, info);
2453 }
2454
2455 // Run through each of the intents that can handle this type of clip data, and cross
2456 // reference them with the components that are actual configuration components
2457 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2458 PackageManager.MATCH_DEFAULT_ONLY);
2459 for (ResolveInfo info : activities) {
2460 final ActivityInfo activityInfo = info.activityInfo;
2461 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2462 activityInfo.name);
2463 if (configurationComponentToWidget.containsKey(infoComponent)) {
2464 supportedConfigurationActivities.add(
2465 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2466 configurationComponentToWidget.get(infoComponent)));
2467 }
2468 }
2469 return supportedConfigurationActivities;
2470 }
2471
Winson Chunga9abd0e2010-10-27 17:18:37 -07002472 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08002473 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2474 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2475 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2476
Adam Cohend9198822011-11-22 16:42:47 -08002477 if (intent == null) {
2478 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2479 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2480 return null;
2481 }
2482
Joe Onorato0589f0f2010-02-08 13:44:00 -08002483 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08002484 boolean customIcon = false;
2485 ShortcutIconResource iconResource = null;
2486
2487 if (bitmap != null && bitmap instanceof Bitmap) {
2488 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002489 customIcon = true;
2490 } else {
2491 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2492 if (extra != null && extra instanceof ShortcutIconResource) {
2493 try {
2494 iconResource = (ShortcutIconResource) extra;
2495 final PackageManager packageManager = context.getPackageManager();
2496 Resources resources = packageManager.getResourcesForApplication(
2497 iconResource.packageName);
2498 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002499 icon = Utilities.createIconBitmap(
2500 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002501 } catch (Exception e) {
2502 Log.w(TAG, "Could not load shortcut icon: " + extra);
2503 }
2504 }
2505 }
2506
Michael Jurkac9d95c52011-08-29 14:03:34 -07002507 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002508
2509 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002510 if (fallbackIcon != null) {
2511 icon = fallbackIcon;
2512 } else {
2513 icon = getFallbackIcon();
2514 info.usingFallbackIcon = true;
2515 }
Joe Onorato56d82912010-03-07 14:32:10 -05002516 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08002517 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05002518
Joe Onorato0589f0f2010-02-08 13:44:00 -08002519 info.title = name;
2520 info.intent = intent;
2521 info.customIcon = customIcon;
2522 info.iconResource = iconResource;
2523
2524 return info;
2525 }
2526
Winson Chungaac01e12011-08-17 10:37:13 -07002527 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2528 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08002529 // If apps can't be on SD, don't even bother.
2530 if (!mAppsCanBeOnExternalStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07002531 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08002532 }
Joe Onorato56d82912010-03-07 14:32:10 -05002533 // If this icon doesn't have a custom icon, check to see
2534 // what's stored in the DB, and if it doesn't match what
2535 // we're going to show, store what we are going to show back
2536 // into the DB. We do this so when we're loading, if the
2537 // package manager can't find an icon (for example because
2538 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07002539 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07002540 cache.put(info, c.getBlob(iconIndex));
2541 return true;
2542 }
2543 return false;
2544 }
2545 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2546 boolean needSave = false;
2547 try {
2548 if (data != null) {
2549 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2550 Bitmap loaded = info.getIcon(mIconCache);
2551 needSave = !saved.sameAs(loaded);
2552 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05002553 needSave = true;
2554 }
Winson Chungaac01e12011-08-17 10:37:13 -07002555 } catch (Exception e) {
2556 needSave = true;
2557 }
2558 if (needSave) {
2559 Log.d(TAG, "going to save icon bitmap for info=" + info);
2560 // This is slower than is ideal, but this only happens once
2561 // or when the app is updated with a new icon.
2562 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05002563 }
2564 }
2565
Joe Onorato9c1289c2009-08-17 11:03:03 -04002566 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07002567 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04002568 * or make a new one.
2569 */
Adam Cohendf2cc412011-04-27 16:56:57 -07002570 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002571 // See if a placeholder was created for us already
2572 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07002573 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002574 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07002575 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002576 folders.put(id, folderInfo);
2577 }
Adam Cohendf2cc412011-04-27 16:56:57 -07002578 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002579 }
2580
Winson Chung11904872012-09-17 16:58:46 -07002581 public static final Comparator<ApplicationInfo> getAppNameComparator() {
2582 final Collator collator = Collator.getInstance();
2583 return new Comparator<ApplicationInfo>() {
2584 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2585 int result = collator.compare(a.title.toString(), b.title.toString());
2586 if (result == 0) {
2587 result = a.componentName.compareTo(b.componentName);
2588 }
2589 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07002590 }
Winson Chung11904872012-09-17 16:58:46 -07002591 };
2592 }
Winson Chung78403fe2011-01-21 15:38:02 -08002593 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2594 = new Comparator<ApplicationInfo>() {
2595 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2596 if (a.firstInstallTime < b.firstInstallTime) return 1;
2597 if (a.firstInstallTime > b.firstInstallTime) return -1;
2598 return 0;
2599 }
2600 };
Winson Chung11904872012-09-17 16:58:46 -07002601 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
2602 final Collator collator = Collator.getInstance();
2603 return new Comparator<AppWidgetProviderInfo>() {
2604 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
2605 return collator.compare(a.label.toString(), b.label.toString());
2606 }
2607 };
2608 }
Winson Chung5308f242011-08-18 12:12:41 -07002609 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
2610 if (info.activityInfo != null) {
2611 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
2612 } else {
2613 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
2614 }
2615 }
Winson Chung785d2eb2011-04-14 16:08:02 -07002616 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07002617 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07002618 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07002619 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07002620 ShortcutNameComparator(PackageManager pm) {
2621 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07002622 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07002623 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07002624 }
2625 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
2626 mPackageManager = pm;
2627 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07002628 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07002629 }
2630 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002631 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07002632 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
2633 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
2634 if (mLabelCache.containsKey(keyA)) {
2635 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002636 } else {
2637 labelA = a.loadLabel(mPackageManager).toString();
2638
Winson Chung5308f242011-08-18 12:12:41 -07002639 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002640 }
Winson Chung5308f242011-08-18 12:12:41 -07002641 if (mLabelCache.containsKey(keyB)) {
2642 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002643 } else {
2644 labelB = b.loadLabel(mPackageManager).toString();
2645
Winson Chung5308f242011-08-18 12:12:41 -07002646 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002647 }
Winson Chung11904872012-09-17 16:58:46 -07002648 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07002649 }
2650 };
Winson Chung1ed747a2011-05-03 16:18:34 -07002651 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07002652 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07002653 private PackageManager mPackageManager;
2654 private HashMap<Object, String> mLabelCache;
2655 WidgetAndShortcutNameComparator(PackageManager pm) {
2656 mPackageManager = pm;
2657 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07002658 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07002659 }
2660 public final int compare(Object a, Object b) {
2661 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07002662 if (mLabelCache.containsKey(a)) {
2663 labelA = mLabelCache.get(a);
2664 } else {
2665 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002666 ((AppWidgetProviderInfo) a).label :
2667 ((ResolveInfo) a).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002668 mLabelCache.put(a, labelA);
2669 }
2670 if (mLabelCache.containsKey(b)) {
2671 labelB = mLabelCache.get(b);
2672 } else {
2673 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002674 ((AppWidgetProviderInfo) b).label :
2675 ((ResolveInfo) b).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002676 mLabelCache.put(b, labelB);
2677 }
Winson Chung11904872012-09-17 16:58:46 -07002678 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07002679 }
2680 };
Joe Onoratobe386092009-11-17 17:32:16 -08002681
2682 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08002683 Log.d(TAG, "mCallbacks=" + mCallbacks);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002684 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
2685 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
2686 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
2687 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04002688 if (mLoaderTask != null) {
2689 mLoaderTask.dumpState();
2690 } else {
2691 Log.d(TAG, "mLoaderTask=null");
2692 }
Joe Onoratobe386092009-11-17 17:32:16 -08002693 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002694}