blob: eaa2fd297d9285abdcd16b570c9025d171720948 [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 {
Daniel Sandler47b50312013-07-25 13:16:14 -04001731 if (c != null) {
1732 c.close();
1733 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001734 }
1735
1736 if (itemsToRemove.size() > 0) {
1737 ContentProviderClient client = contentResolver.acquireContentProviderClient(
1738 LauncherSettings.Favorites.CONTENT_URI);
1739 // Remove dead items
1740 for (long id : itemsToRemove) {
1741 if (DEBUG_LOADERS) {
1742 Log.d(TAG, "Removed id = " + id);
1743 }
1744 // Don't notify content observers
1745 try {
1746 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1747 null, null);
1748 } catch (RemoteException e) {
1749 Log.w(TAG, "Could not remove id = " + id);
1750 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001751 }
1752 }
1753
Adam Cohendcd297f2013-06-18 13:13:40 -07001754 if (loadOldDb) {
1755 long maxScreenId = 0;
1756 // If we're importing we use the old screen order.
1757 for (ItemInfo item: sBgItemsIdMap.values()) {
1758 long screenId = item.screenId;
1759 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1760 !sBgWorkspaceScreens.contains(screenId)) {
1761 sBgWorkspaceScreens.add(screenId);
1762 if (screenId > maxScreenId) {
1763 maxScreenId = screenId;
1764 }
1765 }
1766 }
1767 Collections.sort(sBgWorkspaceScreens);
1768 mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
1769 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1770 } else {
1771 Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1772 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1773 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1774
1775 try {
1776 final int idIndex = sc.getColumnIndexOrThrow(
1777 LauncherSettings.WorkspaceScreens._ID);
1778 final int rankIndex = sc.getColumnIndexOrThrow(
1779 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1780 while (sc.moveToNext()) {
1781 try {
1782 long screenId = sc.getLong(idIndex);
1783 int rank = sc.getInt(rankIndex);
1784
1785 orderedScreens.put(rank, screenId);
1786 } catch (Exception e) {
1787 Log.w(TAG, "Desktop items loading interrupted:", e);
1788 }
1789 }
1790 } finally {
1791 sc.close();
1792 }
1793
1794 Iterator<Integer> iter = orderedScreens.keySet().iterator();
1795 while (iter.hasNext()) {
1796 sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
1797 }
1798
1799 // Remove any empty screens
1800 ArrayList<Long> unusedScreens = new ArrayList<Long>();
1801 unusedScreens.addAll(sBgWorkspaceScreens);
1802
1803 for (ItemInfo item: sBgItemsIdMap.values()) {
1804 long screenId = item.screenId;
1805
1806 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1807 unusedScreens.contains(screenId)) {
1808 unusedScreens.remove(screenId);
1809 }
1810 }
1811
1812 // If there are any empty screens remove them, and update.
1813 if (unusedScreens.size() != 0) {
1814 sBgWorkspaceScreens.removeAll(unusedScreens);
1815 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1816 }
1817 }
1818
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001819 if (DEBUG_LOADERS) {
1820 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1821 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07001822 int nScreens = occupied.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001823 for (int y = 0; y < mCellCountY; y++) {
1824 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07001825
Daniel Sandler566da102013-06-25 23:43:45 -04001826 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07001827 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001828 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07001829 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001830 line += " | ";
1831 }
1832 for (int x = 0; x < mCellCountX; x++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001833 line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001834 }
Joe Onorato36115782010-06-17 13:28:48 -04001835 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001836 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04001837 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001838 }
Joe Onorato36115782010-06-17 13:28:48 -04001839 }
1840 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001841
Adam Cohene25af792013-06-06 23:08:25 -07001842 // We rearrange the screens from the old launcher
1843 // 12345 -> 34512
Adam Cohendcd297f2013-06-18 13:13:40 -07001844 private long permuteScreens(long screen) {
Adam Cohene25af792013-06-06 23:08:25 -07001845 if (screen >= 2) {
1846 return screen - 2;
1847 } else {
1848 return screen + 3;
1849 }
1850 }
1851
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001852 /** Filters the set of items who are directly or indirectly (via another container) on the
1853 * specified screen. */
1854 private void filterCurrentWorkspaceItems(int currentScreen,
1855 ArrayList<ItemInfo> allWorkspaceItems,
1856 ArrayList<ItemInfo> currentScreenItems,
1857 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001858 // Purge any null ItemInfos
1859 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1860 while (iter.hasNext()) {
1861 ItemInfo i = iter.next();
1862 if (i == null) {
1863 iter.remove();
1864 }
1865 }
1866
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001867 // If we aren't filtering on a screen, then the set of items to load is the full set of
1868 // items given.
1869 if (currentScreen < 0) {
1870 currentScreenItems.addAll(allWorkspaceItems);
Joe Onorato36115782010-06-17 13:28:48 -04001871 }
1872
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001873 // Order the set of items by their containers first, this allows use to walk through the
1874 // list sequentially, build up a list of containers that are in the specified screen,
1875 // as well as all items in those containers.
1876 Set<Long> itemsOnScreen = new HashSet<Long>();
1877 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1878 @Override
1879 public int compare(ItemInfo lhs, ItemInfo rhs) {
1880 return (int) (lhs.container - rhs.container);
1881 }
1882 });
1883 for (ItemInfo info : allWorkspaceItems) {
1884 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001885 if (info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001886 currentScreenItems.add(info);
1887 itemsOnScreen.add(info.id);
1888 } else {
1889 otherScreenItems.add(info);
1890 }
1891 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1892 currentScreenItems.add(info);
1893 itemsOnScreen.add(info.id);
1894 } else {
1895 if (itemsOnScreen.contains(info.container)) {
1896 currentScreenItems.add(info);
1897 itemsOnScreen.add(info.id);
1898 } else {
1899 otherScreenItems.add(info);
1900 }
1901 }
1902 }
1903 }
1904
1905 /** Filters the set of widgets which are on the specified screen. */
1906 private void filterCurrentAppWidgets(int currentScreen,
1907 ArrayList<LauncherAppWidgetInfo> appWidgets,
1908 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1909 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1910 // If we aren't filtering on a screen, then the set of items to load is the full set of
1911 // widgets given.
1912 if (currentScreen < 0) {
1913 currentScreenWidgets.addAll(appWidgets);
1914 }
1915
1916 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001917 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001918 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07001919 widget.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001920 currentScreenWidgets.add(widget);
1921 } else {
1922 otherScreenWidgets.add(widget);
1923 }
1924 }
1925 }
1926
1927 /** Filters the set of folders which are on the specified screen. */
1928 private void filterCurrentFolders(int currentScreen,
1929 HashMap<Long, ItemInfo> itemsIdMap,
1930 HashMap<Long, FolderInfo> folders,
1931 HashMap<Long, FolderInfo> currentScreenFolders,
1932 HashMap<Long, FolderInfo> otherScreenFolders) {
1933 // If we aren't filtering on a screen, then the set of items to load is the full set of
1934 // widgets given.
1935 if (currentScreen < 0) {
1936 currentScreenFolders.putAll(folders);
1937 }
1938
1939 for (long id : folders.keySet()) {
1940 ItemInfo info = itemsIdMap.get(id);
1941 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07001942 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001943 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07001944 info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001945 currentScreenFolders.put(id, folder);
1946 } else {
1947 otherScreenFolders.put(id, folder);
1948 }
1949 }
1950 }
1951
1952 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
1953 * right) */
1954 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
1955 // XXX: review this
1956 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07001957 @Override
1958 public int compare(ItemInfo lhs, ItemInfo rhs) {
1959 int cellCountX = LauncherModel.getCellCountX();
1960 int cellCountY = LauncherModel.getCellCountY();
1961 int screenOffset = cellCountX * cellCountY;
1962 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001963 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07001964 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07001965 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07001966 rhs.cellY * cellCountX + rhs.cellX);
1967 return (int) (lr - rr);
1968 }
1969 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001970 }
Winson Chungdb8a8942012-04-03 14:08:41 -07001971
Adam Cohendcd297f2013-06-18 13:13:40 -07001972 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
1973 final ArrayList<Long> orderedScreens) {
1974
1975 final Runnable r = new Runnable() {
1976 @Override
1977 public void run() {
1978 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1979 if (callbacks != null) {
1980 callbacks.bindScreens(orderedScreens);
1981 }
1982 }
1983 };
1984 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
1985 }
1986
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001987 private void bindWorkspaceItems(final Callbacks oldCallbacks,
1988 final ArrayList<ItemInfo> workspaceItems,
1989 final ArrayList<LauncherAppWidgetInfo> appWidgets,
1990 final HashMap<Long, FolderInfo> folders,
1991 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07001992
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001993 final boolean postOnMainThread = (deferredBindRunnables != null);
1994
1995 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07001996 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001997 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04001998 final int start = i;
1999 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002000 final Runnable r = new Runnable() {
2001 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002002 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002003 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002004 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002005 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2006 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002007 }
2008 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002009 };
2010 if (postOnMainThread) {
2011 deferredBindRunnables.add(r);
2012 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002013 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002014 }
Joe Onorato36115782010-06-17 13:28:48 -04002015 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002016
2017 // Bind the folders
2018 if (!folders.isEmpty()) {
2019 final Runnable r = new Runnable() {
2020 public void run() {
2021 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2022 if (callbacks != null) {
2023 callbacks.bindFolders(folders);
2024 }
2025 }
2026 };
2027 if (postOnMainThread) {
2028 deferredBindRunnables.add(r);
2029 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002030 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002031 }
2032 }
2033
2034 // Bind the widgets, one at a time
2035 N = appWidgets.size();
2036 for (int i = 0; i < N; i++) {
2037 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2038 final Runnable r = new Runnable() {
2039 public void run() {
2040 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2041 if (callbacks != null) {
2042 callbacks.bindAppWidget(widget);
2043 }
2044 }
2045 };
2046 if (postOnMainThread) {
2047 deferredBindRunnables.add(r);
2048 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002049 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002050 }
2051 }
2052 }
2053
2054 /**
2055 * Binds all loaded data to actual views on the main thread.
2056 */
2057 private void bindWorkspace(int synchronizeBindPage) {
2058 final long t = SystemClock.uptimeMillis();
2059 Runnable r;
2060
2061 // Don't use these two variables in any of the callback runnables.
2062 // Otherwise we hold a reference to them.
2063 final Callbacks oldCallbacks = mCallbacks.get();
2064 if (oldCallbacks == null) {
2065 // This launcher has exited and nobody bothered to tell us. Just bail.
2066 Log.w(TAG, "LoaderTask running with no launcher");
2067 return;
2068 }
2069
Winson Chung4a2afa32012-07-19 14:53:05 -07002070 final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
2071 final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002072 oldCallbacks.getCurrentWorkspaceScreen();
2073
2074 // Load all the items that are on the current page first (and in the process, unbind
2075 // all the existing workspace items before we call startBinding() below.
2076 unbindWorkspaceItemsOnMainThread();
2077 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2078 ArrayList<LauncherAppWidgetInfo> appWidgets =
2079 new ArrayList<LauncherAppWidgetInfo>();
2080 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2081 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002082 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002083 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002084 workspaceItems.addAll(sBgWorkspaceItems);
2085 appWidgets.addAll(sBgAppWidgets);
2086 folders.putAll(sBgFolders);
2087 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002088 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002089 }
2090
2091 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2092 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2093 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2094 new ArrayList<LauncherAppWidgetInfo>();
2095 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2096 new ArrayList<LauncherAppWidgetInfo>();
2097 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2098 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2099
2100 // Separate the items that are on the current screen, and all the other remaining items
2101 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
2102 otherWorkspaceItems);
2103 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
2104 otherAppWidgets);
2105 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
2106 otherFolders);
2107 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2108 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2109
2110 // Tell the workspace that we're about to start binding items
2111 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002112 public void run() {
2113 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2114 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002115 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002116 }
2117 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002118 };
Winson Chung81b52252012-08-27 15:34:29 -07002119 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002120
Adam Cohendcd297f2013-06-18 13:13:40 -07002121 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2122
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002123 // Load items on the current page
2124 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2125 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002126 if (isLoadingSynchronously) {
2127 r = new Runnable() {
2128 public void run() {
2129 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2130 if (callbacks != null) {
2131 callbacks.onPageBoundSynchronously(currentScreen);
2132 }
2133 }
2134 };
Winson Chung81b52252012-08-27 15:34:29 -07002135 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002136 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002137
Winson Chung4a2afa32012-07-19 14:53:05 -07002138 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2139 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002140 mDeferredBindRunnables.clear();
2141 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002142 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002143
2144 // Tell the workspace that we're done binding items
2145 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002146 public void run() {
2147 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2148 if (callbacks != null) {
Adam Cohene25af792013-06-06 23:08:25 -07002149 callbacks.finishBindingItems(mIsUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002150 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002151
Winson Chung98e030b2012-05-07 16:01:11 -07002152 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002153 if (DEBUG_LOADERS) {
2154 Log.d(TAG, "bound workspace in "
2155 + (SystemClock.uptimeMillis()-t) + "ms");
2156 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002157
2158 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002159 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002160 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002161 if (isLoadingSynchronously) {
2162 mDeferredBindRunnables.add(r);
2163 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002164 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002165 }
Joe Onorato36115782010-06-17 13:28:48 -04002166 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002167
Joe Onorato36115782010-06-17 13:28:48 -04002168 private void loadAndBindAllApps() {
2169 if (DEBUG_LOADERS) {
2170 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2171 }
2172 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002173 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002174 synchronized (LoaderTask.this) {
2175 if (mStopped) {
2176 return;
2177 }
2178 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002179 }
Joe Onorato36115782010-06-17 13:28:48 -04002180 } else {
2181 onlyBindAllApps();
2182 }
2183 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002184
Joe Onorato36115782010-06-17 13:28:48 -04002185 private void onlyBindAllApps() {
2186 final Callbacks oldCallbacks = mCallbacks.get();
2187 if (oldCallbacks == null) {
2188 // This launcher has exited and nobody bothered to tell us. Just bail.
2189 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2190 return;
2191 }
2192
2193 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002194 @SuppressWarnings("unchecked")
Joe Onorato36115782010-06-17 13:28:48 -04002195 final ArrayList<ApplicationInfo> list
Adam Cohen487f7dd2012-06-28 18:12:10 -07002196 = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002197 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002198 public void run() {
2199 final long t = SystemClock.uptimeMillis();
2200 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2201 if (callbacks != null) {
2202 callbacks.bindAllApplications(list);
2203 }
2204 if (DEBUG_LOADERS) {
2205 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2206 + (SystemClock.uptimeMillis()-t) + "ms");
2207 }
2208 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002209 };
2210 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002211 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002212 r.run();
2213 } else {
2214 mHandler.post(r);
2215 }
Joe Onorato36115782010-06-17 13:28:48 -04002216 }
2217
Winson Chung64359a52013-07-08 17:17:08 -07002218 private void loadAllApps() {
2219 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002220
2221 // Don't use these two variables in any of the callback runnables.
2222 // Otherwise we hold a reference to them.
2223 final Callbacks oldCallbacks = mCallbacks.get();
2224 if (oldCallbacks == null) {
2225 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002226 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002227 return;
2228 }
2229
Winson Chung64359a52013-07-08 17:17:08 -07002230 final PackageManager packageManager = mContext.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04002231 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2232 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2233
Winson Chung64359a52013-07-08 17:17:08 -07002234 // Clear the list of apps
2235 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002236
Winson Chung64359a52013-07-08 17:17:08 -07002237 // Query for the set of apps
2238 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2239 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2240 if (DEBUG_LOADERS) {
2241 Log.d(TAG, "queryIntentActivities took "
2242 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2243 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2244 }
2245 // Fail if we don't have any apps
2246 if (apps == null || apps.isEmpty()) {
2247 return;
2248 }
2249 // Sort the applications by name
2250 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2251 Collections.sort(apps,
2252 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2253 if (DEBUG_LOADERS) {
2254 Log.d(TAG, "sort took "
2255 + (SystemClock.uptimeMillis()-sortTime) + "ms");
Joe Onorato9c1289c2009-08-17 11:03:03 -04002256 }
2257
Winson Chung64359a52013-07-08 17:17:08 -07002258 // Create the ApplicationInfos
2259 final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2260 for (int i = 0; i < apps.size(); i++) {
2261 // This builds the icon bitmaps.
2262 mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
2263 mIconCache, mLabelCache));
2264 }
2265
2266 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2267 final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
2268 mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
2269
2270 // Post callback on main thread
2271 mHandler.post(new Runnable() {
2272 public void run() {
2273 final long bindTime = SystemClock.uptimeMillis();
2274 if (callbacks != null) {
2275 callbacks.bindAllApplications(added);
2276 if (DEBUG_LOADERS) {
2277 Log.d(TAG, "bound " + added.size() + " apps in "
2278 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2279 }
2280 } else {
2281 Log.i(TAG, "not binding apps: no Launcher activity");
2282 }
2283 }
2284 });
2285
Joe Onorato36115782010-06-17 13:28:48 -04002286 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002287 Log.d(TAG, "Icons processed in "
2288 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002289 }
2290 }
2291
2292 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002293 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002294 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2295 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2296 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2297 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2298 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2299 }
Joe Onorato36115782010-06-17 13:28:48 -04002300 }
2301 }
2302
2303 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002304 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002305 }
2306
2307 private class PackageUpdatedTask implements Runnable {
2308 int mOp;
2309 String[] mPackages;
2310
2311 public static final int OP_NONE = 0;
2312 public static final int OP_ADD = 1;
2313 public static final int OP_UPDATE = 2;
2314 public static final int OP_REMOVE = 3; // uninstlled
2315 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2316
2317
2318 public PackageUpdatedTask(int op, String[] packages) {
2319 mOp = op;
2320 mPackages = packages;
2321 }
2322
2323 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002324 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002325
2326 final String[] packages = mPackages;
2327 final int N = packages.length;
2328 switch (mOp) {
2329 case OP_ADD:
2330 for (int i=0; i<N; i++) {
2331 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002332 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002333 }
2334 break;
2335 case OP_UPDATE:
2336 for (int i=0; i<N; i++) {
2337 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002338 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002339 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002340 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002341 }
2342 break;
2343 case OP_REMOVE:
2344 case OP_UNAVAILABLE:
2345 for (int i=0; i<N; i++) {
2346 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002347 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002348 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002349 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002350 }
2351 break;
2352 }
2353
2354 ArrayList<ApplicationInfo> added = null;
Joe Onorato36115782010-06-17 13:28:48 -04002355 ArrayList<ApplicationInfo> modified = null;
Winson Chung83892cc2013-05-01 16:53:33 -07002356 final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002357
Adam Cohen487f7dd2012-06-28 18:12:10 -07002358 if (mBgAllAppsList.added.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002359 added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
2360 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002361 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002362 if (mBgAllAppsList.modified.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002363 modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
2364 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002365 }
Winson Chung5d55f332012-07-16 20:45:03 -07002366 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002367 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002368 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002369 }
2370
Joe Onorato36115782010-06-17 13:28:48 -04002371 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2372 if (callbacks == null) {
2373 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2374 return;
2375 }
2376
2377 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002378 // Ensure that we add all the workspace applications to the db
2379 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2380 addAndBindAddedApps(context, added, cb);
Joe Onorato36115782010-06-17 13:28:48 -04002381 }
2382 if (modified != null) {
2383 final ArrayList<ApplicationInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002384
2385 // Update the launcher db to reflect the changes
2386 for (ApplicationInfo a : modifiedFinal) {
2387 ArrayList<ItemInfo> infos =
2388 getItemInfoForComponentName(a.componentName);
2389 for (ItemInfo i : infos) {
2390 if (isShortcutInfoUpdateable(i)) {
2391 ShortcutInfo info = (ShortcutInfo) i;
2392 info.title = a.title.toString();
2393 updateItemInDatabase(context, info);
2394 }
2395 }
2396 }
2397
Joe Onorato36115782010-06-17 13:28:48 -04002398 mHandler.post(new Runnable() {
2399 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002400 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2401 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002402 callbacks.bindAppsUpdated(modifiedFinal);
2403 }
2404 }
2405 });
2406 }
Winson Chung83892cc2013-05-01 16:53:33 -07002407 // If a package has been removed, or an app has been removed as a result of
2408 // an update (for example), make the removed callback.
2409 if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
Winson Chung64359a52013-07-08 17:17:08 -07002410 final boolean packageRemoved = (mOp == OP_REMOVE);
Winson Chung83892cc2013-05-01 16:53:33 -07002411 final ArrayList<String> removedPackageNames =
2412 new ArrayList<String>(Arrays.asList(packages));
2413
Winson Chung64359a52013-07-08 17:17:08 -07002414 // Update the launcher db to reflect the removal of apps
2415 if (packageRemoved) {
2416 for (String pn : removedPackageNames) {
2417 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2418 for (ItemInfo i : infos) {
2419 deleteItemFromDatabase(context, i);
2420 }
2421 }
2422 } else {
2423 for (ApplicationInfo a : removedApps) {
2424 ArrayList<ItemInfo> infos =
2425 getItemInfoForComponentName(a.componentName);
2426 for (ItemInfo i : infos) {
2427 deleteItemFromDatabase(context, i);
2428 }
2429 }
2430 }
2431
Joe Onorato36115782010-06-17 13:28:48 -04002432 mHandler.post(new Runnable() {
2433 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002434 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2435 if (callbacks == cb && cb != null) {
Winson Chung83892cc2013-05-01 16:53:33 -07002436 callbacks.bindComponentsRemoved(removedPackageNames,
Winson Chung64359a52013-07-08 17:17:08 -07002437 removedApps, packageRemoved);
Joe Onorato36115782010-06-17 13:28:48 -04002438 }
2439 }
2440 });
Joe Onoratobe386092009-11-17 17:32:16 -08002441 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002442
Michael Jurkac402cd92013-05-20 15:49:32 +02002443 final ArrayList<Object> widgetsAndShortcuts =
2444 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002445 mHandler.post(new Runnable() {
2446 @Override
2447 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002448 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2449 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002450 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002451 }
2452 }
2453 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002454 }
2455 }
2456
Michael Jurkac402cd92013-05-20 15:49:32 +02002457 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2458 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2459 PackageManager packageManager = context.getPackageManager();
2460 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2461 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2462 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2463 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2464 Collections.sort(widgetsAndShortcuts,
2465 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2466 return widgetsAndShortcuts;
2467 }
2468
Joe Onorato9c1289c2009-08-17 11:03:03 -04002469 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002470 * This is called from the code that adds shortcuts from the intent receiver. This
2471 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002472 */
Joe Onorato56d82912010-03-07 14:32:10 -05002473 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002474 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002475 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002476
Joe Onorato56d82912010-03-07 14:32:10 -05002477 /**
2478 * Make an ShortcutInfo object for a shortcut that is an application.
2479 *
2480 * If c is not null, then it will be used to fill in missing data like the title and icon.
2481 */
2482 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002483 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002484 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002485 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002486
2487 ComponentName componentName = intent.getComponent();
2488 if (componentName == null) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002489 return null;
2490 }
2491
Adam Cohen00fcb492011-11-02 21:53:47 -07002492 try {
2493 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2494 if (!pi.applicationInfo.enabled) {
2495 // If we return null here, the corresponding item will be removed from the launcher
2496 // db and will not appear in the workspace.
2497 return null;
2498 }
Michael Jurka1e2f4652013-07-08 18:03:46 -07002499 info.initFlagsAndFirstInstallTime(pi);
Adam Cohen00fcb492011-11-02 21:53:47 -07002500 } catch (NameNotFoundException e) {
2501 Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
2502 }
2503
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002504 // TODO: See if the PackageManager knows about this case. If it doesn't
2505 // then return null & delete this.
2506
Joe Onorato56d82912010-03-07 14:32:10 -05002507 // the resource -- This may implicitly give us back the fallback icon,
2508 // but don't worry about that. All we're doing with usingFallbackIcon is
2509 // to avoid saving lots of copies of that in the database, and most apps
2510 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002511
2512 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2513 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2514 // via resolveActivity().
2515 ResolveInfo resolveInfo = null;
2516 ComponentName oldComponent = intent.getComponent();
2517 Intent newIntent = new Intent(intent.getAction(), null);
2518 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2519 newIntent.setPackage(oldComponent.getPackageName());
2520 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2521 for (ResolveInfo i : infos) {
2522 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2523 i.activityInfo.name);
2524 if (cn.equals(oldComponent)) {
2525 resolveInfo = i;
2526 }
2527 }
2528 if (resolveInfo == null) {
2529 resolveInfo = manager.resolveActivity(intent, 0);
2530 }
Joe Onorato56d82912010-03-07 14:32:10 -05002531 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002532 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002533 }
Joe Onorato56d82912010-03-07 14:32:10 -05002534 // the db
2535 if (icon == null) {
2536 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002537 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002538 }
2539 }
2540 // the fallback icon
2541 if (icon == null) {
2542 icon = getFallbackIcon();
2543 info.usingFallbackIcon = true;
2544 }
2545 info.setIcon(icon);
2546
2547 // from the resource
2548 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002549 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2550 if (labelCache != null && labelCache.containsKey(key)) {
2551 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002552 } else {
2553 info.title = resolveInfo.activityInfo.loadLabel(manager);
2554 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002555 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002556 }
2557 }
Joe Onorato56d82912010-03-07 14:32:10 -05002558 }
2559 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002560 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002561 if (c != null) {
2562 info.title = c.getString(titleIndex);
2563 }
2564 }
2565 // fall back to the class name of the activity
2566 if (info.title == null) {
2567 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002568 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002569 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2570 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002571 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002572
Winson Chung64359a52013-07-08 17:17:08 -07002573 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2574 ItemInfoFilter f) {
2575 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2576 for (ItemInfo i : infos) {
2577 if (i instanceof ShortcutInfo) {
2578 ShortcutInfo info = (ShortcutInfo) i;
2579 ComponentName cn = info.intent.getComponent();
2580 if (cn != null && f.filterItem(null, info, cn)) {
2581 filtered.add(info);
2582 }
2583 } else if (i instanceof FolderInfo) {
2584 FolderInfo info = (FolderInfo) i;
2585 for (ShortcutInfo s : info.contents) {
2586 ComponentName cn = s.intent.getComponent();
2587 if (cn != null && f.filterItem(info, s, cn)) {
2588 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07002589 }
2590 }
Winson Chung64359a52013-07-08 17:17:08 -07002591 } else if (i instanceof LauncherAppWidgetInfo) {
2592 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2593 ComponentName cn = info.providerName;
2594 if (cn != null && f.filterItem(null, info, cn)) {
2595 filtered.add(info);
2596 }
Winson Chung8a435102012-08-30 17:16:53 -07002597 }
2598 }
Winson Chung64359a52013-07-08 17:17:08 -07002599 return new ArrayList<ItemInfo>(filtered);
2600 }
2601
2602 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
2603 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2604 ItemInfoFilter filter = new ItemInfoFilter() {
2605 @Override
2606 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2607 return cn.getPackageName().equals(pn);
2608 }
2609 };
2610 return filterItemInfos(sBgItemsIdMap.values(), filter);
2611 }
2612
2613 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
2614 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2615 ItemInfoFilter filter = new ItemInfoFilter() {
2616 @Override
2617 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2618 return cn.equals(cname);
2619 }
2620 };
2621 return filterItemInfos(sBgItemsIdMap.values(), filter);
2622 }
2623
2624 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2625 if (i instanceof ShortcutInfo) {
2626 ShortcutInfo info = (ShortcutInfo) i;
2627 // We need to check for ACTION_MAIN otherwise getComponent() might
2628 // return null for some shortcuts (for instance, for shortcuts to
2629 // web pages.)
2630 Intent intent = info.intent;
2631 ComponentName name = intent.getComponent();
2632 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2633 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2634 return true;
2635 }
2636 }
2637 return false;
Winson Chung8a435102012-08-30 17:16:53 -07002638 }
2639
2640 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002641 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002642 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002643 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002644 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2645 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002646
Joe Onorato56d82912010-03-07 14:32:10 -05002647 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002648 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002649 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002650
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002651 // TODO: If there's an explicit component and we can't install that, delete it.
2652
Joe Onorato56d82912010-03-07 14:32:10 -05002653 info.title = c.getString(titleIndex);
2654
Joe Onorato9c1289c2009-08-17 11:03:03 -04002655 int iconType = c.getInt(iconTypeIndex);
2656 switch (iconType) {
2657 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2658 String packageName = c.getString(iconPackageIndex);
2659 String resourceName = c.getString(iconResourceIndex);
2660 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002661 info.customIcon = false;
2662 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002663 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002664 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002665 if (resources != null) {
2666 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002667 icon = Utilities.createIconBitmap(
2668 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002669 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002670 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002671 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002672 }
Joe Onorato56d82912010-03-07 14:32:10 -05002673 // the db
2674 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002675 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002676 }
2677 // the fallback icon
2678 if (icon == null) {
2679 icon = getFallbackIcon();
2680 info.usingFallbackIcon = true;
2681 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002682 break;
2683 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002684 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002685 if (icon == null) {
2686 icon = getFallbackIcon();
2687 info.customIcon = false;
2688 info.usingFallbackIcon = true;
2689 } else {
2690 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002691 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002692 break;
2693 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002694 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002695 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002696 info.customIcon = false;
2697 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002698 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002699 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002700 return info;
2701 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002702
Michael Jurka931dc972011-08-05 15:08:15 -07002703 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002704 @SuppressWarnings("all") // suppress dead code warning
2705 final boolean debug = false;
2706 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002707 Log.d(TAG, "getIconFromCursor app="
2708 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2709 }
2710 byte[] data = c.getBlob(iconIndex);
2711 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002712 return Utilities.createIconBitmap(
2713 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002714 } catch (Exception e) {
2715 return null;
2716 }
2717 }
2718
Winson Chung3d503fb2011-07-13 17:25:49 -07002719 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2720 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002721 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002722 if (info == null) {
2723 return null;
2724 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002725 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002726
2727 return info;
2728 }
2729
Winson Chunga9abd0e2010-10-27 17:18:37 -07002730 /**
Winson Chung55cef262010-10-28 14:14:18 -07002731 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2732 */
2733 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2734 ComponentName component) {
2735 List<AppWidgetProviderInfo> widgets =
2736 AppWidgetManager.getInstance(context).getInstalledProviders();
2737 for (AppWidgetProviderInfo info : widgets) {
2738 if (info.provider.equals(component)) {
2739 return info;
2740 }
2741 }
2742 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002743 }
2744
Winson Chung68846fd2010-10-29 11:00:27 -07002745 /**
2746 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2747 */
2748 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2749 final PackageManager packageManager = context.getPackageManager();
2750 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2751 new ArrayList<WidgetMimeTypeHandlerData>();
2752
2753 final Intent supportsIntent =
2754 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2755 supportsIntent.setType(mimeType);
2756
2757 // Create a set of widget configuration components that we can test against
2758 final List<AppWidgetProviderInfo> widgets =
2759 AppWidgetManager.getInstance(context).getInstalledProviders();
2760 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2761 new HashMap<ComponentName, AppWidgetProviderInfo>();
2762 for (AppWidgetProviderInfo info : widgets) {
2763 configurationComponentToWidget.put(info.configure, info);
2764 }
2765
2766 // Run through each of the intents that can handle this type of clip data, and cross
2767 // reference them with the components that are actual configuration components
2768 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2769 PackageManager.MATCH_DEFAULT_ONLY);
2770 for (ResolveInfo info : activities) {
2771 final ActivityInfo activityInfo = info.activityInfo;
2772 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2773 activityInfo.name);
2774 if (configurationComponentToWidget.containsKey(infoComponent)) {
2775 supportedConfigurationActivities.add(
2776 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2777 configurationComponentToWidget.get(infoComponent)));
2778 }
2779 }
2780 return supportedConfigurationActivities;
2781 }
2782
Winson Chunga9abd0e2010-10-27 17:18:37 -07002783 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08002784 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2785 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2786 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2787
Adam Cohend9198822011-11-22 16:42:47 -08002788 if (intent == null) {
2789 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2790 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2791 return null;
2792 }
2793
Joe Onorato0589f0f2010-02-08 13:44:00 -08002794 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08002795 boolean customIcon = false;
2796 ShortcutIconResource iconResource = null;
2797
2798 if (bitmap != null && bitmap instanceof Bitmap) {
2799 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002800 customIcon = true;
2801 } else {
2802 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2803 if (extra != null && extra instanceof ShortcutIconResource) {
2804 try {
2805 iconResource = (ShortcutIconResource) extra;
2806 final PackageManager packageManager = context.getPackageManager();
2807 Resources resources = packageManager.getResourcesForApplication(
2808 iconResource.packageName);
2809 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002810 icon = Utilities.createIconBitmap(
2811 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002812 } catch (Exception e) {
2813 Log.w(TAG, "Could not load shortcut icon: " + extra);
2814 }
2815 }
2816 }
2817
Michael Jurkac9d95c52011-08-29 14:03:34 -07002818 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002819
2820 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002821 if (fallbackIcon != null) {
2822 icon = fallbackIcon;
2823 } else {
2824 icon = getFallbackIcon();
2825 info.usingFallbackIcon = true;
2826 }
Joe Onorato56d82912010-03-07 14:32:10 -05002827 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08002828 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05002829
Joe Onorato0589f0f2010-02-08 13:44:00 -08002830 info.title = name;
2831 info.intent = intent;
2832 info.customIcon = customIcon;
2833 info.iconResource = iconResource;
2834
2835 return info;
2836 }
2837
Winson Chungaac01e12011-08-17 10:37:13 -07002838 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2839 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08002840 // If apps can't be on SD, don't even bother.
2841 if (!mAppsCanBeOnExternalStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07002842 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08002843 }
Joe Onorato56d82912010-03-07 14:32:10 -05002844 // If this icon doesn't have a custom icon, check to see
2845 // what's stored in the DB, and if it doesn't match what
2846 // we're going to show, store what we are going to show back
2847 // into the DB. We do this so when we're loading, if the
2848 // package manager can't find an icon (for example because
2849 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07002850 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07002851 cache.put(info, c.getBlob(iconIndex));
2852 return true;
2853 }
2854 return false;
2855 }
2856 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2857 boolean needSave = false;
2858 try {
2859 if (data != null) {
2860 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2861 Bitmap loaded = info.getIcon(mIconCache);
2862 needSave = !saved.sameAs(loaded);
2863 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05002864 needSave = true;
2865 }
Winson Chungaac01e12011-08-17 10:37:13 -07002866 } catch (Exception e) {
2867 needSave = true;
2868 }
2869 if (needSave) {
2870 Log.d(TAG, "going to save icon bitmap for info=" + info);
2871 // This is slower than is ideal, but this only happens once
2872 // or when the app is updated with a new icon.
2873 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05002874 }
2875 }
2876
Joe Onorato9c1289c2009-08-17 11:03:03 -04002877 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07002878 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04002879 * or make a new one.
2880 */
Adam Cohendf2cc412011-04-27 16:56:57 -07002881 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002882 // See if a placeholder was created for us already
2883 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07002884 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002885 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07002886 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002887 folders.put(id, folderInfo);
2888 }
Adam Cohendf2cc412011-04-27 16:56:57 -07002889 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002890 }
2891
Winson Chung11904872012-09-17 16:58:46 -07002892 public static final Comparator<ApplicationInfo> getAppNameComparator() {
2893 final Collator collator = Collator.getInstance();
2894 return new Comparator<ApplicationInfo>() {
2895 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2896 int result = collator.compare(a.title.toString(), b.title.toString());
2897 if (result == 0) {
2898 result = a.componentName.compareTo(b.componentName);
2899 }
2900 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07002901 }
Winson Chung11904872012-09-17 16:58:46 -07002902 };
2903 }
Winson Chung78403fe2011-01-21 15:38:02 -08002904 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2905 = new Comparator<ApplicationInfo>() {
2906 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2907 if (a.firstInstallTime < b.firstInstallTime) return 1;
2908 if (a.firstInstallTime > b.firstInstallTime) return -1;
2909 return 0;
2910 }
2911 };
Winson Chung11904872012-09-17 16:58:46 -07002912 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
2913 final Collator collator = Collator.getInstance();
2914 return new Comparator<AppWidgetProviderInfo>() {
2915 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
2916 return collator.compare(a.label.toString(), b.label.toString());
2917 }
2918 };
2919 }
Winson Chung5308f242011-08-18 12:12:41 -07002920 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
2921 if (info.activityInfo != null) {
2922 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
2923 } else {
2924 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
2925 }
2926 }
Winson Chung785d2eb2011-04-14 16:08:02 -07002927 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07002928 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07002929 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07002930 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07002931 ShortcutNameComparator(PackageManager pm) {
2932 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07002933 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07002934 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07002935 }
2936 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
2937 mPackageManager = pm;
2938 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07002939 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07002940 }
2941 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002942 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07002943 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
2944 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
2945 if (mLabelCache.containsKey(keyA)) {
2946 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002947 } else {
2948 labelA = a.loadLabel(mPackageManager).toString();
2949
Winson Chung5308f242011-08-18 12:12:41 -07002950 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002951 }
Winson Chung5308f242011-08-18 12:12:41 -07002952 if (mLabelCache.containsKey(keyB)) {
2953 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002954 } else {
2955 labelB = b.loadLabel(mPackageManager).toString();
2956
Winson Chung5308f242011-08-18 12:12:41 -07002957 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002958 }
Winson Chung11904872012-09-17 16:58:46 -07002959 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07002960 }
2961 };
Winson Chung1ed747a2011-05-03 16:18:34 -07002962 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07002963 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07002964 private PackageManager mPackageManager;
2965 private HashMap<Object, String> mLabelCache;
2966 WidgetAndShortcutNameComparator(PackageManager pm) {
2967 mPackageManager = pm;
2968 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07002969 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07002970 }
2971 public final int compare(Object a, Object b) {
2972 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07002973 if (mLabelCache.containsKey(a)) {
2974 labelA = mLabelCache.get(a);
2975 } else {
2976 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002977 ((AppWidgetProviderInfo) a).label :
2978 ((ResolveInfo) a).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002979 mLabelCache.put(a, labelA);
2980 }
2981 if (mLabelCache.containsKey(b)) {
2982 labelB = mLabelCache.get(b);
2983 } else {
2984 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07002985 ((AppWidgetProviderInfo) b).label :
2986 ((ResolveInfo) b).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07002987 mLabelCache.put(b, labelB);
2988 }
Winson Chung11904872012-09-17 16:58:46 -07002989 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07002990 }
2991 };
Joe Onoratobe386092009-11-17 17:32:16 -08002992
2993 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08002994 Log.d(TAG, "mCallbacks=" + mCallbacks);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002995 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
2996 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
2997 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
2998 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04002999 if (mLoaderTask != null) {
3000 mLoaderTask.dumpState();
3001 } else {
3002 Log.d(TAG, "mLoaderTask=null");
3003 }
Joe Onoratobe386092009-11-17 17:32:16 -08003004 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003005}