blob: 2ac9b1b6ce0341070181a1f1848e2f89b3d28da4 [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,
Winson Chung76828c82013-08-19 15:43:29 -0700241 int firstScreenIndex,
242 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700243 // Lock on the app so that we don't try and get the items while apps are being added
244 LauncherAppState app = LauncherAppState.getInstance();
245 LauncherModel model = app.getModel();
246 boolean found = false;
247 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700248 if (sWorkerThread.getThreadId() != Process.myTid()) {
249 // Flush the LauncherModel worker thread, so that if we just did another
250 // processInstallShortcut, we give it time for its shortcut to get added to the
251 // database (getItemsInLocalCoordinates reads the database)
252 model.flushWorkerThread();
253 }
Winson Chungc9168342013-06-26 14:54:55 -0700254 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700255
256 // Try adding to the workspace screens incrementally, starting at the default or center
257 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700258 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
259 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700260 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700261 int[] tmpCoordinates = new int[2];
262 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700263 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700264 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700265 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700266 }
267 }
268 }
Winson Chungc9168342013-06-26 14:54:55 -0700269 return null;
270 }
271
Winson Chung997a9232013-07-24 15:33:46 -0700272 public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added) {
273 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
274 addAndBindAddedApps(context, added, cb);
275 }
276 public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added,
Winson Chung64359a52013-07-08 17:17:08 -0700277 final Callbacks callbacks) {
Winson Chung997a9232013-07-24 15:33:46 -0700278 if (added.isEmpty()) {
279 throw new RuntimeException("EMPTY ADDED ARRAY?");
280 }
Winson Chung64359a52013-07-08 17:17:08 -0700281 // Process the newly added applications and add them to the database first
282 Runnable r = new Runnable() {
283 public void run() {
284 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
285 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
286
Winson Chung76828c82013-08-19 15:43:29 -0700287 // Get the list of workspace screens. We need to append to this list and
288 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
289 // called.
290 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
291 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
292 for (Integer i : orderedScreens.keySet()) {
293 long screenId = orderedScreens.get(i);
294 workspaceScreens.add(screenId);
295 }
296
Winson Chung64359a52013-07-08 17:17:08 -0700297 synchronized(sBgLock) {
Winson Chung997a9232013-07-24 15:33:46 -0700298 Iterator<ItemInfo> iter = added.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700299 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700300 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700301 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700302 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700303
304 // Short-circuit this logic if the icon exists somewhere on the workspace
305 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
306 continue;
307 }
308
309 // Add this icon to the db, creating a new page if necessary
Winson Chung156ab5b2013-07-12 14:14:16 -0700310 int startSearchPageIndex = 1;
Winson Chung64359a52013-07-08 17:17:08 -0700311 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700312 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700313 if (coords == null) {
Winson Chung64359a52013-07-08 17:17:08 -0700314 LauncherAppState appState = LauncherAppState.getInstance();
315 LauncherProvider lp = appState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700316
317 // If we can't find a valid position, then just add a new screen.
318 // This takes time so we need to re-queue the add until the new
319 // page is added. Create as many screens as necessary to satisfy
320 // the startSearchPageIndex.
321 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700322 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700323 while (numPagesToAdd > 0) {
324 long screenId = lp.generateNewScreenId();
Winson Chung76828c82013-08-19 15:43:29 -0700325 Log.w(TAG, "10249126 - addAndBindAddedApps(" + screenId + ")");
Winson Chungc763c4e2013-07-19 13:49:06 -0700326 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700327 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700328 addedWorkspaceScreensFinal.add(screenId);
329 numPagesToAdd--;
330 }
Winson Chung76828c82013-08-19 15:43:29 -0700331
Winson Chung64359a52013-07-08 17:17:08 -0700332 // Find the coordinate again
333 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700334 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700335 }
336 if (coords == null) {
337 throw new RuntimeException("Coordinates should not be null");
338 }
339
Winson Chung997a9232013-07-24 15:33:46 -0700340 ShortcutInfo shortcutInfo;
341 if (a instanceof ShortcutInfo) {
342 shortcutInfo = (ShortcutInfo) a;
343 } else if (a instanceof ApplicationInfo) {
344 shortcutInfo = ((ApplicationInfo) a).makeShortcut();
345 } else {
346 throw new RuntimeException("Unexpected info type");
347 }
Winson Chung64359a52013-07-08 17:17:08 -0700348 // Add the shortcut to the db
349 addItemToDatabase(context, shortcutInfo,
350 LauncherSettings.Favorites.CONTAINER_DESKTOP,
351 coords.first, coords.second[0], coords.second[1], false);
352 // Save the ShortcutInfo for binding in the workspace
353 addedShortcutsFinal.add(shortcutInfo);
354 }
355 }
356
Winson Chung76828c82013-08-19 15:43:29 -0700357 // Update the workspace screens
358 updateWorkspaceScreenOrder(context, workspaceScreens);
359
Winson Chung997a9232013-07-24 15:33:46 -0700360 if (!addedShortcutsFinal.isEmpty()) {
361 runOnMainThread(new Runnable() {
362 public void run() {
363 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
364 if (callbacks == cb && cb != null) {
365 callbacks.bindAddScreens(addedWorkspaceScreensFinal);
366
367 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
368 long lastScreenId = info.screenId;
369 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
370 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
371 for (ItemInfo i : addedShortcutsFinal) {
372 if (i.screenId == lastScreenId) {
373 addAnimated.add(i);
374 } else {
375 addNotAnimated.add(i);
376 }
377 }
378 // We add the items without animation on non-visible pages, and with
379 // animations on the new page (which we will try and snap to).
380 if (!addNotAnimated.isEmpty()) {
381 callbacks.bindItems(addNotAnimated, 0,
382 addNotAnimated.size(), false);
383 }
384 if (!addAnimated.isEmpty()) {
385 callbacks.bindItems(addAnimated, 0,
386 addAnimated.size(), true);
387 }
388 }
Winson Chung64359a52013-07-08 17:17:08 -0700389 }
Winson Chung997a9232013-07-24 15:33:46 -0700390 });
391 }
Winson Chung64359a52013-07-08 17:17:08 -0700392 }
393 };
394 runOnWorkerThread(r);
395 }
396
Joe Onorato56d82912010-03-07 14:32:10 -0500397 public Bitmap getFallbackIcon() {
Joe Onorato0589f0f2010-02-08 13:44:00 -0800398 return Bitmap.createBitmap(mDefaultIcon);
Joe Onoratof99f8c12009-10-31 17:27:36 -0400399 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800400
Winson Chung81b52252012-08-27 15:34:29 -0700401 public void unbindItemInfosAndClearQueuedBindRunnables() {
402 if (sWorkerThread.getThreadId() == Process.myTid()) {
403 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
404 "main thread");
405 }
406
407 // Clear any deferred bind runnables
408 mDeferredBindRunnables.clear();
409 // Remove any queued bind runnables
410 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
411 // Unbind all the workspace items
412 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700413 }
414
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700415 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700416 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700417 // Ensure that we don't use the same workspace items data structure on the main thread
418 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700419 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
420 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700421 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700422 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
423 tmpAppWidgets.addAll(sBgAppWidgets);
424 }
425 Runnable r = new Runnable() {
426 @Override
427 public void run() {
428 for (ItemInfo item : tmpWorkspaceItems) {
429 item.unbind();
430 }
431 for (ItemInfo item : tmpAppWidgets) {
432 item.unbind();
433 }
434 }
435 };
436 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700437 }
438
Joe Onorato9c1289c2009-08-17 11:03:03 -0400439 /**
440 * Adds an item to the DB if it was not created previously, or move it to a new
441 * <container, screen, cellX, cellY>
442 */
443 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700444 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400445 if (item.container == ItemInfo.NO_ID) {
446 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700447 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400448 } else {
449 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700450 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800451 }
452 }
453
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700454 static void checkItemInfoLocked(
455 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
456 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
457 if (modelItem != null && item != modelItem) {
458 // check all the data is consistent
459 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
460 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
461 ShortcutInfo shortcut = (ShortcutInfo) item;
462 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
463 modelShortcut.intent.filterEquals(shortcut.intent) &&
464 modelShortcut.id == shortcut.id &&
465 modelShortcut.itemType == shortcut.itemType &&
466 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700467 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700468 modelShortcut.cellX == shortcut.cellX &&
469 modelShortcut.cellY == shortcut.cellY &&
470 modelShortcut.spanX == shortcut.spanX &&
471 modelShortcut.spanY == shortcut.spanY &&
472 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
473 (modelShortcut.dropPos != null &&
474 shortcut.dropPos != null &&
475 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
476 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
477 // For all intents and purposes, this is the same object
478 return;
479 }
480 }
481
482 // the modelItem needs to match up perfectly with item if our model is
483 // to be consistent with the database-- for now, just require
484 // modelItem == item or the equality check above
485 String msg = "item: " + ((item != null) ? item.toString() : "null") +
486 "modelItem: " +
487 ((modelItem != null) ? modelItem.toString() : "null") +
488 "Error: ItemInfo passed to checkItemInfo doesn't match original";
489 RuntimeException e = new RuntimeException(msg);
490 if (stackTrace != null) {
491 e.setStackTrace(stackTrace);
492 }
Adam Cohene25af792013-06-06 23:08:25 -0700493 // TODO: something breaks this in the upgrade path
494 //throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700495 }
496 }
497
Michael Jurka816474f2012-06-25 14:49:02 -0700498 static void checkItemInfo(final ItemInfo item) {
499 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
500 final long itemId = item.id;
501 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700502 public void run() {
503 synchronized (sBgLock) {
504 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700505 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700506 }
507 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700508 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700509 }
510
Michael Jurkac9d95c52011-08-29 14:03:34 -0700511 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
512 final ItemInfo item, final String callingFunction) {
513 final long itemId = item.id;
514 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
515 final ContentResolver cr = context.getContentResolver();
516
Adam Cohen487f7dd2012-06-28 18:12:10 -0700517 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700518 Runnable r = new Runnable() {
519 public void run() {
520 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700521 updateItemArrays(item, itemId, stackTrace);
522 }
523 };
524 runOnWorkerThread(r);
525 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700526
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700527 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
528 final ArrayList<ItemInfo> items, final String callingFunction) {
529 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700530
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700531 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
532 Runnable r = new Runnable() {
533 public void run() {
534 ArrayList<ContentProviderOperation> ops =
535 new ArrayList<ContentProviderOperation>();
536 int count = items.size();
537 for (int i = 0; i < count; i++) {
538 ItemInfo item = items.get(i);
539 final long itemId = item.id;
540 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
541 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700542
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700543 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
544 updateItemArrays(item, itemId, stackTrace);
545
546 }
547 try {
548 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
549 } catch (Exception e) {
550 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700551 }
552 }
553 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700554 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700555 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700556
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700557 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
558 // Lock on mBgLock *after* the db operation
559 synchronized (sBgLock) {
560 checkItemInfoLocked(itemId, item, stackTrace);
561
562 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
563 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
564 // Item is in a folder, make sure this folder exists
565 if (!sBgFolders.containsKey(item.container)) {
566 // An items container is being set to a that of an item which is not in
567 // the list of Folders.
568 String msg = "item: " + item + " container being set to: " +
569 item.container + ", not in the list of folders";
570 Log.e(TAG, msg);
571 Launcher.dumpDebugLogsToConsole();
572 }
573 }
574
575 // Items are added/removed from the corresponding FolderInfo elsewhere, such
576 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
577 // that are on the desktop, as appropriate
578 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
579 if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
580 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
581 switch (modelItem.itemType) {
582 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
583 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
584 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
585 if (!sBgWorkspaceItems.contains(modelItem)) {
586 sBgWorkspaceItems.add(modelItem);
587 }
588 break;
589 default:
590 break;
591 }
592 } else {
593 sBgWorkspaceItems.remove(modelItem);
594 }
595 }
596 }
597
Michael Jurkac7700af2013-05-14 20:17:58 +0200598 public void flushWorkerThread() {
599 mFlushingWorkerThread = true;
600 Runnable waiter = new Runnable() {
601 public void run() {
602 synchronized (this) {
603 notifyAll();
604 mFlushingWorkerThread = false;
605 }
606 }
607 };
608
609 synchronized(waiter) {
610 runOnWorkerThread(waiter);
611 if (mLoaderTask != null) {
612 synchronized(mLoaderTask) {
613 mLoaderTask.notify();
614 }
615 }
616 boolean success = false;
617 while (!success) {
618 try {
619 waiter.wait();
620 success = true;
621 } catch (InterruptedException e) {
622 }
623 }
624 }
625 }
626
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800627 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400628 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700629 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700630 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700631 final long screenId, final int cellX, final int cellY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700632 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
Adam Cohendcd297f2013-06-18 13:13:40 -0700633 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
634 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Adam Cohen487f7dd2012-06-28 18:12:10 -0700635 Launcher.sDumpLogs.add(transaction);
636 Log.d(TAG, transaction);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400637 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400638 item.cellX = cellX;
639 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700640
Winson Chung3d503fb2011-07-13 17:25:49 -0700641 // We store hotseat items in canonical form which is this orientation invariant position
642 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700643 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700644 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700645 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700646 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700647 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700648 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400649
650 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400651 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700652 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
653 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700654 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400655
Michael Jurkac9d95c52011-08-29 14:03:34 -0700656 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700657 }
658
659 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700660 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
661 * cellX, cellY have already been updated on the ItemInfos.
662 */
663 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
664 final long container, final int screen) {
665
666 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
667 int count = items.size();
668
669 for (int i = 0; i < count; i++) {
670 ItemInfo item = items.get(i);
671 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700672 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700673 + ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", "
674 + item.cellX + ", " + item.cellY + ")";
675 Launcher.sDumpLogs.add(transaction);
676 item.container = container;
677
678 // We store hotseat items in canonical form which is this orientation invariant position
679 // in the hotseat
680 if (context instanceof Launcher && screen < 0 &&
681 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700682 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700683 item.cellY);
684 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700685 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700686 }
687
688 final ContentValues values = new ContentValues();
689 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
690 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
691 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700692 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700693
694 contentValues.add(values);
695 }
696 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
697 }
698
699 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700700 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800701 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700702 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700703 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Brian Muramatsu5524b492012-10-02 16:55:54 -0700704 String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
Adam Cohendcd297f2013-06-18 13:13:40 -0700705 " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
706 ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Adam Cohen487f7dd2012-06-28 18:12:10 -0700707 Launcher.sDumpLogs.add(transaction);
708 Log.d(TAG, transaction);
Adam Cohend4844c32011-02-18 19:25:06 -0800709 item.cellX = cellX;
710 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700711 item.spanX = spanX;
712 item.spanY = spanY;
713
714 // We store hotseat items in canonical form which is this orientation invariant position
715 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700716 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700717 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700718 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700719 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700720 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700721 }
Adam Cohend4844c32011-02-18 19:25:06 -0800722
Adam Cohend4844c32011-02-18 19:25:06 -0800723 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800724 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700725 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
726 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
727 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
728 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700729 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800730
Michael Jurka816474f2012-06-25 14:49:02 -0700731 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700732 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700733
734 /**
735 * Update an item to the database in a specified container.
736 */
737 static void updateItemInDatabase(Context context, final ItemInfo item) {
738 final ContentValues values = new ContentValues();
739 item.onAddToDatabase(values);
740 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
741 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800742 }
743
744 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400745 * Returns true if the shortcuts already exists in the database.
746 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800747 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400748 static boolean shortcutExists(Context context, String title, Intent intent) {
749 final ContentResolver cr = context.getContentResolver();
750 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
751 new String[] { "title", "intent" }, "title=? and intent=?",
752 new String[] { title, intent.toUri(0) }, null);
753 boolean result = false;
754 try {
755 result = c.moveToFirst();
756 } finally {
757 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800758 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400759 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700760 }
761
Joe Onorato9c1289c2009-08-17 11:03:03 -0400762 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700763 * Returns an ItemInfo array containing all the items in the LauncherModel.
764 * The ItemInfo.id is not set through this function.
765 */
766 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
767 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
768 final ContentResolver cr = context.getContentResolver();
769 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
770 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
771 LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
772 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
773
774 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
775 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
776 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
777 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
778 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
779 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
780 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
781
782 try {
783 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700784 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700785 item.cellX = c.getInt(cellXIndex);
786 item.cellY = c.getInt(cellYIndex);
787 item.spanX = c.getInt(spanXIndex);
788 item.spanY = c.getInt(spanYIndex);
789 item.container = c.getInt(containerIndex);
790 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700791 item.screenId = c.getInt(screenIndex);
Winson Chungaafa03c2010-06-11 17:34:16 -0700792
793 items.add(item);
794 }
795 } catch (Exception e) {
796 items.clear();
797 } finally {
798 c.close();
799 }
800
801 return items;
802 }
803
804 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400805 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
806 */
807 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
808 final ContentResolver cr = context.getContentResolver();
809 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
810 "_id=? and (itemType=? or itemType=?)",
811 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700812 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700813
Joe Onorato9c1289c2009-08-17 11:03:03 -0400814 try {
815 if (c.moveToFirst()) {
816 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
817 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
818 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
819 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
820 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
821 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800822
Joe Onorato9c1289c2009-08-17 11:03:03 -0400823 FolderInfo folderInfo = null;
824 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700825 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
826 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400827 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700828 }
829
Joe Onorato9c1289c2009-08-17 11:03:03 -0400830 folderInfo.title = c.getString(titleIndex);
831 folderInfo.id = id;
832 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700833 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700834 folderInfo.cellX = c.getInt(cellXIndex);
835 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400836
837 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700838 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400839 } finally {
840 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700841 }
842
843 return null;
844 }
845
Joe Onorato9c1289c2009-08-17 11:03:03 -0400846 /**
847 * Add an item to the database in a specified container. Sets the container, screen, cellX and
848 * cellY fields of the item. Also assigns an ID to the item.
849 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700850 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700851 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400852 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400853 item.cellX = cellX;
854 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700855 // We store hotseat items in canonical form which is this orientation invariant position
856 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700857 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700858 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700859 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700860 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700861 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700862 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400863
864 final ContentValues values = new ContentValues();
865 final ContentResolver cr = context.getContentResolver();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400866 item.onAddToDatabase(values);
867
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400868 LauncherAppState app = LauncherAppState.getInstance();
Adam Cohendcd297f2013-06-18 13:13:40 -0700869 item.id = app.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700870 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -0700871 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -0700872
Michael Jurkac9d95c52011-08-29 14:03:34 -0700873 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700874 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700875 String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700876 + item.id + " (" + container + ", " + screenId + ", " + cellX + ", "
Adam Cohen487f7dd2012-06-28 18:12:10 -0700877 + cellY + ")";
878 Launcher.sDumpLogs.add(transaction);
879 Log.d(TAG, transaction);
880
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700881 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
882 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400883
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700884 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700885 synchronized (sBgLock) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700886 checkItemInfoLocked(item.id, item, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700887 sBgItemsIdMap.put(item.id, item);
888 switch (item.itemType) {
889 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
890 sBgFolders.put(item.id, (FolderInfo) item);
891 // Fall through
892 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
893 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
894 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
895 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
896 sBgWorkspaceItems.add(item);
897 } else {
898 if (!sBgFolders.containsKey(item.container)) {
899 // Adding an item to a folder that doesn't exist.
900 String msg = "adding item: " + item + " to a folder that " +
901 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -0700902 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700903 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700904 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700905 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700906 break;
907 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
908 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
909 break;
910 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700911 }
912 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700913 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700914 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700915 }
916
Joe Onorato9c1289c2009-08-17 11:03:03 -0400917 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700918 * Creates a new unique child id, for a given cell span across all layouts.
919 */
Michael Jurka845ba3b2010-09-28 17:09:46 -0700920 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -0700921 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -0700922 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -0700923 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -0700924 }
925
Adam Cohend22015c2010-07-26 22:02:18 -0700926 static int getCellCountX() {
927 return mCellCountX;
Winson Chungaafa03c2010-06-11 17:34:16 -0700928 }
929
Adam Cohend22015c2010-07-26 22:02:18 -0700930 static int getCellCountY() {
931 return mCellCountY;
Winson Chungaafa03c2010-06-11 17:34:16 -0700932 }
933
934 /**
935 * Updates the model orientation helper to take into account the current layout dimensions
936 * when performing local/canonical coordinate transformations.
937 */
938 static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
Adam Cohend22015c2010-07-26 22:02:18 -0700939 mCellCountX = shortAxisCellCount;
940 mCellCountY = longAxisCellCount;
Winson Chungaafa03c2010-06-11 17:34:16 -0700941 }
942
943 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -0700944 * Removes the specified item from the database
945 * @param context
946 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -0400947 */
Michael Jurkac9d95c52011-08-29 14:03:34 -0700948 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400949 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700950 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -0700951
Michael Jurka83df1882011-08-31 20:59:26 -0700952 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700953 public void run() {
Adam Cohen487f7dd2012-06-28 18:12:10 -0700954 String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
Adam Cohendcd297f2013-06-18 13:13:40 -0700955 + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX +
Adam Cohen487f7dd2012-06-28 18:12:10 -0700956 ", " + item.cellY + ")";
957 Launcher.sDumpLogs.add(transaction);
958 Log.d(TAG, transaction);
959
Michael Jurkac9d95c52011-08-29 14:03:34 -0700960 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700961
962 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700963 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700964 switch (item.itemType) {
965 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
966 sBgFolders.remove(item.id);
967 for (ItemInfo info: sBgItemsIdMap.values()) {
968 if (info.container == item.id) {
969 // We are deleting a folder which still contains items that
970 // think they are contained by that folder.
971 String msg = "deleting a folder (" + item + ") which still " +
972 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -0700973 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700974 Launcher.dumpDebugLogsToConsole();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700975 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700976 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700977 sBgWorkspaceItems.remove(item);
978 break;
979 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
980 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
981 sBgWorkspaceItems.remove(item);
982 break;
983 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
984 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
985 break;
986 }
987 sBgItemsIdMap.remove(item.id);
988 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700989 }
990 }
Michael Jurka83df1882011-08-31 20:59:26 -0700991 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700992 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400993 }
994
995 /**
Adam Cohendcd297f2013-06-18 13:13:40 -0700996 * Update the order of the workspace screens in the database. The array list contains
997 * a list of screen ids in the order that they should appear.
998 */
Winson Chungc9168342013-06-26 14:54:55 -0700999 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chung64359a52013-07-08 17:17:08 -07001000 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001001 final ContentResolver cr = context.getContentResolver();
1002 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1003
1004 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001005 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001006 while (iter.hasNext()) {
1007 long id = iter.next();
1008 if (id < 0) {
1009 iter.remove();
1010 }
1011 }
1012
1013 Runnable r = new Runnable() {
1014 @Override
1015 public void run() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001016 // Clear the table
1017 cr.delete(uri, null, null);
Winson Chung76828c82013-08-19 15:43:29 -07001018 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001019 ContentValues[] values = new ContentValues[count];
1020 for (int i = 0; i < count; i++) {
1021 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001022 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001023 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1024 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Winson Chung76828c82013-08-19 15:43:29 -07001025 Log.w(TAG, "10249126 - updateWorkspaceScreenOrder(" + screenId + ", " + i + ")");
Adam Cohendcd297f2013-06-18 13:13:40 -07001026 values[i] = v;
1027 }
1028 cr.bulkInsert(uri, values);
1029 sBgWorkspaceScreens.clear();
1030 sBgWorkspaceScreens.addAll(screensCopy);
1031 }
1032 };
1033 runOnWorkerThread(r);
1034 }
1035
1036 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001037 * Remove the contents of the specified folder from the database
1038 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001039 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001040 final ContentResolver cr = context.getContentResolver();
1041
Michael Jurkac9d95c52011-08-29 14:03:34 -07001042 Runnable r = new Runnable() {
1043 public void run() {
1044 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001045 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001046 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001047 sBgItemsIdMap.remove(info.id);
1048 sBgFolders.remove(info.id);
1049 sBgDbIconCache.remove(info);
1050 sBgWorkspaceItems.remove(info);
1051 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001052
Michael Jurkac9d95c52011-08-29 14:03:34 -07001053 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1054 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001055 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001056 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001057 for (ItemInfo childInfo : info.contents) {
1058 sBgItemsIdMap.remove(childInfo.id);
1059 sBgDbIconCache.remove(childInfo);
1060 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001061 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001062 }
1063 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001064 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001065 }
1066
1067 /**
1068 * Set this as the current Launcher activity object for the loader.
1069 */
1070 public void initialize(Callbacks callbacks) {
1071 synchronized (mLock) {
1072 mCallbacks = new WeakReference<Callbacks>(callbacks);
1073 }
1074 }
1075
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001076 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001077 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1078 * ACTION_PACKAGE_CHANGED.
1079 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001080 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001081 public void onReceive(Context context, Intent intent) {
Joe Onorato36115782010-06-17 13:28:48 -04001082 if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001083
Joe Onorato36115782010-06-17 13:28:48 -04001084 final String action = intent.getAction();
Joe Onoratof99f8c12009-10-31 17:27:36 -04001085
Joe Onorato36115782010-06-17 13:28:48 -04001086 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
1087 || Intent.ACTION_PACKAGE_REMOVED.equals(action)
1088 || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1089 final String packageName = intent.getData().getSchemeSpecificPart();
1090 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001091
Joe Onorato36115782010-06-17 13:28:48 -04001092 int op = PackageUpdatedTask.OP_NONE;
1093
1094 if (packageName == null || packageName.length() == 0) {
1095 // they sent us a bad intent
1096 return;
1097 }
1098
1099 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1100 op = PackageUpdatedTask.OP_UPDATE;
1101 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1102 if (!replacing) {
1103 op = PackageUpdatedTask.OP_REMOVE;
1104 }
1105 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1106 // later, we will update the package at this time
1107 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1108 if (!replacing) {
1109 op = PackageUpdatedTask.OP_ADD;
1110 } else {
1111 op = PackageUpdatedTask.OP_UPDATE;
1112 }
1113 }
1114
1115 if (op != PackageUpdatedTask.OP_NONE) {
1116 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
1117 }
1118
1119 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Joe Onoratocec58332010-10-07 14:37:40 -04001120 // First, schedule to add these apps back in.
1121 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1122 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
1123 // Then, rebind everything.
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001124 startLoaderFromBackground();
Joe Onorato36115782010-06-17 13:28:48 -04001125 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1126 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1127 enqueuePackageUpdated(new PackageUpdatedTask(
1128 PackageUpdatedTask.OP_UNAVAILABLE, packages));
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001129 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001130 // If we have changed locale we need to clear out the labels in all apps/workspace.
1131 forceReload();
1132 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1133 // Check if configuration change was an mcc/mnc change which would affect app resources
1134 // and we would need to clear out the labels in all apps/workspace. Same handling as
1135 // above for ACTION_LOCALE_CHANGED
1136 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001137 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001138 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001139 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001140 forceReload();
1141 }
1142 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001143 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001144 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1145 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001146 if (mCallbacks != null) {
1147 Callbacks callbacks = mCallbacks.get();
1148 if (callbacks != null) {
1149 callbacks.bindSearchablesChanged();
1150 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001151 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001152 }
1153 }
1154
Reena Lee93f824a2011-09-23 17:20:28 -07001155 private void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001156 resetLoadedState(true, true);
1157
Reena Lee93f824a2011-09-23 17:20:28 -07001158 // Do this here because if the launcher activity is running it will be restarted.
1159 // If it's not running startLoaderFromBackground will merely tell it that it needs
1160 // to reload.
1161 startLoaderFromBackground();
1162 }
1163
Winson Chungf0c6ae02012-03-21 16:10:31 -07001164 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1165 synchronized (mLock) {
1166 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1167 // mWorkspaceLoaded to true later
1168 stopLoaderLocked();
1169 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1170 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1171 }
1172 }
1173
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001174 /**
1175 * When the launcher is in the background, it's possible for it to miss paired
1176 * configuration changes. So whenever we trigger the loader from the background
1177 * tell the launcher that it needs to re-run the loader when it comes back instead
1178 * of doing it now.
1179 */
1180 public void startLoaderFromBackground() {
1181 boolean runLoader = false;
1182 if (mCallbacks != null) {
1183 Callbacks callbacks = mCallbacks.get();
1184 if (callbacks != null) {
1185 // Only actually run the loader if they're not paused.
1186 if (!callbacks.setLoadOnResume()) {
1187 runLoader = true;
1188 }
1189 }
1190 }
1191 if (runLoader) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001192 startLoader(false, -1);
Joe Onorato790c2d92010-06-11 00:14:11 -07001193 }
Joe Onorato36115782010-06-17 13:28:48 -04001194 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001195
Reena Lee93f824a2011-09-23 17:20:28 -07001196 // If there is already a loader task running, tell it to stop.
1197 // returns true if isLaunching() was true on the old task
1198 private boolean stopLoaderLocked() {
1199 boolean isLaunching = false;
1200 LoaderTask oldTask = mLoaderTask;
1201 if (oldTask != null) {
1202 if (oldTask.isLaunching()) {
1203 isLaunching = true;
1204 }
1205 oldTask.stopLocked();
1206 }
1207 return isLaunching;
1208 }
1209
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001210 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Joe Onorato36115782010-06-17 13:28:48 -04001211 synchronized (mLock) {
1212 if (DEBUG_LOADERS) {
1213 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1214 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001215
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001216 // Clear any deferred bind-runnables from the synchronized load process
1217 // We must do this before any loading/binding is scheduled below.
1218 mDeferredBindRunnables.clear();
1219
Joe Onorato36115782010-06-17 13:28:48 -04001220 // Don't bother to start the thread if we know it's not going to do anything
1221 if (mCallbacks != null && mCallbacks.get() != null) {
1222 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001223 // also, don't downgrade isLaunching if we're already running
1224 isLaunching = isLaunching || stopLoaderLocked();
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001225 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001226 if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
1227 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1228 } else {
1229 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1230 sWorker.post(mLoaderTask);
1231 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001232 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001233 }
1234 }
1235
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001236 void bindRemainingSynchronousPages() {
1237 // Post the remaining side pages to be loaded
1238 if (!mDeferredBindRunnables.isEmpty()) {
1239 for (final Runnable r : mDeferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001240 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001241 }
1242 mDeferredBindRunnables.clear();
1243 }
1244 }
1245
Joe Onorato36115782010-06-17 13:28:48 -04001246 public void stopLoader() {
1247 synchronized (mLock) {
1248 if (mLoaderTask != null) {
1249 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001250 }
1251 }
Joe Onorato36115782010-06-17 13:28:48 -04001252 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001253
Winson Chung76828c82013-08-19 15:43:29 -07001254 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1255 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1256 final ContentResolver contentResolver = context.getContentResolver();
1257 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1258 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1259 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1260
1261 try {
1262 final int idIndex = sc.getColumnIndexOrThrow(
1263 LauncherSettings.WorkspaceScreens._ID);
1264 final int rankIndex = sc.getColumnIndexOrThrow(
1265 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1266 while (sc.moveToNext()) {
1267 try {
1268 long screenId = sc.getLong(idIndex);
1269 int rank = sc.getInt(rankIndex);
1270
1271 Log.w(TAG, "10249126 - loadWorkspaceScreensDb(" + screenId + ", " + rank + ")");
1272
1273 orderedScreens.put(rank, screenId);
1274 } catch (Exception e) {
1275 Log.w(TAG, "Desktop items loading interrupted - invalid screens: ", e);
1276 }
1277 }
1278 } finally {
1279 sc.close();
1280 }
1281 return orderedScreens;
1282 }
1283
Michael Jurkac57b7a82011-08-09 22:02:20 -07001284 public boolean isAllAppsLoaded() {
1285 return mAllAppsLoaded;
1286 }
1287
Winson Chung36a62fe2012-05-06 18:04:42 -07001288 boolean isLoadingWorkspace() {
1289 synchronized (mLock) {
1290 if (mLoaderTask != null) {
1291 return mLoaderTask.isLoadingWorkspace();
1292 }
1293 }
1294 return false;
1295 }
1296
Joe Onorato36115782010-06-17 13:28:48 -04001297 /**
1298 * Runnable for the thread that loads the contents of the launcher:
1299 * - workspace icons
1300 * - widgets
1301 * - all apps icons
1302 */
1303 private class LoaderTask implements Runnable {
1304 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001305 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001306 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001307 private boolean mStopped;
1308 private boolean mLoadAndBindStepFinished;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001309
Winson Chungc3eecff2011-07-11 17:44:15 -07001310 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001311
1312 LoaderTask(Context context, boolean isLaunching) {
1313 mContext = context;
1314 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001315 mLabelCache = new HashMap<Object, CharSequence>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001316 }
1317
Joe Onorato36115782010-06-17 13:28:48 -04001318 boolean isLaunching() {
1319 return mIsLaunching;
1320 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001321
Winson Chung36a62fe2012-05-06 18:04:42 -07001322 boolean isLoadingWorkspace() {
1323 return mIsLoadingAndBindingWorkspace;
1324 }
1325
Winson Chungc763c4e2013-07-19 13:49:06 -07001326 /** Returns whether this is an upgrade path */
1327 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001328 mIsLoadingAndBindingWorkspace = true;
1329
Joe Onorato36115782010-06-17 13:28:48 -04001330 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001331 if (DEBUG_LOADERS) {
1332 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001333 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001334
Winson Chungc763c4e2013-07-19 13:49:06 -07001335 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001336 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001337 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001338 synchronized (LoaderTask.this) {
1339 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001340 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001341 }
1342 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001343 }
1344 }
1345
Joe Onorato36115782010-06-17 13:28:48 -04001346 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001347 bindWorkspace(-1, isUpgradePath);
1348 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001349 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001350
Joe Onorato36115782010-06-17 13:28:48 -04001351 private void waitForIdle() {
1352 // Wait until the either we're stopped or the other threads are done.
1353 // This way we don't start loading all apps until the workspace has settled
1354 // down.
1355 synchronized (LoaderTask.this) {
1356 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001357
Joe Onorato36115782010-06-17 13:28:48 -04001358 mHandler.postIdle(new Runnable() {
1359 public void run() {
1360 synchronized (LoaderTask.this) {
1361 mLoadAndBindStepFinished = true;
1362 if (DEBUG_LOADERS) {
1363 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001364 }
Joe Onorato36115782010-06-17 13:28:48 -04001365 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001366 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001367 }
Joe Onorato36115782010-06-17 13:28:48 -04001368 });
1369
Michael Jurkac7700af2013-05-14 20:17:58 +02001370 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001371 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001372 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1373 // wait no longer than 1sec at a time
1374 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001375 } catch (InterruptedException ex) {
1376 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001377 }
1378 }
Joe Onorato36115782010-06-17 13:28:48 -04001379 if (DEBUG_LOADERS) {
1380 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001381 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001382 + "ms for previous step to finish binding");
1383 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001384 }
Joe Onorato36115782010-06-17 13:28:48 -04001385 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001386
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001387 void runBindSynchronousPage(int synchronousBindPage) {
1388 if (synchronousBindPage < 0) {
1389 // Ensure that we have a valid page index to load synchronously
1390 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1391 "valid page index");
1392 }
1393 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1394 // Ensure that we don't try and bind a specified page when the pages have not been
1395 // loaded already (we should load everything asynchronously in that case)
1396 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1397 }
1398 synchronized (mLock) {
1399 if (mIsLoaderTaskRunning) {
1400 // Ensure that we are never running the background loading at this point since
1401 // we also touch the background collections
1402 throw new RuntimeException("Error! Background loading is already running");
1403 }
1404 }
1405
1406 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1407 // data structures, we can't allow any other thread to touch that data, but because
1408 // this call is synchronous, we can get away with not locking).
1409
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001410 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001411 // operations from the previous activity. We need to ensure that all queued operations
1412 // are executed before any synchronous binding work is done.
1413 mHandler.flush();
1414
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001415 // Divide the set of loaded items into those that we are binding synchronously, and
1416 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001417 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001418 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1419 // arise from that.
1420 onlyBindAllApps();
1421 }
1422
Joe Onorato36115782010-06-17 13:28:48 -04001423 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001424 boolean isUpgrade = false;
1425
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001426 synchronized (mLock) {
1427 mIsLoaderTaskRunning = true;
1428 }
Joe Onorato36115782010-06-17 13:28:48 -04001429 // Optimize for end-user experience: if the Launcher is up and // running with the
1430 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1431 // workspace first (default).
1432 final Callbacks cbk = mCallbacks.get();
Joe Onorato36115782010-06-17 13:28:48 -04001433 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001434 // Elevate priority when Home launches for the first time to avoid
1435 // starving at boot time. Staring at a blank home is not cool.
1436 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001437 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1438 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001439 android.os.Process.setThreadPriority(mIsLaunching
1440 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1441 }
Winson Chung64359a52013-07-08 17:17:08 -07001442 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001443 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001444
Joe Onorato36115782010-06-17 13:28:48 -04001445 if (mStopped) {
1446 break keep_running;
1447 }
1448
1449 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1450 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001451 synchronized (mLock) {
1452 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001453 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001454 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1455 }
1456 }
Joe Onorato36115782010-06-17 13:28:48 -04001457 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001458
1459 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001460 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1461 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001462
1463 // Restore the default thread priority after we are done loading items
1464 synchronized (mLock) {
1465 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1466 }
Joe Onorato36115782010-06-17 13:28:48 -04001467 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001468
Winson Chungaac01e12011-08-17 10:37:13 -07001469 // Update the saved icons if necessary
1470 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001471 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001472 for (Object key : sBgDbIconCache.keySet()) {
1473 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1474 }
1475 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001476 }
Winson Chungaac01e12011-08-17 10:37:13 -07001477
Winson Chungc763c4e2013-07-19 13:49:06 -07001478 // Ensure that all the applications that are in the system are represented on the home
1479 // screen.
Winson Chung76828c82013-08-19 15:43:29 -07001480 Log.w(TAG, "10249126 - verifyApplications(" + isUpgrade + ")");
Winson Chungc763c4e2013-07-19 13:49:06 -07001481 if (!isUpgrade) {
1482 verifyApplications();
1483 }
1484
Joe Onorato36115782010-06-17 13:28:48 -04001485 // Clear out this reference, otherwise we end up holding it until all of the
1486 // callback runnables are done.
1487 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001488
Joe Onorato36115782010-06-17 13:28:48 -04001489 synchronized (mLock) {
1490 // If we are still the last one to be scheduled, remove ourselves.
1491 if (mLoaderTask == this) {
1492 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001493 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001494 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001495 }
Joe Onorato36115782010-06-17 13:28:48 -04001496 }
1497
1498 public void stopLocked() {
1499 synchronized (LoaderTask.this) {
1500 mStopped = true;
1501 this.notify();
1502 }
1503 }
1504
1505 /**
1506 * Gets the callbacks object. If we've been stopped, or if the launcher object
1507 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1508 * object that was around when the deferred message was scheduled, and if there's
1509 * a new Callbacks object around then also return null. This will save us from
1510 * calling onto it with data that will be ignored.
1511 */
1512 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1513 synchronized (mLock) {
1514 if (mStopped) {
1515 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001516 }
Joe Onorato36115782010-06-17 13:28:48 -04001517
1518 if (mCallbacks == null) {
1519 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001520 }
Joe Onorato36115782010-06-17 13:28:48 -04001521
1522 final Callbacks callbacks = mCallbacks.get();
1523 if (callbacks != oldCallbacks) {
1524 return null;
1525 }
1526 if (callbacks == null) {
1527 Log.w(TAG, "no mCallbacks");
1528 return null;
1529 }
1530
1531 return callbacks;
1532 }
1533 }
1534
Winson Chungc763c4e2013-07-19 13:49:06 -07001535 private void verifyApplications() {
1536 final Context context = mApp.getContext();
1537
1538 // Cross reference all the applications in our apps list with items in the workspace
1539 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001540 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001541 synchronized (sBgLock) {
1542 for (ApplicationInfo app : mBgAllAppsList.data) {
1543 tmpInfos = getItemInfoForComponentName(app.componentName);
Winson Chung76828c82013-08-19 15:43:29 -07001544 Log.w(TAG, "10249126 - \t" + app.componentName.getPackageName() + ", " + tmpInfos.isEmpty());
Winson Chungc763c4e2013-07-19 13:49:06 -07001545 if (tmpInfos.isEmpty()) {
1546 // We are missing an application icon, so add this to the workspace
1547 added.add(app);
1548 // This is a rare event, so lets log it
1549 Log.e(TAG, "Missing Application on load: " + app);
1550 }
1551 }
1552 }
1553 if (!added.isEmpty()) {
1554 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
1555 addAndBindAddedApps(context, added, cb);
1556 }
1557 }
1558
Joe Onorato36115782010-06-17 13:28:48 -04001559 // check & update map of what's occupied; used to discard overlapping/invalid items
Adam Cohendcd297f2013-06-18 13:13:40 -07001560 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
1561 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001562 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001563 if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
1564 if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1565 [(int) item.screenId][0] != null) {
1566 Log.e(TAG, "Error loading shortcut into hotseat " + item
1567 + " into position (" + item.screenId + ":" + item.cellX + ","
1568 + item.cellY + ") occupied by "
1569 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1570 [(int) item.screenId][0]);
1571 return false;
1572 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001573 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001574 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1575 items[(int) item.screenId][0] = item;
1576 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001577 return true;
1578 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001579 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1580 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001581 return true;
1582 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001583
Adam Cohendcd297f2013-06-18 13:13:40 -07001584 if (!occupied.containsKey(item.screenId)) {
1585 ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
1586 occupied.put(item.screenId, items);
1587 }
1588
1589 ItemInfo[][] screens = occupied.get(item.screenId);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001590 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001591 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1592 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001593 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001594 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001595 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001596 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001597 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001598 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001599 return false;
1600 }
1601 }
1602 }
1603 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1604 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001605 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001606 }
1607 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001608
Joe Onorato36115782010-06-17 13:28:48 -04001609 return true;
1610 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001611
Winson Chungc763c4e2013-07-19 13:49:06 -07001612 /** Returns whether this is an upgradge path */
1613 private boolean loadWorkspace() {
Joe Onorato36115782010-06-17 13:28:48 -04001614 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001615
Joe Onorato36115782010-06-17 13:28:48 -04001616 final Context context = mContext;
1617 final ContentResolver contentResolver = context.getContentResolver();
1618 final PackageManager manager = context.getPackageManager();
1619 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1620 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001621
Michael Jurkab85f8a42012-04-25 15:48:32 -07001622 // Make sure the default workspace is loaded, if needed
Winson Chungc763c4e2013-07-19 13:49:06 -07001623 mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
Adam Cohene25af792013-06-06 23:08:25 -07001624
Winson Chungc763c4e2013-07-19 13:49:06 -07001625 // Check if we need to do any upgrade-path logic
1626 boolean loadedOldDb = mApp.getLauncherProvider().justLoadedOldDb();
Michael Jurkab85f8a42012-04-25 15:48:32 -07001627
Winson Chung2abf94d2012-07-18 18:16:38 -07001628 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001629 sBgWorkspaceItems.clear();
1630 sBgAppWidgets.clear();
1631 sBgFolders.clear();
1632 sBgItemsIdMap.clear();
1633 sBgDbIconCache.clear();
Adam Cohendcd297f2013-06-18 13:13:40 -07001634 sBgWorkspaceScreens.clear();
Winson Chung76828c82013-08-19 15:43:29 -07001635 Log.w(TAG, "10249126 - loadWorkspace()");
Romain Guy5c16f3e2010-01-12 17:24:58 -08001636
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001637 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001638 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Adam Cohene25af792013-06-06 23:08:25 -07001639 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001640
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001641 // +1 for the hotseat (it can be larger than the workspace)
1642 // Load workspace in reverse order to ensure that latest items are loaded first (and
1643 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001644 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001645
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001646 try {
1647 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1648 final int intentIndex = c.getColumnIndexOrThrow
1649 (LauncherSettings.Favorites.INTENT);
1650 final int titleIndex = c.getColumnIndexOrThrow
1651 (LauncherSettings.Favorites.TITLE);
1652 final int iconTypeIndex = c.getColumnIndexOrThrow(
1653 LauncherSettings.Favorites.ICON_TYPE);
1654 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1655 final int iconPackageIndex = c.getColumnIndexOrThrow(
1656 LauncherSettings.Favorites.ICON_PACKAGE);
1657 final int iconResourceIndex = c.getColumnIndexOrThrow(
1658 LauncherSettings.Favorites.ICON_RESOURCE);
1659 final int containerIndex = c.getColumnIndexOrThrow(
1660 LauncherSettings.Favorites.CONTAINER);
1661 final int itemTypeIndex = c.getColumnIndexOrThrow(
1662 LauncherSettings.Favorites.ITEM_TYPE);
1663 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1664 LauncherSettings.Favorites.APPWIDGET_ID);
1665 final int screenIndex = c.getColumnIndexOrThrow(
1666 LauncherSettings.Favorites.SCREEN);
1667 final int cellXIndex = c.getColumnIndexOrThrow
1668 (LauncherSettings.Favorites.CELLX);
1669 final int cellYIndex = c.getColumnIndexOrThrow
1670 (LauncherSettings.Favorites.CELLY);
1671 final int spanXIndex = c.getColumnIndexOrThrow
1672 (LauncherSettings.Favorites.SPANX);
1673 final int spanYIndex = c.getColumnIndexOrThrow(
1674 LauncherSettings.Favorites.SPANY);
1675 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1676 //final int displayModeIndex = c.getColumnIndexOrThrow(
1677 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001678
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001679 ShortcutInfo info;
1680 String intentDescription;
1681 LauncherAppWidgetInfo appWidgetInfo;
1682 int container;
1683 long id;
1684 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001685
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001686 while (!mStopped && c.moveToNext()) {
1687 try {
1688 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001689
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001690 switch (itemType) {
1691 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1692 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001693 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001694 intentDescription = c.getString(intentIndex);
1695 try {
1696 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001697 ComponentName cn = intent.getComponent();
Winson Chung1323b482013-08-05 12:41:55 -07001698 if (!isValidPackageComponent(manager, cn)) {
Winson Chungee055712013-07-30 14:46:24 -07001699 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chung1323b482013-08-05 12:41:55 -07001700 // Log the invalid package, and remove it from the db
1701 Uri uri = LauncherSettings.Favorites.getContentUri(id,
1702 false);
Winson Chungee055712013-07-30 14:46:24 -07001703 contentResolver.delete(uri, null, null);
Winson Chung1323b482013-08-05 12:41:55 -07001704 Log.e(TAG, "Invalid package removed: " + cn);
Winson Chungee055712013-07-30 14:46:24 -07001705 } else {
Winson Chung1323b482013-08-05 12:41:55 -07001706 // If apps can be on external storage, then we just
1707 // leave them for the user to remove (maybe add
1708 // visual treatment to it)
1709 Log.e(TAG, "Invalid package found: " + cn);
Winson Chungee055712013-07-30 14:46:24 -07001710 }
1711 continue;
1712 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001713 } catch (URISyntaxException e) {
1714 continue;
1715 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001716
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001717 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1718 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1719 titleIndex, mLabelCache);
1720 } else {
1721 info = getShortcutInfo(c, context, iconTypeIndex,
1722 iconPackageIndex, iconResourceIndex, iconIndex,
1723 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001724
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001725 // App shortcuts that used to be automatically added to Launcher
1726 // didn't always have the correct intent flags set, so do that
1727 // here
1728 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001729 intent.getCategories() != null &&
1730 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001731 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001732 intent.addFlags(
1733 Intent.FLAG_ACTIVITY_NEW_TASK |
1734 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1735 }
Michael Jurka96879562012-03-22 05:54:33 -07001736 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001737
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001738 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07001739 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001740 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001741 container = c.getInt(containerIndex);
1742 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001743 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001744 info.cellX = c.getInt(cellXIndex);
1745 info.cellY = c.getInt(cellYIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001746 // check & update map of what's occupied
1747 if (!checkItemPlacement(occupied, info)) {
1748 break;
1749 }
1750
1751 switch (container) {
1752 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1753 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1754 sBgWorkspaceItems.add(info);
1755 break;
1756 default:
1757 // Item is in a user folder
1758 FolderInfo folderInfo =
1759 findOrMakeFolder(sBgFolders, container);
1760 folderInfo.add(info);
1761 break;
1762 }
1763 sBgItemsIdMap.put(info.id, info);
1764
1765 // now that we've loaded everthing re-save it with the
1766 // icon in case it disappears somehow.
1767 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07001768 } else {
1769 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001770 }
1771 break;
1772
1773 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1774 id = c.getLong(idIndex);
1775 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1776
1777 folderInfo.title = c.getString(titleIndex);
1778 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001779 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001780 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001781 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001782 folderInfo.cellX = c.getInt(cellXIndex);
1783 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001784
Daniel Sandler8802e962010-05-26 16:28:16 -04001785 // check & update map of what's occupied
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001786 if (!checkItemPlacement(occupied, folderInfo)) {
Daniel Sandler8802e962010-05-26 16:28:16 -04001787 break;
1788 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001789 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001790 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1791 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1792 sBgWorkspaceItems.add(folderInfo);
1793 break;
Joe Onorato36115782010-06-17 13:28:48 -04001794 }
Joe Onorato17a89222011-02-08 17:26:11 -08001795
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001796 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1797 sBgFolders.put(folderInfo.id, folderInfo);
1798 break;
1799
1800 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1801 // Read all Launcher-specific widget details
1802 int appWidgetId = c.getInt(appWidgetIdIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001803 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001804
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001805 final AppWidgetProviderInfo provider =
1806 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001807
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001808 if (!isSafeMode && (provider == null || provider.provider == null ||
1809 provider.provider.getPackageName() == null)) {
1810 String log = "Deleting widget that isn't installed anymore: id="
1811 + id + " appWidgetId=" + appWidgetId;
1812 Log.e(TAG, log);
1813 Launcher.sDumpLogs.add(log);
1814 itemsToRemove.add(id);
1815 } else {
1816 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1817 provider.provider);
1818 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07001819 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001820 appWidgetInfo.cellX = c.getInt(cellXIndex);
1821 appWidgetInfo.cellY = c.getInt(cellYIndex);
1822 appWidgetInfo.spanX = c.getInt(spanXIndex);
1823 appWidgetInfo.spanY = c.getInt(spanYIndex);
1824 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1825 appWidgetInfo.minSpanX = minSpan[0];
1826 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001827
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001828 container = c.getInt(containerIndex);
1829 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1830 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1831 Log.e(TAG, "Widget found where container != " +
1832 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1833 continue;
1834 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001835
Adam Cohene25af792013-06-06 23:08:25 -07001836 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001837 // check & update map of what's occupied
1838 if (!checkItemPlacement(occupied, appWidgetInfo)) {
1839 break;
1840 }
1841 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1842 sBgAppWidgets.add(appWidgetInfo);
1843 }
Joe Onorato36115782010-06-17 13:28:48 -04001844 break;
1845 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001846 } catch (Exception e) {
1847 Log.w(TAG, "Desktop items loading interrupted:", e);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001848 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001849 }
1850 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04001851 if (c != null) {
1852 c.close();
1853 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001854 }
1855
1856 if (itemsToRemove.size() > 0) {
1857 ContentProviderClient client = contentResolver.acquireContentProviderClient(
1858 LauncherSettings.Favorites.CONTENT_URI);
1859 // Remove dead items
1860 for (long id : itemsToRemove) {
1861 if (DEBUG_LOADERS) {
1862 Log.d(TAG, "Removed id = " + id);
1863 }
1864 // Don't notify content observers
1865 try {
1866 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1867 null, null);
1868 } catch (RemoteException e) {
1869 Log.w(TAG, "Could not remove id = " + id);
1870 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001871 }
1872 }
1873
Winson Chungc763c4e2013-07-19 13:49:06 -07001874 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001875 long maxScreenId = 0;
1876 // If we're importing we use the old screen order.
1877 for (ItemInfo item: sBgItemsIdMap.values()) {
1878 long screenId = item.screenId;
1879 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1880 !sBgWorkspaceScreens.contains(screenId)) {
Winson Chung76828c82013-08-19 15:43:29 -07001881 Log.w(TAG, "10249126 - loadWorkspace-loadedOldDb(" + screenId + ")");
Adam Cohendcd297f2013-06-18 13:13:40 -07001882 sBgWorkspaceScreens.add(screenId);
1883 if (screenId > maxScreenId) {
1884 maxScreenId = screenId;
1885 }
1886 }
1887 }
1888 Collections.sort(sBgWorkspaceScreens);
1889 mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
1890 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07001891
1892 // Update the max item id after we load an old db
1893 long maxItemId = 0;
1894 // If we're importing we use the old screen order.
1895 for (ItemInfo item: sBgItemsIdMap.values()) {
1896 maxItemId = Math.max(maxItemId, item.id);
1897 }
1898 LauncherAppState app = LauncherAppState.getInstance();
1899 app.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07001900 } else {
Winson Chung76828c82013-08-19 15:43:29 -07001901 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
1902 for (Integer i : orderedScreens.keySet()) {
1903 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07001904 }
1905
1906 // Remove any empty screens
1907 ArrayList<Long> unusedScreens = new ArrayList<Long>();
1908 unusedScreens.addAll(sBgWorkspaceScreens);
1909
1910 for (ItemInfo item: sBgItemsIdMap.values()) {
1911 long screenId = item.screenId;
1912
1913 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1914 unusedScreens.contains(screenId)) {
1915 unusedScreens.remove(screenId);
1916 }
1917 }
1918
1919 // If there are any empty screens remove them, and update.
1920 if (unusedScreens.size() != 0) {
1921 sBgWorkspaceScreens.removeAll(unusedScreens);
1922 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
1923 }
1924 }
1925
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001926 if (DEBUG_LOADERS) {
1927 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
1928 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07001929 int nScreens = occupied.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001930 for (int y = 0; y < mCellCountY; y++) {
1931 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07001932
Daniel Sandler566da102013-06-25 23:43:45 -04001933 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07001934 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001935 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07001936 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001937 line += " | ";
1938 }
1939 for (int x = 0; x < mCellCountX; x++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001940 line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001941 }
Joe Onorato36115782010-06-17 13:28:48 -04001942 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001943 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04001944 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001945 }
Joe Onorato36115782010-06-17 13:28:48 -04001946 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001947 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07001948 }
1949
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001950 /** Filters the set of items who are directly or indirectly (via another container) on the
1951 * specified screen. */
1952 private void filterCurrentWorkspaceItems(int currentScreen,
1953 ArrayList<ItemInfo> allWorkspaceItems,
1954 ArrayList<ItemInfo> currentScreenItems,
1955 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001956 // Purge any null ItemInfos
1957 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1958 while (iter.hasNext()) {
1959 ItemInfo i = iter.next();
1960 if (i == null) {
1961 iter.remove();
1962 }
1963 }
1964
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001965 // If we aren't filtering on a screen, then the set of items to load is the full set of
1966 // items given.
1967 if (currentScreen < 0) {
1968 currentScreenItems.addAll(allWorkspaceItems);
Joe Onorato36115782010-06-17 13:28:48 -04001969 }
1970
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001971 // Order the set of items by their containers first, this allows use to walk through the
1972 // list sequentially, build up a list of containers that are in the specified screen,
1973 // as well as all items in those containers.
1974 Set<Long> itemsOnScreen = new HashSet<Long>();
1975 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1976 @Override
1977 public int compare(ItemInfo lhs, ItemInfo rhs) {
1978 return (int) (lhs.container - rhs.container);
1979 }
1980 });
1981 for (ItemInfo info : allWorkspaceItems) {
1982 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001983 if (info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001984 currentScreenItems.add(info);
1985 itemsOnScreen.add(info.id);
1986 } else {
1987 otherScreenItems.add(info);
1988 }
1989 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1990 currentScreenItems.add(info);
1991 itemsOnScreen.add(info.id);
1992 } else {
1993 if (itemsOnScreen.contains(info.container)) {
1994 currentScreenItems.add(info);
1995 itemsOnScreen.add(info.id);
1996 } else {
1997 otherScreenItems.add(info);
1998 }
1999 }
2000 }
2001 }
2002
2003 /** Filters the set of widgets which are on the specified screen. */
2004 private void filterCurrentAppWidgets(int currentScreen,
2005 ArrayList<LauncherAppWidgetInfo> appWidgets,
2006 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2007 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
2008 // If we aren't filtering on a screen, then the set of items to load is the full set of
2009 // widgets given.
2010 if (currentScreen < 0) {
2011 currentScreenWidgets.addAll(appWidgets);
2012 }
2013
2014 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002015 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002016 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07002017 widget.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002018 currentScreenWidgets.add(widget);
2019 } else {
2020 otherScreenWidgets.add(widget);
2021 }
2022 }
2023 }
2024
2025 /** Filters the set of folders which are on the specified screen. */
2026 private void filterCurrentFolders(int currentScreen,
2027 HashMap<Long, ItemInfo> itemsIdMap,
2028 HashMap<Long, FolderInfo> folders,
2029 HashMap<Long, FolderInfo> currentScreenFolders,
2030 HashMap<Long, FolderInfo> otherScreenFolders) {
2031 // If we aren't filtering on a screen, then the set of items to load is the full set of
2032 // widgets given.
2033 if (currentScreen < 0) {
2034 currentScreenFolders.putAll(folders);
2035 }
2036
2037 for (long id : folders.keySet()) {
2038 ItemInfo info = itemsIdMap.get(id);
2039 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002040 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002041 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Adam Cohendcd297f2013-06-18 13:13:40 -07002042 info.screenId == currentScreen) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002043 currentScreenFolders.put(id, folder);
2044 } else {
2045 otherScreenFolders.put(id, folder);
2046 }
2047 }
2048 }
2049
2050 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2051 * right) */
2052 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
2053 // XXX: review this
2054 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002055 @Override
2056 public int compare(ItemInfo lhs, ItemInfo rhs) {
2057 int cellCountX = LauncherModel.getCellCountX();
2058 int cellCountY = LauncherModel.getCellCountY();
2059 int screenOffset = cellCountX * cellCountY;
2060 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002061 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002062 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002063 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002064 rhs.cellY * cellCountX + rhs.cellX);
2065 return (int) (lr - rr);
2066 }
2067 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002068 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002069
Adam Cohendcd297f2013-06-18 13:13:40 -07002070 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2071 final ArrayList<Long> orderedScreens) {
Winson Chung76828c82013-08-19 15:43:29 -07002072 Log.w(TAG, "10249126 - bindWorkspaceScreens()");
Adam Cohendcd297f2013-06-18 13:13:40 -07002073 final Runnable r = new Runnable() {
2074 @Override
2075 public void run() {
2076 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2077 if (callbacks != null) {
2078 callbacks.bindScreens(orderedScreens);
2079 }
2080 }
2081 };
2082 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2083 }
2084
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002085 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2086 final ArrayList<ItemInfo> workspaceItems,
2087 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2088 final HashMap<Long, FolderInfo> folders,
2089 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002090
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002091 final boolean postOnMainThread = (deferredBindRunnables != null);
2092
2093 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002094 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002095 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002096 final int start = i;
2097 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002098 final Runnable r = new Runnable() {
2099 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002100 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002101 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002102 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002103 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2104 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002105 }
2106 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002107 };
2108 if (postOnMainThread) {
2109 deferredBindRunnables.add(r);
2110 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002111 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002112 }
Joe Onorato36115782010-06-17 13:28:48 -04002113 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002114
2115 // Bind the folders
2116 if (!folders.isEmpty()) {
2117 final Runnable r = new Runnable() {
2118 public void run() {
2119 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2120 if (callbacks != null) {
2121 callbacks.bindFolders(folders);
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 // Bind the widgets, one at a time
2133 N = appWidgets.size();
2134 for (int i = 0; i < N; i++) {
2135 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2136 final Runnable r = new Runnable() {
2137 public void run() {
2138 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2139 if (callbacks != null) {
2140 callbacks.bindAppWidget(widget);
2141 }
2142 }
2143 };
2144 if (postOnMainThread) {
2145 deferredBindRunnables.add(r);
2146 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002147 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002148 }
2149 }
2150 }
2151
2152 /**
2153 * Binds all loaded data to actual views on the main thread.
2154 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002155 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002156 final long t = SystemClock.uptimeMillis();
2157 Runnable r;
2158
2159 // Don't use these two variables in any of the callback runnables.
2160 // Otherwise we hold a reference to them.
2161 final Callbacks oldCallbacks = mCallbacks.get();
2162 if (oldCallbacks == null) {
2163 // This launcher has exited and nobody bothered to tell us. Just bail.
2164 Log.w(TAG, "LoaderTask running with no launcher");
2165 return;
2166 }
2167
Winson Chung4a2afa32012-07-19 14:53:05 -07002168 final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
2169 final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002170 oldCallbacks.getCurrentWorkspaceScreen();
2171
2172 // Load all the items that are on the current page first (and in the process, unbind
2173 // all the existing workspace items before we call startBinding() below.
2174 unbindWorkspaceItemsOnMainThread();
2175 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2176 ArrayList<LauncherAppWidgetInfo> appWidgets =
2177 new ArrayList<LauncherAppWidgetInfo>();
2178 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2179 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002180 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002181 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002182 workspaceItems.addAll(sBgWorkspaceItems);
2183 appWidgets.addAll(sBgAppWidgets);
2184 folders.putAll(sBgFolders);
2185 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002186 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002187 }
2188
2189 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2190 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2191 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2192 new ArrayList<LauncherAppWidgetInfo>();
2193 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2194 new ArrayList<LauncherAppWidgetInfo>();
2195 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2196 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2197
2198 // Separate the items that are on the current screen, and all the other remaining items
2199 filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
2200 otherWorkspaceItems);
2201 filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
2202 otherAppWidgets);
2203 filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
2204 otherFolders);
2205 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2206 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2207
2208 // Tell the workspace that we're about to start binding items
2209 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002210 public void run() {
2211 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2212 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002213 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002214 }
2215 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002216 };
Winson Chung81b52252012-08-27 15:34:29 -07002217 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002218
Adam Cohendcd297f2013-06-18 13:13:40 -07002219 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2220
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002221 // Load items on the current page
2222 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2223 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002224 if (isLoadingSynchronously) {
2225 r = new Runnable() {
2226 public void run() {
2227 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2228 if (callbacks != null) {
2229 callbacks.onPageBoundSynchronously(currentScreen);
2230 }
2231 }
2232 };
Winson Chung81b52252012-08-27 15:34:29 -07002233 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002234 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002235
Winson Chung4a2afa32012-07-19 14:53:05 -07002236 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2237 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002238 mDeferredBindRunnables.clear();
2239 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002240 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002241
2242 // Tell the workspace that we're done binding items
2243 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002244 public void run() {
2245 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2246 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002247 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002248 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002249
Winson Chung98e030b2012-05-07 16:01:11 -07002250 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002251 if (DEBUG_LOADERS) {
2252 Log.d(TAG, "bound workspace in "
2253 + (SystemClock.uptimeMillis()-t) + "ms");
2254 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002255
2256 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002257 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002258 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002259 if (isLoadingSynchronously) {
2260 mDeferredBindRunnables.add(r);
2261 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002262 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002263 }
Joe Onorato36115782010-06-17 13:28:48 -04002264 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002265
Joe Onorato36115782010-06-17 13:28:48 -04002266 private void loadAndBindAllApps() {
2267 if (DEBUG_LOADERS) {
2268 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2269 }
2270 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002271 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002272 synchronized (LoaderTask.this) {
2273 if (mStopped) {
2274 return;
2275 }
2276 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002277 }
Joe Onorato36115782010-06-17 13:28:48 -04002278 } else {
2279 onlyBindAllApps();
2280 }
2281 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002282
Joe Onorato36115782010-06-17 13:28:48 -04002283 private void onlyBindAllApps() {
2284 final Callbacks oldCallbacks = mCallbacks.get();
2285 if (oldCallbacks == null) {
2286 // This launcher has exited and nobody bothered to tell us. Just bail.
2287 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2288 return;
2289 }
2290
2291 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002292 @SuppressWarnings("unchecked")
Joe Onorato36115782010-06-17 13:28:48 -04002293 final ArrayList<ApplicationInfo> list
Adam Cohen487f7dd2012-06-28 18:12:10 -07002294 = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002295 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002296 public void run() {
2297 final long t = SystemClock.uptimeMillis();
2298 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2299 if (callbacks != null) {
2300 callbacks.bindAllApplications(list);
2301 }
2302 if (DEBUG_LOADERS) {
2303 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2304 + (SystemClock.uptimeMillis()-t) + "ms");
2305 }
2306 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002307 };
2308 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002309 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002310 r.run();
2311 } else {
2312 mHandler.post(r);
2313 }
Joe Onorato36115782010-06-17 13:28:48 -04002314 }
2315
Winson Chung64359a52013-07-08 17:17:08 -07002316 private void loadAllApps() {
2317 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002318
2319 // Don't use these two variables in any of the callback runnables.
2320 // Otherwise we hold a reference to them.
2321 final Callbacks oldCallbacks = mCallbacks.get();
2322 if (oldCallbacks == null) {
2323 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002324 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002325 return;
2326 }
2327
Winson Chung64359a52013-07-08 17:17:08 -07002328 final PackageManager packageManager = mContext.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04002329 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2330 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2331
Winson Chung64359a52013-07-08 17:17:08 -07002332 // Clear the list of apps
2333 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002334
Winson Chung64359a52013-07-08 17:17:08 -07002335 // Query for the set of apps
2336 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2337 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2338 if (DEBUG_LOADERS) {
2339 Log.d(TAG, "queryIntentActivities took "
2340 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2341 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2342 }
2343 // Fail if we don't have any apps
2344 if (apps == null || apps.isEmpty()) {
2345 return;
2346 }
2347 // Sort the applications by name
2348 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2349 Collections.sort(apps,
2350 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2351 if (DEBUG_LOADERS) {
2352 Log.d(TAG, "sort took "
2353 + (SystemClock.uptimeMillis()-sortTime) + "ms");
Joe Onorato9c1289c2009-08-17 11:03:03 -04002354 }
2355
Winson Chung64359a52013-07-08 17:17:08 -07002356 // Create the ApplicationInfos
2357 final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2358 for (int i = 0; i < apps.size(); i++) {
2359 // This builds the icon bitmaps.
2360 mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
2361 mIconCache, mLabelCache));
2362 }
2363
2364 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2365 final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
2366 mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
2367
2368 // Post callback on main thread
2369 mHandler.post(new Runnable() {
2370 public void run() {
2371 final long bindTime = SystemClock.uptimeMillis();
2372 if (callbacks != null) {
2373 callbacks.bindAllApplications(added);
2374 if (DEBUG_LOADERS) {
2375 Log.d(TAG, "bound " + added.size() + " apps in "
2376 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2377 }
2378 } else {
2379 Log.i(TAG, "not binding apps: no Launcher activity");
2380 }
2381 }
2382 });
2383
Joe Onorato36115782010-06-17 13:28:48 -04002384 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002385 Log.d(TAG, "Icons processed in "
2386 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002387 }
2388 }
2389
2390 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002391 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002392 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2393 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2394 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2395 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2396 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2397 }
Joe Onorato36115782010-06-17 13:28:48 -04002398 }
2399 }
2400
2401 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002402 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002403 }
2404
2405 private class PackageUpdatedTask implements Runnable {
2406 int mOp;
2407 String[] mPackages;
2408
2409 public static final int OP_NONE = 0;
2410 public static final int OP_ADD = 1;
2411 public static final int OP_UPDATE = 2;
2412 public static final int OP_REMOVE = 3; // uninstlled
2413 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2414
2415
2416 public PackageUpdatedTask(int op, String[] packages) {
2417 mOp = op;
2418 mPackages = packages;
2419 }
2420
2421 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002422 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002423
2424 final String[] packages = mPackages;
2425 final int N = packages.length;
2426 switch (mOp) {
2427 case OP_ADD:
2428 for (int i=0; i<N; i++) {
2429 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002430 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002431 }
2432 break;
2433 case OP_UPDATE:
2434 for (int i=0; i<N; i++) {
2435 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002436 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002437 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002438 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002439 }
2440 break;
2441 case OP_REMOVE:
2442 case OP_UNAVAILABLE:
2443 for (int i=0; i<N; i++) {
2444 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002445 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkad9cb4a12013-03-19 12:01:06 +01002446 WidgetPreviewLoader.removeFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002447 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002448 }
2449 break;
2450 }
2451
2452 ArrayList<ApplicationInfo> added = null;
Joe Onorato36115782010-06-17 13:28:48 -04002453 ArrayList<ApplicationInfo> modified = null;
Winson Chung83892cc2013-05-01 16:53:33 -07002454 final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002455
Adam Cohen487f7dd2012-06-28 18:12:10 -07002456 if (mBgAllAppsList.added.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002457 added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
2458 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002459 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002460 if (mBgAllAppsList.modified.size() > 0) {
Winson Chung5d55f332012-07-16 20:45:03 -07002461 modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
2462 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002463 }
Winson Chung5d55f332012-07-16 20:45:03 -07002464 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002465 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002466 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002467 }
2468
Joe Onorato36115782010-06-17 13:28:48 -04002469 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2470 if (callbacks == null) {
2471 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2472 return;
2473 }
2474
2475 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002476 // Ensure that we add all the workspace applications to the db
Winson Chung997a9232013-07-24 15:33:46 -07002477 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Winson Chung64359a52013-07-08 17:17:08 -07002478 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
Winson Chung997a9232013-07-24 15:33:46 -07002479 addAndBindAddedApps(context, addedInfos, cb);
Joe Onorato36115782010-06-17 13:28:48 -04002480 }
2481 if (modified != null) {
2482 final ArrayList<ApplicationInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002483
2484 // Update the launcher db to reflect the changes
2485 for (ApplicationInfo a : modifiedFinal) {
2486 ArrayList<ItemInfo> infos =
2487 getItemInfoForComponentName(a.componentName);
2488 for (ItemInfo i : infos) {
2489 if (isShortcutInfoUpdateable(i)) {
2490 ShortcutInfo info = (ShortcutInfo) i;
2491 info.title = a.title.toString();
2492 updateItemInDatabase(context, info);
2493 }
2494 }
2495 }
2496
Joe Onorato36115782010-06-17 13:28:48 -04002497 mHandler.post(new Runnable() {
2498 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002499 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2500 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002501 callbacks.bindAppsUpdated(modifiedFinal);
2502 }
2503 }
2504 });
2505 }
Winson Chung83892cc2013-05-01 16:53:33 -07002506 // If a package has been removed, or an app has been removed as a result of
2507 // an update (for example), make the removed callback.
2508 if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
Winson Chung64359a52013-07-08 17:17:08 -07002509 final boolean packageRemoved = (mOp == OP_REMOVE);
Winson Chung83892cc2013-05-01 16:53:33 -07002510 final ArrayList<String> removedPackageNames =
2511 new ArrayList<String>(Arrays.asList(packages));
2512
Winson Chung64359a52013-07-08 17:17:08 -07002513 // Update the launcher db to reflect the removal of apps
2514 if (packageRemoved) {
2515 for (String pn : removedPackageNames) {
2516 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2517 for (ItemInfo i : infos) {
2518 deleteItemFromDatabase(context, i);
2519 }
2520 }
2521 } else {
2522 for (ApplicationInfo a : removedApps) {
2523 ArrayList<ItemInfo> infos =
2524 getItemInfoForComponentName(a.componentName);
2525 for (ItemInfo i : infos) {
2526 deleteItemFromDatabase(context, i);
2527 }
2528 }
2529 }
2530
Joe Onorato36115782010-06-17 13:28:48 -04002531 mHandler.post(new Runnable() {
2532 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002533 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2534 if (callbacks == cb && cb != null) {
Winson Chung83892cc2013-05-01 16:53:33 -07002535 callbacks.bindComponentsRemoved(removedPackageNames,
Winson Chung64359a52013-07-08 17:17:08 -07002536 removedApps, packageRemoved);
Joe Onorato36115782010-06-17 13:28:48 -04002537 }
2538 }
2539 });
Joe Onoratobe386092009-11-17 17:32:16 -08002540 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002541
Michael Jurkac402cd92013-05-20 15:49:32 +02002542 final ArrayList<Object> widgetsAndShortcuts =
2543 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002544 mHandler.post(new Runnable() {
2545 @Override
2546 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002547 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2548 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002549 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002550 }
2551 }
2552 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002553 }
2554 }
2555
Michael Jurkac402cd92013-05-20 15:49:32 +02002556 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2557 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2558 PackageManager packageManager = context.getPackageManager();
2559 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2560 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2561 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2562 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2563 Collections.sort(widgetsAndShortcuts,
2564 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2565 return widgetsAndShortcuts;
2566 }
2567
Winson Chung1323b482013-08-05 12:41:55 -07002568 private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) {
Winson Chungee055712013-07-30 14:46:24 -07002569 if (cn == null) {
2570 return false;
2571 }
2572
2573 try {
2574 return (pm.getActivityInfo(cn, 0) != null);
2575 } catch (NameNotFoundException e) {
2576 return false;
2577 }
2578 }
2579
Joe Onorato9c1289c2009-08-17 11:03:03 -04002580 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002581 * This is called from the code that adds shortcuts from the intent receiver. This
2582 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002583 */
Joe Onorato56d82912010-03-07 14:32:10 -05002584 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002585 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002586 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002587
Joe Onorato56d82912010-03-07 14:32:10 -05002588 /**
2589 * Make an ShortcutInfo object for a shortcut that is an application.
2590 *
2591 * If c is not null, then it will be used to fill in missing data like the title and icon.
2592 */
2593 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002594 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002595 ComponentName componentName = intent.getComponent();
Winson Chung1323b482013-08-05 12:41:55 -07002596 final ShortcutInfo info = new ShortcutInfo();
2597 if (!isValidPackageComponent(manager, componentName)) {
Winson Chungee055712013-07-30 14:46:24 -07002598 Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002599 return null;
Winson Chung1323b482013-08-05 12:41:55 -07002600 } else {
2601 try {
2602 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2603 info.initFlagsAndFirstInstallTime(pi);
2604 } catch (NameNotFoundException e) {
2605 Log.d(TAG, "getPackInfo failed for package " +
2606 componentName.getPackageName());
2607 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002608 }
2609
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002610 // TODO: See if the PackageManager knows about this case. If it doesn't
2611 // then return null & delete this.
2612
Joe Onorato56d82912010-03-07 14:32:10 -05002613 // the resource -- This may implicitly give us back the fallback icon,
2614 // but don't worry about that. All we're doing with usingFallbackIcon is
2615 // to avoid saving lots of copies of that in the database, and most apps
2616 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002617
2618 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2619 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2620 // via resolveActivity().
Winson Chungee055712013-07-30 14:46:24 -07002621 Bitmap icon = null;
Winson Chungc208ff92012-03-29 17:37:41 -07002622 ResolveInfo resolveInfo = null;
2623 ComponentName oldComponent = intent.getComponent();
2624 Intent newIntent = new Intent(intent.getAction(), null);
2625 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2626 newIntent.setPackage(oldComponent.getPackageName());
2627 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2628 for (ResolveInfo i : infos) {
2629 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2630 i.activityInfo.name);
2631 if (cn.equals(oldComponent)) {
2632 resolveInfo = i;
2633 }
2634 }
2635 if (resolveInfo == null) {
2636 resolveInfo = manager.resolveActivity(intent, 0);
2637 }
Joe Onorato56d82912010-03-07 14:32:10 -05002638 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002639 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002640 }
Joe Onorato56d82912010-03-07 14:32:10 -05002641 // the db
2642 if (icon == null) {
2643 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002644 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002645 }
2646 }
2647 // the fallback icon
2648 if (icon == null) {
2649 icon = getFallbackIcon();
2650 info.usingFallbackIcon = true;
2651 }
2652 info.setIcon(icon);
2653
2654 // from the resource
2655 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002656 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2657 if (labelCache != null && labelCache.containsKey(key)) {
2658 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002659 } else {
2660 info.title = resolveInfo.activityInfo.loadLabel(manager);
2661 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002662 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002663 }
2664 }
Joe Onorato56d82912010-03-07 14:32:10 -05002665 }
2666 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002667 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002668 if (c != null) {
2669 info.title = c.getString(titleIndex);
2670 }
2671 }
2672 // fall back to the class name of the activity
2673 if (info.title == null) {
2674 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002675 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002676 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2677 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002678 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002679
Winson Chung64359a52013-07-08 17:17:08 -07002680 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2681 ItemInfoFilter f) {
2682 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2683 for (ItemInfo i : infos) {
2684 if (i instanceof ShortcutInfo) {
2685 ShortcutInfo info = (ShortcutInfo) i;
2686 ComponentName cn = info.intent.getComponent();
2687 if (cn != null && f.filterItem(null, info, cn)) {
2688 filtered.add(info);
2689 }
2690 } else if (i instanceof FolderInfo) {
2691 FolderInfo info = (FolderInfo) i;
2692 for (ShortcutInfo s : info.contents) {
2693 ComponentName cn = s.intent.getComponent();
2694 if (cn != null && f.filterItem(info, s, cn)) {
2695 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07002696 }
2697 }
Winson Chung64359a52013-07-08 17:17:08 -07002698 } else if (i instanceof LauncherAppWidgetInfo) {
2699 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2700 ComponentName cn = info.providerName;
2701 if (cn != null && f.filterItem(null, info, cn)) {
2702 filtered.add(info);
2703 }
Winson Chung8a435102012-08-30 17:16:53 -07002704 }
2705 }
Winson Chung64359a52013-07-08 17:17:08 -07002706 return new ArrayList<ItemInfo>(filtered);
2707 }
2708
2709 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
2710 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2711 ItemInfoFilter filter = new ItemInfoFilter() {
2712 @Override
2713 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2714 return cn.getPackageName().equals(pn);
2715 }
2716 };
2717 return filterItemInfos(sBgItemsIdMap.values(), filter);
2718 }
2719
2720 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
2721 HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
2722 ItemInfoFilter filter = new ItemInfoFilter() {
2723 @Override
2724 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2725 return cn.equals(cname);
2726 }
2727 };
2728 return filterItemInfos(sBgItemsIdMap.values(), filter);
2729 }
2730
2731 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2732 if (i instanceof ShortcutInfo) {
2733 ShortcutInfo info = (ShortcutInfo) i;
2734 // We need to check for ACTION_MAIN otherwise getComponent() might
2735 // return null for some shortcuts (for instance, for shortcuts to
2736 // web pages.)
2737 Intent intent = info.intent;
2738 ComponentName name = intent.getComponent();
2739 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2740 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2741 return true;
2742 }
2743 }
2744 return false;
Winson Chung8a435102012-08-30 17:16:53 -07002745 }
2746
2747 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002748 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002749 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002750 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002751 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2752 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002753
Joe Onorato56d82912010-03-07 14:32:10 -05002754 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002755 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002756 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002757
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002758 // TODO: If there's an explicit component and we can't install that, delete it.
2759
Joe Onorato56d82912010-03-07 14:32:10 -05002760 info.title = c.getString(titleIndex);
2761
Joe Onorato9c1289c2009-08-17 11:03:03 -04002762 int iconType = c.getInt(iconTypeIndex);
2763 switch (iconType) {
2764 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2765 String packageName = c.getString(iconPackageIndex);
2766 String resourceName = c.getString(iconResourceIndex);
2767 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002768 info.customIcon = false;
2769 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002770 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002771 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002772 if (resources != null) {
2773 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002774 icon = Utilities.createIconBitmap(
2775 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002776 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002777 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002778 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002779 }
Joe Onorato56d82912010-03-07 14:32:10 -05002780 // the db
2781 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002782 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002783 }
2784 // the fallback icon
2785 if (icon == null) {
2786 icon = getFallbackIcon();
2787 info.usingFallbackIcon = true;
2788 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002789 break;
2790 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002791 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002792 if (icon == null) {
2793 icon = getFallbackIcon();
2794 info.customIcon = false;
2795 info.usingFallbackIcon = true;
2796 } else {
2797 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002798 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002799 break;
2800 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002801 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002802 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002803 info.customIcon = false;
2804 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002805 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002806 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002807 return info;
2808 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002809
Michael Jurka931dc972011-08-05 15:08:15 -07002810 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002811 @SuppressWarnings("all") // suppress dead code warning
2812 final boolean debug = false;
2813 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002814 Log.d(TAG, "getIconFromCursor app="
2815 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2816 }
2817 byte[] data = c.getBlob(iconIndex);
2818 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002819 return Utilities.createIconBitmap(
2820 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002821 } catch (Exception e) {
2822 return null;
2823 }
2824 }
2825
Winson Chung3d503fb2011-07-13 17:25:49 -07002826 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2827 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002828 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002829 if (info == null) {
2830 return null;
2831 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002832 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002833
2834 return info;
2835 }
2836
Winson Chunga9abd0e2010-10-27 17:18:37 -07002837 /**
Winson Chung55cef262010-10-28 14:14:18 -07002838 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2839 */
2840 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2841 ComponentName component) {
2842 List<AppWidgetProviderInfo> widgets =
2843 AppWidgetManager.getInstance(context).getInstalledProviders();
2844 for (AppWidgetProviderInfo info : widgets) {
2845 if (info.provider.equals(component)) {
2846 return info;
2847 }
2848 }
2849 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002850 }
2851
Winson Chung68846fd2010-10-29 11:00:27 -07002852 /**
2853 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2854 */
2855 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2856 final PackageManager packageManager = context.getPackageManager();
2857 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2858 new ArrayList<WidgetMimeTypeHandlerData>();
2859
2860 final Intent supportsIntent =
2861 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2862 supportsIntent.setType(mimeType);
2863
2864 // Create a set of widget configuration components that we can test against
2865 final List<AppWidgetProviderInfo> widgets =
2866 AppWidgetManager.getInstance(context).getInstalledProviders();
2867 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
2868 new HashMap<ComponentName, AppWidgetProviderInfo>();
2869 for (AppWidgetProviderInfo info : widgets) {
2870 configurationComponentToWidget.put(info.configure, info);
2871 }
2872
2873 // Run through each of the intents that can handle this type of clip data, and cross
2874 // reference them with the components that are actual configuration components
2875 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
2876 PackageManager.MATCH_DEFAULT_ONLY);
2877 for (ResolveInfo info : activities) {
2878 final ActivityInfo activityInfo = info.activityInfo;
2879 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
2880 activityInfo.name);
2881 if (configurationComponentToWidget.containsKey(infoComponent)) {
2882 supportedConfigurationActivities.add(
2883 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
2884 configurationComponentToWidget.get(infoComponent)));
2885 }
2886 }
2887 return supportedConfigurationActivities;
2888 }
2889
Winson Chunga9abd0e2010-10-27 17:18:37 -07002890 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08002891 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
2892 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
2893 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
2894
Adam Cohend9198822011-11-22 16:42:47 -08002895 if (intent == null) {
2896 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
2897 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
2898 return null;
2899 }
2900
Joe Onorato0589f0f2010-02-08 13:44:00 -08002901 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08002902 boolean customIcon = false;
2903 ShortcutIconResource iconResource = null;
2904
2905 if (bitmap != null && bitmap instanceof Bitmap) {
2906 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002907 customIcon = true;
2908 } else {
2909 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
2910 if (extra != null && extra instanceof ShortcutIconResource) {
2911 try {
2912 iconResource = (ShortcutIconResource) extra;
2913 final PackageManager packageManager = context.getPackageManager();
2914 Resources resources = packageManager.getResourcesForApplication(
2915 iconResource.packageName);
2916 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002917 icon = Utilities.createIconBitmap(
2918 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002919 } catch (Exception e) {
2920 Log.w(TAG, "Could not load shortcut icon: " + extra);
2921 }
2922 }
2923 }
2924
Michael Jurkac9d95c52011-08-29 14:03:34 -07002925 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05002926
2927 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002928 if (fallbackIcon != null) {
2929 icon = fallbackIcon;
2930 } else {
2931 icon = getFallbackIcon();
2932 info.usingFallbackIcon = true;
2933 }
Joe Onorato56d82912010-03-07 14:32:10 -05002934 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08002935 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05002936
Joe Onorato0589f0f2010-02-08 13:44:00 -08002937 info.title = name;
2938 info.intent = intent;
2939 info.customIcon = customIcon;
2940 info.iconResource = iconResource;
2941
2942 return info;
2943 }
2944
Winson Chungaac01e12011-08-17 10:37:13 -07002945 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
2946 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08002947 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07002948 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07002949 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08002950 }
Joe Onorato56d82912010-03-07 14:32:10 -05002951 // If this icon doesn't have a custom icon, check to see
2952 // what's stored in the DB, and if it doesn't match what
2953 // we're going to show, store what we are going to show back
2954 // into the DB. We do this so when we're loading, if the
2955 // package manager can't find an icon (for example because
2956 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07002957 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07002958 cache.put(info, c.getBlob(iconIndex));
2959 return true;
2960 }
2961 return false;
2962 }
2963 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
2964 boolean needSave = false;
2965 try {
2966 if (data != null) {
2967 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
2968 Bitmap loaded = info.getIcon(mIconCache);
2969 needSave = !saved.sameAs(loaded);
2970 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05002971 needSave = true;
2972 }
Winson Chungaac01e12011-08-17 10:37:13 -07002973 } catch (Exception e) {
2974 needSave = true;
2975 }
2976 if (needSave) {
2977 Log.d(TAG, "going to save icon bitmap for info=" + info);
2978 // This is slower than is ideal, but this only happens once
2979 // or when the app is updated with a new icon.
2980 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05002981 }
2982 }
2983
Joe Onorato9c1289c2009-08-17 11:03:03 -04002984 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07002985 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04002986 * or make a new one.
2987 */
Adam Cohendf2cc412011-04-27 16:56:57 -07002988 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002989 // See if a placeholder was created for us already
2990 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07002991 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002992 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07002993 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002994 folders.put(id, folderInfo);
2995 }
Adam Cohendf2cc412011-04-27 16:56:57 -07002996 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002997 }
2998
Winson Chung11904872012-09-17 16:58:46 -07002999 public static final Comparator<ApplicationInfo> getAppNameComparator() {
3000 final Collator collator = Collator.getInstance();
3001 return new Comparator<ApplicationInfo>() {
3002 public final int compare(ApplicationInfo a, ApplicationInfo b) {
3003 int result = collator.compare(a.title.toString(), b.title.toString());
3004 if (result == 0) {
3005 result = a.componentName.compareTo(b.componentName);
3006 }
3007 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07003008 }
Winson Chung11904872012-09-17 16:58:46 -07003009 };
3010 }
Winson Chung78403fe2011-01-21 15:38:02 -08003011 public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
3012 = new Comparator<ApplicationInfo>() {
3013 public final int compare(ApplicationInfo a, ApplicationInfo b) {
3014 if (a.firstInstallTime < b.firstInstallTime) return 1;
3015 if (a.firstInstallTime > b.firstInstallTime) return -1;
3016 return 0;
3017 }
3018 };
Winson Chung11904872012-09-17 16:58:46 -07003019 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
3020 final Collator collator = Collator.getInstance();
3021 return new Comparator<AppWidgetProviderInfo>() {
3022 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
3023 return collator.compare(a.label.toString(), b.label.toString());
3024 }
3025 };
3026 }
Winson Chung5308f242011-08-18 12:12:41 -07003027 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3028 if (info.activityInfo != null) {
3029 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3030 } else {
3031 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3032 }
3033 }
Winson Chung785d2eb2011-04-14 16:08:02 -07003034 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07003035 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07003036 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07003037 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003038 ShortcutNameComparator(PackageManager pm) {
3039 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07003040 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003041 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003042 }
3043 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
3044 mPackageManager = pm;
3045 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003046 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003047 }
3048 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003049 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07003050 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
3051 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
3052 if (mLabelCache.containsKey(keyA)) {
3053 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003054 } else {
3055 labelA = a.loadLabel(mPackageManager).toString();
3056
Winson Chung5308f242011-08-18 12:12:41 -07003057 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003058 }
Winson Chung5308f242011-08-18 12:12:41 -07003059 if (mLabelCache.containsKey(keyB)) {
3060 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003061 } else {
3062 labelB = b.loadLabel(mPackageManager).toString();
3063
Winson Chung5308f242011-08-18 12:12:41 -07003064 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003065 }
Winson Chung11904872012-09-17 16:58:46 -07003066 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003067 }
3068 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003069 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003070 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003071 private PackageManager mPackageManager;
3072 private HashMap<Object, String> mLabelCache;
3073 WidgetAndShortcutNameComparator(PackageManager pm) {
3074 mPackageManager = pm;
3075 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003076 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003077 }
3078 public final int compare(Object a, Object b) {
3079 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003080 if (mLabelCache.containsKey(a)) {
3081 labelA = mLabelCache.get(a);
3082 } else {
3083 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003084 ((AppWidgetProviderInfo) a).label :
3085 ((ResolveInfo) a).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003086 mLabelCache.put(a, labelA);
3087 }
3088 if (mLabelCache.containsKey(b)) {
3089 labelB = mLabelCache.get(b);
3090 } else {
3091 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003092 ((AppWidgetProviderInfo) b).label :
3093 ((ResolveInfo) b).loadLabel(mPackageManager).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003094 mLabelCache.put(b, labelB);
3095 }
Winson Chung11904872012-09-17 16:58:46 -07003096 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003097 }
3098 };
Joe Onoratobe386092009-11-17 17:32:16 -08003099
3100 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003101 Log.d(TAG, "mCallbacks=" + mCallbacks);
Adam Cohen487f7dd2012-06-28 18:12:10 -07003102 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3103 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3104 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3105 ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003106 if (mLoaderTask != null) {
3107 mLoaderTask.dumpState();
3108 } else {
3109 Log.d(TAG, "mLoaderTask=null");
3110 }
Joe Onoratobe386092009-11-17 17:32:16 -08003111 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003112}