blob: e6f22d13491350fd2e34838a8455cbf7aa23ece6 [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.
Winson Chung45fa06e2013-08-12 18:36:01 -07001437 Log.d(TAG, "10249126 - verifyApplications(" + isUpgrade + ")");
Winson Chungc763c4e2013-07-19 13:49:06 -07001438 if (!isUpgrade) {
1439 verifyApplications();
1440 }
1441
Joe Onorato36115782010-06-17 13:28:48 -04001442 // Clear out this reference, otherwise we end up holding it until all of the
1443 // callback runnables are done.
1444 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001445
Joe Onorato36115782010-06-17 13:28:48 -04001446 synchronized (mLock) {
1447 // If we are still the last one to be scheduled, remove ourselves.
1448 if (mLoaderTask == this) {
1449 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001450 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001451 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001452 }
Joe Onorato36115782010-06-17 13:28:48 -04001453 }
1454
1455 public void stopLocked() {
1456 synchronized (LoaderTask.this) {
1457 mStopped = true;
1458 this.notify();
1459 }
1460 }
1461
1462 /**
1463 * Gets the callbacks object. If we've been stopped, or if the launcher object
1464 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1465 * object that was around when the deferred message was scheduled, and if there's
1466 * a new Callbacks object around then also return null. This will save us from
1467 * calling onto it with data that will be ignored.
1468 */
1469 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1470 synchronized (mLock) {
1471 if (mStopped) {
1472 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001473 }
Joe Onorato36115782010-06-17 13:28:48 -04001474
1475 if (mCallbacks == null) {
1476 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001477 }
Joe Onorato36115782010-06-17 13:28:48 -04001478
1479 final Callbacks callbacks = mCallbacks.get();
1480 if (callbacks != oldCallbacks) {
1481 return null;
1482 }
1483 if (callbacks == null) {
1484 Log.w(TAG, "no mCallbacks");
1485 return null;
1486 }
1487
1488 return callbacks;
1489 }
1490 }
1491
Winson Chungc763c4e2013-07-19 13:49:06 -07001492 private void verifyApplications() {
1493 final Context context = mApp.getContext();
1494
1495 // Cross reference all the applications in our apps list with items in the workspace
1496 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001497 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001498 synchronized (sBgLock) {
1499 for (ApplicationInfo app : mBgAllAppsList.data) {
1500 tmpInfos = getItemInfoForComponentName(app.componentName);
Winson Chung45fa06e2013-08-12 18:36:01 -07001501 Log.d(TAG, "10249126 - \t" + app.componentName.getPackageName() + ", " + tmpInfos.isEmpty());
Winson Chungc763c4e2013-07-19 13:49:06 -07001502 if (tmpInfos.isEmpty()) {
1503 // We are missing an application icon, so add this to the workspace
1504 added.add(app);
1505 // This is a rare event, so lets log it
1506 Log.e(TAG, "Missing Application on load: " + app);
1507 }
1508 }
1509 }
1510 if (!added.isEmpty()) {
1511 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1512 addAndBindAddedApps(context, added, cb);
1513 }
1514 }
1515
Joe Onorato36115782010-06-17 13:28:48 -04001516 // check & update map of what's occupied; used to discard overlapping/invalid items
Adam Cohendcd297f2013-06-18 13:13:40 -07001517 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
1518 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001519 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001520 if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
1521 if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1522 [(int) item.screenId][0] != null) {
1523 Log.e(TAG, "Error loading shortcut into hotseat " + item
1524 + " into position (" + item.screenId + ":" + item.cellX + ","
1525 + item.cellY + ") occupied by "
1526 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1527 [(int) item.screenId][0]);
1528 return false;
1529 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001530 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001531 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1532 items[(int) item.screenId][0] = item;
1533 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001534 return true;
1535 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001536 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1537 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001538 return true;
1539 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001540
Adam Cohendcd297f2013-06-18 13:13:40 -07001541 if (!occupied.containsKey(item.screenId)) {
1542 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1543 occupied.put(item.screenId, items);
1544 }
1545
1546 ItemInfo[][] screens = occupied.get(item.screenId);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001547 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001548 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1549 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001550 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001551 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001552 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001553 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001554 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001555 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001556 return false;
1557 }
1558 }
1559 }
1560 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1561 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001562 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001563 }
1564 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001565
Joe Onorato36115782010-06-17 13:28:48 -04001566 return true;
1567 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001568
Winson Chungc763c4e2013-07-19 13:49:06 -07001569 /** Returns whether this is an upgradge path */
1570 private boolean loadWorkspace() {
Joe Onorato36115782010-06-17 13:28:48 -04001571 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001572
Joe Onorato36115782010-06-17 13:28:48 -04001573 final Context context = mContext;
1574 final ContentResolver contentResolver = context.getContentResolver();
1575 final PackageManager manager = context.getPackageManager();
1576 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1577 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001578
Michael Jurkab85f8a42012-04-25 15:48:32 -07001579 // Make sure the default workspace is loaded, if needed
Winson Chungc763c4e2013-07-19 13:49:06 -07001580 mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
Adam Cohene25af792013-06-06 23:08:25 -07001581
Winson Chungc763c4e2013-07-19 13:49:06 -07001582 // Check if we need to do any upgrade-path logic
1583 boolean loadedOldDb = mApp.getLauncherProvider().justLoadedOldDb();
Michael Jurkab85f8a42012-04-25 15:48:32 -07001584
Winson Chung2abf94d2012-07-18 18:16:38 -07001585 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001586 sBgWorkspaceItems.clear();
1587 sBgAppWidgets.clear();
1588 sBgFolders.clear();
1589 sBgItemsIdMap.clear();
1590 sBgDbIconCache.clear();
Adam Cohendcd297f2013-06-18 13:13:40 -07001591 sBgWorkspaceScreens.clear();
Winson Chung8481e322013-08-09 16:06:38 -07001592 Log.d(TAG, "10249126 - loadWorkspace()");
Romain Guy5c16f3e2010-01-12 17:24:58 -08001593
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001594 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001595 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Adam Cohene25af792013-06-06 23:08:25 -07001596 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001597
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001598 // +1 for the hotseat (it can be larger than the workspace)
1599 // Load workspace in reverse order to ensure that latest items are loaded first (and
1600 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001601 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001602
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001603 try {
1604 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1605 final int intentIndex = c.getColumnIndexOrThrow
1606 (LauncherSettings.Favorites.INTENT);
1607 final int titleIndex = c.getColumnIndexOrThrow
1608 (LauncherSettings.Favorites.TITLE);
1609 final int iconTypeIndex = c.getColumnIndexOrThrow(
1610 LauncherSettings.Favorites.ICON_TYPE);
1611 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1612 final int iconPackageIndex = c.getColumnIndexOrThrow(
1613 LauncherSettings.Favorites.ICON_PACKAGE);
1614 final int iconResourceIndex = c.getColumnIndexOrThrow(
1615 LauncherSettings.Favorites.ICON_RESOURCE);
1616 final int containerIndex = c.getColumnIndexOrThrow(
1617 LauncherSettings.Favorites.CONTAINER);
1618 final int itemTypeIndex = c.getColumnIndexOrThrow(
1619 LauncherSettings.Favorites.ITEM_TYPE);
1620 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1621 LauncherSettings.Favorites.APPWIDGET_ID);
1622 final int screenIndex = c.getColumnIndexOrThrow(
1623 LauncherSettings.Favorites.SCREEN);
1624 final int cellXIndex = c.getColumnIndexOrThrow
1625 (LauncherSettings.Favorites.CELLX);
1626 final int cellYIndex = c.getColumnIndexOrThrow
1627 (LauncherSettings.Favorites.CELLY);
1628 final int spanXIndex = c.getColumnIndexOrThrow
1629 (LauncherSettings.Favorites.SPANX);
1630 final int spanYIndex = c.getColumnIndexOrThrow(
1631 LauncherSettings.Favorites.SPANY);
1632 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1633 //final int displayModeIndex = c.getColumnIndexOrThrow(
1634 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001635
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001636 ShortcutInfo info;
1637 String intentDescription;
1638 LauncherAppWidgetInfo appWidgetInfo;
1639 int container;
1640 long id;
1641 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001642
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001643 while (!mStopped && c.moveToNext()) {
1644 try {
1645 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001646
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001647 switch (itemType) {
1648 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1649 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001650 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001651 intentDescription = c.getString(intentIndex);
1652 try {
1653 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001654 ComponentName cn = intent.getComponent();
Winson Chung1323b482013-08-05 12:41:55 -07001655 if (!isValidPackageComponent(manager, cn)) {
Winson Chungee055712013-07-30 14:46:24 -07001656 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chung1323b482013-08-05 12:41:55 -07001657 // Log the invalid package, and remove it from the db
1658 Uri uri = LauncherSettings.Favorites.getContentUri(id,
1659 false);
Winson Chungee055712013-07-30 14:46:24 -07001660 contentResolver.delete(uri, null, null);
Winson Chung1323b482013-08-05 12:41:55 -07001661 Log.e(TAG, "Invalid package removed: " + cn);
Winson Chungee055712013-07-30 14:46:24 -07001662 } else {
Winson Chung1323b482013-08-05 12:41:55 -07001663 // If apps can be on external storage, then we just
1664 // leave them for the user to remove (maybe add
1665 // visual treatment to it)
1666 Log.e(TAG, "Invalid package found: " + cn);
Winson Chungee055712013-07-30 14:46:24 -07001667 }
1668 continue;
1669 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001670 } catch (URISyntaxException e) {
1671 continue;
1672 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001673
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001674 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1675 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1676 titleIndex, mLabelCache);
1677 } else {
1678 info = getShortcutInfo(c, context, iconTypeIndex,
1679 iconPackageIndex, iconResourceIndex, iconIndex,
1680 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001681
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001682 // App shortcuts that used to be automatically added to Launcher
1683 // didn't always have the correct intent flags set, so do that
1684 // here
1685 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001686 intent.getCategories() != null &&
1687 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001688 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001689 intent.addFlags(
1690 Intent.FLAG_ACTIVITY_NEW_TASK |
1691 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1692 }
Michael Jurka96879562012-03-22 05:54:33 -07001693 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001694
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001695 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07001696 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001697 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001698 container = c.getInt(containerIndex);
1699 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001700 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001701 info.cellX = c.getInt(cellXIndex);
1702 info.cellY = c.getInt(cellYIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001703 // check & update map of what's occupied
1704 if (!checkItemPlacement(occupied, info)) {
1705 break;
1706 }
1707
1708 switch (container) {
1709 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1710 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1711 sBgWorkspaceItems.add(info);
1712 break;
1713 default:
1714 // Item is in a user folder
1715 FolderInfo folderInfo =
1716 findOrMakeFolder(sBgFolders, container);
1717 folderInfo.add(info);
1718 break;
1719 }
1720 sBgItemsIdMap.put(info.id, info);
1721
1722 // now that we've loaded everthing re-save it with the
1723 // icon in case it disappears somehow.
1724 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07001725 } else {
1726 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001727 }
1728 break;
1729
1730 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1731 id = c.getLong(idIndex);
1732 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1733
1734 folderInfo.title = c.getString(titleIndex);
1735 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001736 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001737 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001738 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001739 folderInfo.cellX = c.getInt(cellXIndex);
1740 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001741
Daniel Sandler8802e962010-05-26 16:28:16 -04001742 // check & update map of what's occupied
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001743 if (!checkItemPlacement(occupied, folderInfo)) {
Daniel Sandler8802e962010-05-26 16:28:16 -04001744 break;
1745 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001746 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001747 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1748 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1749 sBgWorkspaceItems.add(folderInfo);
1750 break;
Joe Onorato36115782010-06-17 13:28:48 -04001751 }
Joe Onorato17a89222011-02-08 17:26:11 -08001752
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001753 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1754 sBgFolders.put(folderInfo.id, folderInfo);
1755 break;
1756
1757 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1758 // Read all Launcher-specific widget details
1759 int appWidgetId = c.getInt(appWidgetIdIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001760 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001761
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001762 final AppWidgetProviderInfo provider =
1763 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001764
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001765 if (!isSafeMode && (provider == null || provider.provider == null ||
1766 provider.provider.getPackageName() == null)) {
1767 String log = "Deleting widget that isn't installed anymore: id="
1768 + id + " appWidgetId=" + appWidgetId;
1769 Log.e(TAG, log);
1770 Launcher.sDumpLogs.add(log);
1771 itemsToRemove.add(id);
1772 } else {
1773 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1774 provider.provider);
1775 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07001776 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001777 appWidgetInfo.cellX = c.getInt(cellXIndex);
1778 appWidgetInfo.cellY = c.getInt(cellYIndex);
1779 appWidgetInfo.spanX = c.getInt(spanXIndex);
1780 appWidgetInfo.spanY = c.getInt(spanYIndex);
1781 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1782 appWidgetInfo.minSpanX = minSpan[0];
1783 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001784
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001785 container = c.getInt(containerIndex);
1786 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1787 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1788 Log.e(TAG, "Widget found where container != " +
1789 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1790 continue;
1791 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001792
Adam Cohene25af792013-06-06 23:08:25 -07001793 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001794 // check & update map of what's occupied
1795 if (!checkItemPlacement(occupied, appWidgetInfo)) {
1796 break;
1797 }
1798 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1799 sBgAppWidgets.add(appWidgetInfo);
1800 }
Joe Onorato36115782010-06-17 13:28:48 -04001801 break;
1802 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001803 } catch (Exception e) {
1804 Log.w(TAG, "Desktop items loading interrupted:", e);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001805 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001806 }
1807 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04001808 if (c != null) {
1809 c.close();
1810 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001811 }
1812
1813 if (itemsToRemove.size() > 0) {
1814 ContentProviderClient client = contentResolver.acquireContentProviderClient(
1815 LauncherSettings.Favorites.CONTENT_URI);
1816 // Remove dead items
1817 for (long id : itemsToRemove) {
1818 if (DEBUG_LOADERS) {
1819 Log.d(TAG, "Removed id = " + id);
1820 }
1821 // Don't notify content observers
1822 try {
1823 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1824 null, null);
1825 } catch (RemoteException e) {
1826 Log.w(TAG, "Could not remove id = " + id);
1827 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001828 }
1829 }
1830
Winson Chungc763c4e2013-07-19 13:49:06 -07001831 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001832 long maxScreenId = 0;
1833 // If we're importing we use the old screen order.
1834 for (ItemInfo item: sBgItemsIdMap.values()) {
1835 long screenId = item.screenId;
1836 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1837 !sBgWorkspaceScreens.contains(screenId)) {
Winson Chung8481e322013-08-09 16:06:38 -07001838 Log.d(TAG, "10249126 - loadWorkspace-loadedOldDb(" + screenId + ")");
Adam Cohendcd297f2013-06-18 13:13:40 -07001839 sBgWorkspaceScreens.add(screenId);
1840 if (screenId > maxScreenId) {
1841 maxScreenId = screenId;
1842 }
1843 }
1844 }
1845 Collections.sort(sBgWorkspaceScreens);
1846 mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
1847 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07001848
1849 // Update the max item id after we load an old db
1850 long maxItemId = 0;
1851 // If we're importing we use the old screen order.
1852 for (ItemInfo item: sBgItemsIdMap.values()) {
1853 maxItemId = Math.max(maxItemId, item.id);
1854 }
1855 LauncherAppState app = LauncherAppState.getInstance();
1856 app.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07001857 } else {
1858 Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1859 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1860 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1861
1862 try {
1863 final int idIndex = sc.getColumnIndexOrThrow(
1864 LauncherSettings.WorkspaceScreens._ID);
1865 final int rankIndex = sc.getColumnIndexOrThrow(
1866 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1867 while (sc.moveToNext()) {
1868 try {
1869 long screenId = sc.getLong(idIndex);
1870 int rank = sc.getInt(rankIndex);
1871
1872 orderedScreens.put(rank, screenId);
1873 } catch (Exception e) {
1874 Log.w(TAG, "Desktop items loading interrupted:", e);
1875 }
1876 }
1877 } finally {
1878 sc.close();
1879 }
1880
1881 Iterator<Integer> iter = orderedScreens.keySet().iterator();
1882 while (iter.hasNext()) {
1883 sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
1884 }
1885
1886 // Remove any empty screens
Winson Chung8481e322013-08-09 16:06:38 -07001887 Log.d(TAG, "10249126 - loadWorkspace-!loadedOldDb()");
Adam Cohendcd297f2013-06-18 13:13:40 -07001888 ArrayList<Long> unusedScreens = new ArrayList<Long>();
1889 unusedScreens.addAll(sBgWorkspaceScreens);
1890
1891 for (ItemInfo item: sBgItemsIdMap.values()) {
1892 long screenId = item.screenId;
1893
1894 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1895 unusedScreens.contains(screenId)) {
1896 unusedScreens.remove(screenId);
1897 }
1898 }
1899
1900 // If there are any empty screens remove them, and update.
1901 if (unusedScreens.size() != 0) {
1902 sBgWorkspaceScreens.removeAll(unusedScreens);
1903 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1904 }
1905 }
1906
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001907 if (DEBUG_LOADERS) {
1908 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1909 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07001910 int nScreens = occupied.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001911 for (int y = 0; y < mCellCountY; y++) {
1912 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07001913
Daniel Sandler566da102013-06-25 23:43:45 -04001914 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07001915 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001916 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07001917 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001918 line += " | ";
1919 }
1920 for (int x = 0; x < mCellCountX; x++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001921 line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001922 }
Joe Onorato36115782010-06-17 13:28:48 -04001923 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001924 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04001925 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001926 }
Joe Onorato36115782010-06-17 13:28:48 -04001927 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001928 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07001929 }
1930
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001931 /** Filters the set of items who are directly or indirectly (via another container) on the
1932 * specified screen. */
1933 private void filterCurrentWorkspaceItems(int currentScreen,
1934 ArrayList<ItemInfo> allWorkspaceItems,
1935 ArrayList<ItemInfo> currentScreenItems,
1936 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001937 // Purge any null ItemInfos
1938 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1939 while (iter.hasNext()) {
1940 ItemInfo i = iter.next();
1941 if (i == null) {
1942 iter.remove();
1943 }
1944 }
1945
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001946 // If we aren't filtering on a screen, then the set of items to load is the full set of
1947 // items given.
1948 if (currentScreen < 0) {
1949 currentScreenItems.addAll(allWorkspaceItems);
Joe Onorato36115782010-06-17 13:28:48 -04001950 }
1951
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001952 // Order the set of items by their containers first, this allows use to walk through the
1953 // list sequentially, build up a list of containers that are in the specified screen,
1954 // as well as all items in those containers.
1955 Set<Long> itemsOnScreen = new HashSet<Long>();
1956 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1957 @Override
1958 public int compare(ItemInfo lhs, ItemInfo rhs) {
1959 return (int) (lhs.container - rhs.container);
1960 }
1961 });
1962 for (ItemInfo info : allWorkspaceItems) {
1963 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001964 if (info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001965 currentScreenItems.add(info);
1966 itemsOnScreen.add(info.id);
1967 } else {
1968 otherScreenItems.add(info);
1969 }
1970 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1971 currentScreenItems.add(info);
1972 itemsOnScreen.add(info.id);
1973 } else {
1974 if (itemsOnScreen.contains(info.container)) {
1975 currentScreenItems.add(info);
1976 itemsOnScreen.add(info.id);
1977 } else {
1978 otherScreenItems.add(info);
1979 }
1980 }
1981 }
1982 }
1983
1984 /** Filters the set of widgets which are on the specified screen. */
1985 private void filterCurrentAppWidgets(int currentScreen,
1986 ArrayList<LauncherAppWidgetInfo> appWidgets,
1987 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1988 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
1989 // If we aren't filtering on a screen, then the set of items to load is the full set of
1990 // widgets given.
1991 if (currentScreen < 0) {
1992 currentScreenWidgets.addAll(appWidgets);
1993 }
1994
1995 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001996 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001997 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07001998 widget.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001999 currentScreenWidgets.add(widget);
2000 } else {
2001 otherScreenWidgets.add(widget);
2002 }
2003 }
2004 }
2005
2006 /** Filters the set of folders which are on the specified screen. */
2007 private void filterCurrentFolders(int currentScreen,
2008 HashMap<Long, ItemInfo> itemsIdMap,
2009 HashMap<Long, FolderInfo> folders,
2010 HashMap<Long, FolderInfo> currentScreenFolders,
2011 HashMap<Long, FolderInfo> otherScreenFolders) {
2012 // If we aren't filtering on a screen, then the set of items to load is the full set of
2013 // widgets given.
2014 if (currentScreen < 0) {
2015 currentScreenFolders.putAll(folders);
2016 }
2017
2018 for (long id : folders.keySet()) {
2019 ItemInfo info = itemsIdMap.get(id);
2020 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002021 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002022 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07002023 info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002024 currentScreenFolders.put(id, folder);
2025 } else {
2026 otherScreenFolders.put(id, folder);
2027 }
2028 }
2029 }
2030
2031 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2032 * right) */
2033 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
2034 // XXX: review this
2035 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002036 @Override
2037 public int compare(ItemInfo lhs, ItemInfo rhs) {
2038 int cellCountX = LauncherModel.getCellCountX();
2039 int cellCountY = LauncherModel.getCellCountY();
2040 int screenOffset = cellCountX * cellCountY;
2041 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002042 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002043 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002044 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002045 rhs.cellY * cellCountX + rhs.cellX);
2046 return (int) (lr - rr);
2047 }
2048 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002049 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002050
Adam Cohendcd297f2013-06-18 13:13:40 -07002051 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2052 final ArrayList<Long> orderedScreens) {
Winson Chung8481e322013-08-09 16:06:38 -07002053 Log.d(TAG, "10249126 - bindWorkspaceScreens()");
Adam Cohendcd297f2013-06-18 13:13:40 -07002054 final Runnable r = new Runnable() {
2055 @Override
2056 public void run() {
2057 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2058 if (callbacks != null) {
2059 callbacks.bindScreens(orderedScreens);
2060 }
2061 }
2062 };
2063 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2064 }
2065
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002066 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2067 final ArrayList<ItemInfo> workspaceItems,
2068 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2069 final HashMap<Long, FolderInfo> folders,
2070 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002071
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002072 final boolean postOnMainThread = (deferredBindRunnables != null);
2073
2074 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002075 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002076 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002077 final int start = i;
2078 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002079 final Runnable r = new Runnable() {
2080 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002081 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002082 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002083 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002084 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2085 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002086 }
2087 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002088 };
2089 if (postOnMainThread) {
2090 deferredBindRunnables.add(r);
2091 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002092 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002093 }
Joe Onorato36115782010-06-17 13:28:48 -04002094 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002095
2096 // Bind the folders
2097 if (!folders.isEmpty()) {
2098 final Runnable r = new Runnable() {
2099 public void run() {
2100 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2101 if (callbacks != null) {
2102 callbacks.bindFolders(folders);
2103 }
2104 }
2105 };
2106 if (postOnMainThread) {
2107 deferredBindRunnables.add(r);
2108 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002109 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002110 }
2111 }
2112
2113 // Bind the widgets, one at a time
2114 N = appWidgets.size();
2115 for (int i = 0; i < N; i++) {
2116 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2117 final Runnable r = new Runnable() {
2118 public void run() {
2119 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2120 if (callbacks != null) {
2121 callbacks.bindAppWidget(widget);
2122 }
2123 }
2124 };
2125 if (postOnMainThread) {
2126 deferredBindRunnables.add(r);
2127 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002128 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002129 }
2130 }
2131 }
2132
2133 /**
2134 * Binds all loaded data to actual views on the main thread.
2135 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002136 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002137 final long t = SystemClock.uptimeMillis();
2138 Runnable r;
2139
2140 // Don't use these two variables in any of the callback runnables.
2141 // Otherwise we hold a reference to them.
2142 final Callbacks oldCallbacks = mCallbacks.get();
2143 if (oldCallbacks == null) {
2144 // This launcher has exited and nobody bothered to tell us. Just bail.
2145 Log.w(TAG, "LoaderTask running with no launcher");
2146 return;
2147 }
2148
Winson Chung4a2afa32012-07-19 14:53:05 -07002149 final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
2150 final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002151 oldCallbacks.getCurrentWorkspaceScreen();
2152
2153 // Load all the items that are on the current page first (and in the process, unbind
2154 // all the existing workspace items before we call startBinding() below.
2155 unbindWorkspaceItemsOnMainThread();
2156 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2157 ArrayList<LauncherAppWidgetInfo> appWidgets =
2158 new ArrayList<LauncherAppWidgetInfo>();
2159 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2160 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002161 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002162 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002163 workspaceItems.addAll(sBgWorkspaceItems);
2164 appWidgets.addAll(sBgAppWidgets);
2165 folders.putAll(sBgFolders);
2166 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002167 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002168 }
2169
2170 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2171 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2172 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2173 new ArrayList<LauncherAppWidgetInfo>();
2174 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2175 new ArrayList<LauncherAppWidgetInfo>();
2176 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2177 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2178
2179 // Separate the items that are on the current screen, and all the other remaining items
2180 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
2181 otherWorkspaceItems);
2182 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
2183 otherAppWidgets);
2184 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
2185 otherFolders);
2186 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2187 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2188
2189 // Tell the workspace that we're about to start binding items
2190 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002191 public void run() {
2192 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2193 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002194 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002195 }
2196 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002197 };
Winson Chung81b52252012-08-27 15:34:29 -07002198 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002199
Adam Cohendcd297f2013-06-18 13:13:40 -07002200 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2201
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002202 // Load items on the current page
2203 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2204 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002205 if (isLoadingSynchronously) {
2206 r = new Runnable() {
2207 public void run() {
2208 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2209 if (callbacks != null) {
2210 callbacks.onPageBoundSynchronously(currentScreen);
2211 }
2212 }
2213 };
Winson Chung81b52252012-08-27 15:34:29 -07002214 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002215 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002216
Winson Chung4a2afa32012-07-19 14:53:05 -07002217 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2218 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002219 mDeferredBindRunnables.clear();
2220 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002221 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002222
2223 // Tell the workspace that we're done binding items
2224 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002225 public void run() {
2226 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2227 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002228 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002229 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002230
Winson Chung98e030b2012-05-07 16:01:11 -07002231 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002232 if (DEBUG_LOADERS) {
2233 Log.d(TAG, "bound workspace in "
2234 + (SystemClock.uptimeMillis()-t) + "ms");
2235 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002236
2237 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002238 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002239 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002240 if (isLoadingSynchronously) {
2241 mDeferredBindRunnables.add(r);
2242 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002243 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002244 }
Joe Onorato36115782010-06-17 13:28:48 -04002245 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002246
Joe Onorato36115782010-06-17 13:28:48 -04002247 private void loadAndBindAllApps() {
2248 if (DEBUG_LOADERS) {
2249 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2250 }
2251 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002252 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002253 synchronized (LoaderTask.this) {
2254 if (mStopped) {
2255 return;
2256 }
2257 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002258 }
Joe Onorato36115782010-06-17 13:28:48 -04002259 } else {
2260 onlyBindAllApps();
2261 }
2262 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002263
Joe Onorato36115782010-06-17 13:28:48 -04002264 private void onlyBindAllApps() {
2265 final Callbacks oldCallbacks = mCallbacks.get();
2266 if (oldCallbacks == null) {
2267 // This launcher has exited and nobody bothered to tell us. Just bail.
2268 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2269 return;
2270 }
2271
2272 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002273 @SuppressWarnings("unchecked")
Joe Onorato36115782010-06-17 13:28:48 -04002274 final ArrayList<ApplicationInfo> list
Adam Cohen487f7dd2012-06-28 18:12:10 -07002275 = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002276 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002277 public void run() {
2278 final long t = SystemClock.uptimeMillis();
2279 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2280 if (callbacks != null) {
2281 callbacks.bindAllApplications(list);
2282 }
2283 if (DEBUG_LOADERS) {
2284 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2285 + (SystemClock.uptimeMillis()-t) + "ms");
2286 }
2287 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002288 };
2289 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002290 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002291 r.run();
2292 } else {
2293 mHandler.post(r);
2294 }
Joe Onorato36115782010-06-17 13:28:48 -04002295 }
2296
Winson Chung64359a52013-07-08 17:17:08 -07002297 private void loadAllApps() {
2298 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002299
2300 // Don't use these two variables in any of the callback runnables.
2301 // Otherwise we hold a reference to them.
2302 final Callbacks oldCallbacks = mCallbacks.get();
2303 if (oldCallbacks == null) {
2304 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002305 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002306 return;
2307 }
2308
Winson Chung64359a52013-07-08 17:17:08 -07002309 final PackageManager packageManager = mContext.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04002310 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2311 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2312
Winson Chung64359a52013-07-08 17:17:08 -07002313 // Clear the list of apps
2314 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002315
Winson Chung64359a52013-07-08 17:17:08 -07002316 // Query for the set of apps
2317 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2318 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2319 if (DEBUG_LOADERS) {
2320 Log.d(TAG, "queryIntentActivities took "
2321 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2322 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2323 }
2324 // Fail if we don't have any apps
2325 if (apps == null || apps.isEmpty()) {
2326 return;
2327 }
2328 // Sort the applications by name
2329 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2330 Collections.sort(apps,
2331 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2332 if (DEBUG_LOADERS) {
2333 Log.d(TAG, "sort took "
2334 + (SystemClock.uptimeMillis()-sortTime) + "ms");
Joe Onorato9c1289c2009-08-17 11:03:03 -04002335 }
2336
Winson Chung64359a52013-07-08 17:17:08 -07002337 // Create the ApplicationInfos
2338 final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2339 for (int i = 0; i < apps.size(); i++) {
2340 // This builds the icon bitmaps.
2341 mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
2342 mIconCache, mLabelCache));
2343 }
2344
2345 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2346 final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
2347 mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
2348
2349 // Post callback on main thread
2350 mHandler.post(new Runnable() {
2351 public void run() {
2352 final long bindTime = SystemClock.uptimeMillis();
2353 if (callbacks != null) {
2354 callbacks.bindAllApplications(added);
2355 if (DEBUG_LOADERS) {
2356 Log.d(TAG, "bound " + added.size() + " apps in "
2357 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2358 }
2359 } else {
2360 Log.i(TAG, "not binding apps: no Launcher activity");
2361 }
2362 }
2363 });
2364
Joe Onorato36115782010-06-17 13:28:48 -04002365 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002366 Log.d(TAG, "Icons processed in "
2367 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002368 }
2369 }
2370
2371 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002372 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002373 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2374 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2375 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2376 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2377 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2378 }
Joe Onorato36115782010-06-17 13:28:48 -04002379 }
2380 }
2381
2382 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002383 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002384 }
2385
2386 private class PackageUpdatedTask implements Runnable {
2387 int mOp;
2388 String[] mPackages;
2389
2390 public static final int OP_NONE = 0;
2391 public static final int OP_ADD = 1;
2392 public static final int OP_UPDATE = 2;
2393 public static final int OP_REMOVE = 3; // uninstlled
2394 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2395
2396
2397 public PackageUpdatedTask(int op, String[] packages) {
2398 mOp = op;
2399 mPackages = packages;
2400 }
2401
2402 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002403 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002404
2405 final String[] packages = mPackages;
2406 final int N = packages.length;
2407 switch (mOp) {
2408 case OP_ADD:
2409 for (int i=0; i<N; i++) {
2410 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002411 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002412 }
2413 break;
2414 case OP_UPDATE:
2415 for (int i=0; i<N; i++) {
2416 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002417 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002418 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002419 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002420 }
2421 break;
2422 case OP_REMOVE:
2423 case OP_UNAVAILABLE:
2424 for (int i=0; i<N; i++) {
2425 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002426 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002427 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002428 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002429 }
2430 break;
2431 }
2432
2433 ArrayList<ApplicationInfo> added = null;
Joe Onorato36115782010-06-17 13:28:48 -04002434 ArrayList<ApplicationInfo> modified = null;
Winson Chung83892cc2013-05-01 16:53:33 -07002435 final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002436
Adam Cohen487f7dd2012-06-28 18:12:10 -07002437 if (mBgAllAppsList.added.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002438 added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
2439 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002440 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002441 if (mBgAllAppsList.modified.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002442 modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
2443 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002444 }
Winson Chung5d55f332012-07-16 20:45:03 -07002445 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002446 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002447 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002448 }
2449
Joe Onorato36115782010-06-17 13:28:48 -04002450 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2451 if (callbacks == null) {
2452 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2453 return;
2454 }
2455
2456 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002457 // Ensure that we add all the workspace applications to the db
Winson Chung997a9232013-07-24 15:33:46 -07002458 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Winson Chung64359a52013-07-08 17:17:08 -07002459 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
Winson Chung997a9232013-07-24 15:33:46 -07002460 addAndBindAddedApps(context, addedInfos, cb);
Joe Onorato36115782010-06-17 13:28:48 -04002461 }
2462 if (modified != null) {
2463 final ArrayList<ApplicationInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002464
2465 // Update the launcher db to reflect the changes
2466 for (ApplicationInfo a : modifiedFinal) {
2467 ArrayList<ItemInfo> infos =
2468 getItemInfoForComponentName(a.componentName);
2469 for (ItemInfo i : infos) {
2470 if (isShortcutInfoUpdateable(i)) {
2471 ShortcutInfo info = (ShortcutInfo) i;
2472 info.title = a.title.toString();
2473 updateItemInDatabase(context, info);
2474 }
2475 }
2476 }
2477
Joe Onorato36115782010-06-17 13:28:48 -04002478 mHandler.post(new Runnable() {
2479 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002480 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2481 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002482 callbacks.bindAppsUpdated(modifiedFinal);
2483 }
2484 }
2485 });
2486 }
Winson Chung83892cc2013-05-01 16:53:33 -07002487 // If a package has been removed, or an app has been removed as a result of
2488 // an update (for example), make the removed callback.
2489 if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
Winson Chung64359a52013-07-08 17:17:08 -07002490 final boolean packageRemoved = (mOp == OP_REMOVE);
Winson Chung83892cc2013-05-01 16:53:33 -07002491 final ArrayList<String> removedPackageNames =
2492 new ArrayList<String>(Arrays.asList(packages));
2493
Winson Chung64359a52013-07-08 17:17:08 -07002494 // Update the launcher db to reflect the removal of apps
2495 if (packageRemoved) {
2496 for (String pn : removedPackageNames) {
2497 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2498 for (ItemInfo i : infos) {
2499 deleteItemFromDatabase(context, i);
2500 }
2501 }
2502 } else {
2503 for (ApplicationInfo a : removedApps) {
2504 ArrayList<ItemInfo> infos =
2505 getItemInfoForComponentName(a.componentName);
2506 for (ItemInfo i : infos) {
2507 deleteItemFromDatabase(context, i);
2508 }
2509 }
2510 }
2511
Joe Onorato36115782010-06-17 13:28:48 -04002512 mHandler.post(new Runnable() {
2513 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002514 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2515 if (callbacks == cb && cb != null) {
Winson Chung83892cc2013-05-01 16:53:33 -07002516 callbacks.bindComponentsRemoved(removedPackageNames,
Winson Chung64359a52013-07-08 17:17:08 -07002517 removedApps, packageRemoved);
Joe Onorato36115782010-06-17 13:28:48 -04002518 }
2519 }
2520 });
Joe Onoratobe386092009-11-17 17:32:16 -08002521 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002522
Michael Jurkac402cd92013-05-20 15:49:32 +02002523 final ArrayList<Object> widgetsAndShortcuts =
2524 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002525 mHandler.post(new Runnable() {
2526 @Override
2527 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002528 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2529 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002530 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002531 }
2532 }
2533 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002534 }
2535 }
2536
Michael Jurkac402cd92013-05-20 15:49:32 +02002537 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2538 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2539 PackageManager packageManager = context.getPackageManager();
2540 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2541 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2542 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2543 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2544 Collections.sort(widgetsAndShortcuts,
2545 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2546 return widgetsAndShortcuts;
2547 }
2548
Winson Chung1323b482013-08-05 12:41:55 -07002549 private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) {
Winson Chungee055712013-07-30 14:46:24 -07002550 if (cn == null) {
2551 return false;
2552 }
2553
2554 try {
2555 return (pm.getActivityInfo(cn, 0) != null);
2556 } catch (NameNotFoundException e) {
2557 return false;
2558 }
2559 }
2560
Joe Onorato9c1289c2009-08-17 11:03:03 -04002561 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002562 * This is called from the code that adds shortcuts from the intent receiver. This
2563 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002564 */
Joe Onorato56d82912010-03-07 14:32:10 -05002565 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002566 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002567 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002568
Joe Onorato56d82912010-03-07 14:32:10 -05002569 /**
2570 * Make an ShortcutInfo object for a shortcut that is an application.
2571 *
2572 * If c is not null, then it will be used to fill in missing data like the title and icon.
2573 */
2574 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002575 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002576 ComponentName componentName = intent.getComponent();
Winson Chung1323b482013-08-05 12:41:55 -07002577 final ShortcutInfo info = new ShortcutInfo();
2578 if (!isValidPackageComponent(manager, componentName)) {
Winson Chungee055712013-07-30 14:46:24 -07002579 Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002580 return null;
Winson Chung1323b482013-08-05 12:41:55 -07002581 } else {
2582 try {
2583 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2584 info.initFlagsAndFirstInstallTime(pi);
2585 } catch (NameNotFoundException e) {
2586 Log.d(TAG, "getPackInfo failed for package " +
2587 componentName.getPackageName());
2588 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002589 }
2590
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002591 // TODO: See if the PackageManager knows about this case. If it doesn't
2592 // then return null & delete this.
2593
Joe Onorato56d82912010-03-07 14:32:10 -05002594 // the resource -- This may implicitly give us back the fallback icon,
2595 // but don't worry about that. All we're doing with usingFallbackIcon is
2596 // to avoid saving lots of copies of that in the database, and most apps
2597 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002598
2599 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2600 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2601 // via resolveActivity().
Winson Chungee055712013-07-30 14:46:24 -07002602 Bitmap icon = null;
Winson Chungc208ff92012-03-29 17:37:41 -07002603 ResolveInfo resolveInfo = null;
2604 ComponentName oldComponent = intent.getComponent();
2605 Intent newIntent = new Intent(intent.getAction(), null);
2606 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2607 newIntent.setPackage(oldComponent.getPackageName());
2608 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2609 for (ResolveInfo i : infos) {
2610 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2611 i.activityInfo.name);
2612 if (cn.equals(oldComponent)) {
2613 resolveInfo = i;
2614 }
2615 }
2616 if (resolveInfo == null) {
2617 resolveInfo = manager.resolveActivity(intent, 0);
2618 }
Joe Onorato56d82912010-03-07 14:32:10 -05002619 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002620 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002621 }
Joe Onorato56d82912010-03-07 14:32:10 -05002622 // the db
2623 if (icon == null) {
2624 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002625 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002626 }
2627 }
2628 // the fallback icon
2629 if (icon == null) {
2630 icon = getFallbackIcon();
2631 info.usingFallbackIcon = true;
2632 }
2633 info.setIcon(icon);
2634
2635 // from the resource
2636 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002637 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2638 if (labelCache != null && labelCache.containsKey(key)) {
2639 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002640 } else {
2641 info.title = resolveInfo.activityInfo.loadLabel(manager);
2642 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002643 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002644 }
2645 }
Joe Onorato56d82912010-03-07 14:32:10 -05002646 }
2647 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002648 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002649 if (c != null) {
2650 info.title = c.getString(titleIndex);
2651 }
2652 }
2653 // fall back to the class name of the activity
2654 if (info.title == null) {
2655 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002656 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002657 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2658 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002659 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002660
Winson Chung64359a52013-07-08 17:17:08 -07002661 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2662 ItemInfoFilter f) {
2663 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2664 for (ItemInfo i : infos) {
2665 if (i instanceof ShortcutInfo) {
2666 ShortcutInfo info = (ShortcutInfo) i;
2667 ComponentName cn = info.intent.getComponent();
2668 if (cn != null && f.filterItem(null, info, cn)) {
2669 filtered.add(info);
2670 }
2671 } else if (i instanceof FolderInfo) {
2672 FolderInfo info = (FolderInfo) i;
2673 for (ShortcutInfo s : info.contents) {
2674 ComponentName cn = s.intent.getComponent();
2675 if (cn != null && f.filterItem(info, s, cn)) {
2676 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07002677 }
2678 }
Winson Chung64359a52013-07-08 17:17:08 -07002679 } else if (i instanceof LauncherAppWidgetInfo) {
2680 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2681 ComponentName cn = info.providerName;
2682 if (cn != null && f.filterItem(null, info, cn)) {
2683 filtered.add(info);
2684 }
Winson Chung8a435102012-08-30 17:16:53 -07002685 }
2686 }
Winson Chung64359a52013-07-08 17:17:08 -07002687 return new ArrayList<ItemInfo>(filtered);
2688 }
2689
2690 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
2691 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2692 ItemInfoFilter filter = new ItemInfoFilter() {
2693 @Override
2694 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2695 return cn.getPackageName().equals(pn);
2696 }
2697 };
2698 return filterItemInfos(sBgItemsIdMap.values(), filter);
2699 }
2700
2701 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
2702 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2703 ItemInfoFilter filter = new ItemInfoFilter() {
2704 @Override
2705 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2706 return cn.equals(cname);
2707 }
2708 };
2709 return filterItemInfos(sBgItemsIdMap.values(), filter);
2710 }
2711
2712 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2713 if (i instanceof ShortcutInfo) {
2714 ShortcutInfo info = (ShortcutInfo) i;
2715 // We need to check for ACTION_MAIN otherwise getComponent() might
2716 // return null for some shortcuts (for instance, for shortcuts to
2717 // web pages.)
2718 Intent intent = info.intent;
2719 ComponentName name = intent.getComponent();
2720 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2721 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2722 return true;
2723 }
2724 }
2725 return false;
Winson Chung8a435102012-08-30 17:16:53 -07002726 }
2727
2728 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002729 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002730 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002731 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002732 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2733 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002734
Joe Onorato56d82912010-03-07 14:32:10 -05002735 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002736 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002737 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002738
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002739 // TODO: If there's an explicit component and we can't install that, delete it.
2740
Joe Onorato56d82912010-03-07 14:32:10 -05002741 info.title = c.getString(titleIndex);
2742
Joe Onorato9c1289c2009-08-17 11:03:03 -04002743 int iconType = c.getInt(iconTypeIndex);
2744 switch (iconType) {
2745 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2746 String packageName = c.getString(iconPackageIndex);
2747 String resourceName = c.getString(iconResourceIndex);
2748 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002749 info.customIcon = false;
2750 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002751 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002752 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002753 if (resources != null) {
2754 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002755 icon = Utilities.createIconBitmap(
2756 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002757 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002758 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002759 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002760 }
Joe Onorato56d82912010-03-07 14:32:10 -05002761 // the db
2762 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002763 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002764 }
2765 // the fallback icon
2766 if (icon == null) {
2767 icon = getFallbackIcon();
2768 info.usingFallbackIcon = true;
2769 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002770 break;
2771 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002772 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002773 if (icon == null) {
2774 icon = getFallbackIcon();
2775 info.customIcon = false;
2776 info.usingFallbackIcon = true;
2777 } else {
2778 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002779 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002780 break;
2781 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002782 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002783 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002784 info.customIcon = false;
2785 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002786 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002787 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002788 return info;
2789 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002790
Michael Jurka931dc972011-08-05 15:08:15 -07002791 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002792 @SuppressWarnings("all") // suppress dead code warning
2793 final boolean debug = false;
2794 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002795 Log.d(TAG, "getIconFromCursor app="
2796 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2797 }
2798 byte[] data = c.getBlob(iconIndex);
2799 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002800 return Utilities.createIconBitmap(
2801 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002802 } catch (Exception e) {
2803 return null;
2804 }
2805 }
2806
Winson Chung3d503fb2011-07-13 17:25:49 -07002807 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2808 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002809 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002810 if (info == null) {
2811 return null;
2812 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002813 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002814
2815 return info;
2816 }
2817
Winson Chunga9abd0e2010-10-27 17:18:37 -07002818 /**
Winson Chung55cef262010-10-28 14:14:18 -07002819 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2820 */
2821 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2822 ComponentName component) {
2823 List<AppWidgetProviderInfo> widgets =
2824 AppWidgetManager.getInstance(context).getInstalledProviders();
2825 for (AppWidgetProviderInfo info : widgets) {
2826 if (info.provider.equals(component)) {
2827 return info;
2828 }
2829 }
2830 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002831 }
2832
Winson Chung68846fd2010-10-29 11:00:27 -07002833 /**
2834 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2835 */
2836 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2837 final PackageManager packageManager = context.getPackageManager();
2838 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2839 new ArrayList<WidgetMimeTypeHandlerData>();
2840
2841 final Intent supportsIntent =
2842 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2843 supportsIntent.setType(mimeType);
2844
2845 // Create a set of widget configuration components that we can test against
2846 final List<AppWidgetProviderInfo> widgets =
2847 AppWidgetManager.getInstance(context).getInstalledProviders();
2848 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2849 new HashMap<ComponentName, AppWidgetProviderInfo>();
2850 for (AppWidgetProviderInfo info : widgets) {
2851 configurationComponentToWidget.put(info.configure, info);
2852 }
2853
2854 // Run through each of the intents that can handle this type of clip data, and cross
2855 // reference them with the components that are actual configuration components
2856 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2857 PackageManager.MATCH_DEFAULT_ONLY);
2858 for (ResolveInfo info : activities) {
2859 final ActivityInfo activityInfo = info.activityInfo;
2860 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2861 activityInfo.name);
2862 if (configurationComponentToWidget.containsKey(infoComponent)) {
2863 supportedConfigurationActivities.add(
2864 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2865 configurationComponentToWidget.get(infoComponent)));
2866 }
2867 }
2868 return supportedConfigurationActivities;
2869 }
2870
Winson Chunga9abd0e2010-10-27 17:18:37 -07002871 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08002872 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2873 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2874 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2875
Adam Cohend9198822011-11-22 16:42:47 -08002876 if (intent == null) {
2877 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2878 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2879 return null;
2880 }
2881
Joe Onorato0589f0f2010-02-08 13:44:00 -08002882 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08002883 boolean customIcon = false;
2884 ShortcutIconResource iconResource = null;
2885
2886 if (bitmap != null && bitmap instanceof Bitmap) {
2887 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002888 customIcon = true;
2889 } else {
2890 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2891 if (extra != null && extra instanceof ShortcutIconResource) {
2892 try {
2893 iconResource = (ShortcutIconResource) extra;
2894 final PackageManager packageManager = context.getPackageManager();
2895 Resources resources = packageManager.getResourcesForApplication(
2896 iconResource.packageName);
2897 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002898 icon = Utilities.createIconBitmap(
2899 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002900 } catch (Exception e) {
2901 Log.w(TAG, "Could not load shortcut icon: " + extra);
2902 }
2903 }
2904 }
2905
Michael Jurkac9d95c52011-08-29 14:03:34 -07002906 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002907
2908 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002909 if (fallbackIcon != null) {
2910 icon = fallbackIcon;
2911 } else {
2912 icon = getFallbackIcon();
2913 info.usingFallbackIcon = true;
2914 }
Joe Onorato56d82912010-03-07 14:32:10 -05002915 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08002916 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05002917
Joe Onorato0589f0f2010-02-08 13:44:00 -08002918 info.title = name;
2919 info.intent = intent;
2920 info.customIcon = customIcon;
2921 info.iconResource = iconResource;
2922
2923 return info;
2924 }
2925
Winson Chungaac01e12011-08-17 10:37:13 -07002926 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2927 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08002928 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07002929 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07002930 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08002931 }
Joe Onorato56d82912010-03-07 14:32:10 -05002932 // If this icon doesn't have a custom icon, check to see
2933 // what's stored in the DB, and if it doesn't match what
2934 // we're going to show, store what we are going to show back
2935 // into the DB. We do this so when we're loading, if the
2936 // package manager can't find an icon (for example because
2937 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07002938 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07002939 cache.put(info, c.getBlob(iconIndex));
2940 return true;
2941 }
2942 return false;
2943 }
2944 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2945 boolean needSave = false;
2946 try {
2947 if (data != null) {
2948 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2949 Bitmap loaded = info.getIcon(mIconCache);
2950 needSave = !saved.sameAs(loaded);
2951 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05002952 needSave = true;
2953 }
Winson Chungaac01e12011-08-17 10:37:13 -07002954 } catch (Exception e) {
2955 needSave = true;
2956 }
2957 if (needSave) {
2958 Log.d(TAG, "going to save icon bitmap for info=" + info);
2959 // This is slower than is ideal, but this only happens once
2960 // or when the app is updated with a new icon.
2961 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05002962 }
2963 }
2964
Joe Onorato9c1289c2009-08-17 11:03:03 -04002965 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07002966 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04002967 * or make a new one.
2968 */
Adam Cohendf2cc412011-04-27 16:56:57 -07002969 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002970 // See if a placeholder was created for us already
2971 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07002972 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002973 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07002974 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002975 folders.put(id, folderInfo);
2976 }
Adam Cohendf2cc412011-04-27 16:56:57 -07002977 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002978 }
2979
Winson Chung11904872012-09-17 16:58:46 -07002980 public static final Comparator<ApplicationInfo> getAppNameComparator() {
2981 final Collator collator = Collator.getInstance();
2982 return new Comparator<ApplicationInfo>() {
2983 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2984 int result = collator.compare(a.title.toString(), b.title.toString());
2985 if (result == 0) {
2986 result = a.componentName.compareTo(b.componentName);
2987 }
2988 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07002989 }
Winson Chung11904872012-09-17 16:58:46 -07002990 };
2991 }
Winson Chung78403fe2011-01-21 15:38:02 -08002992 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
2993 = new Comparator<ApplicationInfo>() {
2994 public final int compare(ApplicationInfo a, ApplicationInfo b) {
2995 if (a.firstInstallTime < b.firstInstallTime) return 1;
2996 if (a.firstInstallTime > b.firstInstallTime) return -1;
2997 return 0;
2998 }
2999 };
Winson Chung11904872012-09-17 16:58:46 -07003000 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
3001 final Collator collator = Collator.getInstance();
3002 return new Comparator<AppWidgetProviderInfo>() {
3003 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
3004 return collator.compare(a.label.toString(), b.label.toString());
3005 }
3006 };
3007 }
Winson Chung5308f242011-08-18 12:12:41 -07003008 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3009 if (info.activityInfo != null) {
3010 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3011 } else {
3012 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3013 }
3014 }
Winson Chung785d2eb2011-04-14 16:08:02 -07003015 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07003016 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07003017 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07003018 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003019 ShortcutNameComparator(PackageManager pm) {
3020 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07003021 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003022 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003023 }
3024 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
3025 mPackageManager = pm;
3026 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003027 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003028 }
3029 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003030 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07003031 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
3032 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
3033 if (mLabelCache.containsKey(keyA)) {
3034 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003035 } else {
3036 labelA = a.loadLabel(mPackageManager).toString();
3037
Winson Chung5308f242011-08-18 12:12:41 -07003038 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003039 }
Winson Chung5308f242011-08-18 12:12:41 -07003040 if (mLabelCache.containsKey(keyB)) {
3041 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003042 } else {
3043 labelB = b.loadLabel(mPackageManager).toString();
3044
Winson Chung5308f242011-08-18 12:12:41 -07003045 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003046 }
Winson Chung11904872012-09-17 16:58:46 -07003047 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003048 }
3049 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003050 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003051 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003052 private PackageManager mPackageManager;
3053 private HashMap<Object, String> mLabelCache;
3054 WidgetAndShortcutNameComparator(PackageManager pm) {
3055 mPackageManager = pm;
3056 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003057 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003058 }
3059 public final int compare(Object a, Object b) {
3060 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003061 if (mLabelCache.containsKey(a)) {
3062 labelA = mLabelCache.get(a);
3063 } else {
3064 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003065 ((AppWidgetProviderInfo) a).label :
3066 ((ResolveInfo) a).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003067 mLabelCache.put(a, labelA);
3068 }
3069 if (mLabelCache.containsKey(b)) {
3070 labelB = mLabelCache.get(b);
3071 } else {
3072 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003073 ((AppWidgetProviderInfo) b).label :
3074 ((ResolveInfo) b).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003075 mLabelCache.put(b, labelB);
3076 }
Winson Chung11904872012-09-17 16:58:46 -07003077 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003078 }
3079 };
Joe Onoratobe386092009-11-17 17:32:16 -08003080
3081 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003082 Log.d(TAG, "mCallbacks=" + mCallbacks);
Adam Cohen487f7dd2012-06-28 18:12:10 -07003083 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3084 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3085 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3086 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003087 if (mLoaderTask != null) {
3088 mLoaderTask.dumpState();
3089 } else {
3090 Log.d(TAG, "mLoaderTask=null");
3091 }
Joe Onoratobe386092009-11-17 17:32:16 -08003092 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003093}