blob: f79e08166e8179cc3ed6b667076a35ff23739c0c [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Narayan Kamathcb1a4772011-06-28 13:46:59 +010019import android.app.SearchManager;
Romain Guy629de3e2010-01-13 12:20:59 -080020import android.appwidget.AppWidgetManager;
21import android.appwidget.AppWidgetProviderInfo;
Winson Chungc9168342013-06-26 14:54:55 -070022import android.content.*;
Joe Onorato0589f0f2010-02-08 13:44:00 -080023import android.content.Intent.ShortcutIconResource;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080024import android.content.pm.ActivityInfo;
Adam Cohen00fcb492011-11-02 21:53:47 -070025import android.content.pm.PackageInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.pm.PackageManager;
Adam Cohen00fcb492011-11-02 21:53:47 -070027import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080028import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070029import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080030import android.content.res.Resources;
31import android.database.Cursor;
32import android.graphics.Bitmap;
33import android.graphics.BitmapFactory;
34import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080035import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040036import android.os.Handler;
37import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080038import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070040import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040041import android.os.SystemClock;
Winson Chungaafa03c2010-06-11 17:34:16 -070042import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070043import android.util.Pair;
Daniel Sandler325dc232013-06-05 22:57:57 -040044import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
Romain Guyedcce092010-03-04 13:03:17 -080045
Michael Jurkac2f801e2011-07-12 14:19:46 -070046import java.lang.ref.WeakReference;
47import java.net.URISyntaxException;
48import java.text.Collator;
49import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070050import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070051import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070052import java.util.Collections;
53import java.util.Comparator;
54import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070055import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070056import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070057import java.util.List;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070058import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070059import java.util.TreeMap;
Michael Jurkac2f801e2011-07-12 14:19:46 -070060
The Android Open Source Project31dd5032009-03-03 19:32:27 -080061/**
62 * Maintains in-memory state of the Launcher. It is expected that there should be only one
63 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070064 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065 */
Joe Onoratof99f8c12009-10-31 17:27:36 -040066public class LauncherModel extends BroadcastReceiver {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080067 static final boolean DEBUG_LOADERS = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -040068 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070069
Joe Onorato36115782010-06-17 13:28:48 -040070 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Joe Onorato17a89222011-02-08 17:26:11 -080071 private final boolean mAppsCanBeOnExternalStorage;
Daniel Sandlerdca66122010-04-13 16:23:58 -040072
Daniel Sandlercc8befa2013-06-11 14:45:48 -040073 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -040074 private final Object mLock = new Object();
75 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -040076 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070077 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +020078 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Winson Chung81b52252012-08-27 15:34:29 -070080 // Specific runnable types that are run on the main thread deferred handler, this allows us to
81 // clear all queued binding runnables when the Launcher activity is destroyed.
82 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
83 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
84
85
Brad Fitzpatrick700889f2010-10-11 09:40:44 -070086 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
87 static {
88 sWorkerThread.start();
89 }
90 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
91
Joe Onoratocc67f472010-06-08 10:54:30 -070092 // We start off with everything not loaded. After that, we assume that
93 // our monitoring of the package manager provides all updates and we never
94 // need to do a requery. These are only ever touched from the loader thread.
95 private boolean mWorkspaceLoaded;
96 private boolean mAllAppsLoaded;
97
Winson Chungb8b2a5a2012-07-12 17:55:31 -070098 // When we are loading pages synchronously, we can't just post the binding of items on the side
99 // pages as this delays the rotation process. Instead, we wait for a callback from the first
100 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
101 // a normal load, we also clear this set of Runnables.
102 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
103
Joe Onorato9c1289c2009-08-17 11:03:03 -0400104 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800105
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700106 // < only access in worker thread >
Adam Cohen487f7dd2012-06-28 18:12:10 -0700107 private AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800108
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700109 // The lock that must be acquired before referencing any static bg data structures. Unlike
110 // other locks, this one can generally be held long-term because we never expect any of these
111 // static data structures to be referenced outside of the worker thread except on the first
112 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700113 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700114
Adam Cohen487f7dd2012-06-28 18:12:10 -0700115 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700116 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700117 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700118
Adam Cohen487f7dd2012-06-28 18:12:10 -0700119 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
120 // created by LauncherModel that are directly on the home screen (however, no widgets or
121 // shortcuts within folders).
122 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700123
Adam Cohen487f7dd2012-06-28 18:12:10 -0700124 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
125 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700126 new ArrayList<LauncherAppWidgetInfo>();
127
Adam Cohen487f7dd2012-06-28 18:12:10 -0700128 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
129 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700130
Adam Cohen487f7dd2012-06-28 18:12:10 -0700131 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
132 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700133
134 // sBgWorkspaceScreens is the ordered set of workspace screens.
135 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
136
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 // </ only access in worker thread >
138
139 private IconCache mIconCache;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800140 private Bitmap mDefaultIcon;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800141
Adam Cohend22015c2010-07-26 22:02:18 -0700142 private static int mCellCountX;
143 private static int mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700144
Reena Lee99a73f32011-10-24 17:27:37 -0700145 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700146
Joe Onorato9c1289c2009-08-17 11:03:03 -0400147 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700148 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400149 public int getCurrentWorkspaceScreen();
150 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700151 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
152 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700153 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700154 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500155 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700156 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400157 public void bindAppWidget(LauncherAppWidgetInfo info);
158 public void bindAllApplications(ArrayList<ApplicationInfo> apps);
Joe Onorato64e6be72010-03-05 15:05:52 -0500159 public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
Winson Chung83892cc2013-05-01 16:53:33 -0700160 public void bindComponentsRemoved(ArrayList<String> packageNames,
161 ArrayList<ApplicationInfo> appInfos,
162 boolean matchPackageNamesOnly);
Michael Jurkac402cd92013-05-20 15:49:32 +0200163 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100164 public void bindSearchablesChanged();
Adam Cohen1462de32012-07-24 22:34:36 -0700165 public void onPageBoundSynchronously(int page);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400166 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800167
Winson Chung64359a52013-07-08 17:17:08 -0700168 public interface ItemInfoFilter {
169 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
170 }
171
Daniel Sandlere4f98912013-06-25 15:13:26 -0400172 LauncherModel(LauncherAppState app, IconCache iconCache) {
173 final Context context = app.getContext();
174
Joe Onorato17a89222011-02-08 17:26:11 -0800175 mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400176 mApp = app;
Adam Cohen487f7dd2012-06-28 18:12:10 -0700177 mBgAllAppsList = new AllAppsList(iconCache);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800178 mIconCache = iconCache;
179
180 mDefaultIcon = Utilities.createIconBitmap(
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400181 mIconCache.getFullResDefaultActivityIcon(), context);
Daniel Sandler2ff10b32010-04-16 15:06:06 -0400182
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400183 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700184 Configuration config = res.getConfiguration();
185 mPreviousConfigMcc = config.mcc;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800186 }
187
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700188 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
189 * posted on the main thread handler. */
190 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700191 runOnMainThread(r, 0);
192 }
193 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700194 if (sWorkerThread.getThreadId() == Process.myTid()) {
195 // If we are on the worker thread, post onto the main handler
196 mHandler.post(r);
197 } else {
198 r.run();
199 }
200 }
201
202 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
203 * posted on the worker thread handler. */
204 private static void runOnWorkerThread(Runnable r) {
205 if (sWorkerThread.getThreadId() == Process.myTid()) {
206 r.run();
207 } else {
208 // If we are not on the worker thread, then post to the worker handler
209 sWorker.post(r);
210 }
211 }
212
Winson Chungc9168342013-06-26 14:54:55 -0700213 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
214 long screen) {
215 final int xCount = LauncherModel.getCellCountX();
216 final int yCount = LauncherModel.getCellCountY();
217 boolean[][] occupied = new boolean[xCount][yCount];
218
219 int cellX, cellY, spanX, spanY;
220 for (int i = 0; i < items.size(); ++i) {
221 final ItemInfo item = items.get(i);
222 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
223 if (item.screenId == screen) {
224 cellX = item.cellX;
225 cellY = item.cellY;
226 spanX = item.spanX;
227 spanY = item.spanY;
228 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
229 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
230 occupied[x][y] = true;
231 }
232 }
233 }
234 }
235 }
236
237 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
238 }
239 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700240 Intent launchIntent,
241 int firstScreenIndex) {
Winson Chungc9168342013-06-26 14:54:55 -0700242 // Lock on the app so that we don't try and get the items while apps are being added
243 LauncherAppState app = LauncherAppState.getInstance();
244 LauncherModel model = app.getModel();
245 boolean found = false;
246 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700247 if (sWorkerThread.getThreadId() != Process.myTid()) {
248 // Flush the LauncherModel worker thread, so that if we just did another
249 // processInstallShortcut, we give it time for its shortcut to get added to the
250 // database (getItemsInLocalCoordinates reads the database)
251 model.flushWorkerThread();
252 }
Winson Chungc9168342013-06-26 14:54:55 -0700253 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700254
255 // Try adding to the workspace screens incrementally, starting at the default or center
256 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung156ab5b2013-07-12 14:14:16 -0700257 firstScreenIndex = Math.min(firstScreenIndex, sBgWorkspaceScreens.size());
258 int count = sBgWorkspaceScreens.size();
259 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700260 int[] tmpCoordinates = new int[2];
261 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
262 sBgWorkspaceScreens.get(screen))) {
263 // Update the Launcher db
264 return new Pair<Long, int[]>(sBgWorkspaceScreens.get(screen), tmpCoordinates);
265 }
266 }
267 }
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) {
303 // If we can't find a valid position, then just add a new screen.
304 // This takes time so we need to re-queue the add until the new
305 // page is added.
306 LauncherAppState appState = LauncherAppState.getInstance();
307 LauncherProvider lp = appState.getLauncherProvider();
308 long screenId = lp.generateNewScreenId();
309 // Update the model
310 sBgWorkspaceScreens.add(screenId);
311 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
312 // Save the screen id for binding in the workspace
313 addedWorkspaceScreensFinal.add(screenId);
314 // Find the coordinate again
315 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung997a9232013-07-24 15:33:46 -0700316 name, launchIntent, startSearchPageIndex);
Winson Chung64359a52013-07-08 17:17:08 -0700317 }
318 if (coords == null) {
319 throw new RuntimeException("Coordinates should not be null");
320 }
321
Winson Chung997a9232013-07-24 15:33:46 -0700322 ShortcutInfo shortcutInfo;
323 if (a instanceof ShortcutInfo) {
324 shortcutInfo = (ShortcutInfo) a;
325 } else if (a instanceof ApplicationInfo) {
326 shortcutInfo = ((ApplicationInfo) a).makeShortcut();
327 } else {
328 throw new RuntimeException("Unexpected info type");
329 }
Winson Chung64359a52013-07-08 17:17:08 -0700330 // Add the shortcut to the db
331 addItemToDatabase(context, shortcutInfo,
332 LauncherSettings.Favorites.CONTAINER_DESKTOP,
333 coords.first, coords.second[0], coords.second[1], false);
334 // Save the ShortcutInfo for binding in the workspace
335 addedShortcutsFinal.add(shortcutInfo);
336 }
337 }
338
Winson Chung997a9232013-07-24 15:33:46 -0700339 if (!addedShortcutsFinal.isEmpty()) {
340 runOnMainThread(new Runnable() {
341 public void run() {
342 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
343 if (callbacks == cb && cb != null) {
344 callbacks.bindAddScreens(addedWorkspaceScreensFinal);
345
346 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
347 long lastScreenId = info.screenId;
348 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
349 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
350 for (ItemInfo i : addedShortcutsFinal) {
351 if (i.screenId == lastScreenId) {
352 addAnimated.add(i);
353 } else {
354 addNotAnimated.add(i);
355 }
356 }
357 // We add the items without animation on non-visible pages, and with
358 // animations on the new page (which we will try and snap to).
359 if (!addNotAnimated.isEmpty()) {
360 callbacks.bindItems(addNotAnimated, 0,
361 addNotAnimated.size(), false);
362 }
363 if (!addAnimated.isEmpty()) {
364 callbacks.bindItems(addAnimated, 0,
365 addAnimated.size(), true);
366 }
367 }
Winson Chung64359a52013-07-08 17:17:08 -0700368 }
Winson Chung997a9232013-07-24 15:33:46 -0700369 });
370 }
Winson Chung64359a52013-07-08 17:17:08 -0700371 }
372 };
373 runOnWorkerThread(r);
374 }
375
Joe Onorato56d82912010-03-07 14:32:10 -0500376 public Bitmap getFallbackIcon() {
Joe Onorato0589f0f2010-02-08 13:44:00 -0800377 return Bitmap.createBitmap(mDefaultIcon);
Joe Onoratof99f8c12009-10-31 17:27:36 -0400378 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800379
Winson Chung81b52252012-08-27 15:34:29 -0700380 public void unbindItemInfosAndClearQueuedBindRunnables() {
381 if (sWorkerThread.getThreadId() == Process.myTid()) {
382 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
383 "main thread");
384 }
385
386 // Clear any deferred bind runnables
387 mDeferredBindRunnables.clear();
388 // Remove any queued bind runnables
389 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
390 // Unbind all the workspace items
391 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700392 }
393
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700394 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700395 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700396 // Ensure that we don't use the same workspace items data structure on the main thread
397 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700398 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
399 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700400 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700401 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
402 tmpAppWidgets.addAll(sBgAppWidgets);
403 }
404 Runnable r = new Runnable() {
405 @Override
406 public void run() {
407 for (ItemInfo item : tmpWorkspaceItems) {
408 item.unbind();
409 }
410 for (ItemInfo item : tmpAppWidgets) {
411 item.unbind();
412 }
413 }
414 };
415 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700416 }
417
Joe Onorato9c1289c2009-08-17 11:03:03 -0400418 /**
419 * Adds an item to the DB if it was not created previously, or move it to a new
420 * <container, screen, cellX, cellY>
421 */
422 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700423 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400424 if (item.container == ItemInfo.NO_ID) {
425 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700426 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400427 } else {
428 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700429 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800430 }
431 }
432
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700433 static void checkItemInfoLocked(
434 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
435 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
436 if (modelItem != null && item != modelItem) {
437 // check all the data is consistent
438 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
439 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
440 ShortcutInfo shortcut = (ShortcutInfo) item;
441 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
442 modelShortcut.intent.filterEquals(shortcut.intent) &&
443 modelShortcut.id == shortcut.id &&
444 modelShortcut.itemType == shortcut.itemType &&
445 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700446 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700447 modelShortcut.cellX == shortcut.cellX &&
448 modelShortcut.cellY == shortcut.cellY &&
449 modelShortcut.spanX == shortcut.spanX &&
450 modelShortcut.spanY == shortcut.spanY &&
451 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
452 (modelShortcut.dropPos != null &&
453 shortcut.dropPos != null &&
454 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
455 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
456 // For all intents and purposes, this is the same object
457 return;
458 }
459 }
460
461 // the modelItem needs to match up perfectly with item if our model is
462 // to be consistent with the database-- for now, just require
463 // modelItem == item or the equality check above
464 String msg = "item: " + ((item != null) ? item.toString() : "null") +
465 "modelItem: " +
466 ((modelItem != null) ? modelItem.toString() : "null") +
467 "Error: ItemInfo passed to checkItemInfo doesn't match original";
468 RuntimeException e = new RuntimeException(msg);
469 if (stackTrace != null) {
470 e.setStackTrace(stackTrace);
471 }
Adam Cohene25af792013-06-06 23:08:25 -0700472 // TODO: something breaks this in the upgrade path
473 //throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700474 }
475 }
476
Michael Jurka816474f2012-06-25 14:49:02 -0700477 static void checkItemInfo(final ItemInfo item) {
478 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
479 final long itemId = item.id;
480 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700481 public void run() {
482 synchronized (sBgLock) {
483 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700484 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700485 }
486 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700487 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700488 }
489
Michael Jurkac9d95c52011-08-29 14:03:34 -0700490 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
491 final ItemInfo item, final String callingFunction) {
492 final long itemId = item.id;
493 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
494 final ContentResolver cr = context.getContentResolver();
495
Adam Cohen487f7dd2012-06-28 18:12:10 -0700496 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700497 Runnable r = new Runnable() {
498 public void run() {
499 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700500 updateItemArrays(item, itemId, stackTrace);
501 }
502 };
503 runOnWorkerThread(r);
504 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700505
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700506 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
507 final ArrayList<ItemInfo> items, final String callingFunction) {
508 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700509
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700510 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
511 Runnable r = new Runnable() {
512 public void run() {
513 ArrayList<ContentProviderOperation> ops =
514 new ArrayList<ContentProviderOperation>();
515 int count = items.size();
516 for (int i = 0; i < count; i++) {
517 ItemInfo item = items.get(i);
518 final long itemId = item.id;
519 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
520 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700521
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700522 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
523 updateItemArrays(item, itemId, stackTrace);
524
525 }
526 try {
527 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
528 } catch (Exception e) {
529 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700530 }
531 }
532 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700533 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700534 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700535
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700536 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
537 // Lock on mBgLock *after* the db operation
538 synchronized (sBgLock) {
539 checkItemInfoLocked(itemId, item, stackTrace);
540
541 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
542 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
543 // Item is in a folder, make sure this folder exists
544 if (!sBgFolders.containsKey(item.container)) {
545 // An items container is being set to a that of an item which is not in
546 // the list of Folders.
547 String msg = "item: " + item + " container being set to: " +
548 item.container + ", not in the list of folders";
549 Log.e(TAG, msg);
550 Launcher.dumpDebugLogsToConsole();
551 }
552 }
553
554 // Items are added/removed from the corresponding FolderInfo elsewhere, such
555 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
556 // that are on the desktop, as appropriate
557 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
558 if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
559 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
560 switch (modelItem.itemType) {
561 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
562 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
563 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
564 if (!sBgWorkspaceItems.contains(modelItem)) {
565 sBgWorkspaceItems.add(modelItem);
566 }
567 break;
568 default:
569 break;
570 }
571 } else {
572 sBgWorkspaceItems.remove(modelItem);
573 }
574 }
575 }
576
Michael Jurkac7700af2013-05-14 20:17:58 +0200577 public void flushWorkerThread() {
578 mFlushingWorkerThread = true;
579 Runnable waiter = new Runnable() {
580 public void run() {
581 synchronized (this) {
582 notifyAll();
583 mFlushingWorkerThread = false;
584 }
585 }
586 };
587
588 synchronized(waiter) {
589 runOnWorkerThread(waiter);
590 if (mLoaderTask != null) {
591 synchronized(mLoaderTask) {
592 mLoaderTask.notify();
593 }
594 }
595 boolean success = false;
596 while (!success) {
597 try {
598 waiter.wait();
599 success = true;
600 } catch (InterruptedException e) {
601 }
602 }
603 }
604 }
605
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800606 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400607 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700608 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700609 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700610 final long screenId, final int cellX, final int cellY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700611 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
Adam Cohendcd297f2013-06-18 13:13:40 -0700612 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
613 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Adam Cohen487f7dd2012-06-28 18:12:10 -0700614 Launcher.sDumpLogs.add(transaction);
615 Log.d(TAG, transaction);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400616 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400617 item.cellX = cellX;
618 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700619
Winson Chung3d503fb2011-07-13 17:25:49 -0700620 // We store hotseat items in canonical form which is this orientation invariant position
621 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700622 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700623 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700624 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700625 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700626 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700627 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400628
629 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400630 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700631 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
632 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700633 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400634
Michael Jurkac9d95c52011-08-29 14:03:34 -0700635 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700636 }
637
638 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700639 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
640 * cellX, cellY have already been updated on the ItemInfos.
641 */
642 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
643 final long container, final int screen) {
644
645 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
646 int count = items.size();
647
648 for (int i = 0; i < count; i++) {
649 ItemInfo item = items.get(i);
650 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700651 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700652 + ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", "
653 + item.cellX + ", " + item.cellY + ")";
654 Launcher.sDumpLogs.add(transaction);
655 item.container = container;
656
657 // We store hotseat items in canonical form which is this orientation invariant position
658 // in the hotseat
659 if (context instanceof Launcher && screen < 0 &&
660 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700661 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700662 item.cellY);
663 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700664 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700665 }
666
667 final ContentValues values = new ContentValues();
668 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
669 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
670 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700671 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700672
673 contentValues.add(values);
674 }
675 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
676 }
677
678 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700679 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800680 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700681 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700682 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700683 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
Adam Cohendcd297f2013-06-18 13:13:40 -0700684 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
685 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Adam Cohen487f7dd2012-06-28 18:12:10 -0700686 Launcher.sDumpLogs.add(transaction);
687 Log.d(TAG, transaction);
Adam Cohend4844c32011-02-18 19:25:06 -0800688 item.cellX = cellX;
689 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700690 item.spanX = spanX;
691 item.spanY = spanY;
692
693 // We store hotseat items in canonical form which is this orientation invariant position
694 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700695 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700696 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700697 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700698 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700699 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700700 }
Adam Cohend4844c32011-02-18 19:25:06 -0800701
Adam Cohend4844c32011-02-18 19:25:06 -0800702 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800703 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700704 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
705 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
706 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
707 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700708 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800709
Michael Jurka816474f2012-06-25 14:49:02 -0700710 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700711 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700712
713 /**
714 * Update an item to the database in a specified container.
715 */
716 static void updateItemInDatabase(Context context, final ItemInfo item) {
717 final ContentValues values = new ContentValues();
718 item.onAddToDatabase(values);
719 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
720 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800721 }
722
723 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400724 * Returns true if the shortcuts already exists in the database.
725 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800726 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400727 static boolean shortcutExists(Context context, String title, Intent intent) {
728 final ContentResolver cr = context.getContentResolver();
729 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
730 new String[] { "title", "intent" }, "title=? and intent=?",
731 new String[] { title, intent.toUri(0) }, null);
732 boolean result = false;
733 try {
734 result = c.moveToFirst();
735 } finally {
736 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800737 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400738 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700739 }
740
Joe Onorato9c1289c2009-08-17 11:03:03 -0400741 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700742 * Returns an ItemInfo array containing all the items in the LauncherModel.
743 * The ItemInfo.id is not set through this function.
744 */
745 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
746 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
747 final ContentResolver cr = context.getContentResolver();
748 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
749 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
750 LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
751 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
752
753 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
754 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
755 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
756 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
757 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
758 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
759 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
760
761 try {
762 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700763 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700764 item.cellX = c.getInt(cellXIndex);
765 item.cellY = c.getInt(cellYIndex);
766 item.spanX = c.getInt(spanXIndex);
767 item.spanY = c.getInt(spanYIndex);
768 item.container = c.getInt(containerIndex);
769 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700770 item.screenId = c.getInt(screenIndex);
Winson Chungaafa03c2010-06-11 17:34:16 -0700771
772 items.add(item);
773 }
774 } catch (Exception e) {
775 items.clear();
776 } finally {
777 c.close();
778 }
779
780 return items;
781 }
782
783 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400784 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
785 */
786 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
787 final ContentResolver cr = context.getContentResolver();
788 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
789 "_id=? and (itemType=? or itemType=?)",
790 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700791 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700792
Joe Onorato9c1289c2009-08-17 11:03:03 -0400793 try {
794 if (c.moveToFirst()) {
795 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
796 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
797 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
798 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
799 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
800 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800801
Joe Onorato9c1289c2009-08-17 11:03:03 -0400802 FolderInfo folderInfo = null;
803 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700804 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
805 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400806 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700807 }
808
Joe Onorato9c1289c2009-08-17 11:03:03 -0400809 folderInfo.title = c.getString(titleIndex);
810 folderInfo.id = id;
811 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700812 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700813 folderInfo.cellX = c.getInt(cellXIndex);
814 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400815
816 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700817 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400818 } finally {
819 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700820 }
821
822 return null;
823 }
824
Joe Onorato9c1289c2009-08-17 11:03:03 -0400825 /**
826 * Add an item to the database in a specified container. Sets the container, screen, cellX and
827 * cellY fields of the item. Also assigns an ID to the item.
828 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700829 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700830 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400831 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400832 item.cellX = cellX;
833 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700834 // We store hotseat items in canonical form which is this orientation invariant position
835 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700836 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700837 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700838 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700839 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700840 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700841 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400842
843 final ContentValues values = new ContentValues();
844 final ContentResolver cr = context.getContentResolver();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400845 item.onAddToDatabase(values);
846
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400847 LauncherAppState app = LauncherAppState.getInstance();
Adam Cohendcd297f2013-06-18 13:13:40 -0700848 item.id = app.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700849 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -0700850 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -0700851
Michael Jurkac9d95c52011-08-29 14:03:34 -0700852 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700853 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700854 String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700855 + item.id + " (" + container + ", " + screenId + ", " + cellX + ", "
Adam Cohen487f7dd2012-06-28 18:12:10 -0700856 + cellY + ")";
857 Launcher.sDumpLogs.add(transaction);
858 Log.d(TAG, transaction);
859
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700860 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
861 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400862
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700863 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700864 synchronized (sBgLock) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700865 checkItemInfoLocked(item.id, item, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700866 sBgItemsIdMap.put(item.id, item);
867 switch (item.itemType) {
868 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
869 sBgFolders.put(item.id, (FolderInfo) item);
870 // Fall through
871 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
872 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
873 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
874 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
875 sBgWorkspaceItems.add(item);
876 } else {
877 if (!sBgFolders.containsKey(item.container)) {
878 // Adding an item to a folder that doesn't exist.
879 String msg = "adding item: " + item + " to a folder that " +
880 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -0700881 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700882 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700883 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700884 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700885 break;
886 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
887 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
888 break;
889 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700890 }
891 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700892 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700893 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700894 }
895
Joe Onorato9c1289c2009-08-17 11:03:03 -0400896 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700897 * Creates a new unique child id, for a given cell span across all layouts.
898 */
Michael Jurka845ba3b2010-09-28 17:09:46 -0700899 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -0700900 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -0700901 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -0700902 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -0700903 }
904
Adam Cohend22015c2010-07-26 22:02:18 -0700905 static int getCellCountX() {
906 return mCellCountX;
Winson Chungaafa03c2010-06-11 17:34:16 -0700907 }
908
Adam Cohend22015c2010-07-26 22:02:18 -0700909 static int getCellCountY() {
910 return mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700911 }
912
913 /**
914 * Updates the model orientation helper to take into account the current layout dimensions
915 * when performing local/canonical coordinate transformations.
916 */
917 static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
Adam Cohend22015c2010-07-26 22:02:18 -0700918 mCellCountX = shortAxisCellCount;
919 mCellCountY = longAxisCellCount;
Winson Chungaafa03c2010-06-11 17:34:16 -0700920 }
921
922 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -0700923 * Removes the specified item from the database
924 * @param context
925 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -0400926 */
Michael Jurkac9d95c52011-08-29 14:03:34 -0700927 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400928 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700929 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -0700930
Michael Jurka83df1882011-08-31 20:59:26 -0700931 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700932 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700933 String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700934 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX +
Adam Cohen487f7dd2012-06-28 18:12:10 -0700935 ", " + item.cellY + ")";
936 Launcher.sDumpLogs.add(transaction);
937 Log.d(TAG, transaction);
938
Michael Jurkac9d95c52011-08-29 14:03:34 -0700939 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700940
941 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700942 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700943 switch (item.itemType) {
944 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
945 sBgFolders.remove(item.id);
946 for (ItemInfo info: sBgItemsIdMap.values()) {
947 if (info.container == item.id) {
948 // We are deleting a folder which still contains items that
949 // think they are contained by that folder.
950 String msg = "deleting a folder (" + item + ") which still " +
951 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -0700952 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700953 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700954 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700955 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700956 sBgWorkspaceItems.remove(item);
957 break;
958 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
959 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
960 sBgWorkspaceItems.remove(item);
961 break;
962 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
963 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
964 break;
965 }
966 sBgItemsIdMap.remove(item.id);
967 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700968 }
969 }
Michael Jurka83df1882011-08-31 20:59:26 -0700970 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700971 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400972 }
973
974 /**
Adam Cohendcd297f2013-06-18 13:13:40 -0700975 * Update the order of the workspace screens in the database. The array list contains
976 * a list of screen ids in the order that they should appear.
977 */
Winson Chungc9168342013-06-26 14:54:55 -0700978 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chung64359a52013-07-08 17:17:08 -0700979 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -0700980 final ContentResolver cr = context.getContentResolver();
981 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
982
983 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -0700984 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -0700985 while (iter.hasNext()) {
986 long id = iter.next();
987 if (id < 0) {
988 iter.remove();
989 }
990 }
991
992 Runnable r = new Runnable() {
993 @Override
994 public void run() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700995 // Clear the table
996 cr.delete(uri, null, null);
997 int count = screens.size();
998 ContentValues[] values = new ContentValues[count];
999 for (int i = 0; i < count; i++) {
1000 ContentValues v = new ContentValues();
1001 long screenId = screens.get(i);
1002 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1003 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001004 values[i] = v;
1005 }
1006 cr.bulkInsert(uri, values);
1007 sBgWorkspaceScreens.clear();
1008 sBgWorkspaceScreens.addAll(screensCopy);
1009 }
1010 };
1011 runOnWorkerThread(r);
1012 }
1013
1014 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001015 * Remove the contents of the specified folder from the database
1016 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001017 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001018 final ContentResolver cr = context.getContentResolver();
1019
Michael Jurkac9d95c52011-08-29 14:03:34 -07001020 Runnable r = new Runnable() {
1021 public void run() {
1022 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001023 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001024 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001025 sBgItemsIdMap.remove(info.id);
1026 sBgFolders.remove(info.id);
1027 sBgDbIconCache.remove(info);
1028 sBgWorkspaceItems.remove(info);
1029 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001030
Michael Jurkac9d95c52011-08-29 14:03:34 -07001031 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1032 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001033 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001034 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001035 for (ItemInfo childInfo : info.contents) {
1036 sBgItemsIdMap.remove(childInfo.id);
1037 sBgDbIconCache.remove(childInfo);
1038 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001039 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001040 }
1041 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001042 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001043 }
1044
1045 /**
1046 * Set this as the current Launcher activity object for the loader.
1047 */
1048 public void initialize(Callbacks callbacks) {
1049 synchronized (mLock) {
1050 mCallbacks = new WeakReference<Callbacks>(callbacks);
1051 }
1052 }
1053
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001054 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001055 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1056 * ACTION_PACKAGE_CHANGED.
1057 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001058 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001059 public void onReceive(Context context, Intent intent) {
Joe Onorato36115782010-06-17 13:28:48 -04001060 if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001061
Joe Onorato36115782010-06-17 13:28:48 -04001062 final String action = intent.getAction();
Joe Onoratof99f8c12009-10-31 17:27:36 -04001063
Joe Onorato36115782010-06-17 13:28:48 -04001064 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
1065 || Intent.ACTION_PACKAGE_REMOVED.equals(action)
1066 || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1067 final String packageName = intent.getData().getSchemeSpecificPart();
1068 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001069
Joe Onorato36115782010-06-17 13:28:48 -04001070 int op = PackageUpdatedTask.OP_NONE;
1071
1072 if (packageName == null || packageName.length() == 0) {
1073 // they sent us a bad intent
1074 return;
1075 }
1076
1077 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1078 op = PackageUpdatedTask.OP_UPDATE;
1079 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1080 if (!replacing) {
1081 op = PackageUpdatedTask.OP_REMOVE;
1082 }
1083 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1084 // later, we will update the package at this time
1085 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1086 if (!replacing) {
1087 op = PackageUpdatedTask.OP_ADD;
1088 } else {
1089 op = PackageUpdatedTask.OP_UPDATE;
1090 }
1091 }
1092
1093 if (op != PackageUpdatedTask.OP_NONE) {
1094 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
1095 }
1096
1097 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Joe Onoratocec58332010-10-07 14:37:40 -04001098 // First, schedule to add these apps back in.
1099 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1100 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
1101 // Then, rebind everything.
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001102 startLoaderFromBackground();
Joe Onorato36115782010-06-17 13:28:48 -04001103 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1104 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1105 enqueuePackageUpdated(new PackageUpdatedTask(
1106 PackageUpdatedTask.OP_UNAVAILABLE, packages));
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001107 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001108 // If we have changed locale we need to clear out the labels in all apps/workspace.
1109 forceReload();
1110 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1111 // Check if configuration change was an mcc/mnc change which would affect app resources
1112 // and we would need to clear out the labels in all apps/workspace. Same handling as
1113 // above for ACTION_LOCALE_CHANGED
1114 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001115 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001116 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001117 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001118 forceReload();
1119 }
1120 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001121 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001122 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1123 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001124 if (mCallbacks != null) {
1125 Callbacks callbacks = mCallbacks.get();
1126 if (callbacks != null) {
1127 callbacks.bindSearchablesChanged();
1128 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001129 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001130 }
1131 }
1132
Reena Lee93f824a2011-09-23 17:20:28 -07001133 private void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001134 resetLoadedState(true, true);
1135
Reena Lee93f824a2011-09-23 17:20:28 -07001136 // Do this here because if the launcher activity is running it will be restarted.
1137 // If it's not running startLoaderFromBackground will merely tell it that it needs
1138 // to reload.
1139 startLoaderFromBackground();
1140 }
1141
Winson Chungf0c6ae02012-03-21 16:10:31 -07001142 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1143 synchronized (mLock) {
1144 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1145 // mWorkspaceLoaded to true later
1146 stopLoaderLocked();
1147 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1148 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1149 }
1150 }
1151
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001152 /**
1153 * When the launcher is in the background, it's possible for it to miss paired
1154 * configuration changes. So whenever we trigger the loader from the background
1155 * tell the launcher that it needs to re-run the loader when it comes back instead
1156 * of doing it now.
1157 */
1158 public void startLoaderFromBackground() {
1159 boolean runLoader = false;
1160 if (mCallbacks != null) {
1161 Callbacks callbacks = mCallbacks.get();
1162 if (callbacks != null) {
1163 // Only actually run the loader if they're not paused.
1164 if (!callbacks.setLoadOnResume()) {
1165 runLoader = true;
1166 }
1167 }
1168 }
1169 if (runLoader) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001170 startLoader(false, -1);
Joe Onorato790c2d92010-06-11 00:14:11 -07001171 }
Joe Onorato36115782010-06-17 13:28:48 -04001172 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001173
Reena Lee93f824a2011-09-23 17:20:28 -07001174 // If there is already a loader task running, tell it to stop.
1175 // returns true if isLaunching() was true on the old task
1176 private boolean stopLoaderLocked() {
1177 boolean isLaunching = false;
1178 LoaderTask oldTask = mLoaderTask;
1179 if (oldTask != null) {
1180 if (oldTask.isLaunching()) {
1181 isLaunching = true;
1182 }
1183 oldTask.stopLocked();
1184 }
1185 return isLaunching;
1186 }
1187
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001188 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Joe Onorato36115782010-06-17 13:28:48 -04001189 synchronized (mLock) {
1190 if (DEBUG_LOADERS) {
1191 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1192 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001193
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001194 // Clear any deferred bind-runnables from the synchronized load process
1195 // We must do this before any loading/binding is scheduled below.
1196 mDeferredBindRunnables.clear();
1197
Joe Onorato36115782010-06-17 13:28:48 -04001198 // Don't bother to start the thread if we know it's not going to do anything
1199 if (mCallbacks != null && mCallbacks.get() != null) {
1200 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001201 // also, don't downgrade isLaunching if we're already running
1202 isLaunching = isLaunching || stopLoaderLocked();
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001203 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001204 if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
1205 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1206 } else {
1207 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1208 sWorker.post(mLoaderTask);
1209 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001210 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001211 }
1212 }
1213
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001214 void bindRemainingSynchronousPages() {
1215 // Post the remaining side pages to be loaded
1216 if (!mDeferredBindRunnables.isEmpty()) {
1217 for (final Runnable r : mDeferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001218 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001219 }
1220 mDeferredBindRunnables.clear();
1221 }
1222 }
1223
Joe Onorato36115782010-06-17 13:28:48 -04001224 public void stopLoader() {
1225 synchronized (mLock) {
1226 if (mLoaderTask != null) {
1227 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001228 }
1229 }
Joe Onorato36115782010-06-17 13:28:48 -04001230 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001231
Michael Jurkac57b7a82011-08-09 22:02:20 -07001232 public boolean isAllAppsLoaded() {
1233 return mAllAppsLoaded;
1234 }
1235
Winson Chung36a62fe2012-05-06 18:04:42 -07001236 boolean isLoadingWorkspace() {
1237 synchronized (mLock) {
1238 if (mLoaderTask != null) {
1239 return mLoaderTask.isLoadingWorkspace();
1240 }
1241 }
1242 return false;
1243 }
1244
Joe Onorato36115782010-06-17 13:28:48 -04001245 /**
1246 * Runnable for the thread that loads the contents of the launcher:
1247 * - workspace icons
1248 * - widgets
1249 * - all apps icons
1250 */
1251 private class LoaderTask implements Runnable {
1252 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001253 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001254 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001255 private boolean mStopped;
1256 private boolean mLoadAndBindStepFinished;
Adam Cohene25af792013-06-06 23:08:25 -07001257 private boolean mIsUpgradePath;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001258
Winson Chungc3eecff2011-07-11 17:44:15 -07001259 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001260
1261 LoaderTask(Context context, boolean isLaunching) {
1262 mContext = context;
1263 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001264 mLabelCache = new HashMap<Object, CharSequence>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001265 }
1266
Joe Onorato36115782010-06-17 13:28:48 -04001267 boolean isLaunching() {
1268 return mIsLaunching;
1269 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001270
Winson Chung36a62fe2012-05-06 18:04:42 -07001271 boolean isLoadingWorkspace() {
1272 return mIsLoadingAndBindingWorkspace;
1273 }
1274
Joe Onorato36115782010-06-17 13:28:48 -04001275 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001276 mIsLoadingAndBindingWorkspace = true;
1277
Joe Onorato36115782010-06-17 13:28:48 -04001278 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001279 if (DEBUG_LOADERS) {
1280 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001281 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001282
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001283 if (!mWorkspaceLoaded) {
Joe Onorato36115782010-06-17 13:28:48 -04001284 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001285 synchronized (LoaderTask.this) {
1286 if (mStopped) {
1287 return;
1288 }
1289 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001290 }
1291 }
1292
Joe Onorato36115782010-06-17 13:28:48 -04001293 // Bind the workspace
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001294 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001295 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001296
Joe Onorato36115782010-06-17 13:28:48 -04001297 private void waitForIdle() {
1298 // Wait until the either we're stopped or the other threads are done.
1299 // This way we don't start loading all apps until the workspace has settled
1300 // down.
1301 synchronized (LoaderTask.this) {
1302 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001303
Joe Onorato36115782010-06-17 13:28:48 -04001304 mHandler.postIdle(new Runnable() {
1305 public void run() {
1306 synchronized (LoaderTask.this) {
1307 mLoadAndBindStepFinished = true;
1308 if (DEBUG_LOADERS) {
1309 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001310 }
Joe Onorato36115782010-06-17 13:28:48 -04001311 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001312 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001313 }
Joe Onorato36115782010-06-17 13:28:48 -04001314 });
1315
Michael Jurkac7700af2013-05-14 20:17:58 +02001316 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001317 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001318 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1319 // wait no longer than 1sec at a time
1320 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001321 } catch (InterruptedException ex) {
1322 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001323 }
1324 }
Joe Onorato36115782010-06-17 13:28:48 -04001325 if (DEBUG_LOADERS) {
1326 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001327 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001328 + "ms for previous step to finish binding");
1329 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001330 }
Joe Onorato36115782010-06-17 13:28:48 -04001331 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001332
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001333 void runBindSynchronousPage(int synchronousBindPage) {
1334 if (synchronousBindPage < 0) {
1335 // Ensure that we have a valid page index to load synchronously
1336 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1337 "valid page index");
1338 }
1339 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1340 // Ensure that we don't try and bind a specified page when the pages have not been
1341 // loaded already (we should load everything asynchronously in that case)
1342 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1343 }
1344 synchronized (mLock) {
1345 if (mIsLoaderTaskRunning) {
1346 // Ensure that we are never running the background loading at this point since
1347 // we also touch the background collections
1348 throw new RuntimeException("Error! Background loading is already running");
1349 }
1350 }
1351
1352 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1353 // data structures, we can't allow any other thread to touch that data, but because
1354 // this call is synchronous, we can get away with not locking).
1355
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001356 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001357 // operations from the previous activity. We need to ensure that all queued operations
1358 // are executed before any synchronous binding work is done.
1359 mHandler.flush();
1360
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001361 // Divide the set of loaded items into those that we are binding synchronously, and
1362 // everything else that is to be bound normally (asynchronously).
1363 bindWorkspace(synchronousBindPage);
1364 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1365 // arise from that.
1366 onlyBindAllApps();
1367 }
1368
Joe Onorato36115782010-06-17 13:28:48 -04001369 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001370 synchronized (mLock) {
1371 mIsLoaderTaskRunning = true;
1372 }
Joe Onorato36115782010-06-17 13:28:48 -04001373 // Optimize for end-user experience: if the Launcher is up and // running with the
1374 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1375 // workspace first (default).
1376 final Callbacks cbk = mCallbacks.get();
Joe Onorato36115782010-06-17 13:28:48 -04001377 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001378 // Elevate priority when Home launches for the first time to avoid
1379 // starving at boot time. Staring at a blank home is not cool.
1380 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001381 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1382 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001383 android.os.Process.setThreadPriority(mIsLaunching
1384 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1385 }
Winson Chung64359a52013-07-08 17:17:08 -07001386 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
1387 loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001388
Joe Onorato36115782010-06-17 13:28:48 -04001389 if (mStopped) {
1390 break keep_running;
1391 }
1392
1393 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1394 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001395 synchronized (mLock) {
1396 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001397 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001398 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1399 }
1400 }
Joe Onorato36115782010-06-17 13:28:48 -04001401 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001402
1403 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001404 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1405 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001406
1407 // Restore the default thread priority after we are done loading items
1408 synchronized (mLock) {
1409 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1410 }
Joe Onorato36115782010-06-17 13:28:48 -04001411 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001412
Winson Chungaac01e12011-08-17 10:37:13 -07001413 // Update the saved icons if necessary
1414 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001415 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001416 for (Object key : sBgDbIconCache.keySet()) {
1417 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1418 }
1419 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001420 }
Winson Chungaac01e12011-08-17 10:37:13 -07001421
Joe Onorato36115782010-06-17 13:28:48 -04001422 // Clear out this reference, otherwise we end up holding it until all of the
1423 // callback runnables are done.
1424 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001425
Joe Onorato36115782010-06-17 13:28:48 -04001426 synchronized (mLock) {
1427 // If we are still the last one to be scheduled, remove ourselves.
1428 if (mLoaderTask == this) {
1429 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001430 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001431 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001432 }
Joe Onorato36115782010-06-17 13:28:48 -04001433 }
1434
1435 public void stopLocked() {
1436 synchronized (LoaderTask.this) {
1437 mStopped = true;
1438 this.notify();
1439 }
1440 }
1441
1442 /**
1443 * Gets the callbacks object. If we've been stopped, or if the launcher object
1444 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1445 * object that was around when the deferred message was scheduled, and if there's
1446 * a new Callbacks object around then also return null. This will save us from
1447 * calling onto it with data that will be ignored.
1448 */
1449 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1450 synchronized (mLock) {
1451 if (mStopped) {
1452 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001453 }
Joe Onorato36115782010-06-17 13:28:48 -04001454
1455 if (mCallbacks == null) {
1456 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001457 }
Joe Onorato36115782010-06-17 13:28:48 -04001458
1459 final Callbacks callbacks = mCallbacks.get();
1460 if (callbacks != oldCallbacks) {
1461 return null;
1462 }
1463 if (callbacks == null) {
1464 Log.w(TAG, "no mCallbacks");
1465 return null;
1466 }
1467
1468 return callbacks;
1469 }
1470 }
1471
1472 // check & update map of what's occupied; used to discard overlapping/invalid items
Adam Cohendcd297f2013-06-18 13:13:40 -07001473 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
1474 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001475 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001476 if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
1477 if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1478 [(int) item.screenId][0] != null) {
1479 Log.e(TAG, "Error loading shortcut into hotseat " + item
1480 + " into position (" + item.screenId + ":" + item.cellX + ","
1481 + item.cellY + ") occupied by "
1482 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1483 [(int) item.screenId][0]);
1484 return false;
1485 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001486 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001487 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1488 items[(int) item.screenId][0] = item;
1489 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001490 return true;
1491 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001492 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1493 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001494 return true;
1495 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001496
Adam Cohendcd297f2013-06-18 13:13:40 -07001497 if (!occupied.containsKey(item.screenId)) {
1498 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1499 occupied.put(item.screenId, items);
1500 }
1501
1502 ItemInfo[][] screens = occupied.get(item.screenId);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001503 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001504 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1505 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001506 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001507 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001508 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001509 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001510 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001511 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001512 return false;
1513 }
1514 }
1515 }
1516 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1517 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001518 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001519 }
1520 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001521
Joe Onorato36115782010-06-17 13:28:48 -04001522 return true;
1523 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001524
Joe Onorato36115782010-06-17 13:28:48 -04001525 private void loadWorkspace() {
1526 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001527
Joe Onorato36115782010-06-17 13:28:48 -04001528 final Context context = mContext;
1529 final ContentResolver contentResolver = context.getContentResolver();
1530 final PackageManager manager = context.getPackageManager();
1531 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1532 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001533
Michael Jurkab85f8a42012-04-25 15:48:32 -07001534 // Make sure the default workspace is loaded, if needed
Adam Cohene25af792013-06-06 23:08:25 -07001535 boolean loadOldDb = mApp.getLauncherProvider().shouldLoadOldDb();
1536 Uri contentUri = loadOldDb ? LauncherSettings.Favorites.OLD_CONTENT_URI :
1537 LauncherSettings.Favorites.CONTENT_URI;
1538
1539 mIsUpgradePath = loadOldDb;
Michael Jurkab85f8a42012-04-25 15:48:32 -07001540
Winson Chung2abf94d2012-07-18 18:16:38 -07001541 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001542 sBgWorkspaceItems.clear();
1543 sBgAppWidgets.clear();
1544 sBgFolders.clear();
1545 sBgItemsIdMap.clear();
1546 sBgDbIconCache.clear();
Adam Cohendcd297f2013-06-18 13:13:40 -07001547 sBgWorkspaceScreens.clear();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001548
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001549 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001550
Adam Cohene25af792013-06-06 23:08:25 -07001551 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001552
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001553 // +1 for the hotseat (it can be larger than the workspace)
1554 // Load workspace in reverse order to ensure that latest items are loaded first (and
1555 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001556 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001557
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001558 try {
1559 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1560 final int intentIndex = c.getColumnIndexOrThrow
1561 (LauncherSettings.Favorites.INTENT);
1562 final int titleIndex = c.getColumnIndexOrThrow
1563 (LauncherSettings.Favorites.TITLE);
1564 final int iconTypeIndex = c.getColumnIndexOrThrow(
1565 LauncherSettings.Favorites.ICON_TYPE);
1566 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1567 final int iconPackageIndex = c.getColumnIndexOrThrow(
1568 LauncherSettings.Favorites.ICON_PACKAGE);
1569 final int iconResourceIndex = c.getColumnIndexOrThrow(
1570 LauncherSettings.Favorites.ICON_RESOURCE);
1571 final int containerIndex = c.getColumnIndexOrThrow(
1572 LauncherSettings.Favorites.CONTAINER);
1573 final int itemTypeIndex = c.getColumnIndexOrThrow(
1574 LauncherSettings.Favorites.ITEM_TYPE);
1575 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1576 LauncherSettings.Favorites.APPWIDGET_ID);
1577 final int screenIndex = c.getColumnIndexOrThrow(
1578 LauncherSettings.Favorites.SCREEN);
1579 final int cellXIndex = c.getColumnIndexOrThrow
1580 (LauncherSettings.Favorites.CELLX);
1581 final int cellYIndex = c.getColumnIndexOrThrow
1582 (LauncherSettings.Favorites.CELLY);
1583 final int spanXIndex = c.getColumnIndexOrThrow
1584 (LauncherSettings.Favorites.SPANX);
1585 final int spanYIndex = c.getColumnIndexOrThrow(
1586 LauncherSettings.Favorites.SPANY);
1587 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1588 //final int displayModeIndex = c.getColumnIndexOrThrow(
1589 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001590
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001591 ShortcutInfo info;
1592 String intentDescription;
1593 LauncherAppWidgetInfo appWidgetInfo;
1594 int container;
1595 long id;
1596 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001597
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001598 while (!mStopped && c.moveToNext()) {
1599 try {
1600 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001601
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001602 switch (itemType) {
1603 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1604 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1605 intentDescription = c.getString(intentIndex);
1606 try {
1607 intent = Intent.parseUri(intentDescription, 0);
1608 } catch (URISyntaxException e) {
1609 continue;
1610 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001611
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001612 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1613 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1614 titleIndex, mLabelCache);
1615 } else {
1616 info = getShortcutInfo(c, context, iconTypeIndex,
1617 iconPackageIndex, iconResourceIndex, iconIndex,
1618 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001619
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001620 // App shortcuts that used to be automatically added to Launcher
1621 // didn't always have the correct intent flags set, so do that
1622 // here
1623 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001624 intent.getCategories() != null &&
1625 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001626 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001627 intent.addFlags(
1628 Intent.FLAG_ACTIVITY_NEW_TASK |
1629 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1630 }
Michael Jurka96879562012-03-22 05:54:33 -07001631 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001632
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001633 if (info != null) {
1634 info.intent = intent;
1635 info.id = c.getLong(idIndex);
1636 container = c.getInt(containerIndex);
1637 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001638 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001639 info.cellX = c.getInt(cellXIndex);
1640 info.cellY = c.getInt(cellYIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001641 // check & update map of what's occupied
1642 if (!checkItemPlacement(occupied, info)) {
1643 break;
1644 }
1645
1646 switch (container) {
1647 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1648 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1649 sBgWorkspaceItems.add(info);
1650 break;
1651 default:
1652 // Item is in a user folder
1653 FolderInfo folderInfo =
1654 findOrMakeFolder(sBgFolders, container);
1655 folderInfo.add(info);
1656 break;
1657 }
Adam Cohene25af792013-06-06 23:08:25 -07001658 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
1659 loadOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001660 info.screenId = permuteScreens(info.screenId);
Adam Cohene25af792013-06-06 23:08:25 -07001661 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001662 sBgItemsIdMap.put(info.id, info);
1663
1664 // now that we've loaded everthing re-save it with the
1665 // icon in case it disappears somehow.
1666 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
1667 } else {
1668 // Failed to load the shortcut, probably because the
1669 // activity manager couldn't resolve it (maybe the app
1670 // was uninstalled), or the db row was somehow screwed up.
1671 // Delete it.
1672 id = c.getLong(idIndex);
1673 Log.e(TAG, "Error loading shortcut " + id + ", removing it");
1674 contentResolver.delete(LauncherSettings.Favorites.getContentUri(
1675 id, false), null, null);
1676 }
1677 break;
1678
1679 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1680 id = c.getLong(idIndex);
1681 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1682
1683 folderInfo.title = c.getString(titleIndex);
1684 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001685 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001686 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001687 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001688 folderInfo.cellX = c.getInt(cellXIndex);
1689 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001690
Daniel Sandler8802e962010-05-26 16:28:16 -04001691 // check & update map of what's occupied
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001692 if (!checkItemPlacement(occupied, folderInfo)) {
Daniel Sandler8802e962010-05-26 16:28:16 -04001693 break;
1694 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001695 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001696 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1697 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1698 sBgWorkspaceItems.add(folderInfo);
1699 break;
Joe Onorato36115782010-06-17 13:28:48 -04001700 }
Adam Cohene25af792013-06-06 23:08:25 -07001701 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
1702 loadOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001703 folderInfo.screenId = permuteScreens(folderInfo.screenId);
Adam Cohene25af792013-06-06 23:08:25 -07001704 }
Joe Onorato17a89222011-02-08 17:26:11 -08001705
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001706 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1707 sBgFolders.put(folderInfo.id, folderInfo);
1708 break;
1709
1710 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1711 // Read all Launcher-specific widget details
1712 int appWidgetId = c.getInt(appWidgetIdIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001713 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001714
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001715 final AppWidgetProviderInfo provider =
1716 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001717
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001718 if (!isSafeMode && (provider == null || provider.provider == null ||
1719 provider.provider.getPackageName() == null)) {
1720 String log = "Deleting widget that isn't installed anymore: id="
1721 + id + " appWidgetId=" + appWidgetId;
1722 Log.e(TAG, log);
1723 Launcher.sDumpLogs.add(log);
1724 itemsToRemove.add(id);
1725 } else {
1726 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1727 provider.provider);
1728 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07001729 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001730 appWidgetInfo.cellX = c.getInt(cellXIndex);
1731 appWidgetInfo.cellY = c.getInt(cellYIndex);
1732 appWidgetInfo.spanX = c.getInt(spanXIndex);
1733 appWidgetInfo.spanY = c.getInt(spanYIndex);
1734 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1735 appWidgetInfo.minSpanX = minSpan[0];
1736 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001737
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001738 container = c.getInt(containerIndex);
1739 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1740 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1741 Log.e(TAG, "Widget found where container != " +
1742 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1743 continue;
1744 }
Adam Cohene25af792013-06-06 23:08:25 -07001745 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
1746 loadOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001747 appWidgetInfo.screenId =
1748 permuteScreens(appWidgetInfo.screenId);
Adam Cohene25af792013-06-06 23:08:25 -07001749 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001750
Adam Cohene25af792013-06-06 23:08:25 -07001751 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001752 // check & update map of what's occupied
1753 if (!checkItemPlacement(occupied, appWidgetInfo)) {
1754 break;
1755 }
1756 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1757 sBgAppWidgets.add(appWidgetInfo);
1758 }
Joe Onorato36115782010-06-17 13:28:48 -04001759 break;
1760 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001761 } catch (Exception e) {
1762 Log.w(TAG, "Desktop items loading interrupted:", e);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001763 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001764 }
1765 } finally {
1766 c.close();
1767 }
1768
1769 if (itemsToRemove.size() > 0) {
1770 ContentProviderClient client = contentResolver.acquireContentProviderClient(
1771 LauncherSettings.Favorites.CONTENT_URI);
1772 // Remove dead items
1773 for (long id : itemsToRemove) {
1774 if (DEBUG_LOADERS) {
1775 Log.d(TAG, "Removed id = " + id);
1776 }
1777 // Don't notify content observers
1778 try {
1779 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1780 null, null);
1781 } catch (RemoteException e) {
1782 Log.w(TAG, "Could not remove id = " + id);
1783 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001784 }
1785 }
1786
Adam Cohendcd297f2013-06-18 13:13:40 -07001787 if (loadOldDb) {
1788 long maxScreenId = 0;
1789 // If we're importing we use the old screen order.
1790 for (ItemInfo item: sBgItemsIdMap.values()) {
1791 long screenId = item.screenId;
1792 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1793 !sBgWorkspaceScreens.contains(screenId)) {
1794 sBgWorkspaceScreens.add(screenId);
1795 if (screenId > maxScreenId) {
1796 maxScreenId = screenId;
1797 }
1798 }
1799 }
1800 Collections.sort(sBgWorkspaceScreens);
1801 mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
1802 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1803 } else {
1804 Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1805 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1806 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1807
1808 try {
1809 final int idIndex = sc.getColumnIndexOrThrow(
1810 LauncherSettings.WorkspaceScreens._ID);
1811 final int rankIndex = sc.getColumnIndexOrThrow(
1812 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1813 while (sc.moveToNext()) {
1814 try {
1815 long screenId = sc.getLong(idIndex);
1816 int rank = sc.getInt(rankIndex);
1817
1818 orderedScreens.put(rank, screenId);
1819 } catch (Exception e) {
1820 Log.w(TAG, "Desktop items loading interrupted:", e);
1821 }
1822 }
1823 } finally {
1824 sc.close();
1825 }
1826
1827 Iterator<Integer> iter = orderedScreens.keySet().iterator();
1828 while (iter.hasNext()) {
1829 sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
1830 }
1831
1832 // Remove any empty screens
1833 ArrayList<Long> unusedScreens = new ArrayList<Long>();
1834 unusedScreens.addAll(sBgWorkspaceScreens);
1835
1836 for (ItemInfo item: sBgItemsIdMap.values()) {
1837 long screenId = item.screenId;
1838
1839 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1840 unusedScreens.contains(screenId)) {
1841 unusedScreens.remove(screenId);
1842 }
1843 }
1844
1845 // If there are any empty screens remove them, and update.
1846 if (unusedScreens.size() != 0) {
1847 sBgWorkspaceScreens.removeAll(unusedScreens);
1848 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1849 }
1850 }
1851
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001852 if (DEBUG_LOADERS) {
1853 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1854 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07001855 int nScreens = occupied.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001856 for (int y = 0; y < mCellCountY; y++) {
1857 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07001858
Daniel Sandler566da102013-06-25 23:43:45 -04001859 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07001860 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001861 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07001862 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001863 line += " | ";
1864 }
1865 for (int x = 0; x < mCellCountX; x++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001866 line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001867 }
Joe Onorato36115782010-06-17 13:28:48 -04001868 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001869 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04001870 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001871 }
Joe Onorato36115782010-06-17 13:28:48 -04001872 }
1873 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001874
Adam Cohene25af792013-06-06 23:08:25 -07001875 // We rearrange the screens from the old launcher
1876 // 12345 -> 34512
Adam Cohendcd297f2013-06-18 13:13:40 -07001877 private long permuteScreens(long screen) {
Adam Cohene25af792013-06-06 23:08:25 -07001878 if (screen >= 2) {
1879 return screen - 2;
1880 } else {
1881 return screen + 3;
1882 }
1883 }
1884
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001885 /** Filters the set of items who are directly or indirectly (via another container) on the
1886 * specified screen. */
1887 private void filterCurrentWorkspaceItems(int currentScreen,
1888 ArrayList<ItemInfo> allWorkspaceItems,
1889 ArrayList<ItemInfo> currentScreenItems,
1890 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001891 // Purge any null ItemInfos
1892 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1893 while (iter.hasNext()) {
1894 ItemInfo i = iter.next();
1895 if (i == null) {
1896 iter.remove();
1897 }
1898 }
1899
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001900 // If we aren't filtering on a screen, then the set of items to load is the full set of
1901 // items given.
1902 if (currentScreen < 0) {
1903 currentScreenItems.addAll(allWorkspaceItems);
Joe Onorato36115782010-06-17 13:28:48 -04001904 }
1905
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001906 // Order the set of items by their containers first, this allows use to walk through the
1907 // list sequentially, build up a list of containers that are in the specified screen,
1908 // as well as all items in those containers.
1909 Set<Long> itemsOnScreen = new HashSet<Long>();
1910 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1911 @Override
1912 public int compare(ItemInfo lhs, ItemInfo rhs) {
1913 return (int) (lhs.container - rhs.container);
1914 }
1915 });
1916 for (ItemInfo info : allWorkspaceItems) {
1917 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001918 if (info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001919 currentScreenItems.add(info);
1920 itemsOnScreen.add(info.id);
1921 } else {
1922 otherScreenItems.add(info);
1923 }
1924 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1925 currentScreenItems.add(info);
1926 itemsOnScreen.add(info.id);
1927 } else {
1928 if (itemsOnScreen.contains(info.container)) {
1929 currentScreenItems.add(info);
1930 itemsOnScreen.add(info.id);
1931 } else {
1932 otherScreenItems.add(info);
1933 }
1934 }
1935 }
1936 }
1937
1938 /** Filters the set of widgets which are on the specified screen. */
1939 private void filterCurrentAppWidgets(int currentScreen,
1940 ArrayList<LauncherAppWidgetInfo> appWidgets,
1941 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1942 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1943 // If we aren't filtering on a screen, then the set of items to load is the full set of
1944 // widgets given.
1945 if (currentScreen < 0) {
1946 currentScreenWidgets.addAll(appWidgets);
1947 }
1948
1949 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001950 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001951 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07001952 widget.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001953 currentScreenWidgets.add(widget);
1954 } else {
1955 otherScreenWidgets.add(widget);
1956 }
1957 }
1958 }
1959
1960 /** Filters the set of folders which are on the specified screen. */
1961 private void filterCurrentFolders(int currentScreen,
1962 HashMap<Long, ItemInfo> itemsIdMap,
1963 HashMap<Long, FolderInfo> folders,
1964 HashMap<Long, FolderInfo> currentScreenFolders,
1965 HashMap<Long, FolderInfo> otherScreenFolders) {
1966 // If we aren't filtering on a screen, then the set of items to load is the full set of
1967 // widgets given.
1968 if (currentScreen < 0) {
1969 currentScreenFolders.putAll(folders);
1970 }
1971
1972 for (long id : folders.keySet()) {
1973 ItemInfo info = itemsIdMap.get(id);
1974 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07001975 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001976 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07001977 info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001978 currentScreenFolders.put(id, folder);
1979 } else {
1980 otherScreenFolders.put(id, folder);
1981 }
1982 }
1983 }
1984
1985 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
1986 * right) */
1987 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
1988 // XXX: review this
1989 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07001990 @Override
1991 public int compare(ItemInfo lhs, ItemInfo rhs) {
1992 int cellCountX = LauncherModel.getCellCountX();
1993 int cellCountY = LauncherModel.getCellCountY();
1994 int screenOffset = cellCountX * cellCountY;
1995 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001996 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07001997 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07001998 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07001999 rhs.cellY * cellCountX + rhs.cellX);
2000 return (int) (lr - rr);
2001 }
2002 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002003 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002004
Adam Cohendcd297f2013-06-18 13:13:40 -07002005 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2006 final ArrayList<Long> orderedScreens) {
2007
2008 final Runnable r = new Runnable() {
2009 @Override
2010 public void run() {
2011 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2012 if (callbacks != null) {
2013 callbacks.bindScreens(orderedScreens);
2014 }
2015 }
2016 };
2017 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2018 }
2019
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002020 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2021 final ArrayList<ItemInfo> workspaceItems,
2022 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2023 final HashMap<Long, FolderInfo> folders,
2024 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002025
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002026 final boolean postOnMainThread = (deferredBindRunnables != null);
2027
2028 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002029 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002030 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002031 final int start = i;
2032 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002033 final Runnable r = new Runnable() {
2034 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002035 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002036 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002037 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002038 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2039 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002040 }
2041 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002042 };
2043 if (postOnMainThread) {
2044 deferredBindRunnables.add(r);
2045 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002046 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002047 }
Joe Onorato36115782010-06-17 13:28:48 -04002048 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002049
2050 // Bind the folders
2051 if (!folders.isEmpty()) {
2052 final Runnable r = new Runnable() {
2053 public void run() {
2054 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2055 if (callbacks != null) {
2056 callbacks.bindFolders(folders);
2057 }
2058 }
2059 };
2060 if (postOnMainThread) {
2061 deferredBindRunnables.add(r);
2062 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002063 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002064 }
2065 }
2066
2067 // Bind the widgets, one at a time
2068 N = appWidgets.size();
2069 for (int i = 0; i < N; i++) {
2070 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2071 final Runnable r = new Runnable() {
2072 public void run() {
2073 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2074 if (callbacks != null) {
2075 callbacks.bindAppWidget(widget);
2076 }
2077 }
2078 };
2079 if (postOnMainThread) {
2080 deferredBindRunnables.add(r);
2081 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002082 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002083 }
2084 }
2085 }
2086
2087 /**
2088 * Binds all loaded data to actual views on the main thread.
2089 */
2090 private void bindWorkspace(int synchronizeBindPage) {
2091 final long t = SystemClock.uptimeMillis();
2092 Runnable r;
2093
2094 // Don't use these two variables in any of the callback runnables.
2095 // Otherwise we hold a reference to them.
2096 final Callbacks oldCallbacks = mCallbacks.get();
2097 if (oldCallbacks == null) {
2098 // This launcher has exited and nobody bothered to tell us. Just bail.
2099 Log.w(TAG, "LoaderTask running with no launcher");
2100 return;
2101 }
2102
Winson Chung4a2afa32012-07-19 14:53:05 -07002103 final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
2104 final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002105 oldCallbacks.getCurrentWorkspaceScreen();
2106
2107 // Load all the items that are on the current page first (and in the process, unbind
2108 // all the existing workspace items before we call startBinding() below.
2109 unbindWorkspaceItemsOnMainThread();
2110 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2111 ArrayList<LauncherAppWidgetInfo> appWidgets =
2112 new ArrayList<LauncherAppWidgetInfo>();
2113 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2114 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002115 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002116 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002117 workspaceItems.addAll(sBgWorkspaceItems);
2118 appWidgets.addAll(sBgAppWidgets);
2119 folders.putAll(sBgFolders);
2120 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002121 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002122 }
2123
2124 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2125 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2126 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2127 new ArrayList<LauncherAppWidgetInfo>();
2128 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2129 new ArrayList<LauncherAppWidgetInfo>();
2130 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2131 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2132
2133 // Separate the items that are on the current screen, and all the other remaining items
2134 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
2135 otherWorkspaceItems);
2136 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
2137 otherAppWidgets);
2138 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
2139 otherFolders);
2140 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2141 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2142
2143 // Tell the workspace that we're about to start binding items
2144 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002145 public void run() {
2146 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2147 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002148 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002149 }
2150 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002151 };
Winson Chung81b52252012-08-27 15:34:29 -07002152 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002153
Adam Cohendcd297f2013-06-18 13:13:40 -07002154 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2155
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002156 // Load items on the current page
2157 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2158 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002159 if (isLoadingSynchronously) {
2160 r = new Runnable() {
2161 public void run() {
2162 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2163 if (callbacks != null) {
2164 callbacks.onPageBoundSynchronously(currentScreen);
2165 }
2166 }
2167 };
Winson Chung81b52252012-08-27 15:34:29 -07002168 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002169 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002170
Winson Chung4a2afa32012-07-19 14:53:05 -07002171 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2172 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002173 mDeferredBindRunnables.clear();
2174 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002175 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002176
2177 // Tell the workspace that we're done binding items
2178 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002179 public void run() {
2180 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2181 if (callbacks != null) {
Adam Cohene25af792013-06-06 23:08:25 -07002182 callbacks.finishBindingItems(mIsUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002183 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002184
Winson Chung98e030b2012-05-07 16:01:11 -07002185 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002186 if (DEBUG_LOADERS) {
2187 Log.d(TAG, "bound workspace in "
2188 + (SystemClock.uptimeMillis()-t) + "ms");
2189 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002190
2191 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002192 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002193 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002194 if (isLoadingSynchronously) {
2195 mDeferredBindRunnables.add(r);
2196 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002197 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002198 }
Joe Onorato36115782010-06-17 13:28:48 -04002199 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002200
Joe Onorato36115782010-06-17 13:28:48 -04002201 private void loadAndBindAllApps() {
2202 if (DEBUG_LOADERS) {
2203 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2204 }
2205 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002206 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002207 synchronized (LoaderTask.this) {
2208 if (mStopped) {
2209 return;
2210 }
2211 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002212 }
Joe Onorato36115782010-06-17 13:28:48 -04002213 } else {
2214 onlyBindAllApps();
2215 }
2216 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002217
Joe Onorato36115782010-06-17 13:28:48 -04002218 private void onlyBindAllApps() {
2219 final Callbacks oldCallbacks = mCallbacks.get();
2220 if (oldCallbacks == null) {
2221 // This launcher has exited and nobody bothered to tell us. Just bail.
2222 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2223 return;
2224 }
2225
2226 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002227 @SuppressWarnings("unchecked")
Joe Onorato36115782010-06-17 13:28:48 -04002228 final ArrayList<ApplicationInfo> list
Adam Cohen487f7dd2012-06-28 18:12:10 -07002229 = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002230 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002231 public void run() {
2232 final long t = SystemClock.uptimeMillis();
2233 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2234 if (callbacks != null) {
2235 callbacks.bindAllApplications(list);
2236 }
2237 if (DEBUG_LOADERS) {
2238 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2239 + (SystemClock.uptimeMillis()-t) + "ms");
2240 }
2241 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002242 };
2243 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002244 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002245 r.run();
2246 } else {
2247 mHandler.post(r);
2248 }
Joe Onorato36115782010-06-17 13:28:48 -04002249 }
2250
Winson Chung64359a52013-07-08 17:17:08 -07002251 private void loadAllApps() {
2252 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002253
2254 // Don't use these two variables in any of the callback runnables.
2255 // Otherwise we hold a reference to them.
2256 final Callbacks oldCallbacks = mCallbacks.get();
2257 if (oldCallbacks == null) {
2258 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002259 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002260 return;
2261 }
2262
Winson Chung64359a52013-07-08 17:17:08 -07002263 final PackageManager packageManager = mContext.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04002264 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2265 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2266
Winson Chung64359a52013-07-08 17:17:08 -07002267 // Clear the list of apps
2268 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002269
Winson Chung64359a52013-07-08 17:17:08 -07002270 // Query for the set of apps
2271 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2272 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2273 if (DEBUG_LOADERS) {
2274 Log.d(TAG, "queryIntentActivities took "
2275 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2276 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2277 }
2278 // Fail if we don't have any apps
2279 if (apps == null || apps.isEmpty()) {
2280 return;
2281 }
2282 // Sort the applications by name
2283 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2284 Collections.sort(apps,
2285 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2286 if (DEBUG_LOADERS) {
2287 Log.d(TAG, "sort took "
2288 + (SystemClock.uptimeMillis()-sortTime) + "ms");
Joe Onorato9c1289c2009-08-17 11:03:03 -04002289 }
2290
Winson Chung64359a52013-07-08 17:17:08 -07002291 // Create the ApplicationInfos
2292 final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2293 for (int i = 0; i < apps.size(); i++) {
2294 // This builds the icon bitmaps.
2295 mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
2296 mIconCache, mLabelCache));
2297 }
2298
2299 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2300 final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
2301 mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
2302
2303 // Post callback on main thread
2304 mHandler.post(new Runnable() {
2305 public void run() {
2306 final long bindTime = SystemClock.uptimeMillis();
2307 if (callbacks != null) {
2308 callbacks.bindAllApplications(added);
2309 if (DEBUG_LOADERS) {
2310 Log.d(TAG, "bound " + added.size() + " apps in "
2311 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2312 }
2313 } else {
2314 Log.i(TAG, "not binding apps: no Launcher activity");
2315 }
2316 }
2317 });
2318
Joe Onorato36115782010-06-17 13:28:48 -04002319 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002320 Log.d(TAG, "Icons processed in "
2321 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002322 }
2323 }
2324
2325 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002326 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002327 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2328 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2329 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2330 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2331 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2332 }
Joe Onorato36115782010-06-17 13:28:48 -04002333 }
2334 }
2335
2336 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002337 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002338 }
2339
2340 private class PackageUpdatedTask implements Runnable {
2341 int mOp;
2342 String[] mPackages;
2343
2344 public static final int OP_NONE = 0;
2345 public static final int OP_ADD = 1;
2346 public static final int OP_UPDATE = 2;
2347 public static final int OP_REMOVE = 3; // uninstlled
2348 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2349
2350
2351 public PackageUpdatedTask(int op, String[] packages) {
2352 mOp = op;
2353 mPackages = packages;
2354 }
2355
2356 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002357 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002358
2359 final String[] packages = mPackages;
2360 final int N = packages.length;
2361 switch (mOp) {
2362 case OP_ADD:
2363 for (int i=0; i<N; i++) {
2364 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002365 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002366 }
2367 break;
2368 case OP_UPDATE:
2369 for (int i=0; i<N; i++) {
2370 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002371 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002372 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002373 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002374 }
2375 break;
2376 case OP_REMOVE:
2377 case OP_UNAVAILABLE:
2378 for (int i=0; i<N; i++) {
2379 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002380 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002381 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002382 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002383 }
2384 break;
2385 }
2386
2387 ArrayList<ApplicationInfo> added = null;
Joe Onorato36115782010-06-17 13:28:48 -04002388 ArrayList<ApplicationInfo> modified = null;
Winson Chung83892cc2013-05-01 16:53:33 -07002389 final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002390
Adam Cohen487f7dd2012-06-28 18:12:10 -07002391 if (mBgAllAppsList.added.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002392 added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
2393 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002394 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002395 if (mBgAllAppsList.modified.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002396 modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
2397 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002398 }
Winson Chung5d55f332012-07-16 20:45:03 -07002399 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002400 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002401 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002402 }
2403
Joe Onorato36115782010-06-17 13:28:48 -04002404 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2405 if (callbacks == null) {
2406 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2407 return;
2408 }
2409
2410 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002411 // Ensure that we add all the workspace applications to the db
Winson Chung997a9232013-07-24 15:33:46 -07002412 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Winson Chung64359a52013-07-08 17:17:08 -07002413 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
Winson Chung997a9232013-07-24 15:33:46 -07002414 addAndBindAddedApps(context, addedInfos, cb);
Joe Onorato36115782010-06-17 13:28:48 -04002415 }
2416 if (modified != null) {
2417 final ArrayList<ApplicationInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002418
2419 // Update the launcher db to reflect the changes
2420 for (ApplicationInfo a : modifiedFinal) {
2421 ArrayList<ItemInfo> infos =
2422 getItemInfoForComponentName(a.componentName);
2423 for (ItemInfo i : infos) {
2424 if (isShortcutInfoUpdateable(i)) {
2425 ShortcutInfo info = (ShortcutInfo) i;
2426 info.title = a.title.toString();
2427 updateItemInDatabase(context, info);
2428 }
2429 }
2430 }
2431
Joe Onorato36115782010-06-17 13:28:48 -04002432 mHandler.post(new Runnable() {
2433 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002434 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2435 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002436 callbacks.bindAppsUpdated(modifiedFinal);
2437 }
2438 }
2439 });
2440 }
Winson Chung83892cc2013-05-01 16:53:33 -07002441 // If a package has been removed, or an app has been removed as a result of
2442 // an update (for example), make the removed callback.
2443 if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
Winson Chung64359a52013-07-08 17:17:08 -07002444 final boolean packageRemoved = (mOp == OP_REMOVE);
Winson Chung83892cc2013-05-01 16:53:33 -07002445 final ArrayList<String> removedPackageNames =
2446 new ArrayList<String>(Arrays.asList(packages));
2447
Winson Chung64359a52013-07-08 17:17:08 -07002448 // Update the launcher db to reflect the removal of apps
2449 if (packageRemoved) {
2450 for (String pn : removedPackageNames) {
2451 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2452 for (ItemInfo i : infos) {
2453 deleteItemFromDatabase(context, i);
2454 }
2455 }
2456 } else {
2457 for (ApplicationInfo a : removedApps) {
2458 ArrayList<ItemInfo> infos =
2459 getItemInfoForComponentName(a.componentName);
2460 for (ItemInfo i : infos) {
2461 deleteItemFromDatabase(context, i);
2462 }
2463 }
2464 }
2465
Joe Onorato36115782010-06-17 13:28:48 -04002466 mHandler.post(new Runnable() {
2467 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002468 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2469 if (callbacks == cb && cb != null) {
Winson Chung83892cc2013-05-01 16:53:33 -07002470 callbacks.bindComponentsRemoved(removedPackageNames,
Winson Chung64359a52013-07-08 17:17:08 -07002471 removedApps, packageRemoved);
Joe Onorato36115782010-06-17 13:28:48 -04002472 }
2473 }
2474 });
Joe Onoratobe386092009-11-17 17:32:16 -08002475 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002476
Michael Jurkac402cd92013-05-20 15:49:32 +02002477 final ArrayList<Object> widgetsAndShortcuts =
2478 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002479 mHandler.post(new Runnable() {
2480 @Override
2481 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002482 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2483 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002484 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002485 }
2486 }
2487 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002488 }
2489 }
2490
Michael Jurkac402cd92013-05-20 15:49:32 +02002491 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2492 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2493 PackageManager packageManager = context.getPackageManager();
2494 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2495 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2496 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2497 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2498 Collections.sort(widgetsAndShortcuts,
2499 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2500 return widgetsAndShortcuts;
2501 }
2502
Joe Onorato9c1289c2009-08-17 11:03:03 -04002503 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002504 * This is called from the code that adds shortcuts from the intent receiver. This
2505 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002506 */
Joe Onorato56d82912010-03-07 14:32:10 -05002507 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002508 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002509 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002510
Joe Onorato56d82912010-03-07 14:32:10 -05002511 /**
2512 * Make an ShortcutInfo object for a shortcut that is an application.
2513 *
2514 * If c is not null, then it will be used to fill in missing data like the title and icon.
2515 */
2516 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002517 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002518 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002519 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002520
2521 ComponentName componentName = intent.getComponent();
2522 if (componentName == null) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002523 return null;
2524 }
2525
Adam Cohen00fcb492011-11-02 21:53:47 -07002526 try {
2527 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2528 if (!pi.applicationInfo.enabled) {
2529 // If we return null here, the corresponding item will be removed from the launcher
2530 // db and will not appear in the workspace.
2531 return null;
2532 }
Michael Jurka1e2f4652013-07-08 18:03:46 -07002533 info.initFlagsAndFirstInstallTime(pi);
Adam Cohen00fcb492011-11-02 21:53:47 -07002534 } catch (NameNotFoundException e) {
2535 Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
2536 }
2537
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002538 // TODO: See if the PackageManager knows about this case. If it doesn't
2539 // then return null & delete this.
2540
Joe Onorato56d82912010-03-07 14:32:10 -05002541 // the resource -- This may implicitly give us back the fallback icon,
2542 // but don't worry about that. All we're doing with usingFallbackIcon is
2543 // to avoid saving lots of copies of that in the database, and most apps
2544 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002545
2546 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2547 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2548 // via resolveActivity().
2549 ResolveInfo resolveInfo = null;
2550 ComponentName oldComponent = intent.getComponent();
2551 Intent newIntent = new Intent(intent.getAction(), null);
2552 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2553 newIntent.setPackage(oldComponent.getPackageName());
2554 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2555 for (ResolveInfo i : infos) {
2556 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2557 i.activityInfo.name);
2558 if (cn.equals(oldComponent)) {
2559 resolveInfo = i;
2560 }
2561 }
2562 if (resolveInfo == null) {
2563 resolveInfo = manager.resolveActivity(intent, 0);
2564 }
Joe Onorato56d82912010-03-07 14:32:10 -05002565 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002566 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002567 }
Joe Onorato56d82912010-03-07 14:32:10 -05002568 // the db
2569 if (icon == null) {
2570 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002571 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002572 }
2573 }
2574 // the fallback icon
2575 if (icon == null) {
2576 icon = getFallbackIcon();
2577 info.usingFallbackIcon = true;
2578 }
2579 info.setIcon(icon);
2580
2581 // from the resource
2582 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002583 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2584 if (labelCache != null && labelCache.containsKey(key)) {
2585 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002586 } else {
2587 info.title = resolveInfo.activityInfo.loadLabel(manager);
2588 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002589 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002590 }
2591 }
Joe Onorato56d82912010-03-07 14:32:10 -05002592 }
2593 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002594 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002595 if (c != null) {
2596 info.title = c.getString(titleIndex);
2597 }
2598 }
2599 // fall back to the class name of the activity
2600 if (info.title == null) {
2601 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002602 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002603 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2604 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002605 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002606
Winson Chung64359a52013-07-08 17:17:08 -07002607 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2608 ItemInfoFilter f) {
2609 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2610 for (ItemInfo i : infos) {
2611 if (i instanceof ShortcutInfo) {
2612 ShortcutInfo info = (ShortcutInfo) i;
2613 ComponentName cn = info.intent.getComponent();
2614 if (cn != null && f.filterItem(null, info, cn)) {
2615 filtered.add(info);
2616 }
2617 } else if (i instanceof FolderInfo) {
2618 FolderInfo info = (FolderInfo) i;
2619 for (ShortcutInfo s : info.contents) {
2620 ComponentName cn = s.intent.getComponent();
2621 if (cn != null && f.filterItem(info, s, cn)) {
2622 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07002623 }
2624 }
Winson Chung64359a52013-07-08 17:17:08 -07002625 } else if (i instanceof LauncherAppWidgetInfo) {
2626 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2627 ComponentName cn = info.providerName;
2628 if (cn != null && f.filterItem(null, info, cn)) {
2629 filtered.add(info);
2630 }
Winson Chung8a435102012-08-30 17:16:53 -07002631 }
2632 }
Winson Chung64359a52013-07-08 17:17:08 -07002633 return new ArrayList<ItemInfo>(filtered);
2634 }
2635
2636 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
2637 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2638 ItemInfoFilter filter = new ItemInfoFilter() {
2639 @Override
2640 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2641 return cn.getPackageName().equals(pn);
2642 }
2643 };
2644 return filterItemInfos(sBgItemsIdMap.values(), filter);
2645 }
2646
2647 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
2648 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2649 ItemInfoFilter filter = new ItemInfoFilter() {
2650 @Override
2651 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2652 return cn.equals(cname);
2653 }
2654 };
2655 return filterItemInfos(sBgItemsIdMap.values(), filter);
2656 }
2657
2658 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2659 if (i instanceof ShortcutInfo) {
2660 ShortcutInfo info = (ShortcutInfo) i;
2661 // We need to check for ACTION_MAIN otherwise getComponent() might
2662 // return null for some shortcuts (for instance, for shortcuts to
2663 // web pages.)
2664 Intent intent = info.intent;
2665 ComponentName name = intent.getComponent();
2666 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2667 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2668 return true;
2669 }
2670 }
2671 return false;
Winson Chung8a435102012-08-30 17:16:53 -07002672 }
2673
2674 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002675 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002676 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002677 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002678 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2679 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002680
Joe Onorato56d82912010-03-07 14:32:10 -05002681 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002682 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002683 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002684
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002685 // TODO: If there's an explicit component and we can't install that, delete it.
2686
Joe Onorato56d82912010-03-07 14:32:10 -05002687 info.title = c.getString(titleIndex);
2688
Joe Onorato9c1289c2009-08-17 11:03:03 -04002689 int iconType = c.getInt(iconTypeIndex);
2690 switch (iconType) {
2691 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2692 String packageName = c.getString(iconPackageIndex);
2693 String resourceName = c.getString(iconResourceIndex);
2694 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002695 info.customIcon = false;
2696 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002697 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002698 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002699 if (resources != null) {
2700 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002701 icon = Utilities.createIconBitmap(
2702 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002703 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002704 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002705 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002706 }
Joe Onorato56d82912010-03-07 14:32:10 -05002707 // the db
2708 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002709 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002710 }
2711 // the fallback icon
2712 if (icon == null) {
2713 icon = getFallbackIcon();
2714 info.usingFallbackIcon = true;
2715 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002716 break;
2717 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002718 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002719 if (icon == null) {
2720 icon = getFallbackIcon();
2721 info.customIcon = false;
2722 info.usingFallbackIcon = true;
2723 } else {
2724 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002725 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002726 break;
2727 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002728 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002729 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002730 info.customIcon = false;
2731 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002732 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002733 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002734 return info;
2735 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002736
Michael Jurka931dc972011-08-05 15:08:15 -07002737 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002738 @SuppressWarnings("all") // suppress dead code warning
2739 final boolean debug = false;
2740 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002741 Log.d(TAG, "getIconFromCursor app="
2742 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2743 }
2744 byte[] data = c.getBlob(iconIndex);
2745 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002746 return Utilities.createIconBitmap(
2747 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002748 } catch (Exception e) {
2749 return null;
2750 }
2751 }
2752
Winson Chung3d503fb2011-07-13 17:25:49 -07002753 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2754 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002755 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002756 if (info == null) {
2757 return null;
2758 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002759 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002760
2761 return info;
2762 }
2763
Winson Chunga9abd0e2010-10-27 17:18:37 -07002764 /**
Winson Chung55cef262010-10-28 14:14:18 -07002765 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2766 */
2767 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2768 ComponentName component) {
2769 List<AppWidgetProviderInfo> widgets =
2770 AppWidgetManager.getInstance(context).getInstalledProviders();
2771 for (AppWidgetProviderInfo info : widgets) {
2772 if (info.provider.equals(component)) {
2773 return info;
2774 }
2775 }
2776 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002777 }
2778
Winson Chung68846fd2010-10-29 11:00:27 -07002779 /**
2780 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2781 */
2782 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2783 final PackageManager packageManager = context.getPackageManager();
2784 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2785 new ArrayList<WidgetMimeTypeHandlerData>();
2786
2787 final Intent supportsIntent =
2788 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2789 supportsIntent.setType(mimeType);
2790
2791 // Create a set of widget configuration components that we can test against
2792 final List<AppWidgetProviderInfo> widgets =
2793 AppWidgetManager.getInstance(context).getInstalledProviders();
2794 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2795 new HashMap<ComponentName, AppWidgetProviderInfo>();
2796 for (AppWidgetProviderInfo info : widgets) {
2797 configurationComponentToWidget.put(info.configure, info);
2798 }
2799
2800 // Run through each of the intents that can handle this type of clip data, and cross
2801 // reference them with the components that are actual configuration components
2802 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2803 PackageManager.MATCH_DEFAULT_ONLY);
2804 for (ResolveInfo info : activities) {
2805 final ActivityInfo activityInfo = info.activityInfo;
2806 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2807 activityInfo.name);
2808 if (configurationComponentToWidget.containsKey(infoComponent)) {
2809 supportedConfigurationActivities.add(
2810 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2811 configurationComponentToWidget.get(infoComponent)));
2812 }
2813 }
2814 return supportedConfigurationActivities;
2815 }
2816
Winson Chunga9abd0e2010-10-27 17:18:37 -07002817 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08002818 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2819 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2820 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2821
Adam Cohend9198822011-11-22 16:42:47 -08002822 if (intent == null) {
2823 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2824 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2825 return null;
2826 }
2827
Joe Onorato0589f0f2010-02-08 13:44:00 -08002828 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08002829 boolean customIcon = false;
2830 ShortcutIconResource iconResource = null;
2831
2832 if (bitmap != null && bitmap instanceof Bitmap) {
2833 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002834 customIcon = true;
2835 } else {
2836 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2837 if (extra != null && extra instanceof ShortcutIconResource) {
2838 try {
2839 iconResource = (ShortcutIconResource) extra;
2840 final PackageManager packageManager = context.getPackageManager();
2841 Resources resources = packageManager.getResourcesForApplication(
2842 iconResource.packageName);
2843 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002844 icon = Utilities.createIconBitmap(
2845 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002846 } catch (Exception e) {
2847 Log.w(TAG, "Could not load shortcut icon: " + extra);
2848 }
2849 }
2850 }
2851
Michael Jurkac9d95c52011-08-29 14:03:34 -07002852 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002853
2854 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002855 if (fallbackIcon != null) {
2856 icon = fallbackIcon;
2857 } else {
2858 icon = getFallbackIcon();
2859 info.usingFallbackIcon = true;
2860 }
Joe Onorato56d82912010-03-07 14:32:10 -05002861 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08002862 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05002863
Joe Onorato0589f0f2010-02-08 13:44:00 -08002864 info.title = name;
2865 info.intent = intent;
2866 info.customIcon = customIcon;
2867 info.iconResource = iconResource;
2868
2869 return info;
2870 }
2871
Winson Chungaac01e12011-08-17 10:37:13 -07002872 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2873 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08002874 // If apps can't be on SD, don't even bother.
2875 if (!mAppsCanBeOnExternalStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07002876 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08002877 }
Joe Onorato56d82912010-03-07 14:32:10 -05002878 // If this icon doesn't have a custom icon, check to see
2879 // what's stored in the DB, and if it doesn't match what
2880 // we're going to show, store what we are going to show back
2881 // into the DB. We do this so when we're loading, if the
2882 // package manager can't find an icon (for example because
2883 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07002884 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07002885 cache.put(info, c.getBlob(iconIndex));
2886 return true;
2887 }
2888 return false;
2889 }
2890 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2891 boolean needSave = false;
2892 try {
2893 if (data != null) {
2894 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2895 Bitmap loaded = info.getIcon(mIconCache);
2896 needSave = !saved.sameAs(loaded);
2897 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05002898 needSave = true;
2899 }
Winson Chungaac01e12011-08-17 10:37:13 -07002900 } catch (Exception e) {
2901 needSave = true;
2902 }
2903 if (needSave) {
2904 Log.d(TAG, "going to save icon bitmap for info=" + info);
2905 // This is slower than is ideal, but this only happens once
2906 // or when the app is updated with a new icon.
2907 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05002908 }
2909 }
2910
Joe Onorato9c1289c2009-08-17 11:03:03 -04002911 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07002912 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04002913 * or make a new one.
2914 */
Adam Cohendf2cc412011-04-27 16:56:57 -07002915 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002916 // See if a placeholder was created for us already
2917 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07002918 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002919 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07002920 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002921 folders.put(id, folderInfo);
2922 }
Adam Cohendf2cc412011-04-27 16:56:57 -07002923 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002924 }
2925
Winson Chung11904872012-09-17 16:58:46 -07002926 public static final Comparator<ApplicationInfo> getAppNameComparator() {
2927 final Collator collator = Collator.getInstance();
2928 return new Comparator<ApplicationInfo>() {
2929 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2930 int result = collator.compare(a.title.toString(), b.title.toString());
2931 if (result == 0) {
2932 result = a.componentName.compareTo(b.componentName);
2933 }
2934 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07002935 }
Winson Chung11904872012-09-17 16:58:46 -07002936 };
2937 }
Winson Chung78403fe2011-01-21 15:38:02 -08002938 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2939 = new Comparator<ApplicationInfo>() {
2940 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2941 if (a.firstInstallTime < b.firstInstallTime) return 1;
2942 if (a.firstInstallTime > b.firstInstallTime) return -1;
2943 return 0;
2944 }
2945 };
Winson Chung11904872012-09-17 16:58:46 -07002946 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
2947 final Collator collator = Collator.getInstance();
2948 return new Comparator<AppWidgetProviderInfo>() {
2949 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
2950 return collator.compare(a.label.toString(), b.label.toString());
2951 }
2952 };
2953 }
Winson Chung5308f242011-08-18 12:12:41 -07002954 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
2955 if (info.activityInfo != null) {
2956 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
2957 } else {
2958 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
2959 }
2960 }
Winson Chung785d2eb2011-04-14 16:08:02 -07002961 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07002962 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07002963 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07002964 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07002965 ShortcutNameComparator(PackageManager pm) {
2966 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07002967 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07002968 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07002969 }
2970 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
2971 mPackageManager = pm;
2972 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07002973 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07002974 }
2975 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002976 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07002977 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
2978 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
2979 if (mLabelCache.containsKey(keyA)) {
2980 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002981 } else {
2982 labelA = a.loadLabel(mPackageManager).toString();
2983
Winson Chung5308f242011-08-18 12:12:41 -07002984 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07002985 }
Winson Chung5308f242011-08-18 12:12:41 -07002986 if (mLabelCache.containsKey(keyB)) {
2987 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002988 } else {
2989 labelB = b.loadLabel(mPackageManager).toString();
2990
Winson Chung5308f242011-08-18 12:12:41 -07002991 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07002992 }
Winson Chung11904872012-09-17 16:58:46 -07002993 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07002994 }
2995 };
Winson Chung1ed747a2011-05-03 16:18:34 -07002996 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07002997 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07002998 private PackageManager mPackageManager;
2999 private HashMap<Object, String> mLabelCache;
3000 WidgetAndShortcutNameComparator(PackageManager pm) {
3001 mPackageManager = pm;
3002 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003003 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003004 }
3005 public final int compare(Object a, Object b) {
3006 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003007 if (mLabelCache.containsKey(a)) {
3008 labelA = mLabelCache.get(a);
3009 } else {
3010 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003011 ((AppWidgetProviderInfo) a).label :
3012 ((ResolveInfo) a).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003013 mLabelCache.put(a, labelA);
3014 }
3015 if (mLabelCache.containsKey(b)) {
3016 labelB = mLabelCache.get(b);
3017 } else {
3018 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003019 ((AppWidgetProviderInfo) b).label :
3020 ((ResolveInfo) b).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003021 mLabelCache.put(b, labelB);
3022 }
Winson Chung11904872012-09-17 16:58:46 -07003023 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003024 }
3025 };
Joe Onoratobe386092009-11-17 17:32:16 -08003026
3027 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003028 Log.d(TAG, "mCallbacks=" + mCallbacks);
Adam Cohen487f7dd2012-06-28 18:12:10 -07003029 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3030 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3031 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3032 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003033 if (mLoaderTask != null) {
3034 mLoaderTask.dumpState();
3035 } else {
3036 Log.d(TAG, "mLoaderTask=null");
3037 }
Joe Onoratobe386092009-11-17 17:32:16 -08003038 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003039}