blob: 8f486e78a0905fdf114621bbeaca38ecf1420449 [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
Winson Chungee055712013-07-30 14:46:24 -070071 private final boolean mAppsCanBeOnRemoveableStorage;
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
Winson Chungee055712013-07-30 14:46:24 -0700175 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
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 }
Winson Chungc9168342013-06-26 14:54:55 -0700268 return null;
269 }
270
Winson Chung997a9232013-07-24 15:33:46 -0700271 public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added) {
272 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
273 addAndBindAddedApps(context, added, cb);
274 }
275 public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added,
Winson Chung64359a52013-07-08 17:17:08 -0700276 final Callbacks callbacks) {
Winson Chung997a9232013-07-24 15:33:46 -0700277 if (added.isEmpty()) {
278 throw new RuntimeException("EMPTY ADDED ARRAY?");
279 }
Winson Chung64359a52013-07-08 17:17:08 -0700280 // Process the newly added applications and add them to the database first
281 Runnable r = new Runnable() {
282 public void run() {
283 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
284 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
285
286 synchronized(sBgLock) {
Winson Chung997a9232013-07-24 15:33:46 -0700287 Iterator<ItemInfo> iter = added.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700288 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700289 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700290 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700291 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700292
293 // Short-circuit this logic if the icon exists somewhere on the workspace
294 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
295 continue;
296 }
297
298 // Add this icon to the db, creating a new page if necessary
Winson Chung156ab5b2013-07-12 14:14:16 -0700299 int startSearchPageIndex = 1;
Winson Chung64359a52013-07-08 17:17:08 -0700300 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung156ab5b2013-07-12 14:14:16 -0700301 name, launchIntent, startSearchPageIndex);
Winson Chung64359a52013-07-08 17:17:08 -0700302 if (coords == null) {
Winson Chung64359a52013-07-08 17:17:08 -0700303 LauncherAppState appState = LauncherAppState.getInstance();
304 LauncherProvider lp = appState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700305
306 // If we can't find a valid position, then just add a new screen.
307 // This takes time so we need to re-queue the add until the new
308 // page is added. Create as many screens as necessary to satisfy
309 // the startSearchPageIndex.
310 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
311 sBgWorkspaceScreens.size());
312 while (numPagesToAdd > 0) {
313 long screenId = lp.generateNewScreenId();
314 // Update the model
315 sBgWorkspaceScreens.add(screenId);
316 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
317 // Save the screen id for binding in the workspace
318 addedWorkspaceScreensFinal.add(screenId);
319 numPagesToAdd--;
320 }
Winson Chung64359a52013-07-08 17:17:08 -0700321 // Find the coordinate again
322 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chungc763c4e2013-07-19 13:49:06 -0700323 name, launchIntent, startSearchPageIndex);
Winson Chung64359a52013-07-08 17:17:08 -0700324 }
325 if (coords == null) {
326 throw new RuntimeException("Coordinates should not be null");
327 }
328
Winson Chung997a9232013-07-24 15:33:46 -0700329 ShortcutInfo shortcutInfo;
330 if (a instanceof ShortcutInfo) {
331 shortcutInfo = (ShortcutInfo) a;
332 } else if (a instanceof ApplicationInfo) {
333 shortcutInfo = ((ApplicationInfo) a).makeShortcut();
334 } else {
335 throw new RuntimeException("Unexpected info type");
336 }
Winson Chung64359a52013-07-08 17:17:08 -0700337 // Add the shortcut to the db
338 addItemToDatabase(context, shortcutInfo,
339 LauncherSettings.Favorites.CONTAINER_DESKTOP,
340 coords.first, coords.second[0], coords.second[1], false);
341 // Save the ShortcutInfo for binding in the workspace
342 addedShortcutsFinal.add(shortcutInfo);
343 }
344 }
345
Winson Chung997a9232013-07-24 15:33:46 -0700346 if (!addedShortcutsFinal.isEmpty()) {
347 runOnMainThread(new Runnable() {
348 public void run() {
349 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
350 if (callbacks == cb && cb != null) {
351 callbacks.bindAddScreens(addedWorkspaceScreensFinal);
352
353 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
354 long lastScreenId = info.screenId;
355 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
356 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
357 for (ItemInfo i : addedShortcutsFinal) {
358 if (i.screenId == lastScreenId) {
359 addAnimated.add(i);
360 } else {
361 addNotAnimated.add(i);
362 }
363 }
364 // We add the items without animation on non-visible pages, and with
365 // animations on the new page (which we will try and snap to).
366 if (!addNotAnimated.isEmpty()) {
367 callbacks.bindItems(addNotAnimated, 0,
368 addNotAnimated.size(), false);
369 }
370 if (!addAnimated.isEmpty()) {
371 callbacks.bindItems(addAnimated, 0,
372 addAnimated.size(), true);
373 }
374 }
Winson Chung64359a52013-07-08 17:17:08 -0700375 }
Winson Chung997a9232013-07-24 15:33:46 -0700376 });
377 }
Winson Chung64359a52013-07-08 17:17:08 -0700378 }
379 };
380 runOnWorkerThread(r);
381 }
382
Joe Onorato56d82912010-03-07 14:32:10 -0500383 public Bitmap getFallbackIcon() {
Joe Onorato0589f0f2010-02-08 13:44:00 -0800384 return Bitmap.createBitmap(mDefaultIcon);
Joe Onoratof99f8c12009-10-31 17:27:36 -0400385 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800386
Winson Chung81b52252012-08-27 15:34:29 -0700387 public void unbindItemInfosAndClearQueuedBindRunnables() {
388 if (sWorkerThread.getThreadId() == Process.myTid()) {
389 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
390 "main thread");
391 }
392
393 // Clear any deferred bind runnables
394 mDeferredBindRunnables.clear();
395 // Remove any queued bind runnables
396 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
397 // Unbind all the workspace items
398 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700399 }
400
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700401 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700402 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700403 // Ensure that we don't use the same workspace items data structure on the main thread
404 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700405 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
406 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700407 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700408 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
409 tmpAppWidgets.addAll(sBgAppWidgets);
410 }
411 Runnable r = new Runnable() {
412 @Override
413 public void run() {
414 for (ItemInfo item : tmpWorkspaceItems) {
415 item.unbind();
416 }
417 for (ItemInfo item : tmpAppWidgets) {
418 item.unbind();
419 }
420 }
421 };
422 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700423 }
424
Joe Onorato9c1289c2009-08-17 11:03:03 -0400425 /**
426 * Adds an item to the DB if it was not created previously, or move it to a new
427 * <container, screen, cellX, cellY>
428 */
429 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700430 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400431 if (item.container == ItemInfo.NO_ID) {
432 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700433 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400434 } else {
435 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700436 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800437 }
438 }
439
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700440 static void checkItemInfoLocked(
441 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
442 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
443 if (modelItem != null && item != modelItem) {
444 // check all the data is consistent
445 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
446 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
447 ShortcutInfo shortcut = (ShortcutInfo) item;
448 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
449 modelShortcut.intent.filterEquals(shortcut.intent) &&
450 modelShortcut.id == shortcut.id &&
451 modelShortcut.itemType == shortcut.itemType &&
452 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700453 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700454 modelShortcut.cellX == shortcut.cellX &&
455 modelShortcut.cellY == shortcut.cellY &&
456 modelShortcut.spanX == shortcut.spanX &&
457 modelShortcut.spanY == shortcut.spanY &&
458 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
459 (modelShortcut.dropPos != null &&
460 shortcut.dropPos != null &&
461 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
462 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
463 // For all intents and purposes, this is the same object
464 return;
465 }
466 }
467
468 // the modelItem needs to match up perfectly with item if our model is
469 // to be consistent with the database-- for now, just require
470 // modelItem == item or the equality check above
471 String msg = "item: " + ((item != null) ? item.toString() : "null") +
472 "modelItem: " +
473 ((modelItem != null) ? modelItem.toString() : "null") +
474 "Error: ItemInfo passed to checkItemInfo doesn't match original";
475 RuntimeException e = new RuntimeException(msg);
476 if (stackTrace != null) {
477 e.setStackTrace(stackTrace);
478 }
Adam Cohene25af792013-06-06 23:08:25 -0700479 // TODO: something breaks this in the upgrade path
480 //throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700481 }
482 }
483
Michael Jurka816474f2012-06-25 14:49:02 -0700484 static void checkItemInfo(final ItemInfo item) {
485 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
486 final long itemId = item.id;
487 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700488 public void run() {
489 synchronized (sBgLock) {
490 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700491 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700492 }
493 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700494 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700495 }
496
Michael Jurkac9d95c52011-08-29 14:03:34 -0700497 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
498 final ItemInfo item, final String callingFunction) {
499 final long itemId = item.id;
500 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
501 final ContentResolver cr = context.getContentResolver();
502
Adam Cohen487f7dd2012-06-28 18:12:10 -0700503 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700504 Runnable r = new Runnable() {
505 public void run() {
506 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700507 updateItemArrays(item, itemId, stackTrace);
508 }
509 };
510 runOnWorkerThread(r);
511 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700512
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700513 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
514 final ArrayList<ItemInfo> items, final String callingFunction) {
515 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700516
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700517 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
518 Runnable r = new Runnable() {
519 public void run() {
520 ArrayList<ContentProviderOperation> ops =
521 new ArrayList<ContentProviderOperation>();
522 int count = items.size();
523 for (int i = 0; i < count; i++) {
524 ItemInfo item = items.get(i);
525 final long itemId = item.id;
526 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
527 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700528
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700529 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
530 updateItemArrays(item, itemId, stackTrace);
531
532 }
533 try {
534 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
535 } catch (Exception e) {
536 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700537 }
538 }
539 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700540 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700541 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700542
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700543 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
544 // Lock on mBgLock *after* the db operation
545 synchronized (sBgLock) {
546 checkItemInfoLocked(itemId, item, stackTrace);
547
548 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
549 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
550 // Item is in a folder, make sure this folder exists
551 if (!sBgFolders.containsKey(item.container)) {
552 // An items container is being set to a that of an item which is not in
553 // the list of Folders.
554 String msg = "item: " + item + " container being set to: " +
555 item.container + ", not in the list of folders";
556 Log.e(TAG, msg);
557 Launcher.dumpDebugLogsToConsole();
558 }
559 }
560
561 // Items are added/removed from the corresponding FolderInfo elsewhere, such
562 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
563 // that are on the desktop, as appropriate
564 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
565 if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
566 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
567 switch (modelItem.itemType) {
568 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
569 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
570 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
571 if (!sBgWorkspaceItems.contains(modelItem)) {
572 sBgWorkspaceItems.add(modelItem);
573 }
574 break;
575 default:
576 break;
577 }
578 } else {
579 sBgWorkspaceItems.remove(modelItem);
580 }
581 }
582 }
583
Michael Jurkac7700af2013-05-14 20:17:58 +0200584 public void flushWorkerThread() {
585 mFlushingWorkerThread = true;
586 Runnable waiter = new Runnable() {
587 public void run() {
588 synchronized (this) {
589 notifyAll();
590 mFlushingWorkerThread = false;
591 }
592 }
593 };
594
595 synchronized(waiter) {
596 runOnWorkerThread(waiter);
597 if (mLoaderTask != null) {
598 synchronized(mLoaderTask) {
599 mLoaderTask.notify();
600 }
601 }
602 boolean success = false;
603 while (!success) {
604 try {
605 waiter.wait();
606 success = true;
607 } catch (InterruptedException e) {
608 }
609 }
610 }
611 }
612
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800613 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400614 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700615 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700616 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700617 final long screenId, final int cellX, final int cellY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700618 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
Adam Cohendcd297f2013-06-18 13:13:40 -0700619 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
620 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Adam Cohen487f7dd2012-06-28 18:12:10 -0700621 Launcher.sDumpLogs.add(transaction);
622 Log.d(TAG, transaction);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400623 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400624 item.cellX = cellX;
625 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700626
Winson Chung3d503fb2011-07-13 17:25:49 -0700627 // We store hotseat items in canonical form which is this orientation invariant position
628 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700629 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700630 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700631 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700632 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700633 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700634 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400635
636 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400637 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700638 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
639 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700640 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400641
Michael Jurkac9d95c52011-08-29 14:03:34 -0700642 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700643 }
644
645 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700646 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
647 * cellX, cellY have already been updated on the ItemInfos.
648 */
649 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
650 final long container, final int screen) {
651
652 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
653 int count = items.size();
654
655 for (int i = 0; i < count; i++) {
656 ItemInfo item = items.get(i);
657 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700658 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700659 + ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", "
660 + item.cellX + ", " + item.cellY + ")";
661 Launcher.sDumpLogs.add(transaction);
662 item.container = container;
663
664 // We store hotseat items in canonical form which is this orientation invariant position
665 // in the hotseat
666 if (context instanceof Launcher && screen < 0 &&
667 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700668 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700669 item.cellY);
670 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700671 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700672 }
673
674 final ContentValues values = new ContentValues();
675 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
676 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
677 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700678 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700679
680 contentValues.add(values);
681 }
682 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
683 }
684
685 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700686 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800687 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700688 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700689 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700690 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
Adam Cohendcd297f2013-06-18 13:13:40 -0700691 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
692 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Adam Cohen487f7dd2012-06-28 18:12:10 -0700693 Launcher.sDumpLogs.add(transaction);
694 Log.d(TAG, transaction);
Adam Cohend4844c32011-02-18 19:25:06 -0800695 item.cellX = cellX;
696 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700697 item.spanX = spanX;
698 item.spanY = spanY;
699
700 // We store hotseat items in canonical form which is this orientation invariant position
701 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700702 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700703 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700704 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700705 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700706 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700707 }
Adam Cohend4844c32011-02-18 19:25:06 -0800708
Adam Cohend4844c32011-02-18 19:25:06 -0800709 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800710 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700711 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
712 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
713 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
714 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700715 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800716
Michael Jurka816474f2012-06-25 14:49:02 -0700717 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700718 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700719
720 /**
721 * Update an item to the database in a specified container.
722 */
723 static void updateItemInDatabase(Context context, final ItemInfo item) {
724 final ContentValues values = new ContentValues();
725 item.onAddToDatabase(values);
726 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
727 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800728 }
729
730 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400731 * Returns true if the shortcuts already exists in the database.
732 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800733 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400734 static boolean shortcutExists(Context context, String title, Intent intent) {
735 final ContentResolver cr = context.getContentResolver();
736 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
737 new String[] { "title", "intent" }, "title=? and intent=?",
738 new String[] { title, intent.toUri(0) }, null);
739 boolean result = false;
740 try {
741 result = c.moveToFirst();
742 } finally {
743 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800744 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400745 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700746 }
747
Joe Onorato9c1289c2009-08-17 11:03:03 -0400748 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700749 * Returns an ItemInfo array containing all the items in the LauncherModel.
750 * The ItemInfo.id is not set through this function.
751 */
752 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
753 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
754 final ContentResolver cr = context.getContentResolver();
755 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
756 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
757 LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
758 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
759
760 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
761 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
762 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
763 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
764 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
765 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
766 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
767
768 try {
769 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700770 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700771 item.cellX = c.getInt(cellXIndex);
772 item.cellY = c.getInt(cellYIndex);
773 item.spanX = c.getInt(spanXIndex);
774 item.spanY = c.getInt(spanYIndex);
775 item.container = c.getInt(containerIndex);
776 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700777 item.screenId = c.getInt(screenIndex);
Winson Chungaafa03c2010-06-11 17:34:16 -0700778
779 items.add(item);
780 }
781 } catch (Exception e) {
782 items.clear();
783 } finally {
784 c.close();
785 }
786
787 return items;
788 }
789
790 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400791 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
792 */
793 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
794 final ContentResolver cr = context.getContentResolver();
795 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
796 "_id=? and (itemType=? or itemType=?)",
797 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700798 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700799
Joe Onorato9c1289c2009-08-17 11:03:03 -0400800 try {
801 if (c.moveToFirst()) {
802 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
803 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
804 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
805 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
806 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
807 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800808
Joe Onorato9c1289c2009-08-17 11:03:03 -0400809 FolderInfo folderInfo = null;
810 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700811 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
812 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400813 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700814 }
815
Joe Onorato9c1289c2009-08-17 11:03:03 -0400816 folderInfo.title = c.getString(titleIndex);
817 folderInfo.id = id;
818 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700819 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700820 folderInfo.cellX = c.getInt(cellXIndex);
821 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400822
823 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700824 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400825 } finally {
826 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700827 }
828
829 return null;
830 }
831
Joe Onorato9c1289c2009-08-17 11:03:03 -0400832 /**
833 * Add an item to the database in a specified container. Sets the container, screen, cellX and
834 * cellY fields of the item. Also assigns an ID to the item.
835 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700836 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700837 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400838 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400839 item.cellX = cellX;
840 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700841 // We store hotseat items in canonical form which is this orientation invariant position
842 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700843 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700844 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700845 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700846 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700847 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700848 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400849
850 final ContentValues values = new ContentValues();
851 final ContentResolver cr = context.getContentResolver();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400852 item.onAddToDatabase(values);
853
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400854 LauncherAppState app = LauncherAppState.getInstance();
Adam Cohendcd297f2013-06-18 13:13:40 -0700855 item.id = app.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700856 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -0700857 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -0700858
Michael Jurkac9d95c52011-08-29 14:03:34 -0700859 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700860 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700861 String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700862 + item.id + " (" + container + ", " + screenId + ", " + cellX + ", "
Adam Cohen487f7dd2012-06-28 18:12:10 -0700863 + cellY + ")";
864 Launcher.sDumpLogs.add(transaction);
865 Log.d(TAG, transaction);
866
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700867 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
868 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400869
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700870 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700871 synchronized (sBgLock) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700872 checkItemInfoLocked(item.id, item, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700873 sBgItemsIdMap.put(item.id, item);
874 switch (item.itemType) {
875 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
876 sBgFolders.put(item.id, (FolderInfo) item);
877 // Fall through
878 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
879 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
880 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
881 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
882 sBgWorkspaceItems.add(item);
883 } else {
884 if (!sBgFolders.containsKey(item.container)) {
885 // Adding an item to a folder that doesn't exist.
886 String msg = "adding item: " + item + " to a folder that " +
887 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -0700888 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700889 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700890 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700891 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700892 break;
893 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
894 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
895 break;
896 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700897 }
898 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700899 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700900 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700901 }
902
Joe Onorato9c1289c2009-08-17 11:03:03 -0400903 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700904 * Creates a new unique child id, for a given cell span across all layouts.
905 */
Michael Jurka845ba3b2010-09-28 17:09:46 -0700906 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -0700907 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -0700908 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -0700909 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -0700910 }
911
Adam Cohend22015c2010-07-26 22:02:18 -0700912 static int getCellCountX() {
913 return mCellCountX;
Winson Chungaafa03c2010-06-11 17:34:16 -0700914 }
915
Adam Cohend22015c2010-07-26 22:02:18 -0700916 static int getCellCountY() {
917 return mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700918 }
919
920 /**
921 * Updates the model orientation helper to take into account the current layout dimensions
922 * when performing local/canonical coordinate transformations.
923 */
924 static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
Adam Cohend22015c2010-07-26 22:02:18 -0700925 mCellCountX = shortAxisCellCount;
926 mCellCountY = longAxisCellCount;
Winson Chungaafa03c2010-06-11 17:34:16 -0700927 }
928
929 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -0700930 * Removes the specified item from the database
931 * @param context
932 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -0400933 */
Michael Jurkac9d95c52011-08-29 14:03:34 -0700934 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400935 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700936 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -0700937
Michael Jurka83df1882011-08-31 20:59:26 -0700938 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700939 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700940 String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700941 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX +
Adam Cohen487f7dd2012-06-28 18:12:10 -0700942 ", " + item.cellY + ")";
943 Launcher.sDumpLogs.add(transaction);
944 Log.d(TAG, transaction);
945
Michael Jurkac9d95c52011-08-29 14:03:34 -0700946 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700947
948 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700949 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700950 switch (item.itemType) {
951 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
952 sBgFolders.remove(item.id);
953 for (ItemInfo info: sBgItemsIdMap.values()) {
954 if (info.container == item.id) {
955 // We are deleting a folder which still contains items that
956 // think they are contained by that folder.
957 String msg = "deleting a folder (" + item + ") which still " +
958 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -0700959 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700960 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700961 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700962 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700963 sBgWorkspaceItems.remove(item);
964 break;
965 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
966 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
967 sBgWorkspaceItems.remove(item);
968 break;
969 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
970 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
971 break;
972 }
973 sBgItemsIdMap.remove(item.id);
974 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700975 }
976 }
Michael Jurka83df1882011-08-31 20:59:26 -0700977 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700978 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400979 }
980
981 /**
Adam Cohendcd297f2013-06-18 13:13:40 -0700982 * Update the order of the workspace screens in the database. The array list contains
983 * a list of screen ids in the order that they should appear.
984 */
Winson Chungc9168342013-06-26 14:54:55 -0700985 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chung64359a52013-07-08 17:17:08 -0700986 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -0700987 final ContentResolver cr = context.getContentResolver();
988 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
989
990 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -0700991 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -0700992 while (iter.hasNext()) {
993 long id = iter.next();
994 if (id < 0) {
995 iter.remove();
996 }
997 }
998
999 Runnable r = new Runnable() {
1000 @Override
1001 public void run() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001002 // Clear the table
1003 cr.delete(uri, null, null);
1004 int count = screens.size();
1005 ContentValues[] values = new ContentValues[count];
1006 for (int i = 0; i < count; i++) {
1007 ContentValues v = new ContentValues();
1008 long screenId = screens.get(i);
1009 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1010 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 values[i] = v;
1012 }
1013 cr.bulkInsert(uri, values);
1014 sBgWorkspaceScreens.clear();
1015 sBgWorkspaceScreens.addAll(screensCopy);
1016 }
1017 };
1018 runOnWorkerThread(r);
1019 }
1020
1021 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001022 * Remove the contents of the specified folder from the database
1023 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001024 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001025 final ContentResolver cr = context.getContentResolver();
1026
Michael Jurkac9d95c52011-08-29 14:03:34 -07001027 Runnable r = new Runnable() {
1028 public void run() {
1029 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001030 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001031 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001032 sBgItemsIdMap.remove(info.id);
1033 sBgFolders.remove(info.id);
1034 sBgDbIconCache.remove(info);
1035 sBgWorkspaceItems.remove(info);
1036 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001037
Michael Jurkac9d95c52011-08-29 14:03:34 -07001038 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1039 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001040 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001041 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001042 for (ItemInfo childInfo : info.contents) {
1043 sBgItemsIdMap.remove(childInfo.id);
1044 sBgDbIconCache.remove(childInfo);
1045 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001046 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001047 }
1048 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001049 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001050 }
1051
1052 /**
1053 * Set this as the current Launcher activity object for the loader.
1054 */
1055 public void initialize(Callbacks callbacks) {
1056 synchronized (mLock) {
1057 mCallbacks = new WeakReference<Callbacks>(callbacks);
1058 }
1059 }
1060
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001061 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001062 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1063 * ACTION_PACKAGE_CHANGED.
1064 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001065 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001066 public void onReceive(Context context, Intent intent) {
Joe Onorato36115782010-06-17 13:28:48 -04001067 if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001068
Joe Onorato36115782010-06-17 13:28:48 -04001069 final String action = intent.getAction();
Joe Onoratof99f8c12009-10-31 17:27:36 -04001070
Joe Onorato36115782010-06-17 13:28:48 -04001071 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
1072 || Intent.ACTION_PACKAGE_REMOVED.equals(action)
1073 || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1074 final String packageName = intent.getData().getSchemeSpecificPart();
1075 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001076
Joe Onorato36115782010-06-17 13:28:48 -04001077 int op = PackageUpdatedTask.OP_NONE;
1078
1079 if (packageName == null || packageName.length() == 0) {
1080 // they sent us a bad intent
1081 return;
1082 }
1083
1084 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1085 op = PackageUpdatedTask.OP_UPDATE;
1086 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1087 if (!replacing) {
1088 op = PackageUpdatedTask.OP_REMOVE;
1089 }
1090 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1091 // later, we will update the package at this time
1092 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1093 if (!replacing) {
1094 op = PackageUpdatedTask.OP_ADD;
1095 } else {
1096 op = PackageUpdatedTask.OP_UPDATE;
1097 }
1098 }
1099
1100 if (op != PackageUpdatedTask.OP_NONE) {
1101 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
1102 }
1103
1104 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Joe Onoratocec58332010-10-07 14:37:40 -04001105 // First, schedule to add these apps back in.
1106 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1107 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
1108 // Then, rebind everything.
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001109 startLoaderFromBackground();
Joe Onorato36115782010-06-17 13:28:48 -04001110 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1111 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1112 enqueuePackageUpdated(new PackageUpdatedTask(
1113 PackageUpdatedTask.OP_UNAVAILABLE, packages));
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001114 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001115 // If we have changed locale we need to clear out the labels in all apps/workspace.
1116 forceReload();
1117 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1118 // Check if configuration change was an mcc/mnc change which would affect app resources
1119 // and we would need to clear out the labels in all apps/workspace. Same handling as
1120 // above for ACTION_LOCALE_CHANGED
1121 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001122 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001123 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001124 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001125 forceReload();
1126 }
1127 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001128 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001129 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1130 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001131 if (mCallbacks != null) {
1132 Callbacks callbacks = mCallbacks.get();
1133 if (callbacks != null) {
1134 callbacks.bindSearchablesChanged();
1135 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001136 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001137 }
1138 }
1139
Reena Lee93f824a2011-09-23 17:20:28 -07001140 private void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001141 resetLoadedState(true, true);
1142
Reena Lee93f824a2011-09-23 17:20:28 -07001143 // Do this here because if the launcher activity is running it will be restarted.
1144 // If it's not running startLoaderFromBackground will merely tell it that it needs
1145 // to reload.
1146 startLoaderFromBackground();
1147 }
1148
Winson Chungf0c6ae02012-03-21 16:10:31 -07001149 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1150 synchronized (mLock) {
1151 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1152 // mWorkspaceLoaded to true later
1153 stopLoaderLocked();
1154 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1155 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1156 }
1157 }
1158
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001159 /**
1160 * When the launcher is in the background, it's possible for it to miss paired
1161 * configuration changes. So whenever we trigger the loader from the background
1162 * tell the launcher that it needs to re-run the loader when it comes back instead
1163 * of doing it now.
1164 */
1165 public void startLoaderFromBackground() {
1166 boolean runLoader = false;
1167 if (mCallbacks != null) {
1168 Callbacks callbacks = mCallbacks.get();
1169 if (callbacks != null) {
1170 // Only actually run the loader if they're not paused.
1171 if (!callbacks.setLoadOnResume()) {
1172 runLoader = true;
1173 }
1174 }
1175 }
1176 if (runLoader) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001177 startLoader(false, -1);
Joe Onorato790c2d92010-06-11 00:14:11 -07001178 }
Joe Onorato36115782010-06-17 13:28:48 -04001179 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001180
Reena Lee93f824a2011-09-23 17:20:28 -07001181 // If there is already a loader task running, tell it to stop.
1182 // returns true if isLaunching() was true on the old task
1183 private boolean stopLoaderLocked() {
1184 boolean isLaunching = false;
1185 LoaderTask oldTask = mLoaderTask;
1186 if (oldTask != null) {
1187 if (oldTask.isLaunching()) {
1188 isLaunching = true;
1189 }
1190 oldTask.stopLocked();
1191 }
1192 return isLaunching;
1193 }
1194
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001195 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Joe Onorato36115782010-06-17 13:28:48 -04001196 synchronized (mLock) {
1197 if (DEBUG_LOADERS) {
1198 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1199 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001200
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001201 // Clear any deferred bind-runnables from the synchronized load process
1202 // We must do this before any loading/binding is scheduled below.
1203 mDeferredBindRunnables.clear();
1204
Joe Onorato36115782010-06-17 13:28:48 -04001205 // Don't bother to start the thread if we know it's not going to do anything
1206 if (mCallbacks != null && mCallbacks.get() != null) {
1207 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001208 // also, don't downgrade isLaunching if we're already running
1209 isLaunching = isLaunching || stopLoaderLocked();
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001210 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001211 if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
1212 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1213 } else {
1214 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1215 sWorker.post(mLoaderTask);
1216 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001217 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001218 }
1219 }
1220
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001221 void bindRemainingSynchronousPages() {
1222 // Post the remaining side pages to be loaded
1223 if (!mDeferredBindRunnables.isEmpty()) {
1224 for (final Runnable r : mDeferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001225 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001226 }
1227 mDeferredBindRunnables.clear();
1228 }
1229 }
1230
Joe Onorato36115782010-06-17 13:28:48 -04001231 public void stopLoader() {
1232 synchronized (mLock) {
1233 if (mLoaderTask != null) {
1234 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001235 }
1236 }
Joe Onorato36115782010-06-17 13:28:48 -04001237 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001238
Michael Jurkac57b7a82011-08-09 22:02:20 -07001239 public boolean isAllAppsLoaded() {
1240 return mAllAppsLoaded;
1241 }
1242
Winson Chung36a62fe2012-05-06 18:04:42 -07001243 boolean isLoadingWorkspace() {
1244 synchronized (mLock) {
1245 if (mLoaderTask != null) {
1246 return mLoaderTask.isLoadingWorkspace();
1247 }
1248 }
1249 return false;
1250 }
1251
Joe Onorato36115782010-06-17 13:28:48 -04001252 /**
1253 * Runnable for the thread that loads the contents of the launcher:
1254 * - workspace icons
1255 * - widgets
1256 * - all apps icons
1257 */
1258 private class LoaderTask implements Runnable {
1259 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001260 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001261 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001262 private boolean mStopped;
1263 private boolean mLoadAndBindStepFinished;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001264
Winson Chungc3eecff2011-07-11 17:44:15 -07001265 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001266
1267 LoaderTask(Context context, boolean isLaunching) {
1268 mContext = context;
1269 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001270 mLabelCache = new HashMap<Object, CharSequence>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001271 }
1272
Joe Onorato36115782010-06-17 13:28:48 -04001273 boolean isLaunching() {
1274 return mIsLaunching;
1275 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001276
Winson Chung36a62fe2012-05-06 18:04:42 -07001277 boolean isLoadingWorkspace() {
1278 return mIsLoadingAndBindingWorkspace;
1279 }
1280
Winson Chungc763c4e2013-07-19 13:49:06 -07001281 /** Returns whether this is an upgrade path */
1282 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001283 mIsLoadingAndBindingWorkspace = true;
1284
Joe Onorato36115782010-06-17 13:28:48 -04001285 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001286 if (DEBUG_LOADERS) {
1287 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001288 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001289
Winson Chungc763c4e2013-07-19 13:49:06 -07001290 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001291 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001292 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001293 synchronized (LoaderTask.this) {
1294 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001295 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001296 }
1297 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001298 }
1299 }
1300
Joe Onorato36115782010-06-17 13:28:48 -04001301 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001302 bindWorkspace(-1, isUpgradePath);
1303 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001304 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001305
Joe Onorato36115782010-06-17 13:28:48 -04001306 private void waitForIdle() {
1307 // Wait until the either we're stopped or the other threads are done.
1308 // This way we don't start loading all apps until the workspace has settled
1309 // down.
1310 synchronized (LoaderTask.this) {
1311 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001312
Joe Onorato36115782010-06-17 13:28:48 -04001313 mHandler.postIdle(new Runnable() {
1314 public void run() {
1315 synchronized (LoaderTask.this) {
1316 mLoadAndBindStepFinished = true;
1317 if (DEBUG_LOADERS) {
1318 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001319 }
Joe Onorato36115782010-06-17 13:28:48 -04001320 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001321 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001322 }
Joe Onorato36115782010-06-17 13:28:48 -04001323 });
1324
Michael Jurkac7700af2013-05-14 20:17:58 +02001325 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001326 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001327 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1328 // wait no longer than 1sec at a time
1329 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001330 } catch (InterruptedException ex) {
1331 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001332 }
1333 }
Joe Onorato36115782010-06-17 13:28:48 -04001334 if (DEBUG_LOADERS) {
1335 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001336 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001337 + "ms for previous step to finish binding");
1338 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001339 }
Joe Onorato36115782010-06-17 13:28:48 -04001340 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001341
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001342 void runBindSynchronousPage(int synchronousBindPage) {
1343 if (synchronousBindPage < 0) {
1344 // Ensure that we have a valid page index to load synchronously
1345 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1346 "valid page index");
1347 }
1348 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1349 // Ensure that we don't try and bind a specified page when the pages have not been
1350 // loaded already (we should load everything asynchronously in that case)
1351 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1352 }
1353 synchronized (mLock) {
1354 if (mIsLoaderTaskRunning) {
1355 // Ensure that we are never running the background loading at this point since
1356 // we also touch the background collections
1357 throw new RuntimeException("Error! Background loading is already running");
1358 }
1359 }
1360
1361 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1362 // data structures, we can't allow any other thread to touch that data, but because
1363 // this call is synchronous, we can get away with not locking).
1364
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001365 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001366 // operations from the previous activity. We need to ensure that all queued operations
1367 // are executed before any synchronous binding work is done.
1368 mHandler.flush();
1369
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001370 // Divide the set of loaded items into those that we are binding synchronously, and
1371 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001372 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001373 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1374 // arise from that.
1375 onlyBindAllApps();
1376 }
1377
Joe Onorato36115782010-06-17 13:28:48 -04001378 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001379 boolean isUpgrade = false;
1380
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001381 synchronized (mLock) {
1382 mIsLoaderTaskRunning = true;
1383 }
Joe Onorato36115782010-06-17 13:28:48 -04001384 // Optimize for end-user experience: if the Launcher is up and // running with the
1385 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1386 // workspace first (default).
1387 final Callbacks cbk = mCallbacks.get();
Joe Onorato36115782010-06-17 13:28:48 -04001388 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001389 // Elevate priority when Home launches for the first time to avoid
1390 // starving at boot time. Staring at a blank home is not cool.
1391 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001392 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1393 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001394 android.os.Process.setThreadPriority(mIsLaunching
1395 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1396 }
Winson Chung64359a52013-07-08 17:17:08 -07001397 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001398 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001399
Joe Onorato36115782010-06-17 13:28:48 -04001400 if (mStopped) {
1401 break keep_running;
1402 }
1403
1404 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1405 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001406 synchronized (mLock) {
1407 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001408 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001409 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410 }
1411 }
Joe Onorato36115782010-06-17 13:28:48 -04001412 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001413
1414 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001415 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1416 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001417
1418 // Restore the default thread priority after we are done loading items
1419 synchronized (mLock) {
1420 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1421 }
Joe Onorato36115782010-06-17 13:28:48 -04001422 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001423
Winson Chungaac01e12011-08-17 10:37:13 -07001424 // Update the saved icons if necessary
1425 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001426 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001427 for (Object key : sBgDbIconCache.keySet()) {
1428 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1429 }
1430 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001431 }
Winson Chungaac01e12011-08-17 10:37:13 -07001432
Winson Chungc763c4e2013-07-19 13:49:06 -07001433 // Ensure that all the applications that are in the system are represented on the home
1434 // screen.
1435 if (!isUpgrade) {
1436 verifyApplications();
1437 }
1438
Joe Onorato36115782010-06-17 13:28:48 -04001439 // Clear out this reference, otherwise we end up holding it until all of the
1440 // callback runnables are done.
1441 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001442
Joe Onorato36115782010-06-17 13:28:48 -04001443 synchronized (mLock) {
1444 // If we are still the last one to be scheduled, remove ourselves.
1445 if (mLoaderTask == this) {
1446 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001447 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001448 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001449 }
Joe Onorato36115782010-06-17 13:28:48 -04001450 }
1451
1452 public void stopLocked() {
1453 synchronized (LoaderTask.this) {
1454 mStopped = true;
1455 this.notify();
1456 }
1457 }
1458
1459 /**
1460 * Gets the callbacks object. If we've been stopped, or if the launcher object
1461 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1462 * object that was around when the deferred message was scheduled, and if there's
1463 * a new Callbacks object around then also return null. This will save us from
1464 * calling onto it with data that will be ignored.
1465 */
1466 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1467 synchronized (mLock) {
1468 if (mStopped) {
1469 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001470 }
Joe Onorato36115782010-06-17 13:28:48 -04001471
1472 if (mCallbacks == null) {
1473 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001474 }
Joe Onorato36115782010-06-17 13:28:48 -04001475
1476 final Callbacks callbacks = mCallbacks.get();
1477 if (callbacks != oldCallbacks) {
1478 return null;
1479 }
1480 if (callbacks == null) {
1481 Log.w(TAG, "no mCallbacks");
1482 return null;
1483 }
1484
1485 return callbacks;
1486 }
1487 }
1488
Winson Chungc763c4e2013-07-19 13:49:06 -07001489 private void verifyApplications() {
1490 final Context context = mApp.getContext();
1491
1492 // Cross reference all the applications in our apps list with items in the workspace
1493 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001494 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001495 synchronized (sBgLock) {
1496 for (ApplicationInfo app : mBgAllAppsList.data) {
1497 tmpInfos = getItemInfoForComponentName(app.componentName);
1498 if (tmpInfos.isEmpty()) {
1499 // We are missing an application icon, so add this to the workspace
1500 added.add(app);
1501 // This is a rare event, so lets log it
1502 Log.e(TAG, "Missing Application on load: " + app);
1503 }
1504 }
1505 }
1506 if (!added.isEmpty()) {
1507 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1508 addAndBindAddedApps(context, added, cb);
1509 }
1510 }
1511
Joe Onorato36115782010-06-17 13:28:48 -04001512 // check & update map of what's occupied; used to discard overlapping/invalid items
Adam Cohendcd297f2013-06-18 13:13:40 -07001513 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
1514 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001515 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001516 if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
1517 if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1518 [(int) item.screenId][0] != null) {
1519 Log.e(TAG, "Error loading shortcut into hotseat " + item
1520 + " into position (" + item.screenId + ":" + item.cellX + ","
1521 + item.cellY + ") occupied by "
1522 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1523 [(int) item.screenId][0]);
1524 return false;
1525 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001526 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001527 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1528 items[(int) item.screenId][0] = item;
1529 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001530 return true;
1531 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001532 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1533 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001534 return true;
1535 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001536
Adam Cohendcd297f2013-06-18 13:13:40 -07001537 if (!occupied.containsKey(item.screenId)) {
1538 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1539 occupied.put(item.screenId, items);
1540 }
1541
1542 ItemInfo[][] screens = occupied.get(item.screenId);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001543 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001544 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1545 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001546 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001547 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001548 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001549 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001550 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001551 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001552 return false;
1553 }
1554 }
1555 }
1556 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1557 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001558 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001559 }
1560 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001561
Joe Onorato36115782010-06-17 13:28:48 -04001562 return true;
1563 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001564
Winson Chungc763c4e2013-07-19 13:49:06 -07001565 /** Returns whether this is an upgradge path */
1566 private boolean loadWorkspace() {
Joe Onorato36115782010-06-17 13:28:48 -04001567 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001568
Joe Onorato36115782010-06-17 13:28:48 -04001569 final Context context = mContext;
1570 final ContentResolver contentResolver = context.getContentResolver();
1571 final PackageManager manager = context.getPackageManager();
1572 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1573 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001574
Michael Jurkab85f8a42012-04-25 15:48:32 -07001575 // Make sure the default workspace is loaded, if needed
Winson Chungc763c4e2013-07-19 13:49:06 -07001576 mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
Adam Cohene25af792013-06-06 23:08:25 -07001577
Winson Chungc763c4e2013-07-19 13:49:06 -07001578 // Check if we need to do any upgrade-path logic
1579 boolean loadedOldDb = mApp.getLauncherProvider().justLoadedOldDb();
Michael Jurkab85f8a42012-04-25 15:48:32 -07001580
Winson Chung2abf94d2012-07-18 18:16:38 -07001581 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001582 sBgWorkspaceItems.clear();
1583 sBgAppWidgets.clear();
1584 sBgFolders.clear();
1585 sBgItemsIdMap.clear();
1586 sBgDbIconCache.clear();
Adam Cohendcd297f2013-06-18 13:13:40 -07001587 sBgWorkspaceScreens.clear();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001588
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001589 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001590 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Adam Cohene25af792013-06-06 23:08:25 -07001591 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001592
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001593 // +1 for the hotseat (it can be larger than the workspace)
1594 // Load workspace in reverse order to ensure that latest items are loaded first (and
1595 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001596 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001597
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001598 try {
1599 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1600 final int intentIndex = c.getColumnIndexOrThrow
1601 (LauncherSettings.Favorites.INTENT);
1602 final int titleIndex = c.getColumnIndexOrThrow
1603 (LauncherSettings.Favorites.TITLE);
1604 final int iconTypeIndex = c.getColumnIndexOrThrow(
1605 LauncherSettings.Favorites.ICON_TYPE);
1606 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1607 final int iconPackageIndex = c.getColumnIndexOrThrow(
1608 LauncherSettings.Favorites.ICON_PACKAGE);
1609 final int iconResourceIndex = c.getColumnIndexOrThrow(
1610 LauncherSettings.Favorites.ICON_RESOURCE);
1611 final int containerIndex = c.getColumnIndexOrThrow(
1612 LauncherSettings.Favorites.CONTAINER);
1613 final int itemTypeIndex = c.getColumnIndexOrThrow(
1614 LauncherSettings.Favorites.ITEM_TYPE);
1615 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1616 LauncherSettings.Favorites.APPWIDGET_ID);
1617 final int screenIndex = c.getColumnIndexOrThrow(
1618 LauncherSettings.Favorites.SCREEN);
1619 final int cellXIndex = c.getColumnIndexOrThrow
1620 (LauncherSettings.Favorites.CELLX);
1621 final int cellYIndex = c.getColumnIndexOrThrow
1622 (LauncherSettings.Favorites.CELLY);
1623 final int spanXIndex = c.getColumnIndexOrThrow
1624 (LauncherSettings.Favorites.SPANX);
1625 final int spanYIndex = c.getColumnIndexOrThrow(
1626 LauncherSettings.Favorites.SPANY);
1627 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1628 //final int displayModeIndex = c.getColumnIndexOrThrow(
1629 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001630
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001631 ShortcutInfo info;
1632 String intentDescription;
1633 LauncherAppWidgetInfo appWidgetInfo;
1634 int container;
1635 long id;
1636 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001637
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001638 while (!mStopped && c.moveToNext()) {
1639 try {
1640 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001641
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001642 switch (itemType) {
1643 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1644 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001645 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001646 intentDescription = c.getString(intentIndex);
1647 try {
1648 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001649 ComponentName cn = intent.getComponent();
Winson Chung1323b482013-08-05 12:41:55 -07001650 if (!isValidPackageComponent(manager, cn)) {
Winson Chungee055712013-07-30 14:46:24 -07001651 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chung1323b482013-08-05 12:41:55 -07001652 // Log the invalid package, and remove it from the db
1653 Uri uri = LauncherSettings.Favorites.getContentUri(id,
1654 false);
Winson Chungee055712013-07-30 14:46:24 -07001655 contentResolver.delete(uri, null, null);
Winson Chung1323b482013-08-05 12:41:55 -07001656 Log.e(TAG, "Invalid package removed: " + cn);
Winson Chungee055712013-07-30 14:46:24 -07001657 } else {
Winson Chung1323b482013-08-05 12:41:55 -07001658 // If apps can be on external storage, then we just
1659 // leave them for the user to remove (maybe add
1660 // visual treatment to it)
1661 Log.e(TAG, "Invalid package found: " + cn);
Winson Chungee055712013-07-30 14:46:24 -07001662 }
1663 continue;
1664 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001665 } catch (URISyntaxException e) {
1666 continue;
1667 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001668
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001669 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1670 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1671 titleIndex, mLabelCache);
1672 } else {
1673 info = getShortcutInfo(c, context, iconTypeIndex,
1674 iconPackageIndex, iconResourceIndex, iconIndex,
1675 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001676
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001677 // App shortcuts that used to be automatically added to Launcher
1678 // didn't always have the correct intent flags set, so do that
1679 // here
1680 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001681 intent.getCategories() != null &&
1682 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001683 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001684 intent.addFlags(
1685 Intent.FLAG_ACTIVITY_NEW_TASK |
1686 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1687 }
Michael Jurka96879562012-03-22 05:54:33 -07001688 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001689
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001690 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07001691 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001692 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001693 container = c.getInt(containerIndex);
1694 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001695 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001696 info.cellX = c.getInt(cellXIndex);
1697 info.cellY = c.getInt(cellYIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001698 // check & update map of what's occupied
1699 if (!checkItemPlacement(occupied, info)) {
1700 break;
1701 }
1702
1703 switch (container) {
1704 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1705 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1706 sBgWorkspaceItems.add(info);
1707 break;
1708 default:
1709 // Item is in a user folder
1710 FolderInfo folderInfo =
1711 findOrMakeFolder(sBgFolders, container);
1712 folderInfo.add(info);
1713 break;
1714 }
1715 sBgItemsIdMap.put(info.id, info);
1716
1717 // now that we've loaded everthing re-save it with the
1718 // icon in case it disappears somehow.
1719 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07001720 } else {
1721 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001722 }
1723 break;
1724
1725 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1726 id = c.getLong(idIndex);
1727 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1728
1729 folderInfo.title = c.getString(titleIndex);
1730 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001731 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001732 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001733 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001734 folderInfo.cellX = c.getInt(cellXIndex);
1735 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001736
Daniel Sandler8802e962010-05-26 16:28:16 -04001737 // check & update map of what's occupied
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001738 if (!checkItemPlacement(occupied, folderInfo)) {
Daniel Sandler8802e962010-05-26 16:28:16 -04001739 break;
1740 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001741 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001742 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1743 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1744 sBgWorkspaceItems.add(folderInfo);
1745 break;
Joe Onorato36115782010-06-17 13:28:48 -04001746 }
Joe Onorato17a89222011-02-08 17:26:11 -08001747
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001748 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1749 sBgFolders.put(folderInfo.id, folderInfo);
1750 break;
1751
1752 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1753 // Read all Launcher-specific widget details
1754 int appWidgetId = c.getInt(appWidgetIdIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001755 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001756
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001757 final AppWidgetProviderInfo provider =
1758 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001759
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001760 if (!isSafeMode && (provider == null || provider.provider == null ||
1761 provider.provider.getPackageName() == null)) {
1762 String log = "Deleting widget that isn't installed anymore: id="
1763 + id + " appWidgetId=" + appWidgetId;
1764 Log.e(TAG, log);
1765 Launcher.sDumpLogs.add(log);
1766 itemsToRemove.add(id);
1767 } else {
1768 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1769 provider.provider);
1770 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07001771 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001772 appWidgetInfo.cellX = c.getInt(cellXIndex);
1773 appWidgetInfo.cellY = c.getInt(cellYIndex);
1774 appWidgetInfo.spanX = c.getInt(spanXIndex);
1775 appWidgetInfo.spanY = c.getInt(spanYIndex);
1776 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1777 appWidgetInfo.minSpanX = minSpan[0];
1778 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001779
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001780 container = c.getInt(containerIndex);
1781 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1782 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1783 Log.e(TAG, "Widget found where container != " +
1784 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1785 continue;
1786 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001787
Adam Cohene25af792013-06-06 23:08:25 -07001788 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001789 // check & update map of what's occupied
1790 if (!checkItemPlacement(occupied, appWidgetInfo)) {
1791 break;
1792 }
1793 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1794 sBgAppWidgets.add(appWidgetInfo);
1795 }
Joe Onorato36115782010-06-17 13:28:48 -04001796 break;
1797 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001798 } catch (Exception e) {
1799 Log.w(TAG, "Desktop items loading interrupted:", e);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001800 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001801 }
1802 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04001803 if (c != null) {
1804 c.close();
1805 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001806 }
1807
1808 if (itemsToRemove.size() > 0) {
1809 ContentProviderClient client = contentResolver.acquireContentProviderClient(
1810 LauncherSettings.Favorites.CONTENT_URI);
1811 // Remove dead items
1812 for (long id : itemsToRemove) {
1813 if (DEBUG_LOADERS) {
1814 Log.d(TAG, "Removed id = " + id);
1815 }
1816 // Don't notify content observers
1817 try {
1818 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1819 null, null);
1820 } catch (RemoteException e) {
1821 Log.w(TAG, "Could not remove id = " + id);
1822 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001823 }
1824 }
1825
Winson Chungc763c4e2013-07-19 13:49:06 -07001826 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001827 long maxScreenId = 0;
1828 // If we're importing we use the old screen order.
1829 for (ItemInfo item: sBgItemsIdMap.values()) {
1830 long screenId = item.screenId;
1831 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1832 !sBgWorkspaceScreens.contains(screenId)) {
1833 sBgWorkspaceScreens.add(screenId);
1834 if (screenId > maxScreenId) {
1835 maxScreenId = screenId;
1836 }
1837 }
1838 }
1839 Collections.sort(sBgWorkspaceScreens);
1840 mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
1841 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07001842
1843 // Update the max item id after we load an old db
1844 long maxItemId = 0;
1845 // If we're importing we use the old screen order.
1846 for (ItemInfo item: sBgItemsIdMap.values()) {
1847 maxItemId = Math.max(maxItemId, item.id);
1848 }
1849 LauncherAppState app = LauncherAppState.getInstance();
1850 app.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07001851 } else {
1852 Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1853 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1854 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1855
1856 try {
1857 final int idIndex = sc.getColumnIndexOrThrow(
1858 LauncherSettings.WorkspaceScreens._ID);
1859 final int rankIndex = sc.getColumnIndexOrThrow(
1860 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1861 while (sc.moveToNext()) {
1862 try {
1863 long screenId = sc.getLong(idIndex);
1864 int rank = sc.getInt(rankIndex);
1865
1866 orderedScreens.put(rank, screenId);
1867 } catch (Exception e) {
1868 Log.w(TAG, "Desktop items loading interrupted:", e);
1869 }
1870 }
1871 } finally {
1872 sc.close();
1873 }
1874
1875 Iterator<Integer> iter = orderedScreens.keySet().iterator();
1876 while (iter.hasNext()) {
1877 sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
1878 }
1879
1880 // Remove any empty screens
1881 ArrayList<Long> unusedScreens = new ArrayList<Long>();
1882 unusedScreens.addAll(sBgWorkspaceScreens);
1883
1884 for (ItemInfo item: sBgItemsIdMap.values()) {
1885 long screenId = item.screenId;
1886
1887 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1888 unusedScreens.contains(screenId)) {
1889 unusedScreens.remove(screenId);
1890 }
1891 }
1892
1893 // If there are any empty screens remove them, and update.
1894 if (unusedScreens.size() != 0) {
1895 sBgWorkspaceScreens.removeAll(unusedScreens);
1896 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1897 }
1898 }
1899
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001900 if (DEBUG_LOADERS) {
1901 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1902 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07001903 int nScreens = occupied.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001904 for (int y = 0; y < mCellCountY; y++) {
1905 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07001906
Daniel Sandler566da102013-06-25 23:43:45 -04001907 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07001908 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001909 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07001910 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001911 line += " | ";
1912 }
1913 for (int x = 0; x < mCellCountX; x++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001914 line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001915 }
Joe Onorato36115782010-06-17 13:28:48 -04001916 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001917 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04001918 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001919 }
Joe Onorato36115782010-06-17 13:28:48 -04001920 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001921 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07001922 }
1923
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001924 /** Filters the set of items who are directly or indirectly (via another container) on the
1925 * specified screen. */
1926 private void filterCurrentWorkspaceItems(int currentScreen,
1927 ArrayList<ItemInfo> allWorkspaceItems,
1928 ArrayList<ItemInfo> currentScreenItems,
1929 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001930 // Purge any null ItemInfos
1931 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1932 while (iter.hasNext()) {
1933 ItemInfo i = iter.next();
1934 if (i == null) {
1935 iter.remove();
1936 }
1937 }
1938
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001939 // If we aren't filtering on a screen, then the set of items to load is the full set of
1940 // items given.
1941 if (currentScreen < 0) {
1942 currentScreenItems.addAll(allWorkspaceItems);
Joe Onorato36115782010-06-17 13:28:48 -04001943 }
1944
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001945 // Order the set of items by their containers first, this allows use to walk through the
1946 // list sequentially, build up a list of containers that are in the specified screen,
1947 // as well as all items in those containers.
1948 Set<Long> itemsOnScreen = new HashSet<Long>();
1949 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1950 @Override
1951 public int compare(ItemInfo lhs, ItemInfo rhs) {
1952 return (int) (lhs.container - rhs.container);
1953 }
1954 });
1955 for (ItemInfo info : allWorkspaceItems) {
1956 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001957 if (info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001958 currentScreenItems.add(info);
1959 itemsOnScreen.add(info.id);
1960 } else {
1961 otherScreenItems.add(info);
1962 }
1963 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1964 currentScreenItems.add(info);
1965 itemsOnScreen.add(info.id);
1966 } else {
1967 if (itemsOnScreen.contains(info.container)) {
1968 currentScreenItems.add(info);
1969 itemsOnScreen.add(info.id);
1970 } else {
1971 otherScreenItems.add(info);
1972 }
1973 }
1974 }
1975 }
1976
1977 /** Filters the set of widgets which are on the specified screen. */
1978 private void filterCurrentAppWidgets(int currentScreen,
1979 ArrayList<LauncherAppWidgetInfo> appWidgets,
1980 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1981 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1982 // If we aren't filtering on a screen, then the set of items to load is the full set of
1983 // widgets given.
1984 if (currentScreen < 0) {
1985 currentScreenWidgets.addAll(appWidgets);
1986 }
1987
1988 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001989 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001990 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07001991 widget.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001992 currentScreenWidgets.add(widget);
1993 } else {
1994 otherScreenWidgets.add(widget);
1995 }
1996 }
1997 }
1998
1999 /** Filters the set of folders which are on the specified screen. */
2000 private void filterCurrentFolders(int currentScreen,
2001 HashMap<Long, ItemInfo> itemsIdMap,
2002 HashMap<Long, FolderInfo> folders,
2003 HashMap<Long, FolderInfo> currentScreenFolders,
2004 HashMap<Long, FolderInfo> otherScreenFolders) {
2005 // If we aren't filtering on a screen, then the set of items to load is the full set of
2006 // widgets given.
2007 if (currentScreen < 0) {
2008 currentScreenFolders.putAll(folders);
2009 }
2010
2011 for (long id : folders.keySet()) {
2012 ItemInfo info = itemsIdMap.get(id);
2013 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002014 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002015 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07002016 info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002017 currentScreenFolders.put(id, folder);
2018 } else {
2019 otherScreenFolders.put(id, folder);
2020 }
2021 }
2022 }
2023
2024 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2025 * right) */
2026 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
2027 // XXX: review this
2028 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002029 @Override
2030 public int compare(ItemInfo lhs, ItemInfo rhs) {
2031 int cellCountX = LauncherModel.getCellCountX();
2032 int cellCountY = LauncherModel.getCellCountY();
2033 int screenOffset = cellCountX * cellCountY;
2034 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002035 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002036 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002037 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002038 rhs.cellY * cellCountX + rhs.cellX);
2039 return (int) (lr - rr);
2040 }
2041 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002042 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002043
Adam Cohendcd297f2013-06-18 13:13:40 -07002044 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2045 final ArrayList<Long> orderedScreens) {
2046
2047 final Runnable r = new Runnable() {
2048 @Override
2049 public void run() {
2050 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2051 if (callbacks != null) {
2052 callbacks.bindScreens(orderedScreens);
2053 }
2054 }
2055 };
2056 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2057 }
2058
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002059 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2060 final ArrayList<ItemInfo> workspaceItems,
2061 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2062 final HashMap<Long, FolderInfo> folders,
2063 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002064
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002065 final boolean postOnMainThread = (deferredBindRunnables != null);
2066
2067 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002068 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002069 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002070 final int start = i;
2071 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002072 final Runnable r = new Runnable() {
2073 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002074 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002075 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002076 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002077 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2078 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002079 }
2080 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002081 };
2082 if (postOnMainThread) {
2083 deferredBindRunnables.add(r);
2084 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002085 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002086 }
Joe Onorato36115782010-06-17 13:28:48 -04002087 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002088
2089 // Bind the folders
2090 if (!folders.isEmpty()) {
2091 final Runnable r = new Runnable() {
2092 public void run() {
2093 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2094 if (callbacks != null) {
2095 callbacks.bindFolders(folders);
2096 }
2097 }
2098 };
2099 if (postOnMainThread) {
2100 deferredBindRunnables.add(r);
2101 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002102 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002103 }
2104 }
2105
2106 // Bind the widgets, one at a time
2107 N = appWidgets.size();
2108 for (int i = 0; i < N; i++) {
2109 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2110 final Runnable r = new Runnable() {
2111 public void run() {
2112 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2113 if (callbacks != null) {
2114 callbacks.bindAppWidget(widget);
2115 }
2116 }
2117 };
2118 if (postOnMainThread) {
2119 deferredBindRunnables.add(r);
2120 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002121 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002122 }
2123 }
2124 }
2125
2126 /**
2127 * Binds all loaded data to actual views on the main thread.
2128 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002129 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002130 final long t = SystemClock.uptimeMillis();
2131 Runnable r;
2132
2133 // Don't use these two variables in any of the callback runnables.
2134 // Otherwise we hold a reference to them.
2135 final Callbacks oldCallbacks = mCallbacks.get();
2136 if (oldCallbacks == null) {
2137 // This launcher has exited and nobody bothered to tell us. Just bail.
2138 Log.w(TAG, "LoaderTask running with no launcher");
2139 return;
2140 }
2141
Winson Chung4a2afa32012-07-19 14:53:05 -07002142 final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
2143 final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002144 oldCallbacks.getCurrentWorkspaceScreen();
2145
2146 // Load all the items that are on the current page first (and in the process, unbind
2147 // all the existing workspace items before we call startBinding() below.
2148 unbindWorkspaceItemsOnMainThread();
2149 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2150 ArrayList<LauncherAppWidgetInfo> appWidgets =
2151 new ArrayList<LauncherAppWidgetInfo>();
2152 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2153 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002154 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002155 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002156 workspaceItems.addAll(sBgWorkspaceItems);
2157 appWidgets.addAll(sBgAppWidgets);
2158 folders.putAll(sBgFolders);
2159 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002160 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002161 }
2162
2163 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2164 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2165 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2166 new ArrayList<LauncherAppWidgetInfo>();
2167 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2168 new ArrayList<LauncherAppWidgetInfo>();
2169 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2170 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2171
2172 // Separate the items that are on the current screen, and all the other remaining items
2173 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
2174 otherWorkspaceItems);
2175 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
2176 otherAppWidgets);
2177 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
2178 otherFolders);
2179 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2180 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2181
2182 // Tell the workspace that we're about to start binding items
2183 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002184 public void run() {
2185 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2186 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002187 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002188 }
2189 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002190 };
Winson Chung81b52252012-08-27 15:34:29 -07002191 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002192
Adam Cohendcd297f2013-06-18 13:13:40 -07002193 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2194
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002195 // Load items on the current page
2196 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2197 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002198 if (isLoadingSynchronously) {
2199 r = new Runnable() {
2200 public void run() {
2201 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2202 if (callbacks != null) {
2203 callbacks.onPageBoundSynchronously(currentScreen);
2204 }
2205 }
2206 };
Winson Chung81b52252012-08-27 15:34:29 -07002207 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002208 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002209
Winson Chung4a2afa32012-07-19 14:53:05 -07002210 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2211 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002212 mDeferredBindRunnables.clear();
2213 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002214 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002215
2216 // Tell the workspace that we're done binding items
2217 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002218 public void run() {
2219 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2220 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002221 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002222 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002223
Winson Chung98e030b2012-05-07 16:01:11 -07002224 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002225 if (DEBUG_LOADERS) {
2226 Log.d(TAG, "bound workspace in "
2227 + (SystemClock.uptimeMillis()-t) + "ms");
2228 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002229
2230 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002231 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002232 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002233 if (isLoadingSynchronously) {
2234 mDeferredBindRunnables.add(r);
2235 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002236 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002237 }
Joe Onorato36115782010-06-17 13:28:48 -04002238 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002239
Joe Onorato36115782010-06-17 13:28:48 -04002240 private void loadAndBindAllApps() {
2241 if (DEBUG_LOADERS) {
2242 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2243 }
2244 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002245 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002246 synchronized (LoaderTask.this) {
2247 if (mStopped) {
2248 return;
2249 }
2250 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002251 }
Joe Onorato36115782010-06-17 13:28:48 -04002252 } else {
2253 onlyBindAllApps();
2254 }
2255 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002256
Joe Onorato36115782010-06-17 13:28:48 -04002257 private void onlyBindAllApps() {
2258 final Callbacks oldCallbacks = mCallbacks.get();
2259 if (oldCallbacks == null) {
2260 // This launcher has exited and nobody bothered to tell us. Just bail.
2261 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2262 return;
2263 }
2264
2265 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002266 @SuppressWarnings("unchecked")
Joe Onorato36115782010-06-17 13:28:48 -04002267 final ArrayList<ApplicationInfo> list
Adam Cohen487f7dd2012-06-28 18:12:10 -07002268 = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002269 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002270 public void run() {
2271 final long t = SystemClock.uptimeMillis();
2272 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2273 if (callbacks != null) {
2274 callbacks.bindAllApplications(list);
2275 }
2276 if (DEBUG_LOADERS) {
2277 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2278 + (SystemClock.uptimeMillis()-t) + "ms");
2279 }
2280 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002281 };
2282 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002283 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002284 r.run();
2285 } else {
2286 mHandler.post(r);
2287 }
Joe Onorato36115782010-06-17 13:28:48 -04002288 }
2289
Winson Chung64359a52013-07-08 17:17:08 -07002290 private void loadAllApps() {
2291 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002292
2293 // Don't use these two variables in any of the callback runnables.
2294 // Otherwise we hold a reference to them.
2295 final Callbacks oldCallbacks = mCallbacks.get();
2296 if (oldCallbacks == null) {
2297 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002298 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002299 return;
2300 }
2301
Winson Chung64359a52013-07-08 17:17:08 -07002302 final PackageManager packageManager = mContext.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04002303 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2304 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2305
Winson Chung64359a52013-07-08 17:17:08 -07002306 // Clear the list of apps
2307 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002308
Winson Chung64359a52013-07-08 17:17:08 -07002309 // Query for the set of apps
2310 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2311 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2312 if (DEBUG_LOADERS) {
2313 Log.d(TAG, "queryIntentActivities took "
2314 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2315 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2316 }
2317 // Fail if we don't have any apps
2318 if (apps == null || apps.isEmpty()) {
2319 return;
2320 }
2321 // Sort the applications by name
2322 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2323 Collections.sort(apps,
2324 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2325 if (DEBUG_LOADERS) {
2326 Log.d(TAG, "sort took "
2327 + (SystemClock.uptimeMillis()-sortTime) + "ms");
Joe Onorato9c1289c2009-08-17 11:03:03 -04002328 }
2329
Winson Chung64359a52013-07-08 17:17:08 -07002330 // Create the ApplicationInfos
2331 final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2332 for (int i = 0; i < apps.size(); i++) {
2333 // This builds the icon bitmaps.
2334 mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
2335 mIconCache, mLabelCache));
2336 }
2337
2338 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2339 final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
2340 mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
2341
2342 // Post callback on main thread
2343 mHandler.post(new Runnable() {
2344 public void run() {
2345 final long bindTime = SystemClock.uptimeMillis();
2346 if (callbacks != null) {
2347 callbacks.bindAllApplications(added);
2348 if (DEBUG_LOADERS) {
2349 Log.d(TAG, "bound " + added.size() + " apps in "
2350 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2351 }
2352 } else {
2353 Log.i(TAG, "not binding apps: no Launcher activity");
2354 }
2355 }
2356 });
2357
Joe Onorato36115782010-06-17 13:28:48 -04002358 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002359 Log.d(TAG, "Icons processed in "
2360 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002361 }
2362 }
2363
2364 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002365 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002366 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2367 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2368 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2369 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2370 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2371 }
Joe Onorato36115782010-06-17 13:28:48 -04002372 }
2373 }
2374
2375 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002376 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002377 }
2378
2379 private class PackageUpdatedTask implements Runnable {
2380 int mOp;
2381 String[] mPackages;
2382
2383 public static final int OP_NONE = 0;
2384 public static final int OP_ADD = 1;
2385 public static final int OP_UPDATE = 2;
2386 public static final int OP_REMOVE = 3; // uninstlled
2387 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2388
2389
2390 public PackageUpdatedTask(int op, String[] packages) {
2391 mOp = op;
2392 mPackages = packages;
2393 }
2394
2395 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002396 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002397
2398 final String[] packages = mPackages;
2399 final int N = packages.length;
2400 switch (mOp) {
2401 case OP_ADD:
2402 for (int i=0; i<N; i++) {
2403 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002404 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002405 }
2406 break;
2407 case OP_UPDATE:
2408 for (int i=0; i<N; i++) {
2409 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002410 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002411 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002412 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002413 }
2414 break;
2415 case OP_REMOVE:
2416 case OP_UNAVAILABLE:
2417 for (int i=0; i<N; i++) {
2418 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002419 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002420 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002421 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002422 }
2423 break;
2424 }
2425
2426 ArrayList<ApplicationInfo> added = null;
Joe Onorato36115782010-06-17 13:28:48 -04002427 ArrayList<ApplicationInfo> modified = null;
Winson Chung83892cc2013-05-01 16:53:33 -07002428 final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002429
Adam Cohen487f7dd2012-06-28 18:12:10 -07002430 if (mBgAllAppsList.added.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002431 added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
2432 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002433 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002434 if (mBgAllAppsList.modified.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002435 modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
2436 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002437 }
Winson Chung5d55f332012-07-16 20:45:03 -07002438 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002439 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002440 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002441 }
2442
Joe Onorato36115782010-06-17 13:28:48 -04002443 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2444 if (callbacks == null) {
2445 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2446 return;
2447 }
2448
2449 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002450 // Ensure that we add all the workspace applications to the db
Winson Chung997a9232013-07-24 15:33:46 -07002451 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Winson Chung64359a52013-07-08 17:17:08 -07002452 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
Winson Chung997a9232013-07-24 15:33:46 -07002453 addAndBindAddedApps(context, addedInfos, cb);
Joe Onorato36115782010-06-17 13:28:48 -04002454 }
2455 if (modified != null) {
2456 final ArrayList<ApplicationInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002457
2458 // Update the launcher db to reflect the changes
2459 for (ApplicationInfo a : modifiedFinal) {
2460 ArrayList<ItemInfo> infos =
2461 getItemInfoForComponentName(a.componentName);
2462 for (ItemInfo i : infos) {
2463 if (isShortcutInfoUpdateable(i)) {
2464 ShortcutInfo info = (ShortcutInfo) i;
2465 info.title = a.title.toString();
2466 updateItemInDatabase(context, info);
2467 }
2468 }
2469 }
2470
Joe Onorato36115782010-06-17 13:28:48 -04002471 mHandler.post(new Runnable() {
2472 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002473 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2474 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002475 callbacks.bindAppsUpdated(modifiedFinal);
2476 }
2477 }
2478 });
2479 }
Winson Chung83892cc2013-05-01 16:53:33 -07002480 // If a package has been removed, or an app has been removed as a result of
2481 // an update (for example), make the removed callback.
2482 if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
Winson Chung64359a52013-07-08 17:17:08 -07002483 final boolean packageRemoved = (mOp == OP_REMOVE);
Winson Chung83892cc2013-05-01 16:53:33 -07002484 final ArrayList<String> removedPackageNames =
2485 new ArrayList<String>(Arrays.asList(packages));
2486
Winson Chung64359a52013-07-08 17:17:08 -07002487 // Update the launcher db to reflect the removal of apps
2488 if (packageRemoved) {
2489 for (String pn : removedPackageNames) {
2490 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2491 for (ItemInfo i : infos) {
2492 deleteItemFromDatabase(context, i);
2493 }
2494 }
2495 } else {
2496 for (ApplicationInfo a : removedApps) {
2497 ArrayList<ItemInfo> infos =
2498 getItemInfoForComponentName(a.componentName);
2499 for (ItemInfo i : infos) {
2500 deleteItemFromDatabase(context, i);
2501 }
2502 }
2503 }
2504
Joe Onorato36115782010-06-17 13:28:48 -04002505 mHandler.post(new Runnable() {
2506 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002507 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2508 if (callbacks == cb && cb != null) {
Winson Chung83892cc2013-05-01 16:53:33 -07002509 callbacks.bindComponentsRemoved(removedPackageNames,
Winson Chung64359a52013-07-08 17:17:08 -07002510 removedApps, packageRemoved);
Joe Onorato36115782010-06-17 13:28:48 -04002511 }
2512 }
2513 });
Joe Onoratobe386092009-11-17 17:32:16 -08002514 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002515
Michael Jurkac402cd92013-05-20 15:49:32 +02002516 final ArrayList<Object> widgetsAndShortcuts =
2517 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002518 mHandler.post(new Runnable() {
2519 @Override
2520 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002521 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2522 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002523 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002524 }
2525 }
2526 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002527 }
2528 }
2529
Michael Jurkac402cd92013-05-20 15:49:32 +02002530 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2531 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2532 PackageManager packageManager = context.getPackageManager();
2533 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2534 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2535 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2536 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2537 Collections.sort(widgetsAndShortcuts,
2538 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2539 return widgetsAndShortcuts;
2540 }
2541
Winson Chung1323b482013-08-05 12:41:55 -07002542 private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) {
Winson Chungee055712013-07-30 14:46:24 -07002543 if (cn == null) {
2544 return false;
2545 }
2546
2547 try {
2548 return (pm.getActivityInfo(cn, 0) != null);
2549 } catch (NameNotFoundException e) {
2550 return false;
2551 }
2552 }
2553
Joe Onorato9c1289c2009-08-17 11:03:03 -04002554 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002555 * This is called from the code that adds shortcuts from the intent receiver. This
2556 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002557 */
Joe Onorato56d82912010-03-07 14:32:10 -05002558 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002559 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002560 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002561
Joe Onorato56d82912010-03-07 14:32:10 -05002562 /**
2563 * Make an ShortcutInfo object for a shortcut that is an application.
2564 *
2565 * If c is not null, then it will be used to fill in missing data like the title and icon.
2566 */
2567 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002568 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002569 ComponentName componentName = intent.getComponent();
Winson Chung1323b482013-08-05 12:41:55 -07002570 final ShortcutInfo info = new ShortcutInfo();
2571 if (!isValidPackageComponent(manager, componentName)) {
Winson Chungee055712013-07-30 14:46:24 -07002572 Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002573 return null;
Winson Chung1323b482013-08-05 12:41:55 -07002574 } else {
2575 try {
2576 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2577 info.initFlagsAndFirstInstallTime(pi);
2578 } catch (NameNotFoundException e) {
2579 Log.d(TAG, "getPackInfo failed for package " +
2580 componentName.getPackageName());
2581 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002582 }
2583
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002584 // TODO: See if the PackageManager knows about this case. If it doesn't
2585 // then return null & delete this.
2586
Joe Onorato56d82912010-03-07 14:32:10 -05002587 // the resource -- This may implicitly give us back the fallback icon,
2588 // but don't worry about that. All we're doing with usingFallbackIcon is
2589 // to avoid saving lots of copies of that in the database, and most apps
2590 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002591
2592 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2593 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2594 // via resolveActivity().
Winson Chungee055712013-07-30 14:46:24 -07002595 Bitmap icon = null;
Winson Chungc208ff92012-03-29 17:37:41 -07002596 ResolveInfo resolveInfo = null;
2597 ComponentName oldComponent = intent.getComponent();
2598 Intent newIntent = new Intent(intent.getAction(), null);
2599 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2600 newIntent.setPackage(oldComponent.getPackageName());
2601 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2602 for (ResolveInfo i : infos) {
2603 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2604 i.activityInfo.name);
2605 if (cn.equals(oldComponent)) {
2606 resolveInfo = i;
2607 }
2608 }
2609 if (resolveInfo == null) {
2610 resolveInfo = manager.resolveActivity(intent, 0);
2611 }
Joe Onorato56d82912010-03-07 14:32:10 -05002612 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002613 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002614 }
Joe Onorato56d82912010-03-07 14:32:10 -05002615 // the db
2616 if (icon == null) {
2617 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002618 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002619 }
2620 }
2621 // the fallback icon
2622 if (icon == null) {
2623 icon = getFallbackIcon();
2624 info.usingFallbackIcon = true;
2625 }
2626 info.setIcon(icon);
2627
2628 // from the resource
2629 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002630 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2631 if (labelCache != null && labelCache.containsKey(key)) {
2632 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002633 } else {
2634 info.title = resolveInfo.activityInfo.loadLabel(manager);
2635 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002636 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002637 }
2638 }
Joe Onorato56d82912010-03-07 14:32:10 -05002639 }
2640 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002641 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002642 if (c != null) {
2643 info.title = c.getString(titleIndex);
2644 }
2645 }
2646 // fall back to the class name of the activity
2647 if (info.title == null) {
2648 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002649 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002650 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2651 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002652 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002653
Winson Chung64359a52013-07-08 17:17:08 -07002654 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2655 ItemInfoFilter f) {
2656 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2657 for (ItemInfo i : infos) {
2658 if (i instanceof ShortcutInfo) {
2659 ShortcutInfo info = (ShortcutInfo) i;
2660 ComponentName cn = info.intent.getComponent();
2661 if (cn != null && f.filterItem(null, info, cn)) {
2662 filtered.add(info);
2663 }
2664 } else if (i instanceof FolderInfo) {
2665 FolderInfo info = (FolderInfo) i;
2666 for (ShortcutInfo s : info.contents) {
2667 ComponentName cn = s.intent.getComponent();
2668 if (cn != null && f.filterItem(info, s, cn)) {
2669 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07002670 }
2671 }
Winson Chung64359a52013-07-08 17:17:08 -07002672 } else if (i instanceof LauncherAppWidgetInfo) {
2673 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2674 ComponentName cn = info.providerName;
2675 if (cn != null && f.filterItem(null, info, cn)) {
2676 filtered.add(info);
2677 }
Winson Chung8a435102012-08-30 17:16:53 -07002678 }
2679 }
Winson Chung64359a52013-07-08 17:17:08 -07002680 return new ArrayList<ItemInfo>(filtered);
2681 }
2682
2683 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
2684 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2685 ItemInfoFilter filter = new ItemInfoFilter() {
2686 @Override
2687 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2688 return cn.getPackageName().equals(pn);
2689 }
2690 };
2691 return filterItemInfos(sBgItemsIdMap.values(), filter);
2692 }
2693
2694 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
2695 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2696 ItemInfoFilter filter = new ItemInfoFilter() {
2697 @Override
2698 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2699 return cn.equals(cname);
2700 }
2701 };
2702 return filterItemInfos(sBgItemsIdMap.values(), filter);
2703 }
2704
2705 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2706 if (i instanceof ShortcutInfo) {
2707 ShortcutInfo info = (ShortcutInfo) i;
2708 // We need to check for ACTION_MAIN otherwise getComponent() might
2709 // return null for some shortcuts (for instance, for shortcuts to
2710 // web pages.)
2711 Intent intent = info.intent;
2712 ComponentName name = intent.getComponent();
2713 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2714 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2715 return true;
2716 }
2717 }
2718 return false;
Winson Chung8a435102012-08-30 17:16:53 -07002719 }
2720
2721 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002722 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002723 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002724 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002725 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2726 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002727
Joe Onorato56d82912010-03-07 14:32:10 -05002728 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002729 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002730 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002731
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002732 // TODO: If there's an explicit component and we can't install that, delete it.
2733
Joe Onorato56d82912010-03-07 14:32:10 -05002734 info.title = c.getString(titleIndex);
2735
Joe Onorato9c1289c2009-08-17 11:03:03 -04002736 int iconType = c.getInt(iconTypeIndex);
2737 switch (iconType) {
2738 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2739 String packageName = c.getString(iconPackageIndex);
2740 String resourceName = c.getString(iconResourceIndex);
2741 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002742 info.customIcon = false;
2743 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002744 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002745 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002746 if (resources != null) {
2747 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002748 icon = Utilities.createIconBitmap(
2749 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002750 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002751 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002752 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002753 }
Joe Onorato56d82912010-03-07 14:32:10 -05002754 // the db
2755 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002756 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002757 }
2758 // the fallback icon
2759 if (icon == null) {
2760 icon = getFallbackIcon();
2761 info.usingFallbackIcon = true;
2762 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002763 break;
2764 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002765 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002766 if (icon == null) {
2767 icon = getFallbackIcon();
2768 info.customIcon = false;
2769 info.usingFallbackIcon = true;
2770 } else {
2771 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002772 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002773 break;
2774 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002775 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002776 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002777 info.customIcon = false;
2778 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002779 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002780 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002781 return info;
2782 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002783
Michael Jurka931dc972011-08-05 15:08:15 -07002784 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002785 @SuppressWarnings("all") // suppress dead code warning
2786 final boolean debug = false;
2787 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002788 Log.d(TAG, "getIconFromCursor app="
2789 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2790 }
2791 byte[] data = c.getBlob(iconIndex);
2792 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002793 return Utilities.createIconBitmap(
2794 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002795 } catch (Exception e) {
2796 return null;
2797 }
2798 }
2799
Winson Chung3d503fb2011-07-13 17:25:49 -07002800 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2801 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002802 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002803 if (info == null) {
2804 return null;
2805 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002806 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002807
2808 return info;
2809 }
2810
Winson Chunga9abd0e2010-10-27 17:18:37 -07002811 /**
Winson Chung55cef262010-10-28 14:14:18 -07002812 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2813 */
2814 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2815 ComponentName component) {
2816 List<AppWidgetProviderInfo> widgets =
2817 AppWidgetManager.getInstance(context).getInstalledProviders();
2818 for (AppWidgetProviderInfo info : widgets) {
2819 if (info.provider.equals(component)) {
2820 return info;
2821 }
2822 }
2823 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002824 }
2825
Winson Chung68846fd2010-10-29 11:00:27 -07002826 /**
2827 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2828 */
2829 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2830 final PackageManager packageManager = context.getPackageManager();
2831 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2832 new ArrayList<WidgetMimeTypeHandlerData>();
2833
2834 final Intent supportsIntent =
2835 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2836 supportsIntent.setType(mimeType);
2837
2838 // Create a set of widget configuration components that we can test against
2839 final List<AppWidgetProviderInfo> widgets =
2840 AppWidgetManager.getInstance(context).getInstalledProviders();
2841 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2842 new HashMap<ComponentName, AppWidgetProviderInfo>();
2843 for (AppWidgetProviderInfo info : widgets) {
2844 configurationComponentToWidget.put(info.configure, info);
2845 }
2846
2847 // Run through each of the intents that can handle this type of clip data, and cross
2848 // reference them with the components that are actual configuration components
2849 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2850 PackageManager.MATCH_DEFAULT_ONLY);
2851 for (ResolveInfo info : activities) {
2852 final ActivityInfo activityInfo = info.activityInfo;
2853 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2854 activityInfo.name);
2855 if (configurationComponentToWidget.containsKey(infoComponent)) {
2856 supportedConfigurationActivities.add(
2857 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2858 configurationComponentToWidget.get(infoComponent)));
2859 }
2860 }
2861 return supportedConfigurationActivities;
2862 }
2863
Winson Chunga9abd0e2010-10-27 17:18:37 -07002864 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08002865 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2866 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2867 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2868
Adam Cohend9198822011-11-22 16:42:47 -08002869 if (intent == null) {
2870 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2871 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2872 return null;
2873 }
2874
Joe Onorato0589f0f2010-02-08 13:44:00 -08002875 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08002876 boolean customIcon = false;
2877 ShortcutIconResource iconResource = null;
2878
2879 if (bitmap != null && bitmap instanceof Bitmap) {
2880 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002881 customIcon = true;
2882 } else {
2883 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2884 if (extra != null && extra instanceof ShortcutIconResource) {
2885 try {
2886 iconResource = (ShortcutIconResource) extra;
2887 final PackageManager packageManager = context.getPackageManager();
2888 Resources resources = packageManager.getResourcesForApplication(
2889 iconResource.packageName);
2890 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002891 icon = Utilities.createIconBitmap(
2892 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002893 } catch (Exception e) {
2894 Log.w(TAG, "Could not load shortcut icon: " + extra);
2895 }
2896 }
2897 }
2898
Michael Jurkac9d95c52011-08-29 14:03:34 -07002899 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002900
2901 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002902 if (fallbackIcon != null) {
2903 icon = fallbackIcon;
2904 } else {
2905 icon = getFallbackIcon();
2906 info.usingFallbackIcon = true;
2907 }
Joe Onorato56d82912010-03-07 14:32:10 -05002908 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08002909 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05002910
Joe Onorato0589f0f2010-02-08 13:44:00 -08002911 info.title = name;
2912 info.intent = intent;
2913 info.customIcon = customIcon;
2914 info.iconResource = iconResource;
2915
2916 return info;
2917 }
2918
Winson Chungaac01e12011-08-17 10:37:13 -07002919 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2920 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08002921 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07002922 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07002923 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08002924 }
Joe Onorato56d82912010-03-07 14:32:10 -05002925 // If this icon doesn't have a custom icon, check to see
2926 // what's stored in the DB, and if it doesn't match what
2927 // we're going to show, store what we are going to show back
2928 // into the DB. We do this so when we're loading, if the
2929 // package manager can't find an icon (for example because
2930 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07002931 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07002932 cache.put(info, c.getBlob(iconIndex));
2933 return true;
2934 }
2935 return false;
2936 }
2937 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2938 boolean needSave = false;
2939 try {
2940 if (data != null) {
2941 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2942 Bitmap loaded = info.getIcon(mIconCache);
2943 needSave = !saved.sameAs(loaded);
2944 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05002945 needSave = true;
2946 }
Winson Chungaac01e12011-08-17 10:37:13 -07002947 } catch (Exception e) {
2948 needSave = true;
2949 }
2950 if (needSave) {
2951 Log.d(TAG, "going to save icon bitmap for info=" + info);
2952 // This is slower than is ideal, but this only happens once
2953 // or when the app is updated with a new icon.
2954 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05002955 }
2956 }
2957
Joe Onorato9c1289c2009-08-17 11:03:03 -04002958 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07002959 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04002960 * or make a new one.
2961 */
Adam Cohendf2cc412011-04-27 16:56:57 -07002962 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002963 // See if a placeholder was created for us already
2964 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07002965 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002966 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07002967 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002968 folders.put(id, folderInfo);
2969 }
Adam Cohendf2cc412011-04-27 16:56:57 -07002970 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002971 }
2972
Winson Chung11904872012-09-17 16:58:46 -07002973 public static final Comparator<ApplicationInfo> getAppNameComparator() {
2974 final Collator collator = Collator.getInstance();
2975 return new Comparator<ApplicationInfo>() {
2976 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2977 int result = collator.compare(a.title.toString(), b.title.toString());
2978 if (result == 0) {
2979 result = a.componentName.compareTo(b.componentName);
2980 }
2981 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07002982 }
Winson Chung11904872012-09-17 16:58:46 -07002983 };
2984 }
Winson Chung78403fe2011-01-21 15:38:02 -08002985 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2986 = new Comparator<ApplicationInfo>() {
2987 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2988 if (a.firstInstallTime < b.firstInstallTime) return 1;
2989 if (a.firstInstallTime > b.firstInstallTime) return -1;
2990 return 0;
2991 }
2992 };
Winson Chung11904872012-09-17 16:58:46 -07002993 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
2994 final Collator collator = Collator.getInstance();
2995 return new Comparator<AppWidgetProviderInfo>() {
2996 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
2997 return collator.compare(a.label.toString(), b.label.toString());
2998 }
2999 };
3000 }
Winson Chung5308f242011-08-18 12:12:41 -07003001 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3002 if (info.activityInfo != null) {
3003 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3004 } else {
3005 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3006 }
3007 }
Winson Chung785d2eb2011-04-14 16:08:02 -07003008 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07003009 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07003010 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07003011 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003012 ShortcutNameComparator(PackageManager pm) {
3013 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07003014 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003015 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003016 }
3017 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
3018 mPackageManager = pm;
3019 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003020 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003021 }
3022 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003023 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07003024 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
3025 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
3026 if (mLabelCache.containsKey(keyA)) {
3027 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003028 } else {
3029 labelA = a.loadLabel(mPackageManager).toString();
3030
Winson Chung5308f242011-08-18 12:12:41 -07003031 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003032 }
Winson Chung5308f242011-08-18 12:12:41 -07003033 if (mLabelCache.containsKey(keyB)) {
3034 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003035 } else {
3036 labelB = b.loadLabel(mPackageManager).toString();
3037
Winson Chung5308f242011-08-18 12:12:41 -07003038 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003039 }
Winson Chung11904872012-09-17 16:58:46 -07003040 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003041 }
3042 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003043 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003044 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003045 private PackageManager mPackageManager;
3046 private HashMap<Object, String> mLabelCache;
3047 WidgetAndShortcutNameComparator(PackageManager pm) {
3048 mPackageManager = pm;
3049 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003050 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003051 }
3052 public final int compare(Object a, Object b) {
3053 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003054 if (mLabelCache.containsKey(a)) {
3055 labelA = mLabelCache.get(a);
3056 } else {
3057 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003058 ((AppWidgetProviderInfo) a).label :
3059 ((ResolveInfo) a).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003060 mLabelCache.put(a, labelA);
3061 }
3062 if (mLabelCache.containsKey(b)) {
3063 labelB = mLabelCache.get(b);
3064 } else {
3065 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003066 ((AppWidgetProviderInfo) b).label :
3067 ((ResolveInfo) b).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003068 mLabelCache.put(b, labelB);
3069 }
Winson Chung11904872012-09-17 16:58:46 -07003070 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003071 }
3072 };
Joe Onoratobe386092009-11-17 17:32:16 -08003073
3074 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003075 Log.d(TAG, "mCallbacks=" + mCallbacks);
Adam Cohen487f7dd2012-06-28 18:12:10 -07003076 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3077 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3078 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3079 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003080 if (mLoaderTask != null) {
3081 mLoaderTask.dumpState();
3082 } else {
3083 Log.d(TAG, "mLoaderTask=null");
3084 }
Joe Onoratobe386092009-11-17 17:32:16 -08003085 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003086}