blob: b085441334d47d66323933e3513a7ea4d43d3c50 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Narayan Kamathcb1a4772011-06-28 13:46:59 +010019import android.app.SearchManager;
Romain Guy629de3e2010-01-13 12:20:59 -080020import android.appwidget.AppWidgetManager;
21import android.appwidget.AppWidgetProviderInfo;
Winson Chungc9168342013-06-26 14:54:55 -070022import android.content.*;
Joe Onorato0589f0f2010-02-08 13:44:00 -080023import android.content.Intent.ShortcutIconResource;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080024import android.content.pm.ActivityInfo;
Adam Cohen00fcb492011-11-02 21:53:47 -070025import android.content.pm.PackageInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.pm.PackageManager;
Adam Cohen00fcb492011-11-02 21:53:47 -070027import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080028import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070029import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080030import android.content.res.Resources;
31import android.database.Cursor;
32import android.graphics.Bitmap;
33import android.graphics.BitmapFactory;
34import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080035import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040036import android.os.Handler;
37import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080038import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070040import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040041import android.os.SystemClock;
Winson Chungaafa03c2010-06-11 17:34:16 -070042import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070043import android.util.Pair;
Daniel Sandler325dc232013-06-05 22:57:57 -040044import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
Romain Guyedcce092010-03-04 13:03:17 -080045
Michael Jurkac2f801e2011-07-12 14:19:46 -070046import java.lang.ref.WeakReference;
47import java.net.URISyntaxException;
48import java.text.Collator;
49import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070050import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070051import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070052import java.util.Collections;
53import java.util.Comparator;
54import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070055import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070056import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070057import java.util.List;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070058import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070059import java.util.TreeMap;
Michael Jurkac2f801e2011-07-12 14:19:46 -070060
The Android Open Source Project31dd5032009-03-03 19:32:27 -080061/**
62 * Maintains in-memory state of the Launcher. It is expected that there should be only one
63 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070064 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065 */
Joe Onoratof99f8c12009-10-31 17:27:36 -040066public class LauncherModel extends BroadcastReceiver {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080067 static final boolean DEBUG_LOADERS = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -040068 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070069
Joe Onorato36115782010-06-17 13:28:48 -040070 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Winson Chungee055712013-07-30 14:46:24 -070071 private final boolean mAppsCanBeOnRemoveableStorage;
Daniel Sandlerdca66122010-04-13 16:23:58 -040072
Daniel Sandlercc8befa2013-06-11 14:45:48 -040073 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -040074 private final Object mLock = new Object();
75 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -040076 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070077 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +020078 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Winson Chung81b52252012-08-27 15:34:29 -070080 // Specific runnable types that are run on the main thread deferred handler, this allows us to
81 // clear all queued binding runnables when the Launcher activity is destroyed.
82 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
83 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
84
85
Brad Fitzpatrick700889f2010-10-11 09:40:44 -070086 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
87 static {
88 sWorkerThread.start();
89 }
90 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
91
Joe Onoratocc67f472010-06-08 10:54:30 -070092 // We start off with everything not loaded. After that, we assume that
93 // our monitoring of the package manager provides all updates and we never
94 // need to do a requery. These are only ever touched from the loader thread.
95 private boolean mWorkspaceLoaded;
96 private boolean mAllAppsLoaded;
97
Winson Chungb8b2a5a2012-07-12 17:55:31 -070098 // When we are loading pages synchronously, we can't just post the binding of items on the side
99 // pages as this delays the rotation process. Instead, we wait for a callback from the first
100 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
101 // a normal load, we also clear this set of Runnables.
102 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
103
Joe Onorato9c1289c2009-08-17 11:03:03 -0400104 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800105
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700106 // < only access in worker thread >
Adam Cohen487f7dd2012-06-28 18:12:10 -0700107 private AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800108
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700109 // The lock that must be acquired before referencing any static bg data structures. Unlike
110 // other locks, this one can generally be held long-term because we never expect any of these
111 // static data structures to be referenced outside of the worker thread except on the first
112 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700113 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700114
Adam Cohen487f7dd2012-06-28 18:12:10 -0700115 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700116 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700117 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700118
Adam Cohen487f7dd2012-06-28 18:12:10 -0700119 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
120 // created by LauncherModel that are directly on the home screen (however, no widgets or
121 // shortcuts within folders).
122 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700123
Adam Cohen487f7dd2012-06-28 18:12:10 -0700124 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
125 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700126 new ArrayList<LauncherAppWidgetInfo>();
127
Adam Cohen487f7dd2012-06-28 18:12:10 -0700128 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
129 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700130
Adam Cohen487f7dd2012-06-28 18:12:10 -0700131 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
132 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700133
134 // sBgWorkspaceScreens is the ordered set of workspace screens.
135 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
136
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 // </ only access in worker thread >
138
139 private IconCache mIconCache;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800140 private Bitmap mDefaultIcon;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800141
Adam Cohend22015c2010-07-26 22:02:18 -0700142 private static int mCellCountX;
143 private static int mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700144
Reena Lee99a73f32011-10-24 17:27:37 -0700145 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700146
Joe Onorato9c1289c2009-08-17 11:03:03 -0400147 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700148 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400149 public int getCurrentWorkspaceScreen();
150 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700151 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
152 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700153 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700154 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500155 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700156 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400157 public void bindAppWidget(LauncherAppWidgetInfo info);
158 public void bindAllApplications(ArrayList<ApplicationInfo> apps);
Joe Onorato64e6be72010-03-05 15:05:52 -0500159 public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
Winson Chung83892cc2013-05-01 16:53:33 -0700160 public void bindComponentsRemoved(ArrayList<String> packageNames,
161 ArrayList<ApplicationInfo> appInfos,
162 boolean matchPackageNamesOnly);
Michael Jurkac402cd92013-05-20 15:49:32 +0200163 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100164 public void bindSearchablesChanged();
Adam Cohen1462de32012-07-24 22:34:36 -0700165 public void onPageBoundSynchronously(int page);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400166 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800167
Winson Chung64359a52013-07-08 17:17:08 -0700168 public interface ItemInfoFilter {
169 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
170 }
171
Daniel Sandlere4f98912013-06-25 15:13:26 -0400172 LauncherModel(LauncherAppState app, IconCache iconCache) {
173 final Context context = app.getContext();
174
Winson Chungee055712013-07-30 14:46:24 -0700175 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400176 mApp = app;
Adam Cohen487f7dd2012-06-28 18:12:10 -0700177 mBgAllAppsList = new AllAppsList(iconCache);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800178 mIconCache = iconCache;
179
180 mDefaultIcon = Utilities.createIconBitmap(
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400181 mIconCache.getFullResDefaultActivityIcon(), context);
Daniel Sandler2ff10b32010-04-16 15:06:06 -0400182
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400183 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700184 Configuration config = res.getConfiguration();
185 mPreviousConfigMcc = config.mcc;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800186 }
187
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700188 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
189 * posted on the main thread handler. */
190 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700191 runOnMainThread(r, 0);
192 }
193 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700194 if (sWorkerThread.getThreadId() == Process.myTid()) {
195 // If we are on the worker thread, post onto the main handler
196 mHandler.post(r);
197 } else {
198 r.run();
199 }
200 }
201
202 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
203 * posted on the worker thread handler. */
204 private static void runOnWorkerThread(Runnable r) {
205 if (sWorkerThread.getThreadId() == Process.myTid()) {
206 r.run();
207 } else {
208 // If we are not on the worker thread, then post to the worker handler
209 sWorker.post(r);
210 }
211 }
212
Winson Chungc9168342013-06-26 14:54:55 -0700213 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
214 long screen) {
215 final int xCount = LauncherModel.getCellCountX();
216 final int yCount = LauncherModel.getCellCountY();
217 boolean[][] occupied = new boolean[xCount][yCount];
218
219 int cellX, cellY, spanX, spanY;
220 for (int i = 0; i < items.size(); ++i) {
221 final ItemInfo item = items.get(i);
222 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
223 if (item.screenId == screen) {
224 cellX = item.cellX;
225 cellY = item.cellY;
226 spanX = item.spanX;
227 spanY = item.spanY;
228 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
229 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
230 occupied[x][y] = true;
231 }
232 }
233 }
234 }
235 }
236
237 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
238 }
239 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700240 Intent launchIntent,
241 int firstScreenIndex) {
Winson Chungc9168342013-06-26 14:54:55 -0700242 // Lock on the app so that we don't try and get the items while apps are being added
243 LauncherAppState app = LauncherAppState.getInstance();
244 LauncherModel model = app.getModel();
245 boolean found = false;
246 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700247 if (sWorkerThread.getThreadId() != Process.myTid()) {
248 // Flush the LauncherModel worker thread, so that if we just did another
249 // processInstallShortcut, we give it time for its shortcut to get added to the
250 // database (getItemsInLocalCoordinates reads the database)
251 model.flushWorkerThread();
252 }
Winson Chungc9168342013-06-26 14:54:55 -0700253 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700254
255 // Try adding to the workspace screens incrementally, starting at the default or center
256 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung156ab5b2013-07-12 14:14:16 -0700257 firstScreenIndex = Math.min(firstScreenIndex, sBgWorkspaceScreens.size());
258 int count = sBgWorkspaceScreens.size();
259 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700260 int[] tmpCoordinates = new int[2];
261 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
262 sBgWorkspaceScreens.get(screen))) {
263 // Update the Launcher db
264 return new Pair<Long, int[]>(sBgWorkspaceScreens.get(screen), tmpCoordinates);
265 }
266 }
267 }
Winson Chungc9168342013-06-26 14:54:55 -0700268 return null;
269 }
270
Winson Chung997a9232013-07-24 15:33:46 -0700271 public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added) {
272 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
273 addAndBindAddedApps(context, added, cb);
274 }
275 public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added,
Winson Chung64359a52013-07-08 17:17:08 -0700276 final Callbacks callbacks) {
Winson Chung997a9232013-07-24 15:33:46 -0700277 if (added.isEmpty()) {
278 throw new RuntimeException("EMPTY ADDED ARRAY?");
279 }
Winson Chung64359a52013-07-08 17:17:08 -0700280 // Process the newly added applications and add them to the database first
281 Runnable r = new Runnable() {
282 public void run() {
283 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
284 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
285
286 synchronized(sBgLock) {
Winson Chung997a9232013-07-24 15:33:46 -0700287 Iterator<ItemInfo> iter = added.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700288 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700289 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700290 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700291 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700292
293 // Short-circuit this logic if the icon exists somewhere on the workspace
294 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
295 continue;
296 }
297
298 // Add this icon to the db, creating a new page if necessary
Winson Chung156ab5b2013-07-12 14:14:16 -0700299 int startSearchPageIndex = 1;
Winson Chung64359a52013-07-08 17:17:08 -0700300 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung156ab5b2013-07-12 14:14:16 -0700301 name, launchIntent, startSearchPageIndex);
Winson Chung64359a52013-07-08 17:17:08 -0700302 if (coords == null) {
Winson Chung64359a52013-07-08 17:17:08 -0700303 LauncherAppState appState = LauncherAppState.getInstance();
304 LauncherProvider lp = appState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700305
306 // If we can't find a valid position, then just add a new screen.
307 // This takes time so we need to re-queue the add until the new
308 // page is added. Create as many screens as necessary to satisfy
309 // the startSearchPageIndex.
310 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
311 sBgWorkspaceScreens.size());
312 while (numPagesToAdd > 0) {
313 long screenId = lp.generateNewScreenId();
Winson Chung8481e322013-08-09 16:06:38 -0700314 Log.d(TAG, "10249126 - addAndBindAddedApps(" + screenId + ")");
Winson Chungc763c4e2013-07-19 13:49:06 -0700315 // Update the model
316 sBgWorkspaceScreens.add(screenId);
317 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
318 // Save the screen id for binding in the workspace
319 addedWorkspaceScreensFinal.add(screenId);
320 numPagesToAdd--;
321 }
Winson Chung64359a52013-07-08 17:17:08 -0700322 // Find the coordinate again
323 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chungc763c4e2013-07-19 13:49:06 -0700324 name, launchIntent, startSearchPageIndex);
Winson Chung64359a52013-07-08 17:17:08 -0700325 }
326 if (coords == null) {
327 throw new RuntimeException("Coordinates should not be null");
328 }
329
Winson Chung997a9232013-07-24 15:33:46 -0700330 ShortcutInfo shortcutInfo;
331 if (a instanceof ShortcutInfo) {
332 shortcutInfo = (ShortcutInfo) a;
333 } else if (a instanceof ApplicationInfo) {
334 shortcutInfo = ((ApplicationInfo) a).makeShortcut();
335 } else {
336 throw new RuntimeException("Unexpected info type");
337 }
Winson Chung64359a52013-07-08 17:17:08 -0700338 // Add the shortcut to the db
339 addItemToDatabase(context, shortcutInfo,
340 LauncherSettings.Favorites.CONTAINER_DESKTOP,
341 coords.first, coords.second[0], coords.second[1], false);
342 // Save the ShortcutInfo for binding in the workspace
343 addedShortcutsFinal.add(shortcutInfo);
344 }
345 }
346
Winson Chung997a9232013-07-24 15:33:46 -0700347 if (!addedShortcutsFinal.isEmpty()) {
348 runOnMainThread(new Runnable() {
349 public void run() {
350 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
351 if (callbacks == cb && cb != null) {
352 callbacks.bindAddScreens(addedWorkspaceScreensFinal);
353
354 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
355 long lastScreenId = info.screenId;
356 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
357 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
358 for (ItemInfo i : addedShortcutsFinal) {
359 if (i.screenId == lastScreenId) {
360 addAnimated.add(i);
361 } else {
362 addNotAnimated.add(i);
363 }
364 }
365 // We add the items without animation on non-visible pages, and with
366 // animations on the new page (which we will try and snap to).
367 if (!addNotAnimated.isEmpty()) {
368 callbacks.bindItems(addNotAnimated, 0,
369 addNotAnimated.size(), false);
370 }
371 if (!addAnimated.isEmpty()) {
372 callbacks.bindItems(addAnimated, 0,
373 addAnimated.size(), true);
374 }
375 }
Winson Chung64359a52013-07-08 17:17:08 -0700376 }
Winson Chung997a9232013-07-24 15:33:46 -0700377 });
378 }
Winson Chung64359a52013-07-08 17:17:08 -0700379 }
380 };
381 runOnWorkerThread(r);
382 }
383
Joe Onorato56d82912010-03-07 14:32:10 -0500384 public Bitmap getFallbackIcon() {
Joe Onorato0589f0f2010-02-08 13:44:00 -0800385 return Bitmap.createBitmap(mDefaultIcon);
Joe Onoratof99f8c12009-10-31 17:27:36 -0400386 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800387
Winson Chung81b52252012-08-27 15:34:29 -0700388 public void unbindItemInfosAndClearQueuedBindRunnables() {
389 if (sWorkerThread.getThreadId() == Process.myTid()) {
390 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
391 "main thread");
392 }
393
394 // Clear any deferred bind runnables
395 mDeferredBindRunnables.clear();
396 // Remove any queued bind runnables
397 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
398 // Unbind all the workspace items
399 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700400 }
401
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700402 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700403 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700404 // Ensure that we don't use the same workspace items data structure on the main thread
405 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700406 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
407 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700408 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700409 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
410 tmpAppWidgets.addAll(sBgAppWidgets);
411 }
412 Runnable r = new Runnable() {
413 @Override
414 public void run() {
415 for (ItemInfo item : tmpWorkspaceItems) {
416 item.unbind();
417 }
418 for (ItemInfo item : tmpAppWidgets) {
419 item.unbind();
420 }
421 }
422 };
423 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700424 }
425
Joe Onorato9c1289c2009-08-17 11:03:03 -0400426 /**
427 * Adds an item to the DB if it was not created previously, or move it to a new
428 * <container, screen, cellX, cellY>
429 */
430 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700431 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400432 if (item.container == ItemInfo.NO_ID) {
433 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700434 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400435 } else {
436 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700437 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800438 }
439 }
440
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700441 static void checkItemInfoLocked(
442 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
443 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
444 if (modelItem != null && item != modelItem) {
445 // check all the data is consistent
446 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
447 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
448 ShortcutInfo shortcut = (ShortcutInfo) item;
449 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
450 modelShortcut.intent.filterEquals(shortcut.intent) &&
451 modelShortcut.id == shortcut.id &&
452 modelShortcut.itemType == shortcut.itemType &&
453 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700454 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700455 modelShortcut.cellX == shortcut.cellX &&
456 modelShortcut.cellY == shortcut.cellY &&
457 modelShortcut.spanX == shortcut.spanX &&
458 modelShortcut.spanY == shortcut.spanY &&
459 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
460 (modelShortcut.dropPos != null &&
461 shortcut.dropPos != null &&
462 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
463 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
464 // For all intents and purposes, this is the same object
465 return;
466 }
467 }
468
469 // the modelItem needs to match up perfectly with item if our model is
470 // to be consistent with the database-- for now, just require
471 // modelItem == item or the equality check above
472 String msg = "item: " + ((item != null) ? item.toString() : "null") +
473 "modelItem: " +
474 ((modelItem != null) ? modelItem.toString() : "null") +
475 "Error: ItemInfo passed to checkItemInfo doesn't match original";
476 RuntimeException e = new RuntimeException(msg);
477 if (stackTrace != null) {
478 e.setStackTrace(stackTrace);
479 }
Adam Cohene25af792013-06-06 23:08:25 -0700480 // TODO: something breaks this in the upgrade path
481 //throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700482 }
483 }
484
Michael Jurka816474f2012-06-25 14:49:02 -0700485 static void checkItemInfo(final ItemInfo item) {
486 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
487 final long itemId = item.id;
488 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700489 public void run() {
490 synchronized (sBgLock) {
491 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700492 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700493 }
494 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700495 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700496 }
497
Michael Jurkac9d95c52011-08-29 14:03:34 -0700498 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
499 final ItemInfo item, final String callingFunction) {
500 final long itemId = item.id;
501 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
502 final ContentResolver cr = context.getContentResolver();
503
Adam Cohen487f7dd2012-06-28 18:12:10 -0700504 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700505 Runnable r = new Runnable() {
506 public void run() {
507 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700508 updateItemArrays(item, itemId, stackTrace);
509 }
510 };
511 runOnWorkerThread(r);
512 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700513
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700514 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
515 final ArrayList<ItemInfo> items, final String callingFunction) {
516 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700517
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700518 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
519 Runnable r = new Runnable() {
520 public void run() {
521 ArrayList<ContentProviderOperation> ops =
522 new ArrayList<ContentProviderOperation>();
523 int count = items.size();
524 for (int i = 0; i < count; i++) {
525 ItemInfo item = items.get(i);
526 final long itemId = item.id;
527 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
528 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700529
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700530 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
531 updateItemArrays(item, itemId, stackTrace);
532
533 }
534 try {
535 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
536 } catch (Exception e) {
537 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700538 }
539 }
540 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700541 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700542 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700543
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700544 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
545 // Lock on mBgLock *after* the db operation
546 synchronized (sBgLock) {
547 checkItemInfoLocked(itemId, item, stackTrace);
548
549 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
550 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
551 // Item is in a folder, make sure this folder exists
552 if (!sBgFolders.containsKey(item.container)) {
553 // An items container is being set to a that of an item which is not in
554 // the list of Folders.
555 String msg = "item: " + item + " container being set to: " +
556 item.container + ", not in the list of folders";
557 Log.e(TAG, msg);
558 Launcher.dumpDebugLogsToConsole();
559 }
560 }
561
562 // Items are added/removed from the corresponding FolderInfo elsewhere, such
563 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
564 // that are on the desktop, as appropriate
565 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
566 if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
567 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
568 switch (modelItem.itemType) {
569 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
570 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
571 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
572 if (!sBgWorkspaceItems.contains(modelItem)) {
573 sBgWorkspaceItems.add(modelItem);
574 }
575 break;
576 default:
577 break;
578 }
579 } else {
580 sBgWorkspaceItems.remove(modelItem);
581 }
582 }
583 }
584
Michael Jurkac7700af2013-05-14 20:17:58 +0200585 public void flushWorkerThread() {
586 mFlushingWorkerThread = true;
587 Runnable waiter = new Runnable() {
588 public void run() {
589 synchronized (this) {
590 notifyAll();
591 mFlushingWorkerThread = false;
592 }
593 }
594 };
595
596 synchronized(waiter) {
597 runOnWorkerThread(waiter);
598 if (mLoaderTask != null) {
599 synchronized(mLoaderTask) {
600 mLoaderTask.notify();
601 }
602 }
603 boolean success = false;
604 while (!success) {
605 try {
606 waiter.wait();
607 success = true;
608 } catch (InterruptedException e) {
609 }
610 }
611 }
612 }
613
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800614 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400615 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700616 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700617 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700618 final long screenId, final int cellX, final int cellY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700619 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
Adam Cohendcd297f2013-06-18 13:13:40 -0700620 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
621 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Adam Cohen487f7dd2012-06-28 18:12:10 -0700622 Launcher.sDumpLogs.add(transaction);
623 Log.d(TAG, transaction);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400624 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400625 item.cellX = cellX;
626 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700627
Winson Chung3d503fb2011-07-13 17:25:49 -0700628 // We store hotseat items in canonical form which is this orientation invariant position
629 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700630 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700631 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700632 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700633 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700634 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700635 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400636
637 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400638 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700639 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
640 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700641 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400642
Michael Jurkac9d95c52011-08-29 14:03:34 -0700643 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700644 }
645
646 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700647 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
648 * cellX, cellY have already been updated on the ItemInfos.
649 */
650 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
651 final long container, final int screen) {
652
653 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
654 int count = items.size();
655
656 for (int i = 0; i < count; i++) {
657 ItemInfo item = items.get(i);
658 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700659 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700660 + ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", "
661 + item.cellX + ", " + item.cellY + ")";
662 Launcher.sDumpLogs.add(transaction);
663 item.container = container;
664
665 // We store hotseat items in canonical form which is this orientation invariant position
666 // in the hotseat
667 if (context instanceof Launcher && screen < 0 &&
668 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700669 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700670 item.cellY);
671 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700672 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700673 }
674
675 final ContentValues values = new ContentValues();
676 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
677 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
678 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700679 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700680
681 contentValues.add(values);
682 }
683 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
684 }
685
686 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700687 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800688 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700689 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700690 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700691 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
Adam Cohendcd297f2013-06-18 13:13:40 -0700692 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
693 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Adam Cohen487f7dd2012-06-28 18:12:10 -0700694 Launcher.sDumpLogs.add(transaction);
695 Log.d(TAG, transaction);
Adam Cohend4844c32011-02-18 19:25:06 -0800696 item.cellX = cellX;
697 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700698 item.spanX = spanX;
699 item.spanY = spanY;
700
701 // We store hotseat items in canonical form which is this orientation invariant position
702 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700703 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700704 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700705 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700706 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700707 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700708 }
Adam Cohend4844c32011-02-18 19:25:06 -0800709
Adam Cohend4844c32011-02-18 19:25:06 -0800710 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800711 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700712 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
713 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
714 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
715 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700716 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800717
Michael Jurka816474f2012-06-25 14:49:02 -0700718 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700719 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700720
721 /**
722 * Update an item to the database in a specified container.
723 */
724 static void updateItemInDatabase(Context context, final ItemInfo item) {
725 final ContentValues values = new ContentValues();
726 item.onAddToDatabase(values);
727 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
728 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800729 }
730
731 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400732 * Returns true if the shortcuts already exists in the database.
733 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800734 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400735 static boolean shortcutExists(Context context, String title, Intent intent) {
736 final ContentResolver cr = context.getContentResolver();
737 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
738 new String[] { "title", "intent" }, "title=? and intent=?",
739 new String[] { title, intent.toUri(0) }, null);
740 boolean result = false;
741 try {
742 result = c.moveToFirst();
743 } finally {
744 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800745 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400746 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700747 }
748
Joe Onorato9c1289c2009-08-17 11:03:03 -0400749 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700750 * Returns an ItemInfo array containing all the items in the LauncherModel.
751 * The ItemInfo.id is not set through this function.
752 */
753 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
754 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
755 final ContentResolver cr = context.getContentResolver();
756 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
757 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
758 LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
759 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
760
761 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
762 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
763 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
764 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
765 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
766 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
767 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
768
769 try {
770 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700771 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700772 item.cellX = c.getInt(cellXIndex);
773 item.cellY = c.getInt(cellYIndex);
774 item.spanX = c.getInt(spanXIndex);
775 item.spanY = c.getInt(spanYIndex);
776 item.container = c.getInt(containerIndex);
777 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700778 item.screenId = c.getInt(screenIndex);
Winson Chungaafa03c2010-06-11 17:34:16 -0700779
780 items.add(item);
781 }
782 } catch (Exception e) {
783 items.clear();
784 } finally {
785 c.close();
786 }
787
788 return items;
789 }
790
791 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400792 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
793 */
794 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
795 final ContentResolver cr = context.getContentResolver();
796 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
797 "_id=? and (itemType=? or itemType=?)",
798 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700799 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700800
Joe Onorato9c1289c2009-08-17 11:03:03 -0400801 try {
802 if (c.moveToFirst()) {
803 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
804 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
805 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
806 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
807 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
808 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800809
Joe Onorato9c1289c2009-08-17 11:03:03 -0400810 FolderInfo folderInfo = null;
811 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700812 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
813 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400814 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700815 }
816
Joe Onorato9c1289c2009-08-17 11:03:03 -0400817 folderInfo.title = c.getString(titleIndex);
818 folderInfo.id = id;
819 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700820 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700821 folderInfo.cellX = c.getInt(cellXIndex);
822 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400823
824 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700825 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400826 } finally {
827 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700828 }
829
830 return null;
831 }
832
Joe Onorato9c1289c2009-08-17 11:03:03 -0400833 /**
834 * Add an item to the database in a specified container. Sets the container, screen, cellX and
835 * cellY fields of the item. Also assigns an ID to the item.
836 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700837 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700838 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400839 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400840 item.cellX = cellX;
841 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700842 // We store hotseat items in canonical form which is this orientation invariant position
843 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700844 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700845 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700846 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700847 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700848 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700849 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400850
851 final ContentValues values = new ContentValues();
852 final ContentResolver cr = context.getContentResolver();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400853 item.onAddToDatabase(values);
854
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400855 LauncherAppState app = LauncherAppState.getInstance();
Adam Cohendcd297f2013-06-18 13:13:40 -0700856 item.id = app.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700857 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -0700858 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -0700859
Michael Jurkac9d95c52011-08-29 14:03:34 -0700860 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700861 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700862 String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700863 + item.id + " (" + container + ", " + screenId + ", " + cellX + ", "
Adam Cohen487f7dd2012-06-28 18:12:10 -0700864 + cellY + ")";
865 Launcher.sDumpLogs.add(transaction);
866 Log.d(TAG, transaction);
867
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700868 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
869 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400870
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700871 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700872 synchronized (sBgLock) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700873 checkItemInfoLocked(item.id, item, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700874 sBgItemsIdMap.put(item.id, item);
875 switch (item.itemType) {
876 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
877 sBgFolders.put(item.id, (FolderInfo) item);
878 // Fall through
879 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
880 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
881 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
882 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
883 sBgWorkspaceItems.add(item);
884 } else {
885 if (!sBgFolders.containsKey(item.container)) {
886 // Adding an item to a folder that doesn't exist.
887 String msg = "adding item: " + item + " to a folder that " +
888 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -0700889 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700890 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700891 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700892 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700893 break;
894 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
895 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
896 break;
897 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700898 }
899 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700900 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700901 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700902 }
903
Joe Onorato9c1289c2009-08-17 11:03:03 -0400904 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700905 * Creates a new unique child id, for a given cell span across all layouts.
906 */
Michael Jurka845ba3b2010-09-28 17:09:46 -0700907 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -0700908 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -0700909 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -0700910 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -0700911 }
912
Adam Cohend22015c2010-07-26 22:02:18 -0700913 static int getCellCountX() {
914 return mCellCountX;
Winson Chungaafa03c2010-06-11 17:34:16 -0700915 }
916
Adam Cohend22015c2010-07-26 22:02:18 -0700917 static int getCellCountY() {
918 return mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700919 }
920
921 /**
922 * Updates the model orientation helper to take into account the current layout dimensions
923 * when performing local/canonical coordinate transformations.
924 */
925 static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
Adam Cohend22015c2010-07-26 22:02:18 -0700926 mCellCountX = shortAxisCellCount;
927 mCellCountY = longAxisCellCount;
Winson Chungaafa03c2010-06-11 17:34:16 -0700928 }
929
930 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -0700931 * Removes the specified item from the database
932 * @param context
933 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -0400934 */
Michael Jurkac9d95c52011-08-29 14:03:34 -0700935 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400936 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700937 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -0700938
Michael Jurka83df1882011-08-31 20:59:26 -0700939 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700940 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700941 String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700942 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX +
Adam Cohen487f7dd2012-06-28 18:12:10 -0700943 ", " + item.cellY + ")";
944 Launcher.sDumpLogs.add(transaction);
945 Log.d(TAG, transaction);
946
Michael Jurkac9d95c52011-08-29 14:03:34 -0700947 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700948
949 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700950 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700951 switch (item.itemType) {
952 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
953 sBgFolders.remove(item.id);
954 for (ItemInfo info: sBgItemsIdMap.values()) {
955 if (info.container == item.id) {
956 // We are deleting a folder which still contains items that
957 // think they are contained by that folder.
958 String msg = "deleting a folder (" + item + ") which still " +
959 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -0700960 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700961 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700962 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700963 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700964 sBgWorkspaceItems.remove(item);
965 break;
966 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
967 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
968 sBgWorkspaceItems.remove(item);
969 break;
970 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
971 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
972 break;
973 }
974 sBgItemsIdMap.remove(item.id);
975 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700976 }
977 }
Michael Jurka83df1882011-08-31 20:59:26 -0700978 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700979 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400980 }
981
982 /**
Adam Cohendcd297f2013-06-18 13:13:40 -0700983 * Update the order of the workspace screens in the database. The array list contains
984 * a list of screen ids in the order that they should appear.
985 */
Winson Chungc9168342013-06-26 14:54:55 -0700986 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chung64359a52013-07-08 17:17:08 -0700987 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -0700988 final ContentResolver cr = context.getContentResolver();
989 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
990
991 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -0700992 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -0700993 while (iter.hasNext()) {
994 long id = iter.next();
995 if (id < 0) {
996 iter.remove();
997 }
998 }
999
1000 Runnable r = new Runnable() {
1001 @Override
1002 public void run() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001003 // Clear the table
1004 cr.delete(uri, null, null);
1005 int count = screens.size();
1006 ContentValues[] values = new ContentValues[count];
1007 for (int i = 0; i < count; i++) {
1008 ContentValues v = new ContentValues();
1009 long screenId = screens.get(i);
1010 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1011 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Winson Chung8481e322013-08-09 16:06:38 -07001012 Log.d(TAG, "10249126 - updateWorkspaceScreenOrder(" + screenId + ", " + i + ")");
Adam Cohendcd297f2013-06-18 13:13:40 -07001013 values[i] = v;
1014 }
1015 cr.bulkInsert(uri, values);
1016 sBgWorkspaceScreens.clear();
1017 sBgWorkspaceScreens.addAll(screensCopy);
1018 }
1019 };
1020 runOnWorkerThread(r);
1021 }
1022
1023 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001024 * Remove the contents of the specified folder from the database
1025 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001026 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001027 final ContentResolver cr = context.getContentResolver();
1028
Michael Jurkac9d95c52011-08-29 14:03:34 -07001029 Runnable r = new Runnable() {
1030 public void run() {
1031 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001032 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001033 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001034 sBgItemsIdMap.remove(info.id);
1035 sBgFolders.remove(info.id);
1036 sBgDbIconCache.remove(info);
1037 sBgWorkspaceItems.remove(info);
1038 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001039
Michael Jurkac9d95c52011-08-29 14:03:34 -07001040 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1041 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001042 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001043 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001044 for (ItemInfo childInfo : info.contents) {
1045 sBgItemsIdMap.remove(childInfo.id);
1046 sBgDbIconCache.remove(childInfo);
1047 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001048 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001049 }
1050 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001051 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001052 }
1053
1054 /**
1055 * Set this as the current Launcher activity object for the loader.
1056 */
1057 public void initialize(Callbacks callbacks) {
1058 synchronized (mLock) {
1059 mCallbacks = new WeakReference<Callbacks>(callbacks);
1060 }
1061 }
1062
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001063 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001064 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1065 * ACTION_PACKAGE_CHANGED.
1066 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001067 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001068 public void onReceive(Context context, Intent intent) {
Joe Onorato36115782010-06-17 13:28:48 -04001069 if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001070
Joe Onorato36115782010-06-17 13:28:48 -04001071 final String action = intent.getAction();
Joe Onoratof99f8c12009-10-31 17:27:36 -04001072
Joe Onorato36115782010-06-17 13:28:48 -04001073 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
1074 || Intent.ACTION_PACKAGE_REMOVED.equals(action)
1075 || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1076 final String packageName = intent.getData().getSchemeSpecificPart();
1077 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001078
Joe Onorato36115782010-06-17 13:28:48 -04001079 int op = PackageUpdatedTask.OP_NONE;
1080
1081 if (packageName == null || packageName.length() == 0) {
1082 // they sent us a bad intent
1083 return;
1084 }
1085
1086 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1087 op = PackageUpdatedTask.OP_UPDATE;
1088 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1089 if (!replacing) {
1090 op = PackageUpdatedTask.OP_REMOVE;
1091 }
1092 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1093 // later, we will update the package at this time
1094 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1095 if (!replacing) {
1096 op = PackageUpdatedTask.OP_ADD;
1097 } else {
1098 op = PackageUpdatedTask.OP_UPDATE;
1099 }
1100 }
1101
1102 if (op != PackageUpdatedTask.OP_NONE) {
1103 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
1104 }
1105
1106 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Joe Onoratocec58332010-10-07 14:37:40 -04001107 // First, schedule to add these apps back in.
1108 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1109 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
1110 // Then, rebind everything.
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001111 startLoaderFromBackground();
Joe Onorato36115782010-06-17 13:28:48 -04001112 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1113 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1114 enqueuePackageUpdated(new PackageUpdatedTask(
1115 PackageUpdatedTask.OP_UNAVAILABLE, packages));
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001116 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001117 // If we have changed locale we need to clear out the labels in all apps/workspace.
1118 forceReload();
1119 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1120 // Check if configuration change was an mcc/mnc change which would affect app resources
1121 // and we would need to clear out the labels in all apps/workspace. Same handling as
1122 // above for ACTION_LOCALE_CHANGED
1123 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001124 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001125 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001126 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001127 forceReload();
1128 }
1129 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001130 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001131 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1132 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001133 if (mCallbacks != null) {
1134 Callbacks callbacks = mCallbacks.get();
1135 if (callbacks != null) {
1136 callbacks.bindSearchablesChanged();
1137 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001138 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001139 }
1140 }
1141
Reena Lee93f824a2011-09-23 17:20:28 -07001142 private void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001143 resetLoadedState(true, true);
1144
Reena Lee93f824a2011-09-23 17:20:28 -07001145 // Do this here because if the launcher activity is running it will be restarted.
1146 // If it's not running startLoaderFromBackground will merely tell it that it needs
1147 // to reload.
1148 startLoaderFromBackground();
1149 }
1150
Winson Chungf0c6ae02012-03-21 16:10:31 -07001151 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1152 synchronized (mLock) {
1153 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1154 // mWorkspaceLoaded to true later
1155 stopLoaderLocked();
1156 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1157 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1158 }
1159 }
1160
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001161 /**
1162 * When the launcher is in the background, it's possible for it to miss paired
1163 * configuration changes. So whenever we trigger the loader from the background
1164 * tell the launcher that it needs to re-run the loader when it comes back instead
1165 * of doing it now.
1166 */
1167 public void startLoaderFromBackground() {
1168 boolean runLoader = false;
1169 if (mCallbacks != null) {
1170 Callbacks callbacks = mCallbacks.get();
1171 if (callbacks != null) {
1172 // Only actually run the loader if they're not paused.
1173 if (!callbacks.setLoadOnResume()) {
1174 runLoader = true;
1175 }
1176 }
1177 }
1178 if (runLoader) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001179 startLoader(false, -1);
Joe Onorato790c2d92010-06-11 00:14:11 -07001180 }
Joe Onorato36115782010-06-17 13:28:48 -04001181 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001182
Reena Lee93f824a2011-09-23 17:20:28 -07001183 // If there is already a loader task running, tell it to stop.
1184 // returns true if isLaunching() was true on the old task
1185 private boolean stopLoaderLocked() {
1186 boolean isLaunching = false;
1187 LoaderTask oldTask = mLoaderTask;
1188 if (oldTask != null) {
1189 if (oldTask.isLaunching()) {
1190 isLaunching = true;
1191 }
1192 oldTask.stopLocked();
1193 }
1194 return isLaunching;
1195 }
1196
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001197 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Joe Onorato36115782010-06-17 13:28:48 -04001198 synchronized (mLock) {
1199 if (DEBUG_LOADERS) {
1200 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1201 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001202
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001203 // Clear any deferred bind-runnables from the synchronized load process
1204 // We must do this before any loading/binding is scheduled below.
1205 mDeferredBindRunnables.clear();
1206
Joe Onorato36115782010-06-17 13:28:48 -04001207 // Don't bother to start the thread if we know it's not going to do anything
1208 if (mCallbacks != null && mCallbacks.get() != null) {
1209 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001210 // also, don't downgrade isLaunching if we're already running
1211 isLaunching = isLaunching || stopLoaderLocked();
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001212 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001213 if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
1214 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1215 } else {
1216 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1217 sWorker.post(mLoaderTask);
1218 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001219 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001220 }
1221 }
1222
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001223 void bindRemainingSynchronousPages() {
1224 // Post the remaining side pages to be loaded
1225 if (!mDeferredBindRunnables.isEmpty()) {
1226 for (final Runnable r : mDeferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001227 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001228 }
1229 mDeferredBindRunnables.clear();
1230 }
1231 }
1232
Joe Onorato36115782010-06-17 13:28:48 -04001233 public void stopLoader() {
1234 synchronized (mLock) {
1235 if (mLoaderTask != null) {
1236 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001237 }
1238 }
Joe Onorato36115782010-06-17 13:28:48 -04001239 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001240
Michael Jurkac57b7a82011-08-09 22:02:20 -07001241 public boolean isAllAppsLoaded() {
1242 return mAllAppsLoaded;
1243 }
1244
Winson Chung36a62fe2012-05-06 18:04:42 -07001245 boolean isLoadingWorkspace() {
1246 synchronized (mLock) {
1247 if (mLoaderTask != null) {
1248 return mLoaderTask.isLoadingWorkspace();
1249 }
1250 }
1251 return false;
1252 }
1253
Joe Onorato36115782010-06-17 13:28:48 -04001254 /**
1255 * Runnable for the thread that loads the contents of the launcher:
1256 * - workspace icons
1257 * - widgets
1258 * - all apps icons
1259 */
1260 private class LoaderTask implements Runnable {
1261 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001262 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001263 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001264 private boolean mStopped;
1265 private boolean mLoadAndBindStepFinished;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001266
Winson Chungc3eecff2011-07-11 17:44:15 -07001267 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001268
1269 LoaderTask(Context context, boolean isLaunching) {
1270 mContext = context;
1271 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001272 mLabelCache = new HashMap<Object, CharSequence>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001273 }
1274
Joe Onorato36115782010-06-17 13:28:48 -04001275 boolean isLaunching() {
1276 return mIsLaunching;
1277 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001278
Winson Chung36a62fe2012-05-06 18:04:42 -07001279 boolean isLoadingWorkspace() {
1280 return mIsLoadingAndBindingWorkspace;
1281 }
1282
Winson Chungc763c4e2013-07-19 13:49:06 -07001283 /** Returns whether this is an upgrade path */
1284 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001285 mIsLoadingAndBindingWorkspace = true;
1286
Joe Onorato36115782010-06-17 13:28:48 -04001287 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001288 if (DEBUG_LOADERS) {
1289 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001290 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001291
Winson Chungc763c4e2013-07-19 13:49:06 -07001292 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001293 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001294 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001295 synchronized (LoaderTask.this) {
1296 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001297 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001298 }
1299 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001300 }
1301 }
1302
Joe Onorato36115782010-06-17 13:28:48 -04001303 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001304 bindWorkspace(-1, isUpgradePath);
1305 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001306 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001307
Joe Onorato36115782010-06-17 13:28:48 -04001308 private void waitForIdle() {
1309 // Wait until the either we're stopped or the other threads are done.
1310 // This way we don't start loading all apps until the workspace has settled
1311 // down.
1312 synchronized (LoaderTask.this) {
1313 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001314
Joe Onorato36115782010-06-17 13:28:48 -04001315 mHandler.postIdle(new Runnable() {
1316 public void run() {
1317 synchronized (LoaderTask.this) {
1318 mLoadAndBindStepFinished = true;
1319 if (DEBUG_LOADERS) {
1320 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001321 }
Joe Onorato36115782010-06-17 13:28:48 -04001322 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001323 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001324 }
Joe Onorato36115782010-06-17 13:28:48 -04001325 });
1326
Michael Jurkac7700af2013-05-14 20:17:58 +02001327 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001328 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001329 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1330 // wait no longer than 1sec at a time
1331 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001332 } catch (InterruptedException ex) {
1333 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001334 }
1335 }
Joe Onorato36115782010-06-17 13:28:48 -04001336 if (DEBUG_LOADERS) {
1337 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001338 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001339 + "ms for previous step to finish binding");
1340 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001341 }
Joe Onorato36115782010-06-17 13:28:48 -04001342 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001343
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001344 void runBindSynchronousPage(int synchronousBindPage) {
1345 if (synchronousBindPage < 0) {
1346 // Ensure that we have a valid page index to load synchronously
1347 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1348 "valid page index");
1349 }
1350 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1351 // Ensure that we don't try and bind a specified page when the pages have not been
1352 // loaded already (we should load everything asynchronously in that case)
1353 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1354 }
1355 synchronized (mLock) {
1356 if (mIsLoaderTaskRunning) {
1357 // Ensure that we are never running the background loading at this point since
1358 // we also touch the background collections
1359 throw new RuntimeException("Error! Background loading is already running");
1360 }
1361 }
1362
1363 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1364 // data structures, we can't allow any other thread to touch that data, but because
1365 // this call is synchronous, we can get away with not locking).
1366
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001367 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001368 // operations from the previous activity. We need to ensure that all queued operations
1369 // are executed before any synchronous binding work is done.
1370 mHandler.flush();
1371
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001372 // Divide the set of loaded items into those that we are binding synchronously, and
1373 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001374 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001375 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1376 // arise from that.
1377 onlyBindAllApps();
1378 }
1379
Joe Onorato36115782010-06-17 13:28:48 -04001380 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001381 boolean isUpgrade = false;
1382
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001383 synchronized (mLock) {
1384 mIsLoaderTaskRunning = true;
1385 }
Joe Onorato36115782010-06-17 13:28:48 -04001386 // Optimize for end-user experience: if the Launcher is up and // running with the
1387 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1388 // workspace first (default).
1389 final Callbacks cbk = mCallbacks.get();
Joe Onorato36115782010-06-17 13:28:48 -04001390 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001391 // Elevate priority when Home launches for the first time to avoid
1392 // starving at boot time. Staring at a blank home is not cool.
1393 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001394 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1395 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001396 android.os.Process.setThreadPriority(mIsLaunching
1397 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1398 }
Winson Chung64359a52013-07-08 17:17:08 -07001399 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001400 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001401
Joe Onorato36115782010-06-17 13:28:48 -04001402 if (mStopped) {
1403 break keep_running;
1404 }
1405
1406 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1407 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001408 synchronized (mLock) {
1409 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001410 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001411 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412 }
1413 }
Joe Onorato36115782010-06-17 13:28:48 -04001414 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001415
1416 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001417 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1418 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001419
1420 // Restore the default thread priority after we are done loading items
1421 synchronized (mLock) {
1422 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423 }
Joe Onorato36115782010-06-17 13:28:48 -04001424 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001425
Winson Chungaac01e12011-08-17 10:37:13 -07001426 // Update the saved icons if necessary
1427 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001428 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001429 for (Object key : sBgDbIconCache.keySet()) {
1430 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1431 }
1432 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001433 }
Winson Chungaac01e12011-08-17 10:37:13 -07001434
Winson Chungc763c4e2013-07-19 13:49:06 -07001435 // Ensure that all the applications that are in the system are represented on the home
1436 // screen.
1437 if (!isUpgrade) {
1438 verifyApplications();
1439 }
1440
Joe Onorato36115782010-06-17 13:28:48 -04001441 // Clear out this reference, otherwise we end up holding it until all of the
1442 // callback runnables are done.
1443 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001444
Joe Onorato36115782010-06-17 13:28:48 -04001445 synchronized (mLock) {
1446 // If we are still the last one to be scheduled, remove ourselves.
1447 if (mLoaderTask == this) {
1448 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001449 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001450 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001451 }
Joe Onorato36115782010-06-17 13:28:48 -04001452 }
1453
1454 public void stopLocked() {
1455 synchronized (LoaderTask.this) {
1456 mStopped = true;
1457 this.notify();
1458 }
1459 }
1460
1461 /**
1462 * Gets the callbacks object. If we've been stopped, or if the launcher object
1463 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1464 * object that was around when the deferred message was scheduled, and if there's
1465 * a new Callbacks object around then also return null. This will save us from
1466 * calling onto it with data that will be ignored.
1467 */
1468 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1469 synchronized (mLock) {
1470 if (mStopped) {
1471 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001472 }
Joe Onorato36115782010-06-17 13:28:48 -04001473
1474 if (mCallbacks == null) {
1475 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001476 }
Joe Onorato36115782010-06-17 13:28:48 -04001477
1478 final Callbacks callbacks = mCallbacks.get();
1479 if (callbacks != oldCallbacks) {
1480 return null;
1481 }
1482 if (callbacks == null) {
1483 Log.w(TAG, "no mCallbacks");
1484 return null;
1485 }
1486
1487 return callbacks;
1488 }
1489 }
1490
Winson Chungc763c4e2013-07-19 13:49:06 -07001491 private void verifyApplications() {
1492 final Context context = mApp.getContext();
1493
1494 // Cross reference all the applications in our apps list with items in the workspace
1495 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001496 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001497 synchronized (sBgLock) {
1498 for (ApplicationInfo app : mBgAllAppsList.data) {
1499 tmpInfos = getItemInfoForComponentName(app.componentName);
1500 if (tmpInfos.isEmpty()) {
1501 // We are missing an application icon, so add this to the workspace
1502 added.add(app);
1503 // This is a rare event, so lets log it
1504 Log.e(TAG, "Missing Application on load: " + app);
1505 }
1506 }
1507 }
1508 if (!added.isEmpty()) {
1509 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1510 addAndBindAddedApps(context, added, cb);
1511 }
1512 }
1513
Joe Onorato36115782010-06-17 13:28:48 -04001514 // check & update map of what's occupied; used to discard overlapping/invalid items
Adam Cohendcd297f2013-06-18 13:13:40 -07001515 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
1516 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001517 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001518 if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
1519 if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1520 [(int) item.screenId][0] != null) {
1521 Log.e(TAG, "Error loading shortcut into hotseat " + item
1522 + " into position (" + item.screenId + ":" + item.cellX + ","
1523 + item.cellY + ") occupied by "
1524 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1525 [(int) item.screenId][0]);
1526 return false;
1527 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001528 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001529 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1530 items[(int) item.screenId][0] = item;
1531 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001532 return true;
1533 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001534 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1535 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001536 return true;
1537 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001538
Adam Cohendcd297f2013-06-18 13:13:40 -07001539 if (!occupied.containsKey(item.screenId)) {
1540 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1541 occupied.put(item.screenId, items);
1542 }
1543
1544 ItemInfo[][] screens = occupied.get(item.screenId);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001545 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001546 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1547 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001548 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001549 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001550 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001551 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001552 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001553 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001554 return false;
1555 }
1556 }
1557 }
1558 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1559 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001560 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001561 }
1562 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001563
Joe Onorato36115782010-06-17 13:28:48 -04001564 return true;
1565 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001566
Winson Chungc763c4e2013-07-19 13:49:06 -07001567 /** Returns whether this is an upgradge path */
1568 private boolean loadWorkspace() {
Joe Onorato36115782010-06-17 13:28:48 -04001569 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001570
Joe Onorato36115782010-06-17 13:28:48 -04001571 final Context context = mContext;
1572 final ContentResolver contentResolver = context.getContentResolver();
1573 final PackageManager manager = context.getPackageManager();
1574 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1575 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001576
Michael Jurkab85f8a42012-04-25 15:48:32 -07001577 // Make sure the default workspace is loaded, if needed
Winson Chungc763c4e2013-07-19 13:49:06 -07001578 mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
Adam Cohene25af792013-06-06 23:08:25 -07001579
Winson Chungc763c4e2013-07-19 13:49:06 -07001580 // Check if we need to do any upgrade-path logic
1581 boolean loadedOldDb = mApp.getLauncherProvider().justLoadedOldDb();
Michael Jurkab85f8a42012-04-25 15:48:32 -07001582
Winson Chung2abf94d2012-07-18 18:16:38 -07001583 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001584 sBgWorkspaceItems.clear();
1585 sBgAppWidgets.clear();
1586 sBgFolders.clear();
1587 sBgItemsIdMap.clear();
1588 sBgDbIconCache.clear();
Adam Cohendcd297f2013-06-18 13:13:40 -07001589 sBgWorkspaceScreens.clear();
Winson Chung8481e322013-08-09 16:06:38 -07001590 Log.d(TAG, "10249126 - loadWorkspace()");
Romain Guy5c16f3e2010-01-12 17:24:58 -08001591
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001592 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001593 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Adam Cohene25af792013-06-06 23:08:25 -07001594 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001595
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001596 // +1 for the hotseat (it can be larger than the workspace)
1597 // Load workspace in reverse order to ensure that latest items are loaded first (and
1598 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001599 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001600
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001601 try {
1602 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1603 final int intentIndex = c.getColumnIndexOrThrow
1604 (LauncherSettings.Favorites.INTENT);
1605 final int titleIndex = c.getColumnIndexOrThrow
1606 (LauncherSettings.Favorites.TITLE);
1607 final int iconTypeIndex = c.getColumnIndexOrThrow(
1608 LauncherSettings.Favorites.ICON_TYPE);
1609 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1610 final int iconPackageIndex = c.getColumnIndexOrThrow(
1611 LauncherSettings.Favorites.ICON_PACKAGE);
1612 final int iconResourceIndex = c.getColumnIndexOrThrow(
1613 LauncherSettings.Favorites.ICON_RESOURCE);
1614 final int containerIndex = c.getColumnIndexOrThrow(
1615 LauncherSettings.Favorites.CONTAINER);
1616 final int itemTypeIndex = c.getColumnIndexOrThrow(
1617 LauncherSettings.Favorites.ITEM_TYPE);
1618 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1619 LauncherSettings.Favorites.APPWIDGET_ID);
1620 final int screenIndex = c.getColumnIndexOrThrow(
1621 LauncherSettings.Favorites.SCREEN);
1622 final int cellXIndex = c.getColumnIndexOrThrow
1623 (LauncherSettings.Favorites.CELLX);
1624 final int cellYIndex = c.getColumnIndexOrThrow
1625 (LauncherSettings.Favorites.CELLY);
1626 final int spanXIndex = c.getColumnIndexOrThrow
1627 (LauncherSettings.Favorites.SPANX);
1628 final int spanYIndex = c.getColumnIndexOrThrow(
1629 LauncherSettings.Favorites.SPANY);
1630 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1631 //final int displayModeIndex = c.getColumnIndexOrThrow(
1632 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001633
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001634 ShortcutInfo info;
1635 String intentDescription;
1636 LauncherAppWidgetInfo appWidgetInfo;
1637 int container;
1638 long id;
1639 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001640
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001641 while (!mStopped && c.moveToNext()) {
1642 try {
1643 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001644
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001645 switch (itemType) {
1646 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1647 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001648 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001649 intentDescription = c.getString(intentIndex);
1650 try {
1651 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001652 ComponentName cn = intent.getComponent();
Winson Chung1323b482013-08-05 12:41:55 -07001653 if (!isValidPackageComponent(manager, cn)) {
Winson Chungee055712013-07-30 14:46:24 -07001654 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chung1323b482013-08-05 12:41:55 -07001655 // Log the invalid package, and remove it from the db
1656 Uri uri = LauncherSettings.Favorites.getContentUri(id,
1657 false);
Winson Chungee055712013-07-30 14:46:24 -07001658 contentResolver.delete(uri, null, null);
Winson Chung1323b482013-08-05 12:41:55 -07001659 Log.e(TAG, "Invalid package removed: " + cn);
Winson Chungee055712013-07-30 14:46:24 -07001660 } else {
Winson Chung1323b482013-08-05 12:41:55 -07001661 // If apps can be on external storage, then we just
1662 // leave them for the user to remove (maybe add
1663 // visual treatment to it)
1664 Log.e(TAG, "Invalid package found: " + cn);
Winson Chungee055712013-07-30 14:46:24 -07001665 }
1666 continue;
1667 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001668 } catch (URISyntaxException e) {
1669 continue;
1670 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001671
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001672 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1673 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1674 titleIndex, mLabelCache);
1675 } else {
1676 info = getShortcutInfo(c, context, iconTypeIndex,
1677 iconPackageIndex, iconResourceIndex, iconIndex,
1678 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001679
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001680 // App shortcuts that used to be automatically added to Launcher
1681 // didn't always have the correct intent flags set, so do that
1682 // here
1683 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001684 intent.getCategories() != null &&
1685 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001686 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001687 intent.addFlags(
1688 Intent.FLAG_ACTIVITY_NEW_TASK |
1689 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1690 }
Michael Jurka96879562012-03-22 05:54:33 -07001691 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001692
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001693 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07001694 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001695 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001696 container = c.getInt(containerIndex);
1697 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001698 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001699 info.cellX = c.getInt(cellXIndex);
1700 info.cellY = c.getInt(cellYIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001701 // check & update map of what's occupied
1702 if (!checkItemPlacement(occupied, info)) {
1703 break;
1704 }
1705
1706 switch (container) {
1707 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1708 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1709 sBgWorkspaceItems.add(info);
1710 break;
1711 default:
1712 // Item is in a user folder
1713 FolderInfo folderInfo =
1714 findOrMakeFolder(sBgFolders, container);
1715 folderInfo.add(info);
1716 break;
1717 }
1718 sBgItemsIdMap.put(info.id, info);
1719
1720 // now that we've loaded everthing re-save it with the
1721 // icon in case it disappears somehow.
1722 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07001723 } else {
1724 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001725 }
1726 break;
1727
1728 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1729 id = c.getLong(idIndex);
1730 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1731
1732 folderInfo.title = c.getString(titleIndex);
1733 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001734 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001735 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001736 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001737 folderInfo.cellX = c.getInt(cellXIndex);
1738 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001739
Daniel Sandler8802e962010-05-26 16:28:16 -04001740 // check & update map of what's occupied
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001741 if (!checkItemPlacement(occupied, folderInfo)) {
Daniel Sandler8802e962010-05-26 16:28:16 -04001742 break;
1743 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001744 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001745 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1746 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1747 sBgWorkspaceItems.add(folderInfo);
1748 break;
Joe Onorato36115782010-06-17 13:28:48 -04001749 }
Joe Onorato17a89222011-02-08 17:26:11 -08001750
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001751 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1752 sBgFolders.put(folderInfo.id, folderInfo);
1753 break;
1754
1755 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1756 // Read all Launcher-specific widget details
1757 int appWidgetId = c.getInt(appWidgetIdIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001758 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001759
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001760 final AppWidgetProviderInfo provider =
1761 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001762
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001763 if (!isSafeMode && (provider == null || provider.provider == null ||
1764 provider.provider.getPackageName() == null)) {
1765 String log = "Deleting widget that isn't installed anymore: id="
1766 + id + " appWidgetId=" + appWidgetId;
1767 Log.e(TAG, log);
1768 Launcher.sDumpLogs.add(log);
1769 itemsToRemove.add(id);
1770 } else {
1771 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1772 provider.provider);
1773 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07001774 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001775 appWidgetInfo.cellX = c.getInt(cellXIndex);
1776 appWidgetInfo.cellY = c.getInt(cellYIndex);
1777 appWidgetInfo.spanX = c.getInt(spanXIndex);
1778 appWidgetInfo.spanY = c.getInt(spanYIndex);
1779 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1780 appWidgetInfo.minSpanX = minSpan[0];
1781 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001782
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001783 container = c.getInt(containerIndex);
1784 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1785 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1786 Log.e(TAG, "Widget found where container != " +
1787 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1788 continue;
1789 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001790
Adam Cohene25af792013-06-06 23:08:25 -07001791 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001792 // check & update map of what's occupied
1793 if (!checkItemPlacement(occupied, appWidgetInfo)) {
1794 break;
1795 }
1796 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1797 sBgAppWidgets.add(appWidgetInfo);
1798 }
Joe Onorato36115782010-06-17 13:28:48 -04001799 break;
1800 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001801 } catch (Exception e) {
1802 Log.w(TAG, "Desktop items loading interrupted:", e);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001803 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001804 }
1805 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04001806 if (c != null) {
1807 c.close();
1808 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001809 }
1810
1811 if (itemsToRemove.size() > 0) {
1812 ContentProviderClient client = contentResolver.acquireContentProviderClient(
1813 LauncherSettings.Favorites.CONTENT_URI);
1814 // Remove dead items
1815 for (long id : itemsToRemove) {
1816 if (DEBUG_LOADERS) {
1817 Log.d(TAG, "Removed id = " + id);
1818 }
1819 // Don't notify content observers
1820 try {
1821 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1822 null, null);
1823 } catch (RemoteException e) {
1824 Log.w(TAG, "Could not remove id = " + id);
1825 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001826 }
1827 }
1828
Winson Chungc763c4e2013-07-19 13:49:06 -07001829 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001830 long maxScreenId = 0;
1831 // If we're importing we use the old screen order.
1832 for (ItemInfo item: sBgItemsIdMap.values()) {
1833 long screenId = item.screenId;
1834 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1835 !sBgWorkspaceScreens.contains(screenId)) {
Winson Chung8481e322013-08-09 16:06:38 -07001836 Log.d(TAG, "10249126 - loadWorkspace-loadedOldDb(" + screenId + ")");
Adam Cohendcd297f2013-06-18 13:13:40 -07001837 sBgWorkspaceScreens.add(screenId);
1838 if (screenId > maxScreenId) {
1839 maxScreenId = screenId;
1840 }
1841 }
1842 }
1843 Collections.sort(sBgWorkspaceScreens);
1844 mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
1845 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07001846
1847 // Update the max item id after we load an old db
1848 long maxItemId = 0;
1849 // If we're importing we use the old screen order.
1850 for (ItemInfo item: sBgItemsIdMap.values()) {
1851 maxItemId = Math.max(maxItemId, item.id);
1852 }
1853 LauncherAppState app = LauncherAppState.getInstance();
1854 app.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07001855 } else {
1856 Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1857 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1858 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1859
1860 try {
1861 final int idIndex = sc.getColumnIndexOrThrow(
1862 LauncherSettings.WorkspaceScreens._ID);
1863 final int rankIndex = sc.getColumnIndexOrThrow(
1864 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1865 while (sc.moveToNext()) {
1866 try {
1867 long screenId = sc.getLong(idIndex);
1868 int rank = sc.getInt(rankIndex);
1869
1870 orderedScreens.put(rank, screenId);
1871 } catch (Exception e) {
1872 Log.w(TAG, "Desktop items loading interrupted:", e);
1873 }
1874 }
1875 } finally {
1876 sc.close();
1877 }
1878
1879 Iterator<Integer> iter = orderedScreens.keySet().iterator();
1880 while (iter.hasNext()) {
1881 sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
1882 }
1883
1884 // Remove any empty screens
Winson Chung8481e322013-08-09 16:06:38 -07001885 Log.d(TAG, "10249126 - loadWorkspace-!loadedOldDb()");
Adam Cohendcd297f2013-06-18 13:13:40 -07001886 ArrayList<Long> unusedScreens = new ArrayList<Long>();
1887 unusedScreens.addAll(sBgWorkspaceScreens);
1888
1889 for (ItemInfo item: sBgItemsIdMap.values()) {
1890 long screenId = item.screenId;
1891
1892 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1893 unusedScreens.contains(screenId)) {
1894 unusedScreens.remove(screenId);
1895 }
1896 }
1897
1898 // If there are any empty screens remove them, and update.
1899 if (unusedScreens.size() != 0) {
1900 sBgWorkspaceScreens.removeAll(unusedScreens);
1901 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1902 }
1903 }
1904
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001905 if (DEBUG_LOADERS) {
1906 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1907 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07001908 int nScreens = occupied.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001909 for (int y = 0; y < mCellCountY; y++) {
1910 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07001911
Daniel Sandler566da102013-06-25 23:43:45 -04001912 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07001913 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001914 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07001915 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001916 line += " | ";
1917 }
1918 for (int x = 0; x < mCellCountX; x++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001919 line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001920 }
Joe Onorato36115782010-06-17 13:28:48 -04001921 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001922 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04001923 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001924 }
Joe Onorato36115782010-06-17 13:28:48 -04001925 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001926 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07001927 }
1928
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001929 /** Filters the set of items who are directly or indirectly (via another container) on the
1930 * specified screen. */
1931 private void filterCurrentWorkspaceItems(int currentScreen,
1932 ArrayList<ItemInfo> allWorkspaceItems,
1933 ArrayList<ItemInfo> currentScreenItems,
1934 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001935 // Purge any null ItemInfos
1936 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1937 while (iter.hasNext()) {
1938 ItemInfo i = iter.next();
1939 if (i == null) {
1940 iter.remove();
1941 }
1942 }
1943
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001944 // If we aren't filtering on a screen, then the set of items to load is the full set of
1945 // items given.
1946 if (currentScreen < 0) {
1947 currentScreenItems.addAll(allWorkspaceItems);
Joe Onorato36115782010-06-17 13:28:48 -04001948 }
1949
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001950 // Order the set of items by their containers first, this allows use to walk through the
1951 // list sequentially, build up a list of containers that are in the specified screen,
1952 // as well as all items in those containers.
1953 Set<Long> itemsOnScreen = new HashSet<Long>();
1954 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1955 @Override
1956 public int compare(ItemInfo lhs, ItemInfo rhs) {
1957 return (int) (lhs.container - rhs.container);
1958 }
1959 });
1960 for (ItemInfo info : allWorkspaceItems) {
1961 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001962 if (info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001963 currentScreenItems.add(info);
1964 itemsOnScreen.add(info.id);
1965 } else {
1966 otherScreenItems.add(info);
1967 }
1968 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1969 currentScreenItems.add(info);
1970 itemsOnScreen.add(info.id);
1971 } else {
1972 if (itemsOnScreen.contains(info.container)) {
1973 currentScreenItems.add(info);
1974 itemsOnScreen.add(info.id);
1975 } else {
1976 otherScreenItems.add(info);
1977 }
1978 }
1979 }
1980 }
1981
1982 /** Filters the set of widgets which are on the specified screen. */
1983 private void filterCurrentAppWidgets(int currentScreen,
1984 ArrayList<LauncherAppWidgetInfo> appWidgets,
1985 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1986 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1987 // If we aren't filtering on a screen, then the set of items to load is the full set of
1988 // widgets given.
1989 if (currentScreen < 0) {
1990 currentScreenWidgets.addAll(appWidgets);
1991 }
1992
1993 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001994 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001995 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07001996 widget.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001997 currentScreenWidgets.add(widget);
1998 } else {
1999 otherScreenWidgets.add(widget);
2000 }
2001 }
2002 }
2003
2004 /** Filters the set of folders which are on the specified screen. */
2005 private void filterCurrentFolders(int currentScreen,
2006 HashMap<Long, ItemInfo> itemsIdMap,
2007 HashMap<Long, FolderInfo> folders,
2008 HashMap<Long, FolderInfo> currentScreenFolders,
2009 HashMap<Long, FolderInfo> otherScreenFolders) {
2010 // If we aren't filtering on a screen, then the set of items to load is the full set of
2011 // widgets given.
2012 if (currentScreen < 0) {
2013 currentScreenFolders.putAll(folders);
2014 }
2015
2016 for (long id : folders.keySet()) {
2017 ItemInfo info = itemsIdMap.get(id);
2018 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002019 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002020 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07002021 info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002022 currentScreenFolders.put(id, folder);
2023 } else {
2024 otherScreenFolders.put(id, folder);
2025 }
2026 }
2027 }
2028
2029 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2030 * right) */
2031 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
2032 // XXX: review this
2033 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002034 @Override
2035 public int compare(ItemInfo lhs, ItemInfo rhs) {
2036 int cellCountX = LauncherModel.getCellCountX();
2037 int cellCountY = LauncherModel.getCellCountY();
2038 int screenOffset = cellCountX * cellCountY;
2039 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002040 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002041 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002042 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002043 rhs.cellY * cellCountX + rhs.cellX);
2044 return (int) (lr - rr);
2045 }
2046 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002047 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002048
Adam Cohendcd297f2013-06-18 13:13:40 -07002049 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2050 final ArrayList<Long> orderedScreens) {
Winson Chung8481e322013-08-09 16:06:38 -07002051 Log.d(TAG, "10249126 - bindWorkspaceScreens()");
Adam Cohendcd297f2013-06-18 13:13:40 -07002052 final Runnable r = new Runnable() {
2053 @Override
2054 public void run() {
2055 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2056 if (callbacks != null) {
2057 callbacks.bindScreens(orderedScreens);
2058 }
2059 }
2060 };
2061 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2062 }
2063
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002064 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2065 final ArrayList<ItemInfo> workspaceItems,
2066 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2067 final HashMap<Long, FolderInfo> folders,
2068 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002069
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002070 final boolean postOnMainThread = (deferredBindRunnables != null);
2071
2072 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002073 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002074 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002075 final int start = i;
2076 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002077 final Runnable r = new Runnable() {
2078 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002079 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002080 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002081 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002082 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2083 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002084 }
2085 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002086 };
2087 if (postOnMainThread) {
2088 deferredBindRunnables.add(r);
2089 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002090 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002091 }
Joe Onorato36115782010-06-17 13:28:48 -04002092 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002093
2094 // Bind the folders
2095 if (!folders.isEmpty()) {
2096 final Runnable r = new Runnable() {
2097 public void run() {
2098 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2099 if (callbacks != null) {
2100 callbacks.bindFolders(folders);
2101 }
2102 }
2103 };
2104 if (postOnMainThread) {
2105 deferredBindRunnables.add(r);
2106 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002107 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002108 }
2109 }
2110
2111 // Bind the widgets, one at a time
2112 N = appWidgets.size();
2113 for (int i = 0; i < N; i++) {
2114 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2115 final Runnable r = new Runnable() {
2116 public void run() {
2117 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2118 if (callbacks != null) {
2119 callbacks.bindAppWidget(widget);
2120 }
2121 }
2122 };
2123 if (postOnMainThread) {
2124 deferredBindRunnables.add(r);
2125 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002126 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002127 }
2128 }
2129 }
2130
2131 /**
2132 * Binds all loaded data to actual views on the main thread.
2133 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002134 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002135 final long t = SystemClock.uptimeMillis();
2136 Runnable r;
2137
2138 // Don't use these two variables in any of the callback runnables.
2139 // Otherwise we hold a reference to them.
2140 final Callbacks oldCallbacks = mCallbacks.get();
2141 if (oldCallbacks == null) {
2142 // This launcher has exited and nobody bothered to tell us. Just bail.
2143 Log.w(TAG, "LoaderTask running with no launcher");
2144 return;
2145 }
2146
Winson Chung4a2afa32012-07-19 14:53:05 -07002147 final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
2148 final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002149 oldCallbacks.getCurrentWorkspaceScreen();
2150
2151 // Load all the items that are on the current page first (and in the process, unbind
2152 // all the existing workspace items before we call startBinding() below.
2153 unbindWorkspaceItemsOnMainThread();
2154 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2155 ArrayList<LauncherAppWidgetInfo> appWidgets =
2156 new ArrayList<LauncherAppWidgetInfo>();
2157 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2158 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002159 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002160 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002161 workspaceItems.addAll(sBgWorkspaceItems);
2162 appWidgets.addAll(sBgAppWidgets);
2163 folders.putAll(sBgFolders);
2164 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002165 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002166 }
2167
2168 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2169 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2170 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2171 new ArrayList<LauncherAppWidgetInfo>();
2172 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2173 new ArrayList<LauncherAppWidgetInfo>();
2174 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2175 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2176
2177 // Separate the items that are on the current screen, and all the other remaining items
2178 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
2179 otherWorkspaceItems);
2180 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
2181 otherAppWidgets);
2182 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
2183 otherFolders);
2184 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2185 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2186
2187 // Tell the workspace that we're about to start binding items
2188 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002189 public void run() {
2190 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2191 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002192 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002193 }
2194 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002195 };
Winson Chung81b52252012-08-27 15:34:29 -07002196 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002197
Adam Cohendcd297f2013-06-18 13:13:40 -07002198 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2199
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002200 // Load items on the current page
2201 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2202 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002203 if (isLoadingSynchronously) {
2204 r = new Runnable() {
2205 public void run() {
2206 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2207 if (callbacks != null) {
2208 callbacks.onPageBoundSynchronously(currentScreen);
2209 }
2210 }
2211 };
Winson Chung81b52252012-08-27 15:34:29 -07002212 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002213 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002214
Winson Chung4a2afa32012-07-19 14:53:05 -07002215 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2216 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002217 mDeferredBindRunnables.clear();
2218 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002219 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002220
2221 // Tell the workspace that we're done binding items
2222 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002223 public void run() {
2224 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2225 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002226 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002227 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002228
Winson Chung98e030b2012-05-07 16:01:11 -07002229 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002230 if (DEBUG_LOADERS) {
2231 Log.d(TAG, "bound workspace in "
2232 + (SystemClock.uptimeMillis()-t) + "ms");
2233 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002234
2235 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002236 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002237 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002238 if (isLoadingSynchronously) {
2239 mDeferredBindRunnables.add(r);
2240 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002241 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002242 }
Joe Onorato36115782010-06-17 13:28:48 -04002243 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002244
Joe Onorato36115782010-06-17 13:28:48 -04002245 private void loadAndBindAllApps() {
2246 if (DEBUG_LOADERS) {
2247 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2248 }
2249 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002250 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002251 synchronized (LoaderTask.this) {
2252 if (mStopped) {
2253 return;
2254 }
2255 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002256 }
Joe Onorato36115782010-06-17 13:28:48 -04002257 } else {
2258 onlyBindAllApps();
2259 }
2260 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002261
Joe Onorato36115782010-06-17 13:28:48 -04002262 private void onlyBindAllApps() {
2263 final Callbacks oldCallbacks = mCallbacks.get();
2264 if (oldCallbacks == null) {
2265 // This launcher has exited and nobody bothered to tell us. Just bail.
2266 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2267 return;
2268 }
2269
2270 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002271 @SuppressWarnings("unchecked")
Joe Onorato36115782010-06-17 13:28:48 -04002272 final ArrayList<ApplicationInfo> list
Adam Cohen487f7dd2012-06-28 18:12:10 -07002273 = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002274 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002275 public void run() {
2276 final long t = SystemClock.uptimeMillis();
2277 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2278 if (callbacks != null) {
2279 callbacks.bindAllApplications(list);
2280 }
2281 if (DEBUG_LOADERS) {
2282 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2283 + (SystemClock.uptimeMillis()-t) + "ms");
2284 }
2285 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002286 };
2287 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002288 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002289 r.run();
2290 } else {
2291 mHandler.post(r);
2292 }
Joe Onorato36115782010-06-17 13:28:48 -04002293 }
2294
Winson Chung64359a52013-07-08 17:17:08 -07002295 private void loadAllApps() {
2296 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002297
2298 // Don't use these two variables in any of the callback runnables.
2299 // Otherwise we hold a reference to them.
2300 final Callbacks oldCallbacks = mCallbacks.get();
2301 if (oldCallbacks == null) {
2302 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002303 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002304 return;
2305 }
2306
Winson Chung64359a52013-07-08 17:17:08 -07002307 final PackageManager packageManager = mContext.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04002308 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2309 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2310
Winson Chung64359a52013-07-08 17:17:08 -07002311 // Clear the list of apps
2312 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002313
Winson Chung64359a52013-07-08 17:17:08 -07002314 // Query for the set of apps
2315 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2316 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2317 if (DEBUG_LOADERS) {
2318 Log.d(TAG, "queryIntentActivities took "
2319 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2320 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2321 }
2322 // Fail if we don't have any apps
2323 if (apps == null || apps.isEmpty()) {
2324 return;
2325 }
2326 // Sort the applications by name
2327 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2328 Collections.sort(apps,
2329 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2330 if (DEBUG_LOADERS) {
2331 Log.d(TAG, "sort took "
2332 + (SystemClock.uptimeMillis()-sortTime) + "ms");
Joe Onorato9c1289c2009-08-17 11:03:03 -04002333 }
2334
Winson Chung64359a52013-07-08 17:17:08 -07002335 // Create the ApplicationInfos
2336 final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2337 for (int i = 0; i < apps.size(); i++) {
2338 // This builds the icon bitmaps.
2339 mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
2340 mIconCache, mLabelCache));
2341 }
2342
2343 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2344 final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
2345 mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
2346
2347 // Post callback on main thread
2348 mHandler.post(new Runnable() {
2349 public void run() {
2350 final long bindTime = SystemClock.uptimeMillis();
2351 if (callbacks != null) {
2352 callbacks.bindAllApplications(added);
2353 if (DEBUG_LOADERS) {
2354 Log.d(TAG, "bound " + added.size() + " apps in "
2355 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2356 }
2357 } else {
2358 Log.i(TAG, "not binding apps: no Launcher activity");
2359 }
2360 }
2361 });
2362
Joe Onorato36115782010-06-17 13:28:48 -04002363 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002364 Log.d(TAG, "Icons processed in "
2365 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002366 }
2367 }
2368
2369 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002370 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002371 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2372 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2373 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2374 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2375 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2376 }
Joe Onorato36115782010-06-17 13:28:48 -04002377 }
2378 }
2379
2380 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002381 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002382 }
2383
2384 private class PackageUpdatedTask implements Runnable {
2385 int mOp;
2386 String[] mPackages;
2387
2388 public static final int OP_NONE = 0;
2389 public static final int OP_ADD = 1;
2390 public static final int OP_UPDATE = 2;
2391 public static final int OP_REMOVE = 3; // uninstlled
2392 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2393
2394
2395 public PackageUpdatedTask(int op, String[] packages) {
2396 mOp = op;
2397 mPackages = packages;
2398 }
2399
2400 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002401 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002402
2403 final String[] packages = mPackages;
2404 final int N = packages.length;
2405 switch (mOp) {
2406 case OP_ADD:
2407 for (int i=0; i<N; i++) {
2408 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002409 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002410 }
2411 break;
2412 case OP_UPDATE:
2413 for (int i=0; i<N; i++) {
2414 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002415 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002416 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002417 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002418 }
2419 break;
2420 case OP_REMOVE:
2421 case OP_UNAVAILABLE:
2422 for (int i=0; i<N; i++) {
2423 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002424 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002425 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002426 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002427 }
2428 break;
2429 }
2430
2431 ArrayList<ApplicationInfo> added = null;
Joe Onorato36115782010-06-17 13:28:48 -04002432 ArrayList<ApplicationInfo> modified = null;
Winson Chung83892cc2013-05-01 16:53:33 -07002433 final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002434
Adam Cohen487f7dd2012-06-28 18:12:10 -07002435 if (mBgAllAppsList.added.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002436 added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
2437 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002438 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002439 if (mBgAllAppsList.modified.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002440 modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
2441 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002442 }
Winson Chung5d55f332012-07-16 20:45:03 -07002443 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002444 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002445 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002446 }
2447
Joe Onorato36115782010-06-17 13:28:48 -04002448 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2449 if (callbacks == null) {
2450 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2451 return;
2452 }
2453
2454 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002455 // Ensure that we add all the workspace applications to the db
Winson Chung997a9232013-07-24 15:33:46 -07002456 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Winson Chung64359a52013-07-08 17:17:08 -07002457 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
Winson Chung997a9232013-07-24 15:33:46 -07002458 addAndBindAddedApps(context, addedInfos, cb);
Joe Onorato36115782010-06-17 13:28:48 -04002459 }
2460 if (modified != null) {
2461 final ArrayList<ApplicationInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002462
2463 // Update the launcher db to reflect the changes
2464 for (ApplicationInfo a : modifiedFinal) {
2465 ArrayList<ItemInfo> infos =
2466 getItemInfoForComponentName(a.componentName);
2467 for (ItemInfo i : infos) {
2468 if (isShortcutInfoUpdateable(i)) {
2469 ShortcutInfo info = (ShortcutInfo) i;
2470 info.title = a.title.toString();
2471 updateItemInDatabase(context, info);
2472 }
2473 }
2474 }
2475
Joe Onorato36115782010-06-17 13:28:48 -04002476 mHandler.post(new Runnable() {
2477 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002478 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2479 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002480 callbacks.bindAppsUpdated(modifiedFinal);
2481 }
2482 }
2483 });
2484 }
Winson Chung83892cc2013-05-01 16:53:33 -07002485 // If a package has been removed, or an app has been removed as a result of
2486 // an update (for example), make the removed callback.
2487 if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
Winson Chung64359a52013-07-08 17:17:08 -07002488 final boolean packageRemoved = (mOp == OP_REMOVE);
Winson Chung83892cc2013-05-01 16:53:33 -07002489 final ArrayList<String> removedPackageNames =
2490 new ArrayList<String>(Arrays.asList(packages));
2491
Winson Chung64359a52013-07-08 17:17:08 -07002492 // Update the launcher db to reflect the removal of apps
2493 if (packageRemoved) {
2494 for (String pn : removedPackageNames) {
2495 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2496 for (ItemInfo i : infos) {
2497 deleteItemFromDatabase(context, i);
2498 }
2499 }
2500 } else {
2501 for (ApplicationInfo a : removedApps) {
2502 ArrayList<ItemInfo> infos =
2503 getItemInfoForComponentName(a.componentName);
2504 for (ItemInfo i : infos) {
2505 deleteItemFromDatabase(context, i);
2506 }
2507 }
2508 }
2509
Joe Onorato36115782010-06-17 13:28:48 -04002510 mHandler.post(new Runnable() {
2511 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002512 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2513 if (callbacks == cb && cb != null) {
Winson Chung83892cc2013-05-01 16:53:33 -07002514 callbacks.bindComponentsRemoved(removedPackageNames,
Winson Chung64359a52013-07-08 17:17:08 -07002515 removedApps, packageRemoved);
Joe Onorato36115782010-06-17 13:28:48 -04002516 }
2517 }
2518 });
Joe Onoratobe386092009-11-17 17:32:16 -08002519 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002520
Michael Jurkac402cd92013-05-20 15:49:32 +02002521 final ArrayList<Object> widgetsAndShortcuts =
2522 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002523 mHandler.post(new Runnable() {
2524 @Override
2525 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002526 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2527 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002528 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002529 }
2530 }
2531 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002532 }
2533 }
2534
Michael Jurkac402cd92013-05-20 15:49:32 +02002535 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2536 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2537 PackageManager packageManager = context.getPackageManager();
2538 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2539 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2540 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2541 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2542 Collections.sort(widgetsAndShortcuts,
2543 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2544 return widgetsAndShortcuts;
2545 }
2546
Winson Chung1323b482013-08-05 12:41:55 -07002547 private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) {
Winson Chungee055712013-07-30 14:46:24 -07002548 if (cn == null) {
2549 return false;
2550 }
2551
2552 try {
2553 return (pm.getActivityInfo(cn, 0) != null);
2554 } catch (NameNotFoundException e) {
2555 return false;
2556 }
2557 }
2558
Joe Onorato9c1289c2009-08-17 11:03:03 -04002559 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002560 * This is called from the code that adds shortcuts from the intent receiver. This
2561 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002562 */
Joe Onorato56d82912010-03-07 14:32:10 -05002563 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002564 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002565 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002566
Joe Onorato56d82912010-03-07 14:32:10 -05002567 /**
2568 * Make an ShortcutInfo object for a shortcut that is an application.
2569 *
2570 * If c is not null, then it will be used to fill in missing data like the title and icon.
2571 */
2572 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002573 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002574 ComponentName componentName = intent.getComponent();
Winson Chung1323b482013-08-05 12:41:55 -07002575 final ShortcutInfo info = new ShortcutInfo();
2576 if (!isValidPackageComponent(manager, componentName)) {
Winson Chungee055712013-07-30 14:46:24 -07002577 Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002578 return null;
Winson Chung1323b482013-08-05 12:41:55 -07002579 } else {
2580 try {
2581 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2582 info.initFlagsAndFirstInstallTime(pi);
2583 } catch (NameNotFoundException e) {
2584 Log.d(TAG, "getPackInfo failed for package " +
2585 componentName.getPackageName());
2586 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002587 }
2588
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002589 // TODO: See if the PackageManager knows about this case. If it doesn't
2590 // then return null & delete this.
2591
Joe Onorato56d82912010-03-07 14:32:10 -05002592 // the resource -- This may implicitly give us back the fallback icon,
2593 // but don't worry about that. All we're doing with usingFallbackIcon is
2594 // to avoid saving lots of copies of that in the database, and most apps
2595 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002596
2597 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2598 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2599 // via resolveActivity().
Winson Chungee055712013-07-30 14:46:24 -07002600 Bitmap icon = null;
Winson Chungc208ff92012-03-29 17:37:41 -07002601 ResolveInfo resolveInfo = null;
2602 ComponentName oldComponent = intent.getComponent();
2603 Intent newIntent = new Intent(intent.getAction(), null);
2604 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2605 newIntent.setPackage(oldComponent.getPackageName());
2606 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2607 for (ResolveInfo i : infos) {
2608 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2609 i.activityInfo.name);
2610 if (cn.equals(oldComponent)) {
2611 resolveInfo = i;
2612 }
2613 }
2614 if (resolveInfo == null) {
2615 resolveInfo = manager.resolveActivity(intent, 0);
2616 }
Joe Onorato56d82912010-03-07 14:32:10 -05002617 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002618 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002619 }
Joe Onorato56d82912010-03-07 14:32:10 -05002620 // the db
2621 if (icon == null) {
2622 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002623 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002624 }
2625 }
2626 // the fallback icon
2627 if (icon == null) {
2628 icon = getFallbackIcon();
2629 info.usingFallbackIcon = true;
2630 }
2631 info.setIcon(icon);
2632
2633 // from the resource
2634 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002635 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2636 if (labelCache != null && labelCache.containsKey(key)) {
2637 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002638 } else {
2639 info.title = resolveInfo.activityInfo.loadLabel(manager);
2640 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002641 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002642 }
2643 }
Joe Onorato56d82912010-03-07 14:32:10 -05002644 }
2645 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002646 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002647 if (c != null) {
2648 info.title = c.getString(titleIndex);
2649 }
2650 }
2651 // fall back to the class name of the activity
2652 if (info.title == null) {
2653 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002654 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002655 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2656 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002657 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002658
Winson Chung64359a52013-07-08 17:17:08 -07002659 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2660 ItemInfoFilter f) {
2661 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2662 for (ItemInfo i : infos) {
2663 if (i instanceof ShortcutInfo) {
2664 ShortcutInfo info = (ShortcutInfo) i;
2665 ComponentName cn = info.intent.getComponent();
2666 if (cn != null && f.filterItem(null, info, cn)) {
2667 filtered.add(info);
2668 }
2669 } else if (i instanceof FolderInfo) {
2670 FolderInfo info = (FolderInfo) i;
2671 for (ShortcutInfo s : info.contents) {
2672 ComponentName cn = s.intent.getComponent();
2673 if (cn != null && f.filterItem(info, s, cn)) {
2674 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07002675 }
2676 }
Winson Chung64359a52013-07-08 17:17:08 -07002677 } else if (i instanceof LauncherAppWidgetInfo) {
2678 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2679 ComponentName cn = info.providerName;
2680 if (cn != null && f.filterItem(null, info, cn)) {
2681 filtered.add(info);
2682 }
Winson Chung8a435102012-08-30 17:16:53 -07002683 }
2684 }
Winson Chung64359a52013-07-08 17:17:08 -07002685 return new ArrayList<ItemInfo>(filtered);
2686 }
2687
2688 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
2689 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2690 ItemInfoFilter filter = new ItemInfoFilter() {
2691 @Override
2692 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2693 return cn.getPackageName().equals(pn);
2694 }
2695 };
2696 return filterItemInfos(sBgItemsIdMap.values(), filter);
2697 }
2698
2699 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
2700 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2701 ItemInfoFilter filter = new ItemInfoFilter() {
2702 @Override
2703 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2704 return cn.equals(cname);
2705 }
2706 };
2707 return filterItemInfos(sBgItemsIdMap.values(), filter);
2708 }
2709
2710 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2711 if (i instanceof ShortcutInfo) {
2712 ShortcutInfo info = (ShortcutInfo) i;
2713 // We need to check for ACTION_MAIN otherwise getComponent() might
2714 // return null for some shortcuts (for instance, for shortcuts to
2715 // web pages.)
2716 Intent intent = info.intent;
2717 ComponentName name = intent.getComponent();
2718 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2719 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2720 return true;
2721 }
2722 }
2723 return false;
Winson Chung8a435102012-08-30 17:16:53 -07002724 }
2725
2726 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002727 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002728 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002729 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002730 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2731 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002732
Joe Onorato56d82912010-03-07 14:32:10 -05002733 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002734 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002735 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002736
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002737 // TODO: If there's an explicit component and we can't install that, delete it.
2738
Joe Onorato56d82912010-03-07 14:32:10 -05002739 info.title = c.getString(titleIndex);
2740
Joe Onorato9c1289c2009-08-17 11:03:03 -04002741 int iconType = c.getInt(iconTypeIndex);
2742 switch (iconType) {
2743 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2744 String packageName = c.getString(iconPackageIndex);
2745 String resourceName = c.getString(iconResourceIndex);
2746 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002747 info.customIcon = false;
2748 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002749 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002750 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002751 if (resources != null) {
2752 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002753 icon = Utilities.createIconBitmap(
2754 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002755 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002756 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002757 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002758 }
Joe Onorato56d82912010-03-07 14:32:10 -05002759 // the db
2760 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002761 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002762 }
2763 // the fallback icon
2764 if (icon == null) {
2765 icon = getFallbackIcon();
2766 info.usingFallbackIcon = true;
2767 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002768 break;
2769 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002770 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002771 if (icon == null) {
2772 icon = getFallbackIcon();
2773 info.customIcon = false;
2774 info.usingFallbackIcon = true;
2775 } else {
2776 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002777 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002778 break;
2779 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002780 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002781 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002782 info.customIcon = false;
2783 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002784 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002785 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002786 return info;
2787 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002788
Michael Jurka931dc972011-08-05 15:08:15 -07002789 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002790 @SuppressWarnings("all") // suppress dead code warning
2791 final boolean debug = false;
2792 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002793 Log.d(TAG, "getIconFromCursor app="
2794 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2795 }
2796 byte[] data = c.getBlob(iconIndex);
2797 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002798 return Utilities.createIconBitmap(
2799 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002800 } catch (Exception e) {
2801 return null;
2802 }
2803 }
2804
Winson Chung3d503fb2011-07-13 17:25:49 -07002805 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2806 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002807 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002808 if (info == null) {
2809 return null;
2810 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002811 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002812
2813 return info;
2814 }
2815
Winson Chunga9abd0e2010-10-27 17:18:37 -07002816 /**
Winson Chung55cef262010-10-28 14:14:18 -07002817 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2818 */
2819 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2820 ComponentName component) {
2821 List<AppWidgetProviderInfo> widgets =
2822 AppWidgetManager.getInstance(context).getInstalledProviders();
2823 for (AppWidgetProviderInfo info : widgets) {
2824 if (info.provider.equals(component)) {
2825 return info;
2826 }
2827 }
2828 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002829 }
2830
Winson Chung68846fd2010-10-29 11:00:27 -07002831 /**
2832 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2833 */
2834 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2835 final PackageManager packageManager = context.getPackageManager();
2836 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2837 new ArrayList<WidgetMimeTypeHandlerData>();
2838
2839 final Intent supportsIntent =
2840 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2841 supportsIntent.setType(mimeType);
2842
2843 // Create a set of widget configuration components that we can test against
2844 final List<AppWidgetProviderInfo> widgets =
2845 AppWidgetManager.getInstance(context).getInstalledProviders();
2846 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2847 new HashMap<ComponentName, AppWidgetProviderInfo>();
2848 for (AppWidgetProviderInfo info : widgets) {
2849 configurationComponentToWidget.put(info.configure, info);
2850 }
2851
2852 // Run through each of the intents that can handle this type of clip data, and cross
2853 // reference them with the components that are actual configuration components
2854 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2855 PackageManager.MATCH_DEFAULT_ONLY);
2856 for (ResolveInfo info : activities) {
2857 final ActivityInfo activityInfo = info.activityInfo;
2858 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2859 activityInfo.name);
2860 if (configurationComponentToWidget.containsKey(infoComponent)) {
2861 supportedConfigurationActivities.add(
2862 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2863 configurationComponentToWidget.get(infoComponent)));
2864 }
2865 }
2866 return supportedConfigurationActivities;
2867 }
2868
Winson Chunga9abd0e2010-10-27 17:18:37 -07002869 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08002870 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2871 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2872 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2873
Adam Cohend9198822011-11-22 16:42:47 -08002874 if (intent == null) {
2875 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2876 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2877 return null;
2878 }
2879
Joe Onorato0589f0f2010-02-08 13:44:00 -08002880 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08002881 boolean customIcon = false;
2882 ShortcutIconResource iconResource = null;
2883
2884 if (bitmap != null && bitmap instanceof Bitmap) {
2885 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002886 customIcon = true;
2887 } else {
2888 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2889 if (extra != null && extra instanceof ShortcutIconResource) {
2890 try {
2891 iconResource = (ShortcutIconResource) extra;
2892 final PackageManager packageManager = context.getPackageManager();
2893 Resources resources = packageManager.getResourcesForApplication(
2894 iconResource.packageName);
2895 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002896 icon = Utilities.createIconBitmap(
2897 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002898 } catch (Exception e) {
2899 Log.w(TAG, "Could not load shortcut icon: " + extra);
2900 }
2901 }
2902 }
2903
Michael Jurkac9d95c52011-08-29 14:03:34 -07002904 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002905
2906 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002907 if (fallbackIcon != null) {
2908 icon = fallbackIcon;
2909 } else {
2910 icon = getFallbackIcon();
2911 info.usingFallbackIcon = true;
2912 }
Joe Onorato56d82912010-03-07 14:32:10 -05002913 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08002914 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05002915
Joe Onorato0589f0f2010-02-08 13:44:00 -08002916 info.title = name;
2917 info.intent = intent;
2918 info.customIcon = customIcon;
2919 info.iconResource = iconResource;
2920
2921 return info;
2922 }
2923
Winson Chungaac01e12011-08-17 10:37:13 -07002924 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2925 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08002926 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07002927 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07002928 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08002929 }
Joe Onorato56d82912010-03-07 14:32:10 -05002930 // If this icon doesn't have a custom icon, check to see
2931 // what's stored in the DB, and if it doesn't match what
2932 // we're going to show, store what we are going to show back
2933 // into the DB. We do this so when we're loading, if the
2934 // package manager can't find an icon (for example because
2935 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07002936 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07002937 cache.put(info, c.getBlob(iconIndex));
2938 return true;
2939 }
2940 return false;
2941 }
2942 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2943 boolean needSave = false;
2944 try {
2945 if (data != null) {
2946 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2947 Bitmap loaded = info.getIcon(mIconCache);
2948 needSave = !saved.sameAs(loaded);
2949 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05002950 needSave = true;
2951 }
Winson Chungaac01e12011-08-17 10:37:13 -07002952 } catch (Exception e) {
2953 needSave = true;
2954 }
2955 if (needSave) {
2956 Log.d(TAG, "going to save icon bitmap for info=" + info);
2957 // This is slower than is ideal, but this only happens once
2958 // or when the app is updated with a new icon.
2959 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05002960 }
2961 }
2962
Joe Onorato9c1289c2009-08-17 11:03:03 -04002963 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07002964 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04002965 * or make a new one.
2966 */
Adam Cohendf2cc412011-04-27 16:56:57 -07002967 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002968 // See if a placeholder was created for us already
2969 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07002970 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002971 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07002972 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002973 folders.put(id, folderInfo);
2974 }
Adam Cohendf2cc412011-04-27 16:56:57 -07002975 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002976 }
2977
Winson Chung11904872012-09-17 16:58:46 -07002978 public static final Comparator<ApplicationInfo> getAppNameComparator() {
2979 final Collator collator = Collator.getInstance();
2980 return new Comparator<ApplicationInfo>() {
2981 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2982 int result = collator.compare(a.title.toString(), b.title.toString());
2983 if (result == 0) {
2984 result = a.componentName.compareTo(b.componentName);
2985 }
2986 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07002987 }
Winson Chung11904872012-09-17 16:58:46 -07002988 };
2989 }
Winson Chung78403fe2011-01-21 15:38:02 -08002990 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2991 = new Comparator<ApplicationInfo>() {
2992 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2993 if (a.firstInstallTime < b.firstInstallTime) return 1;
2994 if (a.firstInstallTime > b.firstInstallTime) return -1;
2995 return 0;
2996 }
2997 };
Winson Chung11904872012-09-17 16:58:46 -07002998 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
2999 final Collator collator = Collator.getInstance();
3000 return new Comparator<AppWidgetProviderInfo>() {
3001 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
3002 return collator.compare(a.label.toString(), b.label.toString());
3003 }
3004 };
3005 }
Winson Chung5308f242011-08-18 12:12:41 -07003006 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3007 if (info.activityInfo != null) {
3008 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3009 } else {
3010 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3011 }
3012 }
Winson Chung785d2eb2011-04-14 16:08:02 -07003013 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07003014 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07003015 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07003016 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003017 ShortcutNameComparator(PackageManager pm) {
3018 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07003019 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003020 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003021 }
3022 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
3023 mPackageManager = pm;
3024 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003025 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003026 }
3027 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003028 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07003029 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
3030 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
3031 if (mLabelCache.containsKey(keyA)) {
3032 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003033 } else {
3034 labelA = a.loadLabel(mPackageManager).toString();
3035
Winson Chung5308f242011-08-18 12:12:41 -07003036 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003037 }
Winson Chung5308f242011-08-18 12:12:41 -07003038 if (mLabelCache.containsKey(keyB)) {
3039 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003040 } else {
3041 labelB = b.loadLabel(mPackageManager).toString();
3042
Winson Chung5308f242011-08-18 12:12:41 -07003043 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003044 }
Winson Chung11904872012-09-17 16:58:46 -07003045 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003046 }
3047 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003048 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003049 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003050 private PackageManager mPackageManager;
3051 private HashMap<Object, String> mLabelCache;
3052 WidgetAndShortcutNameComparator(PackageManager pm) {
3053 mPackageManager = pm;
3054 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003055 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003056 }
3057 public final int compare(Object a, Object b) {
3058 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003059 if (mLabelCache.containsKey(a)) {
3060 labelA = mLabelCache.get(a);
3061 } else {
3062 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003063 ((AppWidgetProviderInfo) a).label :
3064 ((ResolveInfo) a).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003065 mLabelCache.put(a, labelA);
3066 }
3067 if (mLabelCache.containsKey(b)) {
3068 labelB = mLabelCache.get(b);
3069 } else {
3070 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003071 ((AppWidgetProviderInfo) b).label :
3072 ((ResolveInfo) b).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003073 mLabelCache.put(b, labelB);
3074 }
Winson Chung11904872012-09-17 16:58:46 -07003075 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003076 }
3077 };
Joe Onoratobe386092009-11-17 17:32:16 -08003078
3079 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003080 Log.d(TAG, "mCallbacks=" + mCallbacks);
Adam Cohen487f7dd2012-06-28 18:12:10 -07003081 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3082 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3083 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3084 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003085 if (mLoaderTask != null) {
3086 mLoaderTask.dumpState();
3087 } else {
3088 Log.d(TAG, "mLoaderTask=null");
3089 }
Joe Onoratobe386092009-11-17 17:32:16 -08003090 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003091}