blob: 28530e6ac120a3bec7be1da3824caa7628472343 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Narayan Kamathcb1a4772011-06-28 13:46:59 +010019import android.app.SearchManager;
Romain Guy629de3e2010-01-13 12:20:59 -080020import android.appwidget.AppWidgetManager;
21import android.appwidget.AppWidgetProviderInfo;
Winson Chungc9168342013-06-26 14:54:55 -070022import android.content.*;
Joe Onorato0589f0f2010-02-08 13:44:00 -080023import android.content.Intent.ShortcutIconResource;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080024import android.content.pm.ActivityInfo;
Adam Cohen00fcb492011-11-02 21:53:47 -070025import android.content.pm.PackageInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.pm.PackageManager;
Adam Cohen00fcb492011-11-02 21:53:47 -070027import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080028import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070029import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080030import android.content.res.Resources;
31import android.database.Cursor;
32import android.graphics.Bitmap;
33import android.graphics.BitmapFactory;
34import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080035import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040036import android.os.Handler;
37import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080038import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070040import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040041import android.os.SystemClock;
Winson Chungaafa03c2010-06-11 17:34:16 -070042import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070043import android.util.Pair;
Daniel Sandler325dc232013-06-05 22:57:57 -040044import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
Romain Guyedcce092010-03-04 13:03:17 -080045
Michael Jurkac2f801e2011-07-12 14:19:46 -070046import java.lang.ref.WeakReference;
47import java.net.URISyntaxException;
48import java.text.Collator;
49import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070050import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070051import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070052import java.util.Collections;
53import java.util.Comparator;
54import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070055import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070056import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070057import java.util.List;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070058import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070059import java.util.TreeMap;
Michael Jurkac2f801e2011-07-12 14:19:46 -070060
The Android Open Source Project31dd5032009-03-03 19:32:27 -080061/**
62 * Maintains in-memory state of the Launcher. It is expected that there should be only one
63 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070064 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065 */
Joe Onoratof99f8c12009-10-31 17:27:36 -040066public class LauncherModel extends BroadcastReceiver {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080067 static final boolean DEBUG_LOADERS = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -040068 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070069
Joe Onorato36115782010-06-17 13:28:48 -040070 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Joe Onorato17a89222011-02-08 17:26:11 -080071 private final boolean mAppsCanBeOnExternalStorage;
Daniel Sandlerdca66122010-04-13 16:23:58 -040072
Daniel Sandlercc8befa2013-06-11 14:45:48 -040073 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -040074 private final Object mLock = new Object();
75 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -040076 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070077 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +020078 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Winson Chung81b52252012-08-27 15:34:29 -070080 // Specific runnable types that are run on the main thread deferred handler, this allows us to
81 // clear all queued binding runnables when the Launcher activity is destroyed.
82 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
83 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
84
85
Brad Fitzpatrick700889f2010-10-11 09:40:44 -070086 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
87 static {
88 sWorkerThread.start();
89 }
90 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
91
Joe Onoratocc67f472010-06-08 10:54:30 -070092 // We start off with everything not loaded. After that, we assume that
93 // our monitoring of the package manager provides all updates and we never
94 // need to do a requery. These are only ever touched from the loader thread.
95 private boolean mWorkspaceLoaded;
96 private boolean mAllAppsLoaded;
97
Winson Chungb8b2a5a2012-07-12 17:55:31 -070098 // When we are loading pages synchronously, we can't just post the binding of items on the side
99 // pages as this delays the rotation process. Instead, we wait for a callback from the first
100 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
101 // a normal load, we also clear this set of Runnables.
102 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
103
Joe Onorato9c1289c2009-08-17 11:03:03 -0400104 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800105
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700106 // < only access in worker thread >
Adam Cohen487f7dd2012-06-28 18:12:10 -0700107 private AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800108
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700109 // The lock that must be acquired before referencing any static bg data structures. Unlike
110 // other locks, this one can generally be held long-term because we never expect any of these
111 // static data structures to be referenced outside of the worker thread except on the first
112 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700113 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700114
Adam Cohen487f7dd2012-06-28 18:12:10 -0700115 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700116 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700117 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700118
Adam Cohen487f7dd2012-06-28 18:12:10 -0700119 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
120 // created by LauncherModel that are directly on the home screen (however, no widgets or
121 // shortcuts within folders).
122 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700123
Adam Cohen487f7dd2012-06-28 18:12:10 -0700124 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
125 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700126 new ArrayList<LauncherAppWidgetInfo>();
127
Adam Cohen487f7dd2012-06-28 18:12:10 -0700128 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
129 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700130
Adam Cohen487f7dd2012-06-28 18:12:10 -0700131 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
132 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700133
134 // sBgWorkspaceScreens is the ordered set of workspace screens.
135 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
136
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 // </ only access in worker thread >
138
139 private IconCache mIconCache;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800140 private Bitmap mDefaultIcon;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800141
Adam Cohend22015c2010-07-26 22:02:18 -0700142 private static int mCellCountX;
143 private static int mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700144
Reena Lee99a73f32011-10-24 17:27:37 -0700145 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700146
Joe Onorato9c1289c2009-08-17 11:03:03 -0400147 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700148 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400149 public int getCurrentWorkspaceScreen();
150 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700151 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
152 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700153 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700154 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500155 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700156 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400157 public void bindAppWidget(LauncherAppWidgetInfo info);
158 public void bindAllApplications(ArrayList<ApplicationInfo> apps);
Joe Onorato64e6be72010-03-05 15:05:52 -0500159 public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
Winson Chung83892cc2013-05-01 16:53:33 -0700160 public void bindComponentsRemoved(ArrayList<String> packageNames,
161 ArrayList<ApplicationInfo> appInfos,
162 boolean matchPackageNamesOnly);
Michael Jurkac402cd92013-05-20 15:49:32 +0200163 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100164 public void bindSearchablesChanged();
Adam Cohen1462de32012-07-24 22:34:36 -0700165 public void onPageBoundSynchronously(int page);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400166 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800167
Winson Chung64359a52013-07-08 17:17:08 -0700168 public interface ItemInfoFilter {
169 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
170 }
171
Daniel Sandlere4f98912013-06-25 15:13:26 -0400172 LauncherModel(LauncherAppState app, IconCache iconCache) {
173 final Context context = app.getContext();
174
Joe Onorato17a89222011-02-08 17:26:11 -0800175 mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400176 mApp = app;
Adam Cohen487f7dd2012-06-28 18:12:10 -0700177 mBgAllAppsList = new AllAppsList(iconCache);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800178 mIconCache = iconCache;
179
180 mDefaultIcon = Utilities.createIconBitmap(
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400181 mIconCache.getFullResDefaultActivityIcon(), context);
Daniel Sandler2ff10b32010-04-16 15:06:06 -0400182
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400183 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700184 Configuration config = res.getConfiguration();
185 mPreviousConfigMcc = config.mcc;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800186 }
187
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700188 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
189 * posted on the main thread handler. */
190 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700191 runOnMainThread(r, 0);
192 }
193 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700194 if (sWorkerThread.getThreadId() == Process.myTid()) {
195 // If we are on the worker thread, post onto the main handler
196 mHandler.post(r);
197 } else {
198 r.run();
199 }
200 }
201
202 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
203 * posted on the worker thread handler. */
204 private static void runOnWorkerThread(Runnable r) {
205 if (sWorkerThread.getThreadId() == Process.myTid()) {
206 r.run();
207 } else {
208 // If we are not on the worker thread, then post to the worker handler
209 sWorker.post(r);
210 }
211 }
212
Winson Chungc9168342013-06-26 14:54:55 -0700213 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
214 long screen) {
215 final int xCount = LauncherModel.getCellCountX();
216 final int yCount = LauncherModel.getCellCountY();
217 boolean[][] occupied = new boolean[xCount][yCount];
218
219 int cellX, cellY, spanX, spanY;
220 for (int i = 0; i < items.size(); ++i) {
221 final ItemInfo item = items.get(i);
222 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
223 if (item.screenId == screen) {
224 cellX = item.cellX;
225 cellY = item.cellY;
226 spanX = item.spanX;
227 spanY = item.spanY;
228 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
229 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
230 occupied[x][y] = true;
231 }
232 }
233 }
234 }
235 }
236
237 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
238 }
239 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700240 Intent launchIntent,
241 int firstScreenIndex) {
Winson Chungc9168342013-06-26 14:54:55 -0700242 // Lock on the app so that we don't try and get the items while apps are being added
243 LauncherAppState app = LauncherAppState.getInstance();
244 LauncherModel model = app.getModel();
245 boolean found = false;
246 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700247 if (sWorkerThread.getThreadId() != Process.myTid()) {
248 // Flush the LauncherModel worker thread, so that if we just did another
249 // processInstallShortcut, we give it time for its shortcut to get added to the
250 // database (getItemsInLocalCoordinates reads the database)
251 model.flushWorkerThread();
252 }
Winson Chungc9168342013-06-26 14:54:55 -0700253 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700254
255 // Try adding to the workspace screens incrementally, starting at the default or center
256 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung156ab5b2013-07-12 14:14:16 -0700257 firstScreenIndex = Math.min(firstScreenIndex, sBgWorkspaceScreens.size());
258 int count = sBgWorkspaceScreens.size();
259 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700260 int[] tmpCoordinates = new int[2];
261 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
262 sBgWorkspaceScreens.get(screen))) {
263 // Update the Launcher db
264 return new Pair<Long, int[]>(sBgWorkspaceScreens.get(screen), tmpCoordinates);
265 }
266 }
267 }
268 // XXX: Create a new page and add it to the first spot
269 return null;
270 }
271
Winson Chung64359a52013-07-08 17:17:08 -0700272 public void addAndBindAddedApps(final Context context, final ArrayList<ApplicationInfo> added,
273 final Callbacks callbacks) {
274 // Process the newly added applications and add them to the database first
275 Runnable r = new Runnable() {
276 public void run() {
277 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
278 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
279
280 synchronized(sBgLock) {
281 Iterator<ApplicationInfo> iter = added.iterator();
282 while (iter.hasNext()) {
283 ApplicationInfo a = iter.next();
284 final String name = a.title.toString();
285 final Intent launchIntent = a.intent;
286
287 // Short-circuit this logic if the icon exists somewhere on the workspace
288 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
289 continue;
290 }
291
292 // Add this icon to the db, creating a new page if necessary
Winson Chung156ab5b2013-07-12 14:14:16 -0700293 int startSearchPageIndex = 1;
Winson Chung64359a52013-07-08 17:17:08 -0700294 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung156ab5b2013-07-12 14:14:16 -0700295 name, launchIntent, startSearchPageIndex);
Winson Chung64359a52013-07-08 17:17:08 -0700296 if (coords == null) {
297 // If we can't find a valid position, then just add a new screen.
298 // This takes time so we need to re-queue the add until the new
299 // page is added.
300 LauncherAppState appState = LauncherAppState.getInstance();
301 LauncherProvider lp = appState.getLauncherProvider();
302 long screenId = lp.generateNewScreenId();
303 // Update the model
304 sBgWorkspaceScreens.add(screenId);
305 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
306 // Save the screen id for binding in the workspace
307 addedWorkspaceScreensFinal.add(screenId);
308 // Find the coordinate again
309 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung156ab5b2013-07-12 14:14:16 -0700310 a.title.toString(), a.intent, startSearchPageIndex);
Winson Chung64359a52013-07-08 17:17:08 -0700311 }
312 if (coords == null) {
313 throw new RuntimeException("Coordinates should not be null");
314 }
315
316 final ShortcutInfo shortcutInfo = a.makeShortcut();
317 // Add the shortcut to the db
318 addItemToDatabase(context, shortcutInfo,
319 LauncherSettings.Favorites.CONTAINER_DESKTOP,
320 coords.first, coords.second[0], coords.second[1], false);
321 // Save the ShortcutInfo for binding in the workspace
322 addedShortcutsFinal.add(shortcutInfo);
323 }
324 }
325
326 runOnMainThread(new Runnable() {
327 public void run() {
328 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
329 if (callbacks == cb && cb != null) {
330 callbacks.bindAddScreens(addedWorkspaceScreensFinal);
331 callbacks.bindItems(addedShortcutsFinal, 0,
332 addedShortcutsFinal.size(), true);
333 }
334 }
335 });
336 }
337 };
338 runOnWorkerThread(r);
339 }
340
Joe Onorato56d82912010-03-07 14:32:10 -0500341 public Bitmap getFallbackIcon() {
Joe Onorato0589f0f2010-02-08 13:44:00 -0800342 return Bitmap.createBitmap(mDefaultIcon);
Joe Onoratof99f8c12009-10-31 17:27:36 -0400343 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800344
Winson Chung81b52252012-08-27 15:34:29 -0700345 public void unbindItemInfosAndClearQueuedBindRunnables() {
346 if (sWorkerThread.getThreadId() == Process.myTid()) {
347 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
348 "main thread");
349 }
350
351 // Clear any deferred bind runnables
352 mDeferredBindRunnables.clear();
353 // Remove any queued bind runnables
354 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
355 // Unbind all the workspace items
356 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700357 }
358
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700359 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700360 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700361 // Ensure that we don't use the same workspace items data structure on the main thread
362 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700363 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
364 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700365 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700366 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
367 tmpAppWidgets.addAll(sBgAppWidgets);
368 }
369 Runnable r = new Runnable() {
370 @Override
371 public void run() {
372 for (ItemInfo item : tmpWorkspaceItems) {
373 item.unbind();
374 }
375 for (ItemInfo item : tmpAppWidgets) {
376 item.unbind();
377 }
378 }
379 };
380 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700381 }
382
Joe Onorato9c1289c2009-08-17 11:03:03 -0400383 /**
384 * Adds an item to the DB if it was not created previously, or move it to a new
385 * <container, screen, cellX, cellY>
386 */
387 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700388 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400389 if (item.container == ItemInfo.NO_ID) {
390 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700391 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400392 } else {
393 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700394 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800395 }
396 }
397
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700398 static void checkItemInfoLocked(
399 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
400 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
401 if (modelItem != null && item != modelItem) {
402 // check all the data is consistent
403 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
404 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
405 ShortcutInfo shortcut = (ShortcutInfo) item;
406 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
407 modelShortcut.intent.filterEquals(shortcut.intent) &&
408 modelShortcut.id == shortcut.id &&
409 modelShortcut.itemType == shortcut.itemType &&
410 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700411 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700412 modelShortcut.cellX == shortcut.cellX &&
413 modelShortcut.cellY == shortcut.cellY &&
414 modelShortcut.spanX == shortcut.spanX &&
415 modelShortcut.spanY == shortcut.spanY &&
416 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
417 (modelShortcut.dropPos != null &&
418 shortcut.dropPos != null &&
419 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
420 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
421 // For all intents and purposes, this is the same object
422 return;
423 }
424 }
425
426 // the modelItem needs to match up perfectly with item if our model is
427 // to be consistent with the database-- for now, just require
428 // modelItem == item or the equality check above
429 String msg = "item: " + ((item != null) ? item.toString() : "null") +
430 "modelItem: " +
431 ((modelItem != null) ? modelItem.toString() : "null") +
432 "Error: ItemInfo passed to checkItemInfo doesn't match original";
433 RuntimeException e = new RuntimeException(msg);
434 if (stackTrace != null) {
435 e.setStackTrace(stackTrace);
436 }
Adam Cohene25af792013-06-06 23:08:25 -0700437 // TODO: something breaks this in the upgrade path
438 //throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700439 }
440 }
441
Michael Jurka816474f2012-06-25 14:49:02 -0700442 static void checkItemInfo(final ItemInfo item) {
443 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
444 final long itemId = item.id;
445 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700446 public void run() {
447 synchronized (sBgLock) {
448 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700449 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700450 }
451 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700452 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700453 }
454
Michael Jurkac9d95c52011-08-29 14:03:34 -0700455 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
456 final ItemInfo item, final String callingFunction) {
457 final long itemId = item.id;
458 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
459 final ContentResolver cr = context.getContentResolver();
460
Adam Cohen487f7dd2012-06-28 18:12:10 -0700461 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700462 Runnable r = new Runnable() {
463 public void run() {
464 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700465 updateItemArrays(item, itemId, stackTrace);
466 }
467 };
468 runOnWorkerThread(r);
469 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700470
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700471 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
472 final ArrayList<ItemInfo> items, final String callingFunction) {
473 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700474
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700475 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
476 Runnable r = new Runnable() {
477 public void run() {
478 ArrayList<ContentProviderOperation> ops =
479 new ArrayList<ContentProviderOperation>();
480 int count = items.size();
481 for (int i = 0; i < count; i++) {
482 ItemInfo item = items.get(i);
483 final long itemId = item.id;
484 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
485 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700486
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700487 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
488 updateItemArrays(item, itemId, stackTrace);
489
490 }
491 try {
492 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
493 } catch (Exception e) {
494 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700495 }
496 }
497 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700498 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700499 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700500
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700501 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
502 // Lock on mBgLock *after* the db operation
503 synchronized (sBgLock) {
504 checkItemInfoLocked(itemId, item, stackTrace);
505
506 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
507 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
508 // Item is in a folder, make sure this folder exists
509 if (!sBgFolders.containsKey(item.container)) {
510 // An items container is being set to a that of an item which is not in
511 // the list of Folders.
512 String msg = "item: " + item + " container being set to: " +
513 item.container + ", not in the list of folders";
514 Log.e(TAG, msg);
515 Launcher.dumpDebugLogsToConsole();
516 }
517 }
518
519 // Items are added/removed from the corresponding FolderInfo elsewhere, such
520 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
521 // that are on the desktop, as appropriate
522 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
523 if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
524 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
525 switch (modelItem.itemType) {
526 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
527 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
528 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
529 if (!sBgWorkspaceItems.contains(modelItem)) {
530 sBgWorkspaceItems.add(modelItem);
531 }
532 break;
533 default:
534 break;
535 }
536 } else {
537 sBgWorkspaceItems.remove(modelItem);
538 }
539 }
540 }
541
Michael Jurkac7700af2013-05-14 20:17:58 +0200542 public void flushWorkerThread() {
543 mFlushingWorkerThread = true;
544 Runnable waiter = new Runnable() {
545 public void run() {
546 synchronized (this) {
547 notifyAll();
548 mFlushingWorkerThread = false;
549 }
550 }
551 };
552
553 synchronized(waiter) {
554 runOnWorkerThread(waiter);
555 if (mLoaderTask != null) {
556 synchronized(mLoaderTask) {
557 mLoaderTask.notify();
558 }
559 }
560 boolean success = false;
561 while (!success) {
562 try {
563 waiter.wait();
564 success = true;
565 } catch (InterruptedException e) {
566 }
567 }
568 }
569 }
570
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800571 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400572 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700573 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700574 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700575 final long screenId, final int cellX, final int cellY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700576 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
Adam Cohendcd297f2013-06-18 13:13:40 -0700577 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
578 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Adam Cohen487f7dd2012-06-28 18:12:10 -0700579 Launcher.sDumpLogs.add(transaction);
580 Log.d(TAG, transaction);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400581 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400582 item.cellX = cellX;
583 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700584
Winson Chung3d503fb2011-07-13 17:25:49 -0700585 // We store hotseat items in canonical form which is this orientation invariant position
586 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700587 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700588 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700589 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700590 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700591 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700592 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400593
594 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400595 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700596 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
597 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700598 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400599
Michael Jurkac9d95c52011-08-29 14:03:34 -0700600 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700601 }
602
603 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700604 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
605 * cellX, cellY have already been updated on the ItemInfos.
606 */
607 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
608 final long container, final int screen) {
609
610 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
611 int count = items.size();
612
613 for (int i = 0; i < count; i++) {
614 ItemInfo item = items.get(i);
615 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700616 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700617 + ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", "
618 + item.cellX + ", " + item.cellY + ")";
619 Launcher.sDumpLogs.add(transaction);
620 item.container = container;
621
622 // We store hotseat items in canonical form which is this orientation invariant position
623 // in the hotseat
624 if (context instanceof Launcher && screen < 0 &&
625 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700626 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700627 item.cellY);
628 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700629 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700630 }
631
632 final ContentValues values = new ContentValues();
633 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
634 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
635 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700636 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700637
638 contentValues.add(values);
639 }
640 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
641 }
642
643 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700644 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800645 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700646 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700647 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700648 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
Adam Cohendcd297f2013-06-18 13:13:40 -0700649 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
650 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Adam Cohen487f7dd2012-06-28 18:12:10 -0700651 Launcher.sDumpLogs.add(transaction);
652 Log.d(TAG, transaction);
Adam Cohend4844c32011-02-18 19:25:06 -0800653 item.cellX = cellX;
654 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700655 item.spanX = spanX;
656 item.spanY = spanY;
657
658 // We store hotseat items in canonical form which is this orientation invariant position
659 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700660 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700661 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700662 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700663 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700664 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700665 }
Adam Cohend4844c32011-02-18 19:25:06 -0800666
Adam Cohend4844c32011-02-18 19:25:06 -0800667 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800668 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700669 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
670 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
671 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
672 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700673 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800674
Michael Jurka816474f2012-06-25 14:49:02 -0700675 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700676 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700677
678 /**
679 * Update an item to the database in a specified container.
680 */
681 static void updateItemInDatabase(Context context, final ItemInfo item) {
682 final ContentValues values = new ContentValues();
683 item.onAddToDatabase(values);
684 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
685 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800686 }
687
688 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400689 * Returns true if the shortcuts already exists in the database.
690 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800691 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400692 static boolean shortcutExists(Context context, String title, Intent intent) {
693 final ContentResolver cr = context.getContentResolver();
694 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
695 new String[] { "title", "intent" }, "title=? and intent=?",
696 new String[] { title, intent.toUri(0) }, null);
697 boolean result = false;
698 try {
699 result = c.moveToFirst();
700 } finally {
701 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800702 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400703 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700704 }
705
Joe Onorato9c1289c2009-08-17 11:03:03 -0400706 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700707 * Returns an ItemInfo array containing all the items in the LauncherModel.
708 * The ItemInfo.id is not set through this function.
709 */
710 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
711 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
712 final ContentResolver cr = context.getContentResolver();
713 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
714 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
715 LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
716 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
717
718 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
719 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
720 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
721 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
722 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
723 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
724 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
725
726 try {
727 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700728 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700729 item.cellX = c.getInt(cellXIndex);
730 item.cellY = c.getInt(cellYIndex);
731 item.spanX = c.getInt(spanXIndex);
732 item.spanY = c.getInt(spanYIndex);
733 item.container = c.getInt(containerIndex);
734 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700735 item.screenId = c.getInt(screenIndex);
Winson Chungaafa03c2010-06-11 17:34:16 -0700736
737 items.add(item);
738 }
739 } catch (Exception e) {
740 items.clear();
741 } finally {
742 c.close();
743 }
744
745 return items;
746 }
747
748 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400749 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
750 */
751 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
752 final ContentResolver cr = context.getContentResolver();
753 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
754 "_id=? and (itemType=? or itemType=?)",
755 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700756 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700757
Joe Onorato9c1289c2009-08-17 11:03:03 -0400758 try {
759 if (c.moveToFirst()) {
760 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
761 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
762 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
763 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
764 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
765 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800766
Joe Onorato9c1289c2009-08-17 11:03:03 -0400767 FolderInfo folderInfo = null;
768 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700769 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
770 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400771 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700772 }
773
Joe Onorato9c1289c2009-08-17 11:03:03 -0400774 folderInfo.title = c.getString(titleIndex);
775 folderInfo.id = id;
776 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700777 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700778 folderInfo.cellX = c.getInt(cellXIndex);
779 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400780
781 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700782 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400783 } finally {
784 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700785 }
786
787 return null;
788 }
789
Joe Onorato9c1289c2009-08-17 11:03:03 -0400790 /**
791 * Add an item to the database in a specified container. Sets the container, screen, cellX and
792 * cellY fields of the item. Also assigns an ID to the item.
793 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700794 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700795 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400796 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400797 item.cellX = cellX;
798 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700799 // We store hotseat items in canonical form which is this orientation invariant position
800 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700801 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700802 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700803 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700804 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700805 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700806 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400807
808 final ContentValues values = new ContentValues();
809 final ContentResolver cr = context.getContentResolver();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400810 item.onAddToDatabase(values);
811
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400812 LauncherAppState app = LauncherAppState.getInstance();
Adam Cohendcd297f2013-06-18 13:13:40 -0700813 item.id = app.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700814 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -0700815 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -0700816
Michael Jurkac9d95c52011-08-29 14:03:34 -0700817 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700818 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700819 String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700820 + item.id + " (" + container + ", " + screenId + ", " + cellX + ", "
Adam Cohen487f7dd2012-06-28 18:12:10 -0700821 + cellY + ")";
822 Launcher.sDumpLogs.add(transaction);
823 Log.d(TAG, transaction);
824
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700825 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
826 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400827
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700828 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700829 synchronized (sBgLock) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700830 checkItemInfoLocked(item.id, item, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700831 sBgItemsIdMap.put(item.id, item);
832 switch (item.itemType) {
833 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
834 sBgFolders.put(item.id, (FolderInfo) item);
835 // Fall through
836 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
837 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
838 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
839 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
840 sBgWorkspaceItems.add(item);
841 } else {
842 if (!sBgFolders.containsKey(item.container)) {
843 // Adding an item to a folder that doesn't exist.
844 String msg = "adding item: " + item + " to a folder that " +
845 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -0700846 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700847 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700848 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700849 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700850 break;
851 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
852 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
853 break;
854 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700855 }
856 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700857 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700858 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700859 }
860
Joe Onorato9c1289c2009-08-17 11:03:03 -0400861 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700862 * Creates a new unique child id, for a given cell span across all layouts.
863 */
Michael Jurka845ba3b2010-09-28 17:09:46 -0700864 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -0700865 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -0700866 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -0700867 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -0700868 }
869
Adam Cohend22015c2010-07-26 22:02:18 -0700870 static int getCellCountX() {
871 return mCellCountX;
Winson Chungaafa03c2010-06-11 17:34:16 -0700872 }
873
Adam Cohend22015c2010-07-26 22:02:18 -0700874 static int getCellCountY() {
875 return mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700876 }
877
878 /**
879 * Updates the model orientation helper to take into account the current layout dimensions
880 * when performing local/canonical coordinate transformations.
881 */
882 static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
Adam Cohend22015c2010-07-26 22:02:18 -0700883 mCellCountX = shortAxisCellCount;
884 mCellCountY = longAxisCellCount;
Winson Chungaafa03c2010-06-11 17:34:16 -0700885 }
886
887 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -0700888 * Removes the specified item from the database
889 * @param context
890 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -0400891 */
Michael Jurkac9d95c52011-08-29 14:03:34 -0700892 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400893 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700894 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -0700895
Michael Jurka83df1882011-08-31 20:59:26 -0700896 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700897 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700898 String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700899 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX +
Adam Cohen487f7dd2012-06-28 18:12:10 -0700900 ", " + item.cellY + ")";
901 Launcher.sDumpLogs.add(transaction);
902 Log.d(TAG, transaction);
903
Michael Jurkac9d95c52011-08-29 14:03:34 -0700904 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700905
906 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700907 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700908 switch (item.itemType) {
909 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
910 sBgFolders.remove(item.id);
911 for (ItemInfo info: sBgItemsIdMap.values()) {
912 if (info.container == item.id) {
913 // We are deleting a folder which still contains items that
914 // think they are contained by that folder.
915 String msg = "deleting a folder (" + item + ") which still " +
916 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -0700917 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700918 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700919 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700920 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700921 sBgWorkspaceItems.remove(item);
922 break;
923 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
924 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
925 sBgWorkspaceItems.remove(item);
926 break;
927 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
928 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
929 break;
930 }
931 sBgItemsIdMap.remove(item.id);
932 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700933 }
934 }
Michael Jurka83df1882011-08-31 20:59:26 -0700935 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700936 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400937 }
938
939 /**
Adam Cohendcd297f2013-06-18 13:13:40 -0700940 * Update the order of the workspace screens in the database. The array list contains
941 * a list of screen ids in the order that they should appear.
942 */
Winson Chungc9168342013-06-26 14:54:55 -0700943 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chung64359a52013-07-08 17:17:08 -0700944 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -0700945 final ContentResolver cr = context.getContentResolver();
946 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
947
948 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -0700949 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -0700950 while (iter.hasNext()) {
951 long id = iter.next();
952 if (id < 0) {
953 iter.remove();
954 }
955 }
956
957 Runnable r = new Runnable() {
958 @Override
959 public void run() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700960 // Clear the table
961 cr.delete(uri, null, null);
962 int count = screens.size();
963 ContentValues[] values = new ContentValues[count];
964 for (int i = 0; i < count; i++) {
965 ContentValues v = new ContentValues();
966 long screenId = screens.get(i);
967 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
968 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Adam Cohendcd297f2013-06-18 13:13:40 -0700969 values[i] = v;
970 }
971 cr.bulkInsert(uri, values);
972 sBgWorkspaceScreens.clear();
973 sBgWorkspaceScreens.addAll(screensCopy);
974 }
975 };
976 runOnWorkerThread(r);
977 }
978
979 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400980 * Remove the contents of the specified folder from the database
981 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700982 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400983 final ContentResolver cr = context.getContentResolver();
984
Michael Jurkac9d95c52011-08-29 14:03:34 -0700985 Runnable r = new Runnable() {
986 public void run() {
987 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700988 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700989 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700990 sBgItemsIdMap.remove(info.id);
991 sBgFolders.remove(info.id);
992 sBgDbIconCache.remove(info);
993 sBgWorkspaceItems.remove(info);
994 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700995
Michael Jurkac9d95c52011-08-29 14:03:34 -0700996 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
997 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700998 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700999 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001000 for (ItemInfo childInfo : info.contents) {
1001 sBgItemsIdMap.remove(childInfo.id);
1002 sBgDbIconCache.remove(childInfo);
1003 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001004 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001005 }
1006 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001007 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001008 }
1009
1010 /**
1011 * Set this as the current Launcher activity object for the loader.
1012 */
1013 public void initialize(Callbacks callbacks) {
1014 synchronized (mLock) {
1015 mCallbacks = new WeakReference<Callbacks>(callbacks);
1016 }
1017 }
1018
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001019 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001020 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1021 * ACTION_PACKAGE_CHANGED.
1022 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001023 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001024 public void onReceive(Context context, Intent intent) {
Joe Onorato36115782010-06-17 13:28:48 -04001025 if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001026
Joe Onorato36115782010-06-17 13:28:48 -04001027 final String action = intent.getAction();
Joe Onoratof99f8c12009-10-31 17:27:36 -04001028
Joe Onorato36115782010-06-17 13:28:48 -04001029 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
1030 || Intent.ACTION_PACKAGE_REMOVED.equals(action)
1031 || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1032 final String packageName = intent.getData().getSchemeSpecificPart();
1033 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001034
Joe Onorato36115782010-06-17 13:28:48 -04001035 int op = PackageUpdatedTask.OP_NONE;
1036
1037 if (packageName == null || packageName.length() == 0) {
1038 // they sent us a bad intent
1039 return;
1040 }
1041
1042 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1043 op = PackageUpdatedTask.OP_UPDATE;
1044 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1045 if (!replacing) {
1046 op = PackageUpdatedTask.OP_REMOVE;
1047 }
1048 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1049 // later, we will update the package at this time
1050 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1051 if (!replacing) {
1052 op = PackageUpdatedTask.OP_ADD;
1053 } else {
1054 op = PackageUpdatedTask.OP_UPDATE;
1055 }
1056 }
1057
1058 if (op != PackageUpdatedTask.OP_NONE) {
1059 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
1060 }
1061
1062 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Joe Onoratocec58332010-10-07 14:37:40 -04001063 // First, schedule to add these apps back in.
1064 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1065 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
1066 // Then, rebind everything.
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001067 startLoaderFromBackground();
Joe Onorato36115782010-06-17 13:28:48 -04001068 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1069 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1070 enqueuePackageUpdated(new PackageUpdatedTask(
1071 PackageUpdatedTask.OP_UNAVAILABLE, packages));
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001072 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001073 // If we have changed locale we need to clear out the labels in all apps/workspace.
1074 forceReload();
1075 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1076 // Check if configuration change was an mcc/mnc change which would affect app resources
1077 // and we would need to clear out the labels in all apps/workspace. Same handling as
1078 // above for ACTION_LOCALE_CHANGED
1079 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001080 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001081 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001082 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001083 forceReload();
1084 }
1085 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001086 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001087 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1088 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001089 if (mCallbacks != null) {
1090 Callbacks callbacks = mCallbacks.get();
1091 if (callbacks != null) {
1092 callbacks.bindSearchablesChanged();
1093 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001094 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001095 }
1096 }
1097
Reena Lee93f824a2011-09-23 17:20:28 -07001098 private void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001099 resetLoadedState(true, true);
1100
Reena Lee93f824a2011-09-23 17:20:28 -07001101 // Do this here because if the launcher activity is running it will be restarted.
1102 // If it's not running startLoaderFromBackground will merely tell it that it needs
1103 // to reload.
1104 startLoaderFromBackground();
1105 }
1106
Winson Chungf0c6ae02012-03-21 16:10:31 -07001107 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1108 synchronized (mLock) {
1109 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1110 // mWorkspaceLoaded to true later
1111 stopLoaderLocked();
1112 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1113 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1114 }
1115 }
1116
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001117 /**
1118 * When the launcher is in the background, it's possible for it to miss paired
1119 * configuration changes. So whenever we trigger the loader from the background
1120 * tell the launcher that it needs to re-run the loader when it comes back instead
1121 * of doing it now.
1122 */
1123 public void startLoaderFromBackground() {
1124 boolean runLoader = false;
1125 if (mCallbacks != null) {
1126 Callbacks callbacks = mCallbacks.get();
1127 if (callbacks != null) {
1128 // Only actually run the loader if they're not paused.
1129 if (!callbacks.setLoadOnResume()) {
1130 runLoader = true;
1131 }
1132 }
1133 }
1134 if (runLoader) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001135 startLoader(false, -1);
Joe Onorato790c2d92010-06-11 00:14:11 -07001136 }
Joe Onorato36115782010-06-17 13:28:48 -04001137 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001138
Reena Lee93f824a2011-09-23 17:20:28 -07001139 // If there is already a loader task running, tell it to stop.
1140 // returns true if isLaunching() was true on the old task
1141 private boolean stopLoaderLocked() {
1142 boolean isLaunching = false;
1143 LoaderTask oldTask = mLoaderTask;
1144 if (oldTask != null) {
1145 if (oldTask.isLaunching()) {
1146 isLaunching = true;
1147 }
1148 oldTask.stopLocked();
1149 }
1150 return isLaunching;
1151 }
1152
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001153 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Joe Onorato36115782010-06-17 13:28:48 -04001154 synchronized (mLock) {
1155 if (DEBUG_LOADERS) {
1156 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1157 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001158
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001159 // Clear any deferred bind-runnables from the synchronized load process
1160 // We must do this before any loading/binding is scheduled below.
1161 mDeferredBindRunnables.clear();
1162
Joe Onorato36115782010-06-17 13:28:48 -04001163 // Don't bother to start the thread if we know it's not going to do anything
1164 if (mCallbacks != null && mCallbacks.get() != null) {
1165 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001166 // also, don't downgrade isLaunching if we're already running
1167 isLaunching = isLaunching || stopLoaderLocked();
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001168 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001169 if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
1170 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1171 } else {
1172 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1173 sWorker.post(mLoaderTask);
1174 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001175 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001176 }
1177 }
1178
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001179 void bindRemainingSynchronousPages() {
1180 // Post the remaining side pages to be loaded
1181 if (!mDeferredBindRunnables.isEmpty()) {
1182 for (final Runnable r : mDeferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001183 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001184 }
1185 mDeferredBindRunnables.clear();
1186 }
1187 }
1188
Joe Onorato36115782010-06-17 13:28:48 -04001189 public void stopLoader() {
1190 synchronized (mLock) {
1191 if (mLoaderTask != null) {
1192 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001193 }
1194 }
Joe Onorato36115782010-06-17 13:28:48 -04001195 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001196
Michael Jurkac57b7a82011-08-09 22:02:20 -07001197 public boolean isAllAppsLoaded() {
1198 return mAllAppsLoaded;
1199 }
1200
Winson Chung36a62fe2012-05-06 18:04:42 -07001201 boolean isLoadingWorkspace() {
1202 synchronized (mLock) {
1203 if (mLoaderTask != null) {
1204 return mLoaderTask.isLoadingWorkspace();
1205 }
1206 }
1207 return false;
1208 }
1209
Joe Onorato36115782010-06-17 13:28:48 -04001210 /**
1211 * Runnable for the thread that loads the contents of the launcher:
1212 * - workspace icons
1213 * - widgets
1214 * - all apps icons
1215 */
1216 private class LoaderTask implements Runnable {
1217 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001218 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001219 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001220 private boolean mStopped;
1221 private boolean mLoadAndBindStepFinished;
Adam Cohene25af792013-06-06 23:08:25 -07001222 private boolean mIsUpgradePath;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001223
Winson Chungc3eecff2011-07-11 17:44:15 -07001224 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001225
1226 LoaderTask(Context context, boolean isLaunching) {
1227 mContext = context;
1228 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001229 mLabelCache = new HashMap<Object, CharSequence>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001230 }
1231
Joe Onorato36115782010-06-17 13:28:48 -04001232 boolean isLaunching() {
1233 return mIsLaunching;
1234 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001235
Winson Chung36a62fe2012-05-06 18:04:42 -07001236 boolean isLoadingWorkspace() {
1237 return mIsLoadingAndBindingWorkspace;
1238 }
1239
Joe Onorato36115782010-06-17 13:28:48 -04001240 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001241 mIsLoadingAndBindingWorkspace = true;
1242
Joe Onorato36115782010-06-17 13:28:48 -04001243 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001244 if (DEBUG_LOADERS) {
1245 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001246 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001247
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001248 if (!mWorkspaceLoaded) {
Joe Onorato36115782010-06-17 13:28:48 -04001249 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001250 synchronized (LoaderTask.this) {
1251 if (mStopped) {
1252 return;
1253 }
1254 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001255 }
1256 }
1257
Joe Onorato36115782010-06-17 13:28:48 -04001258 // Bind the workspace
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001259 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001260 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001261
Joe Onorato36115782010-06-17 13:28:48 -04001262 private void waitForIdle() {
1263 // Wait until the either we're stopped or the other threads are done.
1264 // This way we don't start loading all apps until the workspace has settled
1265 // down.
1266 synchronized (LoaderTask.this) {
1267 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001268
Joe Onorato36115782010-06-17 13:28:48 -04001269 mHandler.postIdle(new Runnable() {
1270 public void run() {
1271 synchronized (LoaderTask.this) {
1272 mLoadAndBindStepFinished = true;
1273 if (DEBUG_LOADERS) {
1274 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001275 }
Joe Onorato36115782010-06-17 13:28:48 -04001276 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001277 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001278 }
Joe Onorato36115782010-06-17 13:28:48 -04001279 });
1280
Michael Jurkac7700af2013-05-14 20:17:58 +02001281 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001282 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001283 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1284 // wait no longer than 1sec at a time
1285 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001286 } catch (InterruptedException ex) {
1287 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001288 }
1289 }
Joe Onorato36115782010-06-17 13:28:48 -04001290 if (DEBUG_LOADERS) {
1291 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001292 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001293 + "ms for previous step to finish binding");
1294 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001295 }
Joe Onorato36115782010-06-17 13:28:48 -04001296 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001297
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001298 void runBindSynchronousPage(int synchronousBindPage) {
1299 if (synchronousBindPage < 0) {
1300 // Ensure that we have a valid page index to load synchronously
1301 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1302 "valid page index");
1303 }
1304 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1305 // Ensure that we don't try and bind a specified page when the pages have not been
1306 // loaded already (we should load everything asynchronously in that case)
1307 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1308 }
1309 synchronized (mLock) {
1310 if (mIsLoaderTaskRunning) {
1311 // Ensure that we are never running the background loading at this point since
1312 // we also touch the background collections
1313 throw new RuntimeException("Error! Background loading is already running");
1314 }
1315 }
1316
1317 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1318 // data structures, we can't allow any other thread to touch that data, but because
1319 // this call is synchronous, we can get away with not locking).
1320
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001321 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001322 // operations from the previous activity. We need to ensure that all queued operations
1323 // are executed before any synchronous binding work is done.
1324 mHandler.flush();
1325
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001326 // Divide the set of loaded items into those that we are binding synchronously, and
1327 // everything else that is to be bound normally (asynchronously).
1328 bindWorkspace(synchronousBindPage);
1329 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1330 // arise from that.
1331 onlyBindAllApps();
1332 }
1333
Joe Onorato36115782010-06-17 13:28:48 -04001334 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001335 synchronized (mLock) {
1336 mIsLoaderTaskRunning = true;
1337 }
Joe Onorato36115782010-06-17 13:28:48 -04001338 // Optimize for end-user experience: if the Launcher is up and // running with the
1339 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1340 // workspace first (default).
1341 final Callbacks cbk = mCallbacks.get();
Joe Onorato36115782010-06-17 13:28:48 -04001342 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001343 // Elevate priority when Home launches for the first time to avoid
1344 // starving at boot time. Staring at a blank home is not cool.
1345 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001346 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1347 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001348 android.os.Process.setThreadPriority(mIsLaunching
1349 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1350 }
Winson Chung64359a52013-07-08 17:17:08 -07001351 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
1352 loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001353
Joe Onorato36115782010-06-17 13:28:48 -04001354 if (mStopped) {
1355 break keep_running;
1356 }
1357
1358 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1359 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001360 synchronized (mLock) {
1361 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001362 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001363 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1364 }
1365 }
Joe Onorato36115782010-06-17 13:28:48 -04001366 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001367
1368 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001369 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1370 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001371
1372 // Restore the default thread priority after we are done loading items
1373 synchronized (mLock) {
1374 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1375 }
Joe Onorato36115782010-06-17 13:28:48 -04001376 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001377
Winson Chungaac01e12011-08-17 10:37:13 -07001378 // Update the saved icons if necessary
1379 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001380 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001381 for (Object key : sBgDbIconCache.keySet()) {
1382 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1383 }
1384 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001385 }
Winson Chungaac01e12011-08-17 10:37:13 -07001386
Joe Onorato36115782010-06-17 13:28:48 -04001387 // Clear out this reference, otherwise we end up holding it until all of the
1388 // callback runnables are done.
1389 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001390
Joe Onorato36115782010-06-17 13:28:48 -04001391 synchronized (mLock) {
1392 // If we are still the last one to be scheduled, remove ourselves.
1393 if (mLoaderTask == this) {
1394 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001395 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001396 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001397 }
Joe Onorato36115782010-06-17 13:28:48 -04001398 }
1399
1400 public void stopLocked() {
1401 synchronized (LoaderTask.this) {
1402 mStopped = true;
1403 this.notify();
1404 }
1405 }
1406
1407 /**
1408 * Gets the callbacks object. If we've been stopped, or if the launcher object
1409 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1410 * object that was around when the deferred message was scheduled, and if there's
1411 * a new Callbacks object around then also return null. This will save us from
1412 * calling onto it with data that will be ignored.
1413 */
1414 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1415 synchronized (mLock) {
1416 if (mStopped) {
1417 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001418 }
Joe Onorato36115782010-06-17 13:28:48 -04001419
1420 if (mCallbacks == null) {
1421 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001422 }
Joe Onorato36115782010-06-17 13:28:48 -04001423
1424 final Callbacks callbacks = mCallbacks.get();
1425 if (callbacks != oldCallbacks) {
1426 return null;
1427 }
1428 if (callbacks == null) {
1429 Log.w(TAG, "no mCallbacks");
1430 return null;
1431 }
1432
1433 return callbacks;
1434 }
1435 }
1436
1437 // check & update map of what's occupied; used to discard overlapping/invalid items
Adam Cohendcd297f2013-06-18 13:13:40 -07001438 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
1439 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001440 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001441 if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
1442 if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1443 [(int) item.screenId][0] != null) {
1444 Log.e(TAG, "Error loading shortcut into hotseat " + item
1445 + " into position (" + item.screenId + ":" + item.cellX + ","
1446 + item.cellY + ") occupied by "
1447 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1448 [(int) item.screenId][0]);
1449 return false;
1450 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001451 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001452 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1453 items[(int) item.screenId][0] = item;
1454 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001455 return true;
1456 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001457 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1458 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001459 return true;
1460 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001461
Adam Cohendcd297f2013-06-18 13:13:40 -07001462 if (!occupied.containsKey(item.screenId)) {
1463 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1464 occupied.put(item.screenId, items);
1465 }
1466
1467 ItemInfo[][] screens = occupied.get(item.screenId);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001468 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001469 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1470 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001471 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001472 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001473 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001474 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001475 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001476 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001477 return false;
1478 }
1479 }
1480 }
1481 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1482 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001483 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001484 }
1485 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001486
Joe Onorato36115782010-06-17 13:28:48 -04001487 return true;
1488 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001489
Joe Onorato36115782010-06-17 13:28:48 -04001490 private void loadWorkspace() {
1491 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001492
Joe Onorato36115782010-06-17 13:28:48 -04001493 final Context context = mContext;
1494 final ContentResolver contentResolver = context.getContentResolver();
1495 final PackageManager manager = context.getPackageManager();
1496 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1497 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001498
Michael Jurkab85f8a42012-04-25 15:48:32 -07001499 // Make sure the default workspace is loaded, if needed
Adam Cohene25af792013-06-06 23:08:25 -07001500 boolean loadOldDb = mApp.getLauncherProvider().shouldLoadOldDb();
1501 Uri contentUri = loadOldDb ? LauncherSettings.Favorites.OLD_CONTENT_URI :
1502 LauncherSettings.Favorites.CONTENT_URI;
1503
1504 mIsUpgradePath = loadOldDb;
Michael Jurkab85f8a42012-04-25 15:48:32 -07001505
Winson Chung2abf94d2012-07-18 18:16:38 -07001506 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001507 sBgWorkspaceItems.clear();
1508 sBgAppWidgets.clear();
1509 sBgFolders.clear();
1510 sBgItemsIdMap.clear();
1511 sBgDbIconCache.clear();
Adam Cohendcd297f2013-06-18 13:13:40 -07001512 sBgWorkspaceScreens.clear();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001513
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001514 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001515
Adam Cohene25af792013-06-06 23:08:25 -07001516 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001517
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001518 // +1 for the hotseat (it can be larger than the workspace)
1519 // Load workspace in reverse order to ensure that latest items are loaded first (and
1520 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001521 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001522
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001523 try {
1524 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1525 final int intentIndex = c.getColumnIndexOrThrow
1526 (LauncherSettings.Favorites.INTENT);
1527 final int titleIndex = c.getColumnIndexOrThrow
1528 (LauncherSettings.Favorites.TITLE);
1529 final int iconTypeIndex = c.getColumnIndexOrThrow(
1530 LauncherSettings.Favorites.ICON_TYPE);
1531 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1532 final int iconPackageIndex = c.getColumnIndexOrThrow(
1533 LauncherSettings.Favorites.ICON_PACKAGE);
1534 final int iconResourceIndex = c.getColumnIndexOrThrow(
1535 LauncherSettings.Favorites.ICON_RESOURCE);
1536 final int containerIndex = c.getColumnIndexOrThrow(
1537 LauncherSettings.Favorites.CONTAINER);
1538 final int itemTypeIndex = c.getColumnIndexOrThrow(
1539 LauncherSettings.Favorites.ITEM_TYPE);
1540 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1541 LauncherSettings.Favorites.APPWIDGET_ID);
1542 final int screenIndex = c.getColumnIndexOrThrow(
1543 LauncherSettings.Favorites.SCREEN);
1544 final int cellXIndex = c.getColumnIndexOrThrow
1545 (LauncherSettings.Favorites.CELLX);
1546 final int cellYIndex = c.getColumnIndexOrThrow
1547 (LauncherSettings.Favorites.CELLY);
1548 final int spanXIndex = c.getColumnIndexOrThrow
1549 (LauncherSettings.Favorites.SPANX);
1550 final int spanYIndex = c.getColumnIndexOrThrow(
1551 LauncherSettings.Favorites.SPANY);
1552 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1553 //final int displayModeIndex = c.getColumnIndexOrThrow(
1554 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001555
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001556 ShortcutInfo info;
1557 String intentDescription;
1558 LauncherAppWidgetInfo appWidgetInfo;
1559 int container;
1560 long id;
1561 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001562
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001563 while (!mStopped && c.moveToNext()) {
1564 try {
1565 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001566
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001567 switch (itemType) {
1568 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1569 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1570 intentDescription = c.getString(intentIndex);
1571 try {
1572 intent = Intent.parseUri(intentDescription, 0);
1573 } catch (URISyntaxException e) {
1574 continue;
1575 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001576
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001577 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1578 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1579 titleIndex, mLabelCache);
1580 } else {
1581 info = getShortcutInfo(c, context, iconTypeIndex,
1582 iconPackageIndex, iconResourceIndex, iconIndex,
1583 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001584
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001585 // App shortcuts that used to be automatically added to Launcher
1586 // didn't always have the correct intent flags set, so do that
1587 // here
1588 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001589 intent.getCategories() != null &&
1590 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001591 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001592 intent.addFlags(
1593 Intent.FLAG_ACTIVITY_NEW_TASK |
1594 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1595 }
Michael Jurka96879562012-03-22 05:54:33 -07001596 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001597
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001598 if (info != null) {
1599 info.intent = intent;
1600 info.id = c.getLong(idIndex);
1601 container = c.getInt(containerIndex);
1602 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001603 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001604 info.cellX = c.getInt(cellXIndex);
1605 info.cellY = c.getInt(cellYIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001606 // check & update map of what's occupied
1607 if (!checkItemPlacement(occupied, info)) {
1608 break;
1609 }
1610
1611 switch (container) {
1612 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1613 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1614 sBgWorkspaceItems.add(info);
1615 break;
1616 default:
1617 // Item is in a user folder
1618 FolderInfo folderInfo =
1619 findOrMakeFolder(sBgFolders, container);
1620 folderInfo.add(info);
1621 break;
1622 }
Adam Cohene25af792013-06-06 23:08:25 -07001623 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
1624 loadOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001625 info.screenId = permuteScreens(info.screenId);
Adam Cohene25af792013-06-06 23:08:25 -07001626 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001627 sBgItemsIdMap.put(info.id, info);
1628
1629 // now that we've loaded everthing re-save it with the
1630 // icon in case it disappears somehow.
1631 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
1632 } else {
1633 // Failed to load the shortcut, probably because the
1634 // activity manager couldn't resolve it (maybe the app
1635 // was uninstalled), or the db row was somehow screwed up.
1636 // Delete it.
1637 id = c.getLong(idIndex);
1638 Log.e(TAG, "Error loading shortcut " + id + ", removing it");
1639 contentResolver.delete(LauncherSettings.Favorites.getContentUri(
1640 id, false), null, null);
1641 }
1642 break;
1643
1644 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1645 id = c.getLong(idIndex);
1646 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1647
1648 folderInfo.title = c.getString(titleIndex);
1649 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001650 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001651 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001652 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001653 folderInfo.cellX = c.getInt(cellXIndex);
1654 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001655
Daniel Sandler8802e962010-05-26 16:28:16 -04001656 // check & update map of what's occupied
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001657 if (!checkItemPlacement(occupied, folderInfo)) {
Daniel Sandler8802e962010-05-26 16:28:16 -04001658 break;
1659 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001660 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001661 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1662 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1663 sBgWorkspaceItems.add(folderInfo);
1664 break;
Joe Onorato36115782010-06-17 13:28:48 -04001665 }
Adam Cohene25af792013-06-06 23:08:25 -07001666 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
1667 loadOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001668 folderInfo.screenId = permuteScreens(folderInfo.screenId);
Adam Cohene25af792013-06-06 23:08:25 -07001669 }
Joe Onorato17a89222011-02-08 17:26:11 -08001670
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001671 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1672 sBgFolders.put(folderInfo.id, folderInfo);
1673 break;
1674
1675 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1676 // Read all Launcher-specific widget details
1677 int appWidgetId = c.getInt(appWidgetIdIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001678 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001679
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001680 final AppWidgetProviderInfo provider =
1681 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001682
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001683 if (!isSafeMode && (provider == null || provider.provider == null ||
1684 provider.provider.getPackageName() == null)) {
1685 String log = "Deleting widget that isn't installed anymore: id="
1686 + id + " appWidgetId=" + appWidgetId;
1687 Log.e(TAG, log);
1688 Launcher.sDumpLogs.add(log);
1689 itemsToRemove.add(id);
1690 } else {
1691 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1692 provider.provider);
1693 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07001694 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001695 appWidgetInfo.cellX = c.getInt(cellXIndex);
1696 appWidgetInfo.cellY = c.getInt(cellYIndex);
1697 appWidgetInfo.spanX = c.getInt(spanXIndex);
1698 appWidgetInfo.spanY = c.getInt(spanYIndex);
1699 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1700 appWidgetInfo.minSpanX = minSpan[0];
1701 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001702
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001703 container = c.getInt(containerIndex);
1704 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1705 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1706 Log.e(TAG, "Widget found where container != " +
1707 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1708 continue;
1709 }
Adam Cohene25af792013-06-06 23:08:25 -07001710 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
1711 loadOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001712 appWidgetInfo.screenId =
1713 permuteScreens(appWidgetInfo.screenId);
Adam Cohene25af792013-06-06 23:08:25 -07001714 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001715
Adam Cohene25af792013-06-06 23:08:25 -07001716 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001717 // check & update map of what's occupied
1718 if (!checkItemPlacement(occupied, appWidgetInfo)) {
1719 break;
1720 }
1721 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1722 sBgAppWidgets.add(appWidgetInfo);
1723 }
Joe Onorato36115782010-06-17 13:28:48 -04001724 break;
1725 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001726 } catch (Exception e) {
1727 Log.w(TAG, "Desktop items loading interrupted:", e);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001728 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001729 }
1730 } finally {
1731 c.close();
1732 }
1733
1734 if (itemsToRemove.size() > 0) {
1735 ContentProviderClient client = contentResolver.acquireContentProviderClient(
1736 LauncherSettings.Favorites.CONTENT_URI);
1737 // Remove dead items
1738 for (long id : itemsToRemove) {
1739 if (DEBUG_LOADERS) {
1740 Log.d(TAG, "Removed id = " + id);
1741 }
1742 // Don't notify content observers
1743 try {
1744 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1745 null, null);
1746 } catch (RemoteException e) {
1747 Log.w(TAG, "Could not remove id = " + id);
1748 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001749 }
1750 }
1751
Adam Cohendcd297f2013-06-18 13:13:40 -07001752 if (loadOldDb) {
1753 long maxScreenId = 0;
1754 // If we're importing we use the old screen order.
1755 for (ItemInfo item: sBgItemsIdMap.values()) {
1756 long screenId = item.screenId;
1757 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1758 !sBgWorkspaceScreens.contains(screenId)) {
1759 sBgWorkspaceScreens.add(screenId);
1760 if (screenId > maxScreenId) {
1761 maxScreenId = screenId;
1762 }
1763 }
1764 }
1765 Collections.sort(sBgWorkspaceScreens);
1766 mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
1767 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1768 } else {
1769 Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1770 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1771 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1772
1773 try {
1774 final int idIndex = sc.getColumnIndexOrThrow(
1775 LauncherSettings.WorkspaceScreens._ID);
1776 final int rankIndex = sc.getColumnIndexOrThrow(
1777 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1778 while (sc.moveToNext()) {
1779 try {
1780 long screenId = sc.getLong(idIndex);
1781 int rank = sc.getInt(rankIndex);
1782
1783 orderedScreens.put(rank, screenId);
1784 } catch (Exception e) {
1785 Log.w(TAG, "Desktop items loading interrupted:", e);
1786 }
1787 }
1788 } finally {
1789 sc.close();
1790 }
1791
1792 Iterator<Integer> iter = orderedScreens.keySet().iterator();
1793 while (iter.hasNext()) {
1794 sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
1795 }
1796
1797 // Remove any empty screens
1798 ArrayList<Long> unusedScreens = new ArrayList<Long>();
1799 unusedScreens.addAll(sBgWorkspaceScreens);
1800
1801 for (ItemInfo item: sBgItemsIdMap.values()) {
1802 long screenId = item.screenId;
1803
1804 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1805 unusedScreens.contains(screenId)) {
1806 unusedScreens.remove(screenId);
1807 }
1808 }
1809
1810 // If there are any empty screens remove them, and update.
1811 if (unusedScreens.size() != 0) {
1812 sBgWorkspaceScreens.removeAll(unusedScreens);
1813 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1814 }
1815 }
1816
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001817 if (DEBUG_LOADERS) {
1818 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1819 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07001820 int nScreens = occupied.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001821 for (int y = 0; y < mCellCountY; y++) {
1822 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07001823
Daniel Sandler566da102013-06-25 23:43:45 -04001824 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07001825 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001826 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07001827 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001828 line += " | ";
1829 }
1830 for (int x = 0; x < mCellCountX; x++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001831 line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001832 }
Joe Onorato36115782010-06-17 13:28:48 -04001833 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001834 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04001835 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001836 }
Joe Onorato36115782010-06-17 13:28:48 -04001837 }
1838 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001839
Adam Cohene25af792013-06-06 23:08:25 -07001840 // We rearrange the screens from the old launcher
1841 // 12345 -> 34512
Adam Cohendcd297f2013-06-18 13:13:40 -07001842 private long permuteScreens(long screen) {
Adam Cohene25af792013-06-06 23:08:25 -07001843 if (screen >= 2) {
1844 return screen - 2;
1845 } else {
1846 return screen + 3;
1847 }
1848 }
1849
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001850 /** Filters the set of items who are directly or indirectly (via another container) on the
1851 * specified screen. */
1852 private void filterCurrentWorkspaceItems(int currentScreen,
1853 ArrayList<ItemInfo> allWorkspaceItems,
1854 ArrayList<ItemInfo> currentScreenItems,
1855 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001856 // Purge any null ItemInfos
1857 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1858 while (iter.hasNext()) {
1859 ItemInfo i = iter.next();
1860 if (i == null) {
1861 iter.remove();
1862 }
1863 }
1864
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001865 // If we aren't filtering on a screen, then the set of items to load is the full set of
1866 // items given.
1867 if (currentScreen < 0) {
1868 currentScreenItems.addAll(allWorkspaceItems);
Joe Onorato36115782010-06-17 13:28:48 -04001869 }
1870
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001871 // Order the set of items by their containers first, this allows use to walk through the
1872 // list sequentially, build up a list of containers that are in the specified screen,
1873 // as well as all items in those containers.
1874 Set<Long> itemsOnScreen = new HashSet<Long>();
1875 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1876 @Override
1877 public int compare(ItemInfo lhs, ItemInfo rhs) {
1878 return (int) (lhs.container - rhs.container);
1879 }
1880 });
1881 for (ItemInfo info : allWorkspaceItems) {
1882 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001883 if (info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001884 currentScreenItems.add(info);
1885 itemsOnScreen.add(info.id);
1886 } else {
1887 otherScreenItems.add(info);
1888 }
1889 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1890 currentScreenItems.add(info);
1891 itemsOnScreen.add(info.id);
1892 } else {
1893 if (itemsOnScreen.contains(info.container)) {
1894 currentScreenItems.add(info);
1895 itemsOnScreen.add(info.id);
1896 } else {
1897 otherScreenItems.add(info);
1898 }
1899 }
1900 }
1901 }
1902
1903 /** Filters the set of widgets which are on the specified screen. */
1904 private void filterCurrentAppWidgets(int currentScreen,
1905 ArrayList<LauncherAppWidgetInfo> appWidgets,
1906 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1907 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1908 // If we aren't filtering on a screen, then the set of items to load is the full set of
1909 // widgets given.
1910 if (currentScreen < 0) {
1911 currentScreenWidgets.addAll(appWidgets);
1912 }
1913
1914 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001915 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001916 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07001917 widget.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001918 currentScreenWidgets.add(widget);
1919 } else {
1920 otherScreenWidgets.add(widget);
1921 }
1922 }
1923 }
1924
1925 /** Filters the set of folders which are on the specified screen. */
1926 private void filterCurrentFolders(int currentScreen,
1927 HashMap<Long, ItemInfo> itemsIdMap,
1928 HashMap<Long, FolderInfo> folders,
1929 HashMap<Long, FolderInfo> currentScreenFolders,
1930 HashMap<Long, FolderInfo> otherScreenFolders) {
1931 // If we aren't filtering on a screen, then the set of items to load is the full set of
1932 // widgets given.
1933 if (currentScreen < 0) {
1934 currentScreenFolders.putAll(folders);
1935 }
1936
1937 for (long id : folders.keySet()) {
1938 ItemInfo info = itemsIdMap.get(id);
1939 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07001940 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001941 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07001942 info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001943 currentScreenFolders.put(id, folder);
1944 } else {
1945 otherScreenFolders.put(id, folder);
1946 }
1947 }
1948 }
1949
1950 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
1951 * right) */
1952 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
1953 // XXX: review this
1954 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07001955 @Override
1956 public int compare(ItemInfo lhs, ItemInfo rhs) {
1957 int cellCountX = LauncherModel.getCellCountX();
1958 int cellCountY = LauncherModel.getCellCountY();
1959 int screenOffset = cellCountX * cellCountY;
1960 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001961 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07001962 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07001963 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07001964 rhs.cellY * cellCountX + rhs.cellX);
1965 return (int) (lr - rr);
1966 }
1967 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001968 }
Winson Chungdb8a8942012-04-03 14:08:41 -07001969
Adam Cohendcd297f2013-06-18 13:13:40 -07001970 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
1971 final ArrayList<Long> orderedScreens) {
1972
1973 final Runnable r = new Runnable() {
1974 @Override
1975 public void run() {
1976 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1977 if (callbacks != null) {
1978 callbacks.bindScreens(orderedScreens);
1979 }
1980 }
1981 };
1982 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
1983 }
1984
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001985 private void bindWorkspaceItems(final Callbacks oldCallbacks,
1986 final ArrayList<ItemInfo> workspaceItems,
1987 final ArrayList<LauncherAppWidgetInfo> appWidgets,
1988 final HashMap<Long, FolderInfo> folders,
1989 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07001990
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001991 final boolean postOnMainThread = (deferredBindRunnables != null);
1992
1993 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07001994 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001995 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04001996 final int start = i;
1997 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001998 final Runnable r = new Runnable() {
1999 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002000 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002001 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002002 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002003 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2004 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002005 }
2006 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002007 };
2008 if (postOnMainThread) {
2009 deferredBindRunnables.add(r);
2010 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002011 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002012 }
Joe Onorato36115782010-06-17 13:28:48 -04002013 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002014
2015 // Bind the folders
2016 if (!folders.isEmpty()) {
2017 final Runnable r = new Runnable() {
2018 public void run() {
2019 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2020 if (callbacks != null) {
2021 callbacks.bindFolders(folders);
2022 }
2023 }
2024 };
2025 if (postOnMainThread) {
2026 deferredBindRunnables.add(r);
2027 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002028 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002029 }
2030 }
2031
2032 // Bind the widgets, one at a time
2033 N = appWidgets.size();
2034 for (int i = 0; i < N; i++) {
2035 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2036 final Runnable r = new Runnable() {
2037 public void run() {
2038 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2039 if (callbacks != null) {
2040 callbacks.bindAppWidget(widget);
2041 }
2042 }
2043 };
2044 if (postOnMainThread) {
2045 deferredBindRunnables.add(r);
2046 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002047 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002048 }
2049 }
2050 }
2051
2052 /**
2053 * Binds all loaded data to actual views on the main thread.
2054 */
2055 private void bindWorkspace(int synchronizeBindPage) {
2056 final long t = SystemClock.uptimeMillis();
2057 Runnable r;
2058
2059 // Don't use these two variables in any of the callback runnables.
2060 // Otherwise we hold a reference to them.
2061 final Callbacks oldCallbacks = mCallbacks.get();
2062 if (oldCallbacks == null) {
2063 // This launcher has exited and nobody bothered to tell us. Just bail.
2064 Log.w(TAG, "LoaderTask running with no launcher");
2065 return;
2066 }
2067
Winson Chung4a2afa32012-07-19 14:53:05 -07002068 final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
2069 final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002070 oldCallbacks.getCurrentWorkspaceScreen();
2071
2072 // Load all the items that are on the current page first (and in the process, unbind
2073 // all the existing workspace items before we call startBinding() below.
2074 unbindWorkspaceItemsOnMainThread();
2075 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2076 ArrayList<LauncherAppWidgetInfo> appWidgets =
2077 new ArrayList<LauncherAppWidgetInfo>();
2078 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2079 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002080 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002081 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002082 workspaceItems.addAll(sBgWorkspaceItems);
2083 appWidgets.addAll(sBgAppWidgets);
2084 folders.putAll(sBgFolders);
2085 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002086 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002087 }
2088
2089 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2090 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2091 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2092 new ArrayList<LauncherAppWidgetInfo>();
2093 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2094 new ArrayList<LauncherAppWidgetInfo>();
2095 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2096 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2097
2098 // Separate the items that are on the current screen, and all the other remaining items
2099 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
2100 otherWorkspaceItems);
2101 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
2102 otherAppWidgets);
2103 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
2104 otherFolders);
2105 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2106 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2107
2108 // Tell the workspace that we're about to start binding items
2109 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002110 public void run() {
2111 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2112 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002113 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002114 }
2115 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002116 };
Winson Chung81b52252012-08-27 15:34:29 -07002117 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002118
Adam Cohendcd297f2013-06-18 13:13:40 -07002119 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2120
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002121 // Load items on the current page
2122 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2123 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002124 if (isLoadingSynchronously) {
2125 r = new Runnable() {
2126 public void run() {
2127 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2128 if (callbacks != null) {
2129 callbacks.onPageBoundSynchronously(currentScreen);
2130 }
2131 }
2132 };
Winson Chung81b52252012-08-27 15:34:29 -07002133 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002134 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002135
Winson Chung4a2afa32012-07-19 14:53:05 -07002136 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2137 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002138 mDeferredBindRunnables.clear();
2139 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002140 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002141
2142 // Tell the workspace that we're done binding items
2143 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002144 public void run() {
2145 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2146 if (callbacks != null) {
Adam Cohene25af792013-06-06 23:08:25 -07002147 callbacks.finishBindingItems(mIsUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002148 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002149
Winson Chung98e030b2012-05-07 16:01:11 -07002150 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002151 if (DEBUG_LOADERS) {
2152 Log.d(TAG, "bound workspace in "
2153 + (SystemClock.uptimeMillis()-t) + "ms");
2154 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002155
2156 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002157 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002158 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002159 if (isLoadingSynchronously) {
2160 mDeferredBindRunnables.add(r);
2161 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002162 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002163 }
Joe Onorato36115782010-06-17 13:28:48 -04002164 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002165
Joe Onorato36115782010-06-17 13:28:48 -04002166 private void loadAndBindAllApps() {
2167 if (DEBUG_LOADERS) {
2168 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2169 }
2170 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002171 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002172 synchronized (LoaderTask.this) {
2173 if (mStopped) {
2174 return;
2175 }
2176 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002177 }
Joe Onorato36115782010-06-17 13:28:48 -04002178 } else {
2179 onlyBindAllApps();
2180 }
2181 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002182
Joe Onorato36115782010-06-17 13:28:48 -04002183 private void onlyBindAllApps() {
2184 final Callbacks oldCallbacks = mCallbacks.get();
2185 if (oldCallbacks == null) {
2186 // This launcher has exited and nobody bothered to tell us. Just bail.
2187 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2188 return;
2189 }
2190
2191 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002192 @SuppressWarnings("unchecked")
Joe Onorato36115782010-06-17 13:28:48 -04002193 final ArrayList<ApplicationInfo> list
Adam Cohen487f7dd2012-06-28 18:12:10 -07002194 = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002195 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002196 public void run() {
2197 final long t = SystemClock.uptimeMillis();
2198 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2199 if (callbacks != null) {
2200 callbacks.bindAllApplications(list);
2201 }
2202 if (DEBUG_LOADERS) {
2203 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2204 + (SystemClock.uptimeMillis()-t) + "ms");
2205 }
2206 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002207 };
2208 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002209 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002210 r.run();
2211 } else {
2212 mHandler.post(r);
2213 }
Joe Onorato36115782010-06-17 13:28:48 -04002214 }
2215
Winson Chung64359a52013-07-08 17:17:08 -07002216 private void loadAllApps() {
2217 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002218
2219 // Don't use these two variables in any of the callback runnables.
2220 // Otherwise we hold a reference to them.
2221 final Callbacks oldCallbacks = mCallbacks.get();
2222 if (oldCallbacks == null) {
2223 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002224 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002225 return;
2226 }
2227
Winson Chung64359a52013-07-08 17:17:08 -07002228 final PackageManager packageManager = mContext.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04002229 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2230 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2231
Winson Chung64359a52013-07-08 17:17:08 -07002232 // Clear the list of apps
2233 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002234
Winson Chung64359a52013-07-08 17:17:08 -07002235 // Query for the set of apps
2236 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2237 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2238 if (DEBUG_LOADERS) {
2239 Log.d(TAG, "queryIntentActivities took "
2240 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2241 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2242 }
2243 // Fail if we don't have any apps
2244 if (apps == null || apps.isEmpty()) {
2245 return;
2246 }
2247 // Sort the applications by name
2248 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2249 Collections.sort(apps,
2250 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2251 if (DEBUG_LOADERS) {
2252 Log.d(TAG, "sort took "
2253 + (SystemClock.uptimeMillis()-sortTime) + "ms");
Joe Onorato9c1289c2009-08-17 11:03:03 -04002254 }
2255
Winson Chung64359a52013-07-08 17:17:08 -07002256 // Create the ApplicationInfos
2257 final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2258 for (int i = 0; i < apps.size(); i++) {
2259 // This builds the icon bitmaps.
2260 mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
2261 mIconCache, mLabelCache));
2262 }
2263
2264 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2265 final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
2266 mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
2267
2268 // Post callback on main thread
2269 mHandler.post(new Runnable() {
2270 public void run() {
2271 final long bindTime = SystemClock.uptimeMillis();
2272 if (callbacks != null) {
2273 callbacks.bindAllApplications(added);
2274 if (DEBUG_LOADERS) {
2275 Log.d(TAG, "bound " + added.size() + " apps in "
2276 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2277 }
2278 } else {
2279 Log.i(TAG, "not binding apps: no Launcher activity");
2280 }
2281 }
2282 });
2283
Joe Onorato36115782010-06-17 13:28:48 -04002284 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002285 Log.d(TAG, "Icons processed in "
2286 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002287 }
2288 }
2289
2290 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002291 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002292 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2293 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2294 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2295 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2296 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2297 }
Joe Onorato36115782010-06-17 13:28:48 -04002298 }
2299 }
2300
2301 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002302 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002303 }
2304
2305 private class PackageUpdatedTask implements Runnable {
2306 int mOp;
2307 String[] mPackages;
2308
2309 public static final int OP_NONE = 0;
2310 public static final int OP_ADD = 1;
2311 public static final int OP_UPDATE = 2;
2312 public static final int OP_REMOVE = 3; // uninstlled
2313 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2314
2315
2316 public PackageUpdatedTask(int op, String[] packages) {
2317 mOp = op;
2318 mPackages = packages;
2319 }
2320
2321 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002322 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002323
2324 final String[] packages = mPackages;
2325 final int N = packages.length;
2326 switch (mOp) {
2327 case OP_ADD:
2328 for (int i=0; i<N; i++) {
2329 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002330 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002331 }
2332 break;
2333 case OP_UPDATE:
2334 for (int i=0; i<N; i++) {
2335 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002336 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002337 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002338 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002339 }
2340 break;
2341 case OP_REMOVE:
2342 case OP_UNAVAILABLE:
2343 for (int i=0; i<N; i++) {
2344 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002345 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002346 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002347 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002348 }
2349 break;
2350 }
2351
2352 ArrayList<ApplicationInfo> added = null;
Joe Onorato36115782010-06-17 13:28:48 -04002353 ArrayList<ApplicationInfo> modified = null;
Winson Chung83892cc2013-05-01 16:53:33 -07002354 final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002355
Adam Cohen487f7dd2012-06-28 18:12:10 -07002356 if (mBgAllAppsList.added.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002357 added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
2358 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002359 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002360 if (mBgAllAppsList.modified.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002361 modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
2362 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002363 }
Winson Chung5d55f332012-07-16 20:45:03 -07002364 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002365 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002366 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002367 }
2368
Joe Onorato36115782010-06-17 13:28:48 -04002369 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2370 if (callbacks == null) {
2371 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2372 return;
2373 }
2374
2375 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002376 // Ensure that we add all the workspace applications to the db
2377 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2378 addAndBindAddedApps(context, added, cb);
Joe Onorato36115782010-06-17 13:28:48 -04002379 }
2380 if (modified != null) {
2381 final ArrayList<ApplicationInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002382
2383 // Update the launcher db to reflect the changes
2384 for (ApplicationInfo a : modifiedFinal) {
2385 ArrayList<ItemInfo> infos =
2386 getItemInfoForComponentName(a.componentName);
2387 for (ItemInfo i : infos) {
2388 if (isShortcutInfoUpdateable(i)) {
2389 ShortcutInfo info = (ShortcutInfo) i;
2390 info.title = a.title.toString();
2391 updateItemInDatabase(context, info);
2392 }
2393 }
2394 }
2395
Joe Onorato36115782010-06-17 13:28:48 -04002396 mHandler.post(new Runnable() {
2397 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002398 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2399 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002400 callbacks.bindAppsUpdated(modifiedFinal);
2401 }
2402 }
2403 });
2404 }
Winson Chung83892cc2013-05-01 16:53:33 -07002405 // If a package has been removed, or an app has been removed as a result of
2406 // an update (for example), make the removed callback.
2407 if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
Winson Chung64359a52013-07-08 17:17:08 -07002408 final boolean packageRemoved = (mOp == OP_REMOVE);
Winson Chung83892cc2013-05-01 16:53:33 -07002409 final ArrayList<String> removedPackageNames =
2410 new ArrayList<String>(Arrays.asList(packages));
2411
Winson Chung64359a52013-07-08 17:17:08 -07002412 // Update the launcher db to reflect the removal of apps
2413 if (packageRemoved) {
2414 for (String pn : removedPackageNames) {
2415 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2416 for (ItemInfo i : infos) {
2417 deleteItemFromDatabase(context, i);
2418 }
2419 }
2420 } else {
2421 for (ApplicationInfo a : removedApps) {
2422 ArrayList<ItemInfo> infos =
2423 getItemInfoForComponentName(a.componentName);
2424 for (ItemInfo i : infos) {
2425 deleteItemFromDatabase(context, i);
2426 }
2427 }
2428 }
2429
Joe Onorato36115782010-06-17 13:28:48 -04002430 mHandler.post(new Runnable() {
2431 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002432 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2433 if (callbacks == cb && cb != null) {
Winson Chung83892cc2013-05-01 16:53:33 -07002434 callbacks.bindComponentsRemoved(removedPackageNames,
Winson Chung64359a52013-07-08 17:17:08 -07002435 removedApps, packageRemoved);
Joe Onorato36115782010-06-17 13:28:48 -04002436 }
2437 }
2438 });
Joe Onoratobe386092009-11-17 17:32:16 -08002439 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002440
Michael Jurkac402cd92013-05-20 15:49:32 +02002441 final ArrayList<Object> widgetsAndShortcuts =
2442 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002443 mHandler.post(new Runnable() {
2444 @Override
2445 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002446 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2447 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002448 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002449 }
2450 }
2451 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002452 }
2453 }
2454
Michael Jurkac402cd92013-05-20 15:49:32 +02002455 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2456 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2457 PackageManager packageManager = context.getPackageManager();
2458 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2459 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2460 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2461 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2462 Collections.sort(widgetsAndShortcuts,
2463 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2464 return widgetsAndShortcuts;
2465 }
2466
Joe Onorato9c1289c2009-08-17 11:03:03 -04002467 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002468 * This is called from the code that adds shortcuts from the intent receiver. This
2469 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002470 */
Joe Onorato56d82912010-03-07 14:32:10 -05002471 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002472 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002473 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002474
Joe Onorato56d82912010-03-07 14:32:10 -05002475 /**
2476 * Make an ShortcutInfo object for a shortcut that is an application.
2477 *
2478 * If c is not null, then it will be used to fill in missing data like the title and icon.
2479 */
2480 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002481 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002482 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002483 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002484
2485 ComponentName componentName = intent.getComponent();
2486 if (componentName == null) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002487 return null;
2488 }
2489
Adam Cohen00fcb492011-11-02 21:53:47 -07002490 try {
2491 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2492 if (!pi.applicationInfo.enabled) {
2493 // If we return null here, the corresponding item will be removed from the launcher
2494 // db and will not appear in the workspace.
2495 return null;
2496 }
Michael Jurka1e2f4652013-07-08 18:03:46 -07002497 info.initFlagsAndFirstInstallTime(pi);
Adam Cohen00fcb492011-11-02 21:53:47 -07002498 } catch (NameNotFoundException e) {
2499 Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
2500 }
2501
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002502 // TODO: See if the PackageManager knows about this case. If it doesn't
2503 // then return null & delete this.
2504
Joe Onorato56d82912010-03-07 14:32:10 -05002505 // the resource -- This may implicitly give us back the fallback icon,
2506 // but don't worry about that. All we're doing with usingFallbackIcon is
2507 // to avoid saving lots of copies of that in the database, and most apps
2508 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002509
2510 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2511 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2512 // via resolveActivity().
2513 ResolveInfo resolveInfo = null;
2514 ComponentName oldComponent = intent.getComponent();
2515 Intent newIntent = new Intent(intent.getAction(), null);
2516 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2517 newIntent.setPackage(oldComponent.getPackageName());
2518 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2519 for (ResolveInfo i : infos) {
2520 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2521 i.activityInfo.name);
2522 if (cn.equals(oldComponent)) {
2523 resolveInfo = i;
2524 }
2525 }
2526 if (resolveInfo == null) {
2527 resolveInfo = manager.resolveActivity(intent, 0);
2528 }
Joe Onorato56d82912010-03-07 14:32:10 -05002529 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002530 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002531 }
Joe Onorato56d82912010-03-07 14:32:10 -05002532 // the db
2533 if (icon == null) {
2534 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002535 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002536 }
2537 }
2538 // the fallback icon
2539 if (icon == null) {
2540 icon = getFallbackIcon();
2541 info.usingFallbackIcon = true;
2542 }
2543 info.setIcon(icon);
2544
2545 // from the resource
2546 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002547 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2548 if (labelCache != null && labelCache.containsKey(key)) {
2549 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002550 } else {
2551 info.title = resolveInfo.activityInfo.loadLabel(manager);
2552 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002553 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002554 }
2555 }
Joe Onorato56d82912010-03-07 14:32:10 -05002556 }
2557 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002558 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002559 if (c != null) {
2560 info.title = c.getString(titleIndex);
2561 }
2562 }
2563 // fall back to the class name of the activity
2564 if (info.title == null) {
2565 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002566 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002567 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2568 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002569 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002570
Winson Chung64359a52013-07-08 17:17:08 -07002571 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2572 ItemInfoFilter f) {
2573 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2574 for (ItemInfo i : infos) {
2575 if (i instanceof ShortcutInfo) {
2576 ShortcutInfo info = (ShortcutInfo) i;
2577 ComponentName cn = info.intent.getComponent();
2578 if (cn != null && f.filterItem(null, info, cn)) {
2579 filtered.add(info);
2580 }
2581 } else if (i instanceof FolderInfo) {
2582 FolderInfo info = (FolderInfo) i;
2583 for (ShortcutInfo s : info.contents) {
2584 ComponentName cn = s.intent.getComponent();
2585 if (cn != null && f.filterItem(info, s, cn)) {
2586 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07002587 }
2588 }
Winson Chung64359a52013-07-08 17:17:08 -07002589 } else if (i instanceof LauncherAppWidgetInfo) {
2590 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2591 ComponentName cn = info.providerName;
2592 if (cn != null && f.filterItem(null, info, cn)) {
2593 filtered.add(info);
2594 }
Winson Chung8a435102012-08-30 17:16:53 -07002595 }
2596 }
Winson Chung64359a52013-07-08 17:17:08 -07002597 return new ArrayList<ItemInfo>(filtered);
2598 }
2599
2600 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
2601 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2602 ItemInfoFilter filter = new ItemInfoFilter() {
2603 @Override
2604 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2605 return cn.getPackageName().equals(pn);
2606 }
2607 };
2608 return filterItemInfos(sBgItemsIdMap.values(), filter);
2609 }
2610
2611 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
2612 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2613 ItemInfoFilter filter = new ItemInfoFilter() {
2614 @Override
2615 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2616 return cn.equals(cname);
2617 }
2618 };
2619 return filterItemInfos(sBgItemsIdMap.values(), filter);
2620 }
2621
2622 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2623 if (i instanceof ShortcutInfo) {
2624 ShortcutInfo info = (ShortcutInfo) i;
2625 // We need to check for ACTION_MAIN otherwise getComponent() might
2626 // return null for some shortcuts (for instance, for shortcuts to
2627 // web pages.)
2628 Intent intent = info.intent;
2629 ComponentName name = intent.getComponent();
2630 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2631 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2632 return true;
2633 }
2634 }
2635 return false;
Winson Chung8a435102012-08-30 17:16:53 -07002636 }
2637
2638 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002639 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002640 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002641 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002642 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2643 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002644
Joe Onorato56d82912010-03-07 14:32:10 -05002645 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002646 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002647 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002648
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002649 // TODO: If there's an explicit component and we can't install that, delete it.
2650
Joe Onorato56d82912010-03-07 14:32:10 -05002651 info.title = c.getString(titleIndex);
2652
Joe Onorato9c1289c2009-08-17 11:03:03 -04002653 int iconType = c.getInt(iconTypeIndex);
2654 switch (iconType) {
2655 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2656 String packageName = c.getString(iconPackageIndex);
2657 String resourceName = c.getString(iconResourceIndex);
2658 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002659 info.customIcon = false;
2660 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002661 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002662 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002663 if (resources != null) {
2664 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002665 icon = Utilities.createIconBitmap(
2666 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002667 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002668 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002669 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002670 }
Joe Onorato56d82912010-03-07 14:32:10 -05002671 // the db
2672 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002673 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002674 }
2675 // the fallback icon
2676 if (icon == null) {
2677 icon = getFallbackIcon();
2678 info.usingFallbackIcon = true;
2679 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002680 break;
2681 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002682 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002683 if (icon == null) {
2684 icon = getFallbackIcon();
2685 info.customIcon = false;
2686 info.usingFallbackIcon = true;
2687 } else {
2688 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002689 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002690 break;
2691 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002692 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002693 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002694 info.customIcon = false;
2695 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002696 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002697 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002698 return info;
2699 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002700
Michael Jurka931dc972011-08-05 15:08:15 -07002701 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002702 @SuppressWarnings("all") // suppress dead code warning
2703 final boolean debug = false;
2704 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002705 Log.d(TAG, "getIconFromCursor app="
2706 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2707 }
2708 byte[] data = c.getBlob(iconIndex);
2709 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002710 return Utilities.createIconBitmap(
2711 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002712 } catch (Exception e) {
2713 return null;
2714 }
2715 }
2716
Winson Chung3d503fb2011-07-13 17:25:49 -07002717 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2718 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002719 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002720 if (info == null) {
2721 return null;
2722 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002723 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002724
2725 return info;
2726 }
2727
Winson Chunga9abd0e2010-10-27 17:18:37 -07002728 /**
Winson Chung55cef262010-10-28 14:14:18 -07002729 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2730 */
2731 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2732 ComponentName component) {
2733 List<AppWidgetProviderInfo> widgets =
2734 AppWidgetManager.getInstance(context).getInstalledProviders();
2735 for (AppWidgetProviderInfo info : widgets) {
2736 if (info.provider.equals(component)) {
2737 return info;
2738 }
2739 }
2740 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002741 }
2742
Winson Chung68846fd2010-10-29 11:00:27 -07002743 /**
2744 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2745 */
2746 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2747 final PackageManager packageManager = context.getPackageManager();
2748 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2749 new ArrayList<WidgetMimeTypeHandlerData>();
2750
2751 final Intent supportsIntent =
2752 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2753 supportsIntent.setType(mimeType);
2754
2755 // Create a set of widget configuration components that we can test against
2756 final List<AppWidgetProviderInfo> widgets =
2757 AppWidgetManager.getInstance(context).getInstalledProviders();
2758 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2759 new HashMap<ComponentName, AppWidgetProviderInfo>();
2760 for (AppWidgetProviderInfo info : widgets) {
2761 configurationComponentToWidget.put(info.configure, info);
2762 }
2763
2764 // Run through each of the intents that can handle this type of clip data, and cross
2765 // reference them with the components that are actual configuration components
2766 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2767 PackageManager.MATCH_DEFAULT_ONLY);
2768 for (ResolveInfo info : activities) {
2769 final ActivityInfo activityInfo = info.activityInfo;
2770 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2771 activityInfo.name);
2772 if (configurationComponentToWidget.containsKey(infoComponent)) {
2773 supportedConfigurationActivities.add(
2774 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2775 configurationComponentToWidget.get(infoComponent)));
2776 }
2777 }
2778 return supportedConfigurationActivities;
2779 }
2780
Winson Chunga9abd0e2010-10-27 17:18:37 -07002781 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08002782 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2783 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2784 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2785
Adam Cohend9198822011-11-22 16:42:47 -08002786 if (intent == null) {
2787 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2788 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2789 return null;
2790 }
2791
Joe Onorato0589f0f2010-02-08 13:44:00 -08002792 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08002793 boolean customIcon = false;
2794 ShortcutIconResource iconResource = null;
2795
2796 if (bitmap != null && bitmap instanceof Bitmap) {
2797 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002798 customIcon = true;
2799 } else {
2800 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2801 if (extra != null && extra instanceof ShortcutIconResource) {
2802 try {
2803 iconResource = (ShortcutIconResource) extra;
2804 final PackageManager packageManager = context.getPackageManager();
2805 Resources resources = packageManager.getResourcesForApplication(
2806 iconResource.packageName);
2807 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002808 icon = Utilities.createIconBitmap(
2809 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002810 } catch (Exception e) {
2811 Log.w(TAG, "Could not load shortcut icon: " + extra);
2812 }
2813 }
2814 }
2815
Michael Jurkac9d95c52011-08-29 14:03:34 -07002816 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002817
2818 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002819 if (fallbackIcon != null) {
2820 icon = fallbackIcon;
2821 } else {
2822 icon = getFallbackIcon();
2823 info.usingFallbackIcon = true;
2824 }
Joe Onorato56d82912010-03-07 14:32:10 -05002825 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08002826 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05002827
Joe Onorato0589f0f2010-02-08 13:44:00 -08002828 info.title = name;
2829 info.intent = intent;
2830 info.customIcon = customIcon;
2831 info.iconResource = iconResource;
2832
2833 return info;
2834 }
2835
Winson Chungaac01e12011-08-17 10:37:13 -07002836 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2837 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08002838 // If apps can't be on SD, don't even bother.
2839 if (!mAppsCanBeOnExternalStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07002840 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08002841 }
Joe Onorato56d82912010-03-07 14:32:10 -05002842 // If this icon doesn't have a custom icon, check to see
2843 // what's stored in the DB, and if it doesn't match what
2844 // we're going to show, store what we are going to show back
2845 // into the DB. We do this so when we're loading, if the
2846 // package manager can't find an icon (for example because
2847 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07002848 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07002849 cache.put(info, c.getBlob(iconIndex));
2850 return true;
2851 }
2852 return false;
2853 }
2854 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2855 boolean needSave = false;
2856 try {
2857 if (data != null) {
2858 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2859 Bitmap loaded = info.getIcon(mIconCache);
2860 needSave = !saved.sameAs(loaded);
2861 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05002862 needSave = true;
2863 }
Winson Chungaac01e12011-08-17 10:37:13 -07002864 } catch (Exception e) {
2865 needSave = true;
2866 }
2867 if (needSave) {
2868 Log.d(TAG, "going to save icon bitmap for info=" + info);
2869 // This is slower than is ideal, but this only happens once
2870 // or when the app is updated with a new icon.
2871 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05002872 }
2873 }
2874
Joe Onorato9c1289c2009-08-17 11:03:03 -04002875 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07002876 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04002877 * or make a new one.
2878 */
Adam Cohendf2cc412011-04-27 16:56:57 -07002879 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002880 // See if a placeholder was created for us already
2881 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07002882 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002883 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07002884 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002885 folders.put(id, folderInfo);
2886 }
Adam Cohendf2cc412011-04-27 16:56:57 -07002887 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002888 }
2889
Winson Chung11904872012-09-17 16:58:46 -07002890 public static final Comparator<ApplicationInfo> getAppNameComparator() {
2891 final Collator collator = Collator.getInstance();
2892 return new Comparator<ApplicationInfo>() {
2893 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2894 int result = collator.compare(a.title.toString(), b.title.toString());
2895 if (result == 0) {
2896 result = a.componentName.compareTo(b.componentName);
2897 }
2898 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07002899 }
Winson Chung11904872012-09-17 16:58:46 -07002900 };
2901 }
Winson Chung78403fe2011-01-21 15:38:02 -08002902 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2903 = new Comparator<ApplicationInfo>() {
2904 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2905 if (a.firstInstallTime < b.firstInstallTime) return 1;
2906 if (a.firstInstallTime > b.firstInstallTime) return -1;
2907 return 0;
2908 }
2909 };
Winson Chung11904872012-09-17 16:58:46 -07002910 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
2911 final Collator collator = Collator.getInstance();
2912 return new Comparator<AppWidgetProviderInfo>() {
2913 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
2914 return collator.compare(a.label.toString(), b.label.toString());
2915 }
2916 };
2917 }
Winson Chung5308f242011-08-18 12:12:41 -07002918 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
2919 if (info.activityInfo != null) {
2920 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
2921 } else {
2922 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
2923 }
2924 }
Winson Chung785d2eb2011-04-14 16:08:02 -07002925 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07002926 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07002927 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07002928 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07002929 ShortcutNameComparator(PackageManager pm) {
2930 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07002931 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07002932 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07002933 }
2934 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
2935 mPackageManager = pm;
2936 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07002937 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07002938 }
2939 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002940 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07002941 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
2942 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
2943 if (mLabelCache.containsKey(keyA)) {
2944 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002945 } else {
2946 labelA = a.loadLabel(mPackageManager).toString();
2947
Winson Chung5308f242011-08-18 12:12:41 -07002948 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002949 }
Winson Chung5308f242011-08-18 12:12:41 -07002950 if (mLabelCache.containsKey(keyB)) {
2951 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002952 } else {
2953 labelB = b.loadLabel(mPackageManager).toString();
2954
Winson Chung5308f242011-08-18 12:12:41 -07002955 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002956 }
Winson Chung11904872012-09-17 16:58:46 -07002957 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07002958 }
2959 };
Winson Chung1ed747a2011-05-03 16:18:34 -07002960 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07002961 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07002962 private PackageManager mPackageManager;
2963 private HashMap<Object, String> mLabelCache;
2964 WidgetAndShortcutNameComparator(PackageManager pm) {
2965 mPackageManager = pm;
2966 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07002967 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07002968 }
2969 public final int compare(Object a, Object b) {
2970 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07002971 if (mLabelCache.containsKey(a)) {
2972 labelA = mLabelCache.get(a);
2973 } else {
2974 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002975 ((AppWidgetProviderInfo) a).label :
2976 ((ResolveInfo) a).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002977 mLabelCache.put(a, labelA);
2978 }
2979 if (mLabelCache.containsKey(b)) {
2980 labelB = mLabelCache.get(b);
2981 } else {
2982 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002983 ((AppWidgetProviderInfo) b).label :
2984 ((ResolveInfo) b).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002985 mLabelCache.put(b, labelB);
2986 }
Winson Chung11904872012-09-17 16:58:46 -07002987 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07002988 }
2989 };
Joe Onoratobe386092009-11-17 17:32:16 -08002990
2991 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08002992 Log.d(TAG, "mCallbacks=" + mCallbacks);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002993 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
2994 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
2995 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
2996 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04002997 if (mLoaderTask != null) {
2998 mLoaderTask.dumpState();
2999 } else {
3000 Log.d(TAG, "mLoaderTask=null");
3001 }
Joe Onoratobe386092009-11-17 17:32:16 -08003002 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003003}