blob: fc1c1d06aa7ac3496eb60f5c6f62b5a40daa4deb [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;
1494 ArrayList<ApplicationInfo> added = new ArrayList<ApplicationInfo>();
1495 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();
1650 if (!isValidPackage(manager, cn)) {
1651 if (!mAppsCanBeOnRemoveableStorage) {
1652 // Log the invalid package, and remove it from the database
1653 Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
1654 contentResolver.delete(uri, null, null);
1655 Log.e(TAG, "Invalid package removed in loadWorkspace: " + cn);
1656 } else {
1657 // If apps can be on external storage, then we just leave
1658 // them for the user to remove (maybe add treatment to it)
1659 Log.e(TAG, "Invalid package found in loadWorkspace: " + cn);
1660 }
1661 continue;
1662 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001663 } catch (URISyntaxException e) {
1664 continue;
1665 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001666
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001667 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1668 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1669 titleIndex, mLabelCache);
1670 } else {
1671 info = getShortcutInfo(c, context, iconTypeIndex,
1672 iconPackageIndex, iconResourceIndex, iconIndex,
1673 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001674
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001675 // App shortcuts that used to be automatically added to Launcher
1676 // didn't always have the correct intent flags set, so do that
1677 // here
1678 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001679 intent.getCategories() != null &&
1680 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001681 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001682 intent.addFlags(
1683 Intent.FLAG_ACTIVITY_NEW_TASK |
1684 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1685 }
Michael Jurka96879562012-03-22 05:54:33 -07001686 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001687
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001688 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07001689 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001690 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001691 container = c.getInt(containerIndex);
1692 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001693 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001694 info.cellX = c.getInt(cellXIndex);
1695 info.cellY = c.getInt(cellYIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001696 // check & update map of what's occupied
1697 if (!checkItemPlacement(occupied, info)) {
1698 break;
1699 }
1700
1701 switch (container) {
1702 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1703 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1704 sBgWorkspaceItems.add(info);
1705 break;
1706 default:
1707 // Item is in a user folder
1708 FolderInfo folderInfo =
1709 findOrMakeFolder(sBgFolders, container);
1710 folderInfo.add(info);
1711 break;
1712 }
1713 sBgItemsIdMap.put(info.id, info);
1714
1715 // now that we've loaded everthing re-save it with the
1716 // icon in case it disappears somehow.
1717 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001718 }
1719 break;
1720
1721 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1722 id = c.getLong(idIndex);
1723 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1724
1725 folderInfo.title = c.getString(titleIndex);
1726 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001727 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001728 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001729 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001730 folderInfo.cellX = c.getInt(cellXIndex);
1731 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001732
Daniel Sandler8802e962010-05-26 16:28:16 -04001733 // check & update map of what's occupied
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001734 if (!checkItemPlacement(occupied, folderInfo)) {
Daniel Sandler8802e962010-05-26 16:28:16 -04001735 break;
1736 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001737 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001738 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1739 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1740 sBgWorkspaceItems.add(folderInfo);
1741 break;
Joe Onorato36115782010-06-17 13:28:48 -04001742 }
Joe Onorato17a89222011-02-08 17:26:11 -08001743
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001744 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1745 sBgFolders.put(folderInfo.id, folderInfo);
1746 break;
1747
1748 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1749 // Read all Launcher-specific widget details
1750 int appWidgetId = c.getInt(appWidgetIdIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001751 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001752
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001753 final AppWidgetProviderInfo provider =
1754 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001755
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001756 if (!isSafeMode && (provider == null || provider.provider == null ||
1757 provider.provider.getPackageName() == null)) {
1758 String log = "Deleting widget that isn't installed anymore: id="
1759 + id + " appWidgetId=" + appWidgetId;
1760 Log.e(TAG, log);
1761 Launcher.sDumpLogs.add(log);
1762 itemsToRemove.add(id);
1763 } else {
1764 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1765 provider.provider);
1766 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07001767 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001768 appWidgetInfo.cellX = c.getInt(cellXIndex);
1769 appWidgetInfo.cellY = c.getInt(cellYIndex);
1770 appWidgetInfo.spanX = c.getInt(spanXIndex);
1771 appWidgetInfo.spanY = c.getInt(spanYIndex);
1772 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1773 appWidgetInfo.minSpanX = minSpan[0];
1774 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001775
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001776 container = c.getInt(containerIndex);
1777 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1778 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1779 Log.e(TAG, "Widget found where container != " +
1780 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1781 continue;
1782 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001783
Adam Cohene25af792013-06-06 23:08:25 -07001784 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001785 // check & update map of what's occupied
1786 if (!checkItemPlacement(occupied, appWidgetInfo)) {
1787 break;
1788 }
1789 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1790 sBgAppWidgets.add(appWidgetInfo);
1791 }
Joe Onorato36115782010-06-17 13:28:48 -04001792 break;
1793 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001794 } catch (Exception e) {
1795 Log.w(TAG, "Desktop items loading interrupted:", e);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001796 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001797 }
1798 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04001799 if (c != null) {
1800 c.close();
1801 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001802 }
1803
1804 if (itemsToRemove.size() > 0) {
1805 ContentProviderClient client = contentResolver.acquireContentProviderClient(
1806 LauncherSettings.Favorites.CONTENT_URI);
1807 // Remove dead items
1808 for (long id : itemsToRemove) {
1809 if (DEBUG_LOADERS) {
1810 Log.d(TAG, "Removed id = " + id);
1811 }
1812 // Don't notify content observers
1813 try {
1814 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1815 null, null);
1816 } catch (RemoteException e) {
1817 Log.w(TAG, "Could not remove id = " + id);
1818 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001819 }
1820 }
1821
Winson Chungc763c4e2013-07-19 13:49:06 -07001822 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001823 long maxScreenId = 0;
1824 // If we're importing we use the old screen order.
1825 for (ItemInfo item: sBgItemsIdMap.values()) {
1826 long screenId = item.screenId;
1827 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1828 !sBgWorkspaceScreens.contains(screenId)) {
1829 sBgWorkspaceScreens.add(screenId);
1830 if (screenId > maxScreenId) {
1831 maxScreenId = screenId;
1832 }
1833 }
1834 }
1835 Collections.sort(sBgWorkspaceScreens);
1836 mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
1837 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07001838
1839 // Update the max item id after we load an old db
1840 long maxItemId = 0;
1841 // If we're importing we use the old screen order.
1842 for (ItemInfo item: sBgItemsIdMap.values()) {
1843 maxItemId = Math.max(maxItemId, item.id);
1844 }
1845 LauncherAppState app = LauncherAppState.getInstance();
1846 app.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07001847 } else {
1848 Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1849 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1850 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1851
1852 try {
1853 final int idIndex = sc.getColumnIndexOrThrow(
1854 LauncherSettings.WorkspaceScreens._ID);
1855 final int rankIndex = sc.getColumnIndexOrThrow(
1856 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1857 while (sc.moveToNext()) {
1858 try {
1859 long screenId = sc.getLong(idIndex);
1860 int rank = sc.getInt(rankIndex);
1861
1862 orderedScreens.put(rank, screenId);
1863 } catch (Exception e) {
1864 Log.w(TAG, "Desktop items loading interrupted:", e);
1865 }
1866 }
1867 } finally {
1868 sc.close();
1869 }
1870
1871 Iterator<Integer> iter = orderedScreens.keySet().iterator();
1872 while (iter.hasNext()) {
1873 sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
1874 }
1875
1876 // Remove any empty screens
1877 ArrayList<Long> unusedScreens = new ArrayList<Long>();
1878 unusedScreens.addAll(sBgWorkspaceScreens);
1879
1880 for (ItemInfo item: sBgItemsIdMap.values()) {
1881 long screenId = item.screenId;
1882
1883 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1884 unusedScreens.contains(screenId)) {
1885 unusedScreens.remove(screenId);
1886 }
1887 }
1888
1889 // If there are any empty screens remove them, and update.
1890 if (unusedScreens.size() != 0) {
1891 sBgWorkspaceScreens.removeAll(unusedScreens);
1892 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1893 }
1894 }
1895
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001896 if (DEBUG_LOADERS) {
1897 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1898 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07001899 int nScreens = occupied.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001900 for (int y = 0; y < mCellCountY; y++) {
1901 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07001902
Daniel Sandler566da102013-06-25 23:43:45 -04001903 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07001904 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001905 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07001906 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001907 line += " | ";
1908 }
1909 for (int x = 0; x < mCellCountX; x++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001910 line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001911 }
Joe Onorato36115782010-06-17 13:28:48 -04001912 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001913 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04001914 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001915 }
Joe Onorato36115782010-06-17 13:28:48 -04001916 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001917 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07001918 }
1919
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001920 /** Filters the set of items who are directly or indirectly (via another container) on the
1921 * specified screen. */
1922 private void filterCurrentWorkspaceItems(int currentScreen,
1923 ArrayList<ItemInfo> allWorkspaceItems,
1924 ArrayList<ItemInfo> currentScreenItems,
1925 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001926 // Purge any null ItemInfos
1927 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1928 while (iter.hasNext()) {
1929 ItemInfo i = iter.next();
1930 if (i == null) {
1931 iter.remove();
1932 }
1933 }
1934
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001935 // If we aren't filtering on a screen, then the set of items to load is the full set of
1936 // items given.
1937 if (currentScreen < 0) {
1938 currentScreenItems.addAll(allWorkspaceItems);
Joe Onorato36115782010-06-17 13:28:48 -04001939 }
1940
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001941 // Order the set of items by their containers first, this allows use to walk through the
1942 // list sequentially, build up a list of containers that are in the specified screen,
1943 // as well as all items in those containers.
1944 Set<Long> itemsOnScreen = new HashSet<Long>();
1945 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1946 @Override
1947 public int compare(ItemInfo lhs, ItemInfo rhs) {
1948 return (int) (lhs.container - rhs.container);
1949 }
1950 });
1951 for (ItemInfo info : allWorkspaceItems) {
1952 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001953 if (info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001954 currentScreenItems.add(info);
1955 itemsOnScreen.add(info.id);
1956 } else {
1957 otherScreenItems.add(info);
1958 }
1959 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1960 currentScreenItems.add(info);
1961 itemsOnScreen.add(info.id);
1962 } else {
1963 if (itemsOnScreen.contains(info.container)) {
1964 currentScreenItems.add(info);
1965 itemsOnScreen.add(info.id);
1966 } else {
1967 otherScreenItems.add(info);
1968 }
1969 }
1970 }
1971 }
1972
1973 /** Filters the set of widgets which are on the specified screen. */
1974 private void filterCurrentAppWidgets(int currentScreen,
1975 ArrayList<LauncherAppWidgetInfo> appWidgets,
1976 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1977 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1978 // If we aren't filtering on a screen, then the set of items to load is the full set of
1979 // widgets given.
1980 if (currentScreen < 0) {
1981 currentScreenWidgets.addAll(appWidgets);
1982 }
1983
1984 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001985 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001986 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07001987 widget.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001988 currentScreenWidgets.add(widget);
1989 } else {
1990 otherScreenWidgets.add(widget);
1991 }
1992 }
1993 }
1994
1995 /** Filters the set of folders which are on the specified screen. */
1996 private void filterCurrentFolders(int currentScreen,
1997 HashMap<Long, ItemInfo> itemsIdMap,
1998 HashMap<Long, FolderInfo> folders,
1999 HashMap<Long, FolderInfo> currentScreenFolders,
2000 HashMap<Long, FolderInfo> otherScreenFolders) {
2001 // If we aren't filtering on a screen, then the set of items to load is the full set of
2002 // widgets given.
2003 if (currentScreen < 0) {
2004 currentScreenFolders.putAll(folders);
2005 }
2006
2007 for (long id : folders.keySet()) {
2008 ItemInfo info = itemsIdMap.get(id);
2009 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002010 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002011 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07002012 info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002013 currentScreenFolders.put(id, folder);
2014 } else {
2015 otherScreenFolders.put(id, folder);
2016 }
2017 }
2018 }
2019
2020 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2021 * right) */
2022 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
2023 // XXX: review this
2024 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002025 @Override
2026 public int compare(ItemInfo lhs, ItemInfo rhs) {
2027 int cellCountX = LauncherModel.getCellCountX();
2028 int cellCountY = LauncherModel.getCellCountY();
2029 int screenOffset = cellCountX * cellCountY;
2030 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002031 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002032 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002033 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002034 rhs.cellY * cellCountX + rhs.cellX);
2035 return (int) (lr - rr);
2036 }
2037 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002038 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002039
Adam Cohendcd297f2013-06-18 13:13:40 -07002040 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2041 final ArrayList<Long> orderedScreens) {
2042
2043 final Runnable r = new Runnable() {
2044 @Override
2045 public void run() {
2046 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2047 if (callbacks != null) {
2048 callbacks.bindScreens(orderedScreens);
2049 }
2050 }
2051 };
2052 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2053 }
2054
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002055 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2056 final ArrayList<ItemInfo> workspaceItems,
2057 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2058 final HashMap<Long, FolderInfo> folders,
2059 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002060
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002061 final boolean postOnMainThread = (deferredBindRunnables != null);
2062
2063 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002064 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002065 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002066 final int start = i;
2067 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002068 final Runnable r = new Runnable() {
2069 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002070 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002071 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002072 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002073 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2074 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002075 }
2076 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002077 };
2078 if (postOnMainThread) {
2079 deferredBindRunnables.add(r);
2080 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002081 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002082 }
Joe Onorato36115782010-06-17 13:28:48 -04002083 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002084
2085 // Bind the folders
2086 if (!folders.isEmpty()) {
2087 final Runnable r = new Runnable() {
2088 public void run() {
2089 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2090 if (callbacks != null) {
2091 callbacks.bindFolders(folders);
2092 }
2093 }
2094 };
2095 if (postOnMainThread) {
2096 deferredBindRunnables.add(r);
2097 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002098 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002099 }
2100 }
2101
2102 // Bind the widgets, one at a time
2103 N = appWidgets.size();
2104 for (int i = 0; i < N; i++) {
2105 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2106 final Runnable r = new Runnable() {
2107 public void run() {
2108 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2109 if (callbacks != null) {
2110 callbacks.bindAppWidget(widget);
2111 }
2112 }
2113 };
2114 if (postOnMainThread) {
2115 deferredBindRunnables.add(r);
2116 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002117 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002118 }
2119 }
2120 }
2121
2122 /**
2123 * Binds all loaded data to actual views on the main thread.
2124 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002125 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002126 final long t = SystemClock.uptimeMillis();
2127 Runnable r;
2128
2129 // Don't use these two variables in any of the callback runnables.
2130 // Otherwise we hold a reference to them.
2131 final Callbacks oldCallbacks = mCallbacks.get();
2132 if (oldCallbacks == null) {
2133 // This launcher has exited and nobody bothered to tell us. Just bail.
2134 Log.w(TAG, "LoaderTask running with no launcher");
2135 return;
2136 }
2137
Winson Chung4a2afa32012-07-19 14:53:05 -07002138 final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
2139 final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002140 oldCallbacks.getCurrentWorkspaceScreen();
2141
2142 // Load all the items that are on the current page first (and in the process, unbind
2143 // all the existing workspace items before we call startBinding() below.
2144 unbindWorkspaceItemsOnMainThread();
2145 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2146 ArrayList<LauncherAppWidgetInfo> appWidgets =
2147 new ArrayList<LauncherAppWidgetInfo>();
2148 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2149 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002150 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002151 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002152 workspaceItems.addAll(sBgWorkspaceItems);
2153 appWidgets.addAll(sBgAppWidgets);
2154 folders.putAll(sBgFolders);
2155 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002156 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002157 }
2158
2159 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2160 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2161 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2162 new ArrayList<LauncherAppWidgetInfo>();
2163 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2164 new ArrayList<LauncherAppWidgetInfo>();
2165 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2166 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2167
2168 // Separate the items that are on the current screen, and all the other remaining items
2169 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
2170 otherWorkspaceItems);
2171 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
2172 otherAppWidgets);
2173 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
2174 otherFolders);
2175 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2176 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2177
2178 // Tell the workspace that we're about to start binding items
2179 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002180 public void run() {
2181 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2182 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002183 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002184 }
2185 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002186 };
Winson Chung81b52252012-08-27 15:34:29 -07002187 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002188
Adam Cohendcd297f2013-06-18 13:13:40 -07002189 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2190
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002191 // Load items on the current page
2192 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2193 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002194 if (isLoadingSynchronously) {
2195 r = new Runnable() {
2196 public void run() {
2197 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2198 if (callbacks != null) {
2199 callbacks.onPageBoundSynchronously(currentScreen);
2200 }
2201 }
2202 };
Winson Chung81b52252012-08-27 15:34:29 -07002203 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002204 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002205
Winson Chung4a2afa32012-07-19 14:53:05 -07002206 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2207 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002208 mDeferredBindRunnables.clear();
2209 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002210 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002211
2212 // Tell the workspace that we're done binding items
2213 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002214 public void run() {
2215 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2216 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002217 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002218 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002219
Winson Chung98e030b2012-05-07 16:01:11 -07002220 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002221 if (DEBUG_LOADERS) {
2222 Log.d(TAG, "bound workspace in "
2223 + (SystemClock.uptimeMillis()-t) + "ms");
2224 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002225
2226 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002227 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002228 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002229 if (isLoadingSynchronously) {
2230 mDeferredBindRunnables.add(r);
2231 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002232 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002233 }
Joe Onorato36115782010-06-17 13:28:48 -04002234 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002235
Joe Onorato36115782010-06-17 13:28:48 -04002236 private void loadAndBindAllApps() {
2237 if (DEBUG_LOADERS) {
2238 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2239 }
2240 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002241 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002242 synchronized (LoaderTask.this) {
2243 if (mStopped) {
2244 return;
2245 }
2246 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002247 }
Joe Onorato36115782010-06-17 13:28:48 -04002248 } else {
2249 onlyBindAllApps();
2250 }
2251 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002252
Joe Onorato36115782010-06-17 13:28:48 -04002253 private void onlyBindAllApps() {
2254 final Callbacks oldCallbacks = mCallbacks.get();
2255 if (oldCallbacks == null) {
2256 // This launcher has exited and nobody bothered to tell us. Just bail.
2257 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2258 return;
2259 }
2260
2261 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002262 @SuppressWarnings("unchecked")
Joe Onorato36115782010-06-17 13:28:48 -04002263 final ArrayList<ApplicationInfo> list
Adam Cohen487f7dd2012-06-28 18:12:10 -07002264 = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002265 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002266 public void run() {
2267 final long t = SystemClock.uptimeMillis();
2268 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2269 if (callbacks != null) {
2270 callbacks.bindAllApplications(list);
2271 }
2272 if (DEBUG_LOADERS) {
2273 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2274 + (SystemClock.uptimeMillis()-t) + "ms");
2275 }
2276 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002277 };
2278 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002279 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002280 r.run();
2281 } else {
2282 mHandler.post(r);
2283 }
Joe Onorato36115782010-06-17 13:28:48 -04002284 }
2285
Winson Chung64359a52013-07-08 17:17:08 -07002286 private void loadAllApps() {
2287 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002288
2289 // Don't use these two variables in any of the callback runnables.
2290 // Otherwise we hold a reference to them.
2291 final Callbacks oldCallbacks = mCallbacks.get();
2292 if (oldCallbacks == null) {
2293 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002294 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002295 return;
2296 }
2297
Winson Chung64359a52013-07-08 17:17:08 -07002298 final PackageManager packageManager = mContext.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04002299 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2300 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2301
Winson Chung64359a52013-07-08 17:17:08 -07002302 // Clear the list of apps
2303 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002304
Winson Chung64359a52013-07-08 17:17:08 -07002305 // Query for the set of apps
2306 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2307 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2308 if (DEBUG_LOADERS) {
2309 Log.d(TAG, "queryIntentActivities took "
2310 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2311 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2312 }
2313 // Fail if we don't have any apps
2314 if (apps == null || apps.isEmpty()) {
2315 return;
2316 }
2317 // Sort the applications by name
2318 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2319 Collections.sort(apps,
2320 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2321 if (DEBUG_LOADERS) {
2322 Log.d(TAG, "sort took "
2323 + (SystemClock.uptimeMillis()-sortTime) + "ms");
Joe Onorato9c1289c2009-08-17 11:03:03 -04002324 }
2325
Winson Chung64359a52013-07-08 17:17:08 -07002326 // Create the ApplicationInfos
2327 final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2328 for (int i = 0; i < apps.size(); i++) {
2329 // This builds the icon bitmaps.
2330 mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
2331 mIconCache, mLabelCache));
2332 }
2333
2334 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2335 final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
2336 mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
2337
2338 // Post callback on main thread
2339 mHandler.post(new Runnable() {
2340 public void run() {
2341 final long bindTime = SystemClock.uptimeMillis();
2342 if (callbacks != null) {
2343 callbacks.bindAllApplications(added);
2344 if (DEBUG_LOADERS) {
2345 Log.d(TAG, "bound " + added.size() + " apps in "
2346 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2347 }
2348 } else {
2349 Log.i(TAG, "not binding apps: no Launcher activity");
2350 }
2351 }
2352 });
2353
Joe Onorato36115782010-06-17 13:28:48 -04002354 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002355 Log.d(TAG, "Icons processed in "
2356 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002357 }
2358 }
2359
2360 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002361 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002362 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2363 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2364 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2365 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2366 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2367 }
Joe Onorato36115782010-06-17 13:28:48 -04002368 }
2369 }
2370
2371 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002372 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002373 }
2374
2375 private class PackageUpdatedTask implements Runnable {
2376 int mOp;
2377 String[] mPackages;
2378
2379 public static final int OP_NONE = 0;
2380 public static final int OP_ADD = 1;
2381 public static final int OP_UPDATE = 2;
2382 public static final int OP_REMOVE = 3; // uninstlled
2383 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2384
2385
2386 public PackageUpdatedTask(int op, String[] packages) {
2387 mOp = op;
2388 mPackages = packages;
2389 }
2390
2391 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002392 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002393
2394 final String[] packages = mPackages;
2395 final int N = packages.length;
2396 switch (mOp) {
2397 case OP_ADD:
2398 for (int i=0; i<N; i++) {
2399 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002400 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002401 }
2402 break;
2403 case OP_UPDATE:
2404 for (int i=0; i<N; i++) {
2405 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002406 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002407 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002408 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002409 }
2410 break;
2411 case OP_REMOVE:
2412 case OP_UNAVAILABLE:
2413 for (int i=0; i<N; i++) {
2414 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002415 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002416 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002417 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002418 }
2419 break;
2420 }
2421
2422 ArrayList<ApplicationInfo> added = null;
Joe Onorato36115782010-06-17 13:28:48 -04002423 ArrayList<ApplicationInfo> modified = null;
Winson Chung83892cc2013-05-01 16:53:33 -07002424 final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002425
Adam Cohen487f7dd2012-06-28 18:12:10 -07002426 if (mBgAllAppsList.added.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002427 added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
2428 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002429 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002430 if (mBgAllAppsList.modified.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002431 modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
2432 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002433 }
Winson Chung5d55f332012-07-16 20:45:03 -07002434 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002435 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002436 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002437 }
2438
Joe Onorato36115782010-06-17 13:28:48 -04002439 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2440 if (callbacks == null) {
2441 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2442 return;
2443 }
2444
2445 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002446 // Ensure that we add all the workspace applications to the db
Winson Chung997a9232013-07-24 15:33:46 -07002447 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Winson Chung64359a52013-07-08 17:17:08 -07002448 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
Winson Chung997a9232013-07-24 15:33:46 -07002449 addAndBindAddedApps(context, addedInfos, cb);
Joe Onorato36115782010-06-17 13:28:48 -04002450 }
2451 if (modified != null) {
2452 final ArrayList<ApplicationInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002453
2454 // Update the launcher db to reflect the changes
2455 for (ApplicationInfo a : modifiedFinal) {
2456 ArrayList<ItemInfo> infos =
2457 getItemInfoForComponentName(a.componentName);
2458 for (ItemInfo i : infos) {
2459 if (isShortcutInfoUpdateable(i)) {
2460 ShortcutInfo info = (ShortcutInfo) i;
2461 info.title = a.title.toString();
2462 updateItemInDatabase(context, info);
2463 }
2464 }
2465 }
2466
Joe Onorato36115782010-06-17 13:28:48 -04002467 mHandler.post(new Runnable() {
2468 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002469 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2470 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002471 callbacks.bindAppsUpdated(modifiedFinal);
2472 }
2473 }
2474 });
2475 }
Winson Chung83892cc2013-05-01 16:53:33 -07002476 // If a package has been removed, or an app has been removed as a result of
2477 // an update (for example), make the removed callback.
2478 if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
Winson Chung64359a52013-07-08 17:17:08 -07002479 final boolean packageRemoved = (mOp == OP_REMOVE);
Winson Chung83892cc2013-05-01 16:53:33 -07002480 final ArrayList<String> removedPackageNames =
2481 new ArrayList<String>(Arrays.asList(packages));
2482
Winson Chung64359a52013-07-08 17:17:08 -07002483 // Update the launcher db to reflect the removal of apps
2484 if (packageRemoved) {
2485 for (String pn : removedPackageNames) {
2486 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2487 for (ItemInfo i : infos) {
2488 deleteItemFromDatabase(context, i);
2489 }
2490 }
2491 } else {
2492 for (ApplicationInfo a : removedApps) {
2493 ArrayList<ItemInfo> infos =
2494 getItemInfoForComponentName(a.componentName);
2495 for (ItemInfo i : infos) {
2496 deleteItemFromDatabase(context, i);
2497 }
2498 }
2499 }
2500
Joe Onorato36115782010-06-17 13:28:48 -04002501 mHandler.post(new Runnable() {
2502 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002503 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2504 if (callbacks == cb && cb != null) {
Winson Chung83892cc2013-05-01 16:53:33 -07002505 callbacks.bindComponentsRemoved(removedPackageNames,
Winson Chung64359a52013-07-08 17:17:08 -07002506 removedApps, packageRemoved);
Joe Onorato36115782010-06-17 13:28:48 -04002507 }
2508 }
2509 });
Joe Onoratobe386092009-11-17 17:32:16 -08002510 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002511
Michael Jurkac402cd92013-05-20 15:49:32 +02002512 final ArrayList<Object> widgetsAndShortcuts =
2513 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002514 mHandler.post(new Runnable() {
2515 @Override
2516 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002517 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2518 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002519 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002520 }
2521 }
2522 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002523 }
2524 }
2525
Michael Jurkac402cd92013-05-20 15:49:32 +02002526 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2527 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2528 PackageManager packageManager = context.getPackageManager();
2529 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2530 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2531 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2532 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2533 Collections.sort(widgetsAndShortcuts,
2534 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2535 return widgetsAndShortcuts;
2536 }
2537
Winson Chungee055712013-07-30 14:46:24 -07002538 private boolean isValidPackage(PackageManager pm, ComponentName cn) {
2539 if (cn == null) {
2540 return false;
2541 }
2542
2543 try {
2544 return (pm.getActivityInfo(cn, 0) != null);
2545 } catch (NameNotFoundException e) {
2546 return false;
2547 }
2548 }
2549
Joe Onorato9c1289c2009-08-17 11:03:03 -04002550 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002551 * This is called from the code that adds shortcuts from the intent receiver. This
2552 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002553 */
Joe Onorato56d82912010-03-07 14:32:10 -05002554 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002555 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002556 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002557
Joe Onorato56d82912010-03-07 14:32:10 -05002558 /**
2559 * Make an ShortcutInfo object for a shortcut that is an application.
2560 *
2561 * If c is not null, then it will be used to fill in missing data like the title and icon.
2562 */
2563 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002564 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002565 ComponentName componentName = intent.getComponent();
Winson Chungee055712013-07-30 14:46:24 -07002566 if (!isValidPackage(manager, componentName)) {
2567 Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002568 return null;
2569 }
2570
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002571 // TODO: See if the PackageManager knows about this case. If it doesn't
2572 // then return null & delete this.
2573
Joe Onorato56d82912010-03-07 14:32:10 -05002574 // the resource -- This may implicitly give us back the fallback icon,
2575 // but don't worry about that. All we're doing with usingFallbackIcon is
2576 // to avoid saving lots of copies of that in the database, and most apps
2577 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002578
2579 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2580 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2581 // via resolveActivity().
Winson Chungee055712013-07-30 14:46:24 -07002582 final ShortcutInfo info = new ShortcutInfo();
2583 Bitmap icon = null;
Winson Chungc208ff92012-03-29 17:37:41 -07002584 ResolveInfo resolveInfo = null;
2585 ComponentName oldComponent = intent.getComponent();
2586 Intent newIntent = new Intent(intent.getAction(), null);
2587 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2588 newIntent.setPackage(oldComponent.getPackageName());
2589 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2590 for (ResolveInfo i : infos) {
2591 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2592 i.activityInfo.name);
2593 if (cn.equals(oldComponent)) {
2594 resolveInfo = i;
2595 }
2596 }
2597 if (resolveInfo == null) {
2598 resolveInfo = manager.resolveActivity(intent, 0);
2599 }
Joe Onorato56d82912010-03-07 14:32:10 -05002600 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002601 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002602 }
Joe Onorato56d82912010-03-07 14:32:10 -05002603 // the db
2604 if (icon == null) {
2605 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002606 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002607 }
2608 }
2609 // the fallback icon
2610 if (icon == null) {
2611 icon = getFallbackIcon();
2612 info.usingFallbackIcon = true;
2613 }
2614 info.setIcon(icon);
2615
2616 // from the resource
2617 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002618 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2619 if (labelCache != null && labelCache.containsKey(key)) {
2620 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002621 } else {
2622 info.title = resolveInfo.activityInfo.loadLabel(manager);
2623 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002624 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002625 }
2626 }
Joe Onorato56d82912010-03-07 14:32:10 -05002627 }
2628 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002629 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002630 if (c != null) {
2631 info.title = c.getString(titleIndex);
2632 }
2633 }
2634 // fall back to the class name of the activity
2635 if (info.title == null) {
2636 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002637 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002638 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2639 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002640 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002641
Winson Chung64359a52013-07-08 17:17:08 -07002642 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2643 ItemInfoFilter f) {
2644 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2645 for (ItemInfo i : infos) {
2646 if (i instanceof ShortcutInfo) {
2647 ShortcutInfo info = (ShortcutInfo) i;
2648 ComponentName cn = info.intent.getComponent();
2649 if (cn != null && f.filterItem(null, info, cn)) {
2650 filtered.add(info);
2651 }
2652 } else if (i instanceof FolderInfo) {
2653 FolderInfo info = (FolderInfo) i;
2654 for (ShortcutInfo s : info.contents) {
2655 ComponentName cn = s.intent.getComponent();
2656 if (cn != null && f.filterItem(info, s, cn)) {
2657 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07002658 }
2659 }
Winson Chung64359a52013-07-08 17:17:08 -07002660 } else if (i instanceof LauncherAppWidgetInfo) {
2661 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2662 ComponentName cn = info.providerName;
2663 if (cn != null && f.filterItem(null, info, cn)) {
2664 filtered.add(info);
2665 }
Winson Chung8a435102012-08-30 17:16:53 -07002666 }
2667 }
Winson Chung64359a52013-07-08 17:17:08 -07002668 return new ArrayList<ItemInfo>(filtered);
2669 }
2670
2671 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
2672 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2673 ItemInfoFilter filter = new ItemInfoFilter() {
2674 @Override
2675 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2676 return cn.getPackageName().equals(pn);
2677 }
2678 };
2679 return filterItemInfos(sBgItemsIdMap.values(), filter);
2680 }
2681
2682 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
2683 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2684 ItemInfoFilter filter = new ItemInfoFilter() {
2685 @Override
2686 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2687 return cn.equals(cname);
2688 }
2689 };
2690 return filterItemInfos(sBgItemsIdMap.values(), filter);
2691 }
2692
2693 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2694 if (i instanceof ShortcutInfo) {
2695 ShortcutInfo info = (ShortcutInfo) i;
2696 // We need to check for ACTION_MAIN otherwise getComponent() might
2697 // return null for some shortcuts (for instance, for shortcuts to
2698 // web pages.)
2699 Intent intent = info.intent;
2700 ComponentName name = intent.getComponent();
2701 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2702 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2703 return true;
2704 }
2705 }
2706 return false;
Winson Chung8a435102012-08-30 17:16:53 -07002707 }
2708
2709 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002710 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002711 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002712 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002713 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2714 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002715
Joe Onorato56d82912010-03-07 14:32:10 -05002716 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002717 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002718 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002719
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002720 // TODO: If there's an explicit component and we can't install that, delete it.
2721
Joe Onorato56d82912010-03-07 14:32:10 -05002722 info.title = c.getString(titleIndex);
2723
Joe Onorato9c1289c2009-08-17 11:03:03 -04002724 int iconType = c.getInt(iconTypeIndex);
2725 switch (iconType) {
2726 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2727 String packageName = c.getString(iconPackageIndex);
2728 String resourceName = c.getString(iconResourceIndex);
2729 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002730 info.customIcon = false;
2731 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002732 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002733 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002734 if (resources != null) {
2735 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002736 icon = Utilities.createIconBitmap(
2737 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002738 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002739 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002740 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002741 }
Joe Onorato56d82912010-03-07 14:32:10 -05002742 // the db
2743 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002744 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002745 }
2746 // the fallback icon
2747 if (icon == null) {
2748 icon = getFallbackIcon();
2749 info.usingFallbackIcon = true;
2750 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002751 break;
2752 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002753 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002754 if (icon == null) {
2755 icon = getFallbackIcon();
2756 info.customIcon = false;
2757 info.usingFallbackIcon = true;
2758 } else {
2759 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002760 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002761 break;
2762 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002763 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002764 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002765 info.customIcon = false;
2766 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002767 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002768 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002769 return info;
2770 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002771
Michael Jurka931dc972011-08-05 15:08:15 -07002772 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002773 @SuppressWarnings("all") // suppress dead code warning
2774 final boolean debug = false;
2775 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002776 Log.d(TAG, "getIconFromCursor app="
2777 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2778 }
2779 byte[] data = c.getBlob(iconIndex);
2780 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002781 return Utilities.createIconBitmap(
2782 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002783 } catch (Exception e) {
2784 return null;
2785 }
2786 }
2787
Winson Chung3d503fb2011-07-13 17:25:49 -07002788 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2789 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002790 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002791 if (info == null) {
2792 return null;
2793 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002794 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002795
2796 return info;
2797 }
2798
Winson Chunga9abd0e2010-10-27 17:18:37 -07002799 /**
Winson Chung55cef262010-10-28 14:14:18 -07002800 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2801 */
2802 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2803 ComponentName component) {
2804 List<AppWidgetProviderInfo> widgets =
2805 AppWidgetManager.getInstance(context).getInstalledProviders();
2806 for (AppWidgetProviderInfo info : widgets) {
2807 if (info.provider.equals(component)) {
2808 return info;
2809 }
2810 }
2811 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002812 }
2813
Winson Chung68846fd2010-10-29 11:00:27 -07002814 /**
2815 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2816 */
2817 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2818 final PackageManager packageManager = context.getPackageManager();
2819 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2820 new ArrayList<WidgetMimeTypeHandlerData>();
2821
2822 final Intent supportsIntent =
2823 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2824 supportsIntent.setType(mimeType);
2825
2826 // Create a set of widget configuration components that we can test against
2827 final List<AppWidgetProviderInfo> widgets =
2828 AppWidgetManager.getInstance(context).getInstalledProviders();
2829 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2830 new HashMap<ComponentName, AppWidgetProviderInfo>();
2831 for (AppWidgetProviderInfo info : widgets) {
2832 configurationComponentToWidget.put(info.configure, info);
2833 }
2834
2835 // Run through each of the intents that can handle this type of clip data, and cross
2836 // reference them with the components that are actual configuration components
2837 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2838 PackageManager.MATCH_DEFAULT_ONLY);
2839 for (ResolveInfo info : activities) {
2840 final ActivityInfo activityInfo = info.activityInfo;
2841 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2842 activityInfo.name);
2843 if (configurationComponentToWidget.containsKey(infoComponent)) {
2844 supportedConfigurationActivities.add(
2845 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2846 configurationComponentToWidget.get(infoComponent)));
2847 }
2848 }
2849 return supportedConfigurationActivities;
2850 }
2851
Winson Chunga9abd0e2010-10-27 17:18:37 -07002852 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08002853 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2854 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2855 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2856
Adam Cohend9198822011-11-22 16:42:47 -08002857 if (intent == null) {
2858 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2859 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2860 return null;
2861 }
2862
Joe Onorato0589f0f2010-02-08 13:44:00 -08002863 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08002864 boolean customIcon = false;
2865 ShortcutIconResource iconResource = null;
2866
2867 if (bitmap != null && bitmap instanceof Bitmap) {
2868 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002869 customIcon = true;
2870 } else {
2871 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2872 if (extra != null && extra instanceof ShortcutIconResource) {
2873 try {
2874 iconResource = (ShortcutIconResource) extra;
2875 final PackageManager packageManager = context.getPackageManager();
2876 Resources resources = packageManager.getResourcesForApplication(
2877 iconResource.packageName);
2878 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002879 icon = Utilities.createIconBitmap(
2880 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002881 } catch (Exception e) {
2882 Log.w(TAG, "Could not load shortcut icon: " + extra);
2883 }
2884 }
2885 }
2886
Michael Jurkac9d95c52011-08-29 14:03:34 -07002887 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002888
2889 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002890 if (fallbackIcon != null) {
2891 icon = fallbackIcon;
2892 } else {
2893 icon = getFallbackIcon();
2894 info.usingFallbackIcon = true;
2895 }
Joe Onorato56d82912010-03-07 14:32:10 -05002896 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08002897 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05002898
Joe Onorato0589f0f2010-02-08 13:44:00 -08002899 info.title = name;
2900 info.intent = intent;
2901 info.customIcon = customIcon;
2902 info.iconResource = iconResource;
2903
2904 return info;
2905 }
2906
Winson Chungaac01e12011-08-17 10:37:13 -07002907 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2908 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08002909 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07002910 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07002911 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08002912 }
Joe Onorato56d82912010-03-07 14:32:10 -05002913 // If this icon doesn't have a custom icon, check to see
2914 // what's stored in the DB, and if it doesn't match what
2915 // we're going to show, store what we are going to show back
2916 // into the DB. We do this so when we're loading, if the
2917 // package manager can't find an icon (for example because
2918 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07002919 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07002920 cache.put(info, c.getBlob(iconIndex));
2921 return true;
2922 }
2923 return false;
2924 }
2925 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2926 boolean needSave = false;
2927 try {
2928 if (data != null) {
2929 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2930 Bitmap loaded = info.getIcon(mIconCache);
2931 needSave = !saved.sameAs(loaded);
2932 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05002933 needSave = true;
2934 }
Winson Chungaac01e12011-08-17 10:37:13 -07002935 } catch (Exception e) {
2936 needSave = true;
2937 }
2938 if (needSave) {
2939 Log.d(TAG, "going to save icon bitmap for info=" + info);
2940 // This is slower than is ideal, but this only happens once
2941 // or when the app is updated with a new icon.
2942 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05002943 }
2944 }
2945
Joe Onorato9c1289c2009-08-17 11:03:03 -04002946 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07002947 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04002948 * or make a new one.
2949 */
Adam Cohendf2cc412011-04-27 16:56:57 -07002950 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002951 // See if a placeholder was created for us already
2952 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07002953 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002954 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07002955 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002956 folders.put(id, folderInfo);
2957 }
Adam Cohendf2cc412011-04-27 16:56:57 -07002958 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002959 }
2960
Winson Chung11904872012-09-17 16:58:46 -07002961 public static final Comparator<ApplicationInfo> getAppNameComparator() {
2962 final Collator collator = Collator.getInstance();
2963 return new Comparator<ApplicationInfo>() {
2964 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2965 int result = collator.compare(a.title.toString(), b.title.toString());
2966 if (result == 0) {
2967 result = a.componentName.compareTo(b.componentName);
2968 }
2969 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07002970 }
Winson Chung11904872012-09-17 16:58:46 -07002971 };
2972 }
Winson Chung78403fe2011-01-21 15:38:02 -08002973 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2974 = new Comparator<ApplicationInfo>() {
2975 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2976 if (a.firstInstallTime < b.firstInstallTime) return 1;
2977 if (a.firstInstallTime > b.firstInstallTime) return -1;
2978 return 0;
2979 }
2980 };
Winson Chung11904872012-09-17 16:58:46 -07002981 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
2982 final Collator collator = Collator.getInstance();
2983 return new Comparator<AppWidgetProviderInfo>() {
2984 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
2985 return collator.compare(a.label.toString(), b.label.toString());
2986 }
2987 };
2988 }
Winson Chung5308f242011-08-18 12:12:41 -07002989 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
2990 if (info.activityInfo != null) {
2991 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
2992 } else {
2993 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
2994 }
2995 }
Winson Chung785d2eb2011-04-14 16:08:02 -07002996 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07002997 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07002998 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07002999 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003000 ShortcutNameComparator(PackageManager pm) {
3001 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07003002 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003003 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003004 }
3005 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
3006 mPackageManager = pm;
3007 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003008 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003009 }
3010 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003011 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07003012 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
3013 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
3014 if (mLabelCache.containsKey(keyA)) {
3015 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003016 } else {
3017 labelA = a.loadLabel(mPackageManager).toString();
3018
Winson Chung5308f242011-08-18 12:12:41 -07003019 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003020 }
Winson Chung5308f242011-08-18 12:12:41 -07003021 if (mLabelCache.containsKey(keyB)) {
3022 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003023 } else {
3024 labelB = b.loadLabel(mPackageManager).toString();
3025
Winson Chung5308f242011-08-18 12:12:41 -07003026 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003027 }
Winson Chung11904872012-09-17 16:58:46 -07003028 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003029 }
3030 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003031 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003032 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003033 private PackageManager mPackageManager;
3034 private HashMap<Object, String> mLabelCache;
3035 WidgetAndShortcutNameComparator(PackageManager pm) {
3036 mPackageManager = pm;
3037 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003038 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003039 }
3040 public final int compare(Object a, Object b) {
3041 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003042 if (mLabelCache.containsKey(a)) {
3043 labelA = mLabelCache.get(a);
3044 } else {
3045 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003046 ((AppWidgetProviderInfo) a).label :
3047 ((ResolveInfo) a).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003048 mLabelCache.put(a, labelA);
3049 }
3050 if (mLabelCache.containsKey(b)) {
3051 labelB = mLabelCache.get(b);
3052 } else {
3053 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003054 ((AppWidgetProviderInfo) b).label :
3055 ((ResolveInfo) b).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003056 mLabelCache.put(b, labelB);
3057 }
Winson Chung11904872012-09-17 16:58:46 -07003058 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003059 }
3060 };
Joe Onoratobe386092009-11-17 17:32:16 -08003061
3062 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003063 Log.d(TAG, "mCallbacks=" + mCallbacks);
Adam Cohen487f7dd2012-06-28 18:12:10 -07003064 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3065 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3066 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3067 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003068 if (mLoaderTask != null) {
3069 mLoaderTask.dumpState();
3070 } else {
3071 Log.d(TAG, "mLoaderTask=null");
3072 }
Joe Onoratobe386092009-11-17 17:32:16 -08003073 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003074}